2015-02-10 122 views
6

我正在使用Grunt和Grunt-shell來構建/部署我的Javascript項目。Grunt-shell保存命令輸出作爲變量

我想獲得最新的git-commit號碼並將它作爲一個變量存儲,但不能想象如何。 我試過了回調並設置了一個全局變量。這個變量是在函數中使用,但不包括從其它塊中似乎

grunt.initConfig({ 
... 
shell: { 
     getGitCommitNo: { 
     command: 'git rev-parse --short HEAD', 
     options: { 
      callback: function (err, stdout, stderr, cb) { 
       global['gitCommitNo'] = stdout; 
       grunt.log.ok(global.gitCommitNo); 
       cb(); 
      } 
     } 
     }, 
     philTest: { 
     command: 'echo Git Commit No: ' + global.gitCommitNo 
     }, 
... 
} 

輸出:

>> Starting deployment process for version 1.1 in dev environment 

Running "shell:getGitCommitNo" (shell) task 
bfc82a9 
>> bfc82a9 

Running "shell:printTest" (shell) task 
Git Commit No: undefined 

Done, without errors. 

任何人都可以建議我怎麼可能挽救一個命令行變量的輸出,可用請?

+0

不知道你可以用'shell'插件做到這一點,但你可以寫一個簡單的自定義模塊,如果有必要去做。 – jakerella 2015-02-10 18:38:48

回答

10

發現我實際上可以在回調中使用配置變量(而不是全局)來做到這一點。 (注意下面的行也刪除換行符)。

grunt.config.set('gitCommitNo', stdout.replace('\n', '')); 

那麼這可以通過訪問:

<%=gitCommitNo%> 
+0

這應該被標記爲正確的答案。非常感謝。 – 2015-02-11 10:19:34

+0

注意:我必須在grunt文件的頂部放置'grunt.loadNpmTasks('grunt-shell')'**,在**'grunt.initConfig({...')的上方爲此工作 – 2016-05-12 19:12:52