groovyjenkins-pipelinebitbucket-api

Unable to escape character in groovy bitbucket


I wanted to output shared path viewable on windows to bitbucket, however unable to get the expected output Code snippet in groovy and out put as follow:

event_msg="\\\\blr-archieve\\Sfolder\\bins\\"
event_msg="Shared Path : "+event_msg
println event_msg  //properly getting output \\blr-archieve\Sfolder\bins
addCommentToPR(event_msg)
def addCommentToPR(String... event_msg){
    def event_msg_tmp=""
    event_msg.each { 
        def tmpMsg="${it}"
        event_msg_tmp+=tmpMsg.replaceAll('[ ]', '\\\\ ')
        event_msg_tmp+="\\\\n"
    }
    event_msg=event_msg_tmp
    def Comment_Url= "https://bitbucket.testing.com/rest/api/latest/projects/test/repos/myrepo/pull-requests/123/comments?diffType=EFFECTIVE\\&markup=true\\&avatarSize=48"
    withCredentials([usernameColonPassword(credentialsId: 'TESTING', variable: 'API_PWD')]) {
        println sh(script: 'curl -u $API_PWD -d {\\"text\\":\\"\\ '+event_msg+'\\"} -X POST -i '+Comment_Url+' -H "Content-Type:application/json"', returnStdout: true)
    }
}

Expected output in PR :

\\blr-archieve\Sfolder\bins

Actual output in PR :

lr-archieveSfolderbins

Any inputon how to automatically escape characters is also very usefull


Solution

  • You are mixing together a lot of different syntaxes: groovy, json, and bash. Doing it with string concatenation is a recipe for disaster.

    1. You have groovy special characters covered:
    event_msg = '\\\\blr-archieve\\Sfolder\\bins\\'
    event_msg = 'Shared Path : ' + event_msg
    addCommentToPR(event_msg)
    
    1. Build a json object in groovy and then serialize it using writeJSON. Don't worry about bash at this point.
    def addCommentToPR(String... event_msg) {
        def full_event_msg = event_msg.join('\n')
        def payload = writeJSON json: [text: full_event_msg], returnText: true
    
    1. Pass complex strings with special characters as environment variables to avoid the whole bash tokenization and expansion problem
        def Comment_Url = "https://bitbucket.testing.com/rest/api/latest/projects/test/repos/myrepo/pull-requests/123/comments?diffType=EFFECTIVE&markup=true&avatarSize=48"
        withEnv([
            "PAYLOAD=$payload",
            "COMMENT_URL=$Comment_Url",
        ]) {
            withCredentials([usernameColonPassword(credentialsId: 'TESTING', variable: 'API_PWD')]) {
                println sh(script: 'curl -u "$API_PWD" -d "$PAYLOAD" -X POST -i "$COMMENT_URL" -H "Content-Type:application/json"', returnStdout: true)
            }
        }
    }