2014-10-31 52 views
0

我正在嘗試創建一個Grunt任務,該任務將運行'finger -lp'命令來捕獲登錄到計算機的用戶的名稱和登錄名。從終端執行時從grunt shell命令中捕獲用戶名

這裏的「手指-lp」的標準輸出:

Login: abc123      Name: John Doe 
    Directory: /Users/abc123   Shell: /bin/bash 
    On since Thu Oct 30 19:40 (EDT) on console, idle 19:34 (messages off) 
    On since Fri Oct 31 10:24 (EDT) on ttys002 
    No Mail. 

下面是如何我使用grunt.util.spawn運行相同的指令:

module.exports = function (grunt) { 
     grunt.registerTask('username', '', 
     function() { 
     var done = this.async(); 
     grunt.util.spawn({ 
      cmd: 'finger', 
      args: ['-lp'], 
      opts: {stdio: 'inherit'}, 
      fallback: '' 
     }, function (err, result, code) { 
      console.info('RESULT: ',err, result, code); 
      done(); 
     }); 
     }); 
    }; 

這是上面console.info聲明的輸出:

[email protected]:~/WorkFiles/john-doe/$ grunt username 

    Running "username" task 
    Login: abc123     Name: John Doe 
    Directory: /Users/abc123  Shell: /bin/bash 
    On since Thu Oct 30 19:40 (EDT) on console, idle 19:34 (messages off) 
    On since Fri Oct 31 10:24 (EDT) on ttys002 
    No Mail. 
    RESULT: null { stdout: '', stderr: '', code: 0, toString: [Function] } 0 

因此,Grunt任務沒有執行e命令finger -lp,其方式是將結果輸出到終端,但不被grunt.util.spawn過程捕獲。 result對象中的stdout爲空。

RESULT: null { stdout: '', stderr: '', code: 0, toString: [Function] } 0 

我下面從node的例子,因爲它是什麼grunt.util.spawn用途。

回答

0

我想通了。在grunt命令中捕獲用戶的登錄名和用戶名的方式是使用finger -lp命令運行產卵進程。然後我在輸出上運行一個正則表達式。

這工作在Mac上:

 grunt.registerTask('username', '', 
     function() { 
     var done = this.async(); 
     grunt.util.spawn({ 
      cmd: 'finger', 
      args: ['-lp'] 
     }, function (err, result, code) { 
      var username = ''; 
      var output = result.stdout; 
      if (output) { 
      var matches = result.stdout.match(/Login: ([a-zA-Z0-9]+)[\s\t]+Name: ([a-zA-Z0-9 ]+)/); 
      var login = matches[1]; 
      var name = matches[2]; 
      var username = (name + ' ' + login).toUpperCase(); 
      } 
      grunt.config('developerName', username); 
      done(); 
     }); 
     }); 

這個任務之前,我咕嚕過程中的所有其他任務運行,並且我的username任務的輸出保存到在grunt.config稱爲developerName在那裏我可以使用它的值在接下來的任何其他過程中,如下所示:

module.exports = { 

     dist: { 
     options: { 
      cssDir: "public/resources/", 
      sassDir: "src/resources/", 
      quiet: true, 
      environment: "production", 
      outputStyle: "compressed", 
      force: true, 
      banner: "/*! Concatenated on <%= grunt.template.today('mm-dd-yyyy') %> at <%= grunt.template.today('h:MM:ss TT') %> by <%= grunt.config('developerName') %> */\n" 
     } 
     } 

    }