2017-08-24 40 views
0

有沒有什麼辦法讓gradle exec像shell exec一樣工作?即 - 理解路徑中的可執行文件?爲什麼gradle exec不能使用腳本?

我們有需要在windows和unix上工作的代碼 - 以及許多在兩臺機器上明顯不同的腳本。雖然我可以做一個黑客攻擊這樣的:

npmCommand = Os.isFamily(Os.FAMILY_WINDOWS) ? 'npm.cmd' : '/usr/local/bin/npm'

,然後運行該命令 - 對於某些腳本的路徑不一定是一成不變的 - 它只是可怕的代碼。

有什麼辦法可以解決這個問題 - 即擴展exec任務,找到路徑中的可執行文件並運行它們?

+0

當然,您可以獲得標準的$ PATH值並使用groovy進行處理。順便說一句,可能[重複](https://stackoverflow.com/questions/36273690/is-there-a-way-to-get-gradle-to-exec-a-command-line-in-path)。 – slesh

回答

0

我喜歡一個更好的辦法 - 但我做了一個簡單的函數,我把我們共同的你使用這樣的:

exec { 
    commandLine command("npm"), "install" 
} 

功能如下:

// 
// find a command with this name in the path 
// 
String command(String name) 
{ 
    def onWindows = (System.env.PATH==null); 
    def pathBits = onWindows ? System.env.Path.split(";") : System.env.PATH.split(":"); 
    def isMatch = onWindows ? {path -> 
       for (String extension : System.env.PATHEXT.split(";")) 
       { 
        File theFile = new File(path, name + extension); 
        if (theFile.exists()) 
         return theFile; 
       } 
       return null; 
     } : {path -> def file = new File(path,name);if (file.exists() && file.canExecute()) return file;return null;} 

    def foundLocal = isMatch(file(".")); 
    if (foundLocal) 
     return foundLocal; 
    for (String pathBit : pathBits) 
    { 
     def found = isMatch(pathBit); 
     if (found) 
      return found; 
    } 
    throw new RuntimeException("Failed to find " + name + " in the path") 
} 
相關問題