Jenkins: ${BUILD_LOG, maxLines, escapeHtml} not working - groovy

I am trying to use "${BUILD_LOG, maxLines, escapeHtml}" like discribed in:
How can I take last 20 lines from the $BUILD_LOG variable?
Unfortunately it doesn't work for me.
I get this error:
Script1.groovy: 114: expecting anything but ''\n''; got it anyway # line 114, column 301.
arted by user MYUSERNAME
My code in this line is:
msg.setText("This build (" + build.getFullDisplayName()
+ " ) contains the following tasks:\n\nTASK\t\t\t IMPLEMENTER:\n"
+ taskList + "\n\n\nLink to this
build: ${BUILD_URL} \n ${BUILD_LOG, maxLines=9999, escapeHtml=false}" );
If I take this out the following, it works. Thats why my guess is, that "BUILD_LOG" is not working anymore?
${BUILD_LOG, maxLines=9999, escapeHtml=false}
EDIT:
Maybe as addition: I am trying to do this withing the PreSend groovy script.
Since I am building the Email text dynamically.
${BUILD_URL} works fine, ${BUILD_LOG, maxLines=9999, escapeHtml=false} doesn't (for me) i am looking for a solution for this...
the msg object is a java MimeMessage.
Thanks,
Daniel

That error message is usually related to not closed quotes, comments started with / instead of //, etc. In your code the only thing I can see is that your third line is not finished properly, i.e., after "\n\n\nLink to this you are not closing double quotes and instead you are starting a new line (thereby the expecting anything but ''\n''.
Try to write the whole line:
msg.setText("This build (" + build.getFullDisplayName()
+ " ) contains the following tasks:\n\nTASK\t\t\t IMPLEMENTER:\n"
+ taskList + "\n\n\nLink to this build: ${BUILD_URL} \n ${BUILD_LOG, maxLines=9999, escapeHtml=false}" );
or close the quotes instead:
msg.setText("This build (" + build.getFullDisplayName()
+ " ) contains the following tasks:\n\nTASK\t\t\t IMPLEMENTER:\n"
+ taskList + "\n\n\nLink to this "
+ "build: ${BUILD_URL} \n ${BUILD_LOG, maxLines=9999, escapeHtml=false}" );

I used the below and it's working fine for me.
${BUILD_LOG, maxLines=10, escapeHtml=false}
I tried with Jenkins version 1.617

Have you tried to set escapeHtml=true? It may happen that this token expanded as is and then string in " " becomes not valid.

In latest version variable ${BUILD_LOG} wasn't available for me - only solution to get log in email content was for me setting:
msg.setText(build.getLog())
as Default Pre-send Script in Jenkins global configuration...

Related

Python eval is not working as a string how to use with shell code

I have a function like svn_check which basically check brnach in svn function is given below
def svn_check(request):
url ='eval `/volume/tools/bin/ssh-agent.sh`;printenv;ssh-add -l;/volume/tools/bin/svn info svn+ssh://cng-svn.tema.net/my-2009/branches/NEHA_NEGI'
output, message = subprocess.getstatusoutput(url)
print("CMD : " + str(url))
print("Message : " + str(message))
print("Return Code : " + str(output_br))
return HttpResponse(output_br)
i also have a branch with name NEHA_NEGI. but when i am executing this function it is returning me the error i dont know why it is returning me the error.
CMD : 'eval /volume/tools/bin/ssh-agent.sh;printenv;ssh-add -l;/volume/tools/bin/svn info svn+ssh://cng-svn.tema.net/my-2009/branches/NEHA_NEGI', referer: http://my-site.com:81/
Message : NOTE: ssh-agent is empty; use ssh-add to load your key(s)!, referer: http://my-site.com:81/
Return Code : 1, referer: http://my-site.com:81/
I am getting this in the error log. can anyone please help me relate this why I am getting this error? thanks in advance I am a newbie in shell language.
Or maybe it is happening because eval function is treated as a string. so there s any other way to type so eval can run properly.

How to concatenate variables plus os.enviorn path plus yaml in Python

1)TOPDIR =/../../
2)/ABC/path/
3)name=os.os.environ['ABC'].lower()
4).yaml
I want to Concatenate all four things in one like
Tried below solution :
[TOPDIR + "/ABC/path/" + name .yaml] appending this in Generartor
Not working. Can anyone give solution for this.
TOPDIR = '/../../'
name = os.environ['ABC'].lower()
print([TOPDIR + "/ABC/PATH/" + name + '.yaml'])
This should work.
What's the error it throws actually?
Perhaps you have a typo "os.enviorn" should be "os.environ"

Passing multiple params to a cmd line argument via Powershell - what quotes to use and when

When in Powershell I can run the following command
.\exiftool.exe '-GPSLatitude*=56.9359839838' '-GPSLongitude*=-4.4651045874' DSC01008.JPG '-overwrite_original_in_place'
This works just fine, and the placement of single quotes around those params are required. I went through various iterations of different placements and the above is the only way I could get it to work.
My issue is -> That I'm trying to replace those values with programmatic values. As in something like the following.
$lat = 56.9359839838
$lon = -4.4651045874
$fileName = 'DSC01008.JPG'
.\exiftool.exe -GPSLatitude*=$lat -GPSLongitude*=$lon $fileName '-overwrite_original_in_place'
I've gone through numerous attempts with single/backtick/double quotes, trying to concatenate and anything else I can think of - but that magic format hasn't appeared!
Any thoughts on what I am doing wrong?
As an example I thought this was really work, yet didn't. But it matches up with the command that does when it's hard coded.
EDIT/Update -
The * are required inside the command, otherwise it doesn't work. They are used to get around not passing in reference locators.
If you were to run these commands in PS, then these are the errors that you get.
cmd ->
.\exiftool.exe "-GPSLatitude*=$lat" "-GPSLongtitude*=$lon" $FileName
error ->
No Error, but the file does not get any GPS tags. Nothing actually modified.
cmd ->
$combLat = "`'-GPSLatitude*=$lat`'" # + "
$combLon = "`'-GPSLongitude*=$lon`'" # + "'"
$combined = "$combLat $combLon $fileName"
# $combined will output the following: '-GPSLatitude*=-3.4651045874' '-GPSLongitude*=55.9359839838' 'E:\CameraAddGPS\TestFolder\DSC01010.JPG'
.\exiftool.exe $combined
error ->
.\exiftool.exe : Wildcards don't work in the directory specification
At E:\CameraAddGPS\TestFolder\demo.ps1:25 char:1
+ .\exiftool.exe $combined
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Wildcards don't...y specification:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
No matching files
Update 2 -
This will work, but I do not want to update the image twice.
$combLat = '-GPSLatitude*=' + $lat
$combLon = '-GPSLongitude*=' + $lon
.\exiftool.exe $combLat $fileName '-overwrite_original_in_place'
.\exiftool.exe $combLon $fileName '-overwrite_original_in_place'
The problem is that the latitude and longtitude argumets are "attached" directly to the -GPSLatitute* and -GPSLongtitude* parameter names after the = sign. (The - initial character prevents PowerShell from invoking variable expansion - see GitHub issue #14587.)
One way to work around this is to wrap the -GPSLatitude* and -GPSLongtitude* parameters in " quotes; e.g.
.\exiftool.exe "-GPSLatitude*=$lat" "-GPSLongtitude*=$lon" $FileName -overwrite_original_in_place
Another way is to prefix the - character with a backquote (`); e.g.:
.\exiftool.exe `-GPSLatitude*=$lat `-GPSLongitude*=$lon $fileName -overwrite_original_in_place
I prefer the first variation as it seems more readable to me.
Aside #1: There's no need for the single ' quotes around that last parameter. They don't hurt, but they don't do anything, either.
Aside #2: You can see the actual command line that PowerShell is running if you prefix your command with the getargs command available here:
https://github.com/Bill-Stewart/getargs/releases
The getargs utility outputs the actual command line without any parsing or interpretation and will show the actual command that PowerShell will run.

Python- Trying to print a variable and using (str) in front of number, but still getting a syntax error

I created a variable called "age = 23". I try and add it to another variable called "message" and specify it as a string using the (str) tag in front of the "age" variable.
age = 23
message = "Happy " + (str)age + "rd
birthday!"
print(message)
But whenever I try and run the code it comes back with a snytax error that looks like this:
line 7
message = "Happy " + (str)age + "rd
birthday!"
^
SyntaxError: invalid syntax
1|potter:/ $
You have the brackets in the wrong place, I'm not going to use your example as you've added it as an image, as AChampion mentioned, but an example is:
number = 34
message = "The number is " + str(number)
print(message)
I'd recommend taking some time to read the Python documentation, as this can help get your head around the language and its more basic uses.
message = "Happy " + str(age) + "rd birthday!"
print(message)
If you are learning Python from other languages such as C, you might know this method:
age = 23
print ('Happy %srd birthday!' % (age))
print ('Happy {}rd birthday!'.format(age)) # Use this
Might help: https://pyformat.info/

Lua script unable to detect/catch error while executing invalid linux command

I have the following function that works fine as long as I give it a valid command to execute. As soon as I give it a non-existent command, the script is interrupted with an error message.
#!/usr/bin/lua
function exec_com(com)
local ok,res=pcall(function() return io.popen(com) end)
if ok then
local tmp=res:read('*a')
res:close()
return ok,tmp
else
return ok,res
end
end
local st,val=exec_com('uptime')
print('Executed "uptime" with status:'..tostring(st)..' and value:'..val)
st,val=exec_com('zzzz')
print('Executed "zzzz" with status:'..tostring(st)..' and value:'..val)
When I run the script above I get the following output:
Executed "uptime" with status:true and value: 18:07:38 up 1 day, 23:00, 3 users, load average: 0.37, 0.20, 0.20
sh: zzzz: command not found
Executed "zzzz" with status:true and value:
You can clearly see above that pcall() function still reported success when executing "zzzz" which is odd.
Can someone help me devise a way to catch an exception when executing a non-existent or ill-formed Linux command using Lua script? Thanks.
Edit: Restated my request after getting the clarification that pcall() works as expected, and the problem is due to popen() failing to throw an error.
I use a method which is similar to your "temporary workaround" but which gives you more information:
local cmd = "uptime"
local f = io.popen(cmd .. " 2>&1 || echo ::ERROR::", "r")
local text = f:read "*a"
if text:find "::ERROR::" then
-- something went wrong
print("error: " .. text)
else
-- all is fine!!
print(text)
end
If you look at io.popen(), you'll see that it'll always return a file handle.
Starts program prog in a separated process and returns a file handle
that you can use to read data from this program (if mode is "r", the
default) or to write data to this program (if mode is "w").
Since, a file handle returned is still a valid value for lua, the pcall(), your local function inside the pcall is returning a true value (and an error is not being propagated); thereby, giving you a true status and no output.
I have come up with my own temporary workaround that pipes the error to /dev/null and determines the success/failure of executed command based on the text received from io.popen():read('*a') command.
Here is my new code:
#!/usr/bin/lua
function exec_com(com)
local res=io.popen(com..' 2>/dev/null')
local tmp=res:read('*a')
res:close()
if string.len(tmp)>0 then
return true,tmp
else
return false,'Error executing command: '..com
end
end
local st,val=exec_com('uptime')
print('Executed "uptime" with status:'..tostring(st)..' and value:'..val)
st,val=exec_com('cat /etc/shadow')
print('Executed "cat /etc/shadow" with status:'..tostring(st)..' and value:'..val)
And the corresponding output is now correct:
Executed "uptime" with status:true and value: 00:10:11 up 2 days, 5:02, 3 users, load average: 0.01, 0.05, 0.19
Executed "cat /etc/shadow" with status:false and value:Error executing command: cat /etc/shadow
In my example above I am creating a "generic" error description. This is an intermediate fix and I am still interested in seeing alternative solutions that can return a more meaningful error message describing why the command failed to execute.
Rather than taking the time reading the whole file into a variable, why not just check if the file is empty with f:read(0)?
Local f = io.popen("NotExist")
if not f:read(0) Then
for l in st:lines() do
print(l)
end
else
error("Command Does Not Exist")
end
From the lua Manual:
As a special case, io.read(0) works as a test for end of file: It returns an empty string if there is more to be read or nil otherwise.

Resources