我使用groovy运行以下命令来更新github上的发布说明:
"curl -v -i -X POST -H Content-Type:application/json -H 'Authorization: token 111111122222222222222222222' 'https://api.github.com/repos/company/repoName/releases/$id' -d '$API_JSON'"
API_JSON包含git提交的简短日志:
{"body":
"description=Committer name (35):
JIRA-1111 - SOME COMMENTS - GIT_HASH on DATE-TIME"}
问题是,如果注释中有括号,如(SOME COMMENTS)
中的命令,则
Stdout: /bin/sh: 1: Syntax error: "(" unexpected
我尝试使用正则表达式将括号替换为其内容(如果内容不是数字),但也导致错误。
Stdout: /bin/sh: 1: Syntax error: redirection unexpected
执行curl命令的Groovy脚本:
//replace new lines
description = description.replace('\n','<br/>')
//remove parentheses and their contents if non numerical
description = description.replaceAll("\\((?=[^)]*[a-zA-Z ])[^)]+?\\)","<br/>");
def API_JSON = sprintf ('{"body": "%s"}', description);
def githubCommand = "curl -v -i -X POST -H Content-Type:application/json -H 'Authorization: token 1111111111111111111111111111111’ 'https://api.github.com/repos/company/repo/releases/$id' -d '$API_JSON'"
String[] commands = ["/bin/bash", "-c", githubCommand]
def processBuilder=new ProcessBuilder(commands)
此外 - 如果评论中有新行,但使用正则表达式替换\n
<\br>
修复了问题,则会发生错误,如果没有括号,则说明版本说明已正确更新。
更新:将一个干净的参数数组传递给ProcessBuilder,没有任何工作(即使没有任何括号也没有更新github发布说明)
String postData = /{"body":"I'm (not) sure"}/
String[] command = ['curl', '-v', '-i', '-s','-X', 'POST', '-H','Content-Type:application/json', '-H', 'Authorization: token 111111111111111111111111111111111111111111111111111', 'https://api.github.com/repos/company/reppo/releases/$id', '-d', postData]
def process = new ProcessBuilder(command).redirectErrorStream(true).start()
println process.text
命令退出成功,但它没有做任何事情(也没有输出)
答案 0 :(得分:2)
数据报价不正确,因此您的问题不仅仅是数据中的括号。
以下失败并出现类似错误:
(我正在使用httpbin.org
而不是GitHub,所以任何人都可以测试,删除不相关的curl
参数以简洁,并slashy strings获取数据,因为它包含单引号和双引号,{ {1}}和'
)
"
作为def postData = /{"comment":"I'm (not) sure"}/
def command = "curl -s https://httpbin.org/post -d '${postData}'"
// At this point the command is already broken, the following will fail
String[] commands = ["/bin/bash", "-c", command]
def process = new ProcessBuilder(commands).redirectErrorStream(true).start()
println process.text
的参数传递的字符串如下:
bash
中间的引号打破了我们的字符串,结果命令行被bash拒绝(就像从shell执行时一样):
curl -s https://httpbin.org/post -d '{"comment":"I'm (not) sure"}'
但是,如果您将一个干净的参数数组传递给/bin/bash: -c: line 0: syntax error near unexpected token `('
,它就会起作用:
ProcessBuilder
或者,你可以使用Groovy进行HTTP POST而不需要curl:
String postData = /{"comment":"I'm (not) sure"}/
String[] command = ['curl', '-s', '-i', '-H' ,'Content-Type:application/json', 'https://httpbin.org/post', '-d', postData]
def process = new ProcessBuilder(command).redirectErrorStream(true).start()
println process.text