有没有办法让gradle exec像shell exec一样工作?即 - 了解路径中的可执行文件?
我们有需要在windows和unix上运行的代码 - 以及许多在两台机器上明显不同的脚本。虽然我可以做这样的黑客攻击:
npmCommand = Os.isFamily(Os.FAMILY_WINDOWS) ? 'npm.cmd' : '/usr/local/bin/npm'
然后运行该命令 - 某些脚本的路径不一定是一成不变的 - 它只是可怕的代码。
有没有办法解决问题 - 即扩展exec任务以查找路径中的可执行文件并运行它们?
答案 0 :(得分: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")
}
答案 1 :(得分:0)
怎么样?
if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows'))
{
commandLine 'cmd', '/c', 'commandGoesHere'
}
else
{
commandLine 'sh', '-c', 'commandGoesHere'
}