Reference a variable inside a string with groovy - string

Sorry if it was not clear enough.
I have the following groovy snippet (from Jenkins)
def jdk = jobConfig.java
jobConfig.env.JAVA_HOME="${tool '$jdk'}"
jobConfig.env.PATH="${env.JAVA_HOME}/bin:${env.PATH}"
How can I substitute the value of $jdk variable inside the single quotes on this line?
jobConfig.env.JAVA_HOME="${tool '$jdk'}"
For example, this works with no problems. The usage of tools is OK:
jobConfig.env.JAVA_HOME="${tool 'openjdk_11.0.14'}"
But I want to set the hardcoded value of 'openjdk_11.0.14' to the value coming from def jdk = jobConfig.java
I tried a few variations but couldn't find the solution.
Many thanks

How can I reference the $jdk variable inside the single quotes?
It isn't clear what you mean by that but what you have is this:
jobConfig.env.JAVA_HOME="${tool '$jdk'}"
There are a few things wrong with that but to address how to deal with the single quotes, 1 of the issues is you have nested $ which is going to confuse the situation.
if you are trying to surround the value of jdk with single quotes, you can do this:
def someJavaHomeRelatedVariable ="'${jdk}'"
Note that the quotes are outside of the {} expression.
A separate issue is your use of tool in that expression, but the above explains how to deal with surrounding the value of jdk with single quotes.
EDIT
The question isn't clear but maybe you are wanting to do something like this:
def sout = new StringBuilder()
def jdk = jobConfig.java
def proc = ['tool', jdk].execute()
proc.consumeProcessOutput(sout, null)
proc.waitForOrKill(2000)
jobConfig.env.JAVA_HOME = sout.toString()

Related

How to extract substring (path to folder) from string using batch script or PowerShell

I have been trying to remove in batch script "=" character from string by using this:
set Path_var=%Path_var:^==%
Unfortunately this does not work... I tried also some other common solutions like:
set Path_var=%Path_var:"="=%
set Path_var=%Path_var:'='=%
But without success. Maybe it would be worthy also to explain for what I need it as I am aware you may be able to provide better solution. I extract one line from xml configuration file. The line is following:
<burning addDicomViewer="true" finalizeMedium="true" dicomViewer="C:\user\App_folder\App-name_subfolder_1.1.1_Setup" burnVerification="true" numberOfCopies="0" cleanupProjectData="false" volumeName="Patient Medium"/>
I need to extract from this line this path: "C:\user\App_folder\App-name_subfolder_1.1.1_Setup" (The path will not always be the same)
My strategy was to simply remove definite number of characters before the path as I know this setting will always be the same and therefore the length of the string won`t change.
set /p Path_var= < temp_file01.txt
set Path_var=%Path_var:~81,100%
Then I wanted to use simply substitution to remove the rest. For example:
set Path_var=%Path_var:burnVerification=%
But I ran into problem that my string contains characters like "=" which I can not remove by this method. (Because obviously there are handled as operators) What I was also wondering is what I should do if there will be a space character in my path. Then when I attempt to remove the empty characters at the end I also invalidate my path.
I know batch scripts are not the best for manipulation with strings, but I do not have other choice as my boss want me to use scripting language which does not need compiling.
I asked my work colleague for help and he came with following PowerShell solution:
$path_temp_file01 = "C:\user\temp\tmpFile_backup_script01.txt"
$path_temp_file02 = "C:\user\temp\tmpFile_backup_script02.txt"
$string = [IO.File]::ReadAllText($path_temp_file01)
$Start = $string.IndexOf("C:")
$string = $string.substring($Start)
$End =$string.IndexOf("""")
$string = $string.substring(0,$End)
$string > $path_temp_file02
It works for me. I post it here in the case someone needs similar solution or has better idea how to do that.

Can I use double quotes in Chef attribute declaration?

I have inherited a cookbook that sets some attributes in the ./attributes/default.rb file as per normal.
However, we have a problem with one of the lines is, which is:
default["obscured"]["mysql"] = "#{node['jboss']['jboss_home']}/modules/com/mysql/jdbc/main"
When run, it write this into the node as:
{}/com/mysql/jdbc/main
I can confirm that the node['jboss']['jboss_home'] attribute exists and has correct values.
So, I cannot see any problem with the above, except that every other declaration of this type in our cookbooks has single quotes on the attribute to be set (i.e. left side), not double quotes. I haven't heard this of as being an issue before, but I am pretty new to chef.
Is there any rule that says they must be single quotes?
The answer is that there is no rule.
Using double-quotes in something like this is completely fine:
default["obscured"]["mysql"] = blah blah
The reason I know that is that I just found one being set, with double quotes, that actually works. :-)
What you have there is fine, how are you confirming the value of node['jboss']['jboss_home'] and how are you using it in the template?
In Ruby single and double quoted literals both become Strings but single quotes are relatively literal while double quotes allow backslash escapes and #{} interpolation.
You are most likely hitting the derived attributes problem:
https://coderanger.net/derived-attributes/
The attribute code in your cookbook is getting parsed before the jboss_home attribute is being set. One way or another the solution is to move the interpolation into recipe code.
You could just use a plain old ruby variable instead of the attribute you are trying to construct -- particularly if nothing else in your system ever sets that attribute.
You also should be able to delete the declaration from your attributes file and use this in recipe code as well:
node.default_unless["obscured"]["mysql"] =
"#{node['jboss']['jboss_home']}/modules/com/mysql/jdbc/main"
Although you need to place that statement early in your run_list, before you ever use node["obscured"]["mysql"] as an argument to any resource.

Using variables in Gradle build script

I am using Gradle in my project. I have a task for doing some extra configuration with my war. I need to build a string to use in my task like, lets say I have:
task extraStuff{
doStuff 'org.springframework:spring-web:3.0.6.RELEASE#war'
}
This works fine. What I need to do is define version (actually already defined in properties file) and use this in the task like:
springVersion=3.0.6.RELEASE
task extraStuff{
doStuff 'org.springframework:spring-web:${springVersion}#war'
}
My problem is spring version is not recognised as variable. So how can I pass it inside the string?
If you're developing an Android application using Gradle, you can declare a variable (i.e holding a dependency version) thanks to the keyword def like below:
def version = '1.2'
dependencies {
compile "groupId:artifactId:${version}"
}
I think the problem may lay on string literal delimiters:
The string literals are defined exactly as in groovy so enclose it in single or double quotes (e.g. "3.0.6.RELEASE");
Gstrings are not parsed in single quotes strings (both single '...' or triple '''...''' ones) if i recall correctly;
So the code will be:
springVersion = '3.0.6.RELEASE' //or with double quotes "..."
task extraStuff{
doStuff "org.springframework:spring-web:${springVersion}#war"
}
On android there are actually 2 possibilities how to achieve this. It really depends which suits your needs. Those two possibilities have their pros and cons. You can use def variable or ext{} block. Variable def is awesome because it lets you click on the variable and points exactly where it is defined in the file compared to ext{} block which does NOT points to that exact variable. On the other hand ext{} has one good advantage and that is you can refer variables from project_name/build.gradle to project_name/app/build.gradle which in some cases is very useful BUT as I said if you click on that variable lets say only inside only one file it wont points out to the definition of that variable which is very bad because it takes you more search time if your dependency list grows.
1) def option which is propably best and saves you search time.
def lifecycle = '2.0.0'
dependencies {
implementation 'androidx.lifecycle:lifecycle-extensions:$lifecycle'
}
2) second ext{} block. Its kinda ok if dependency list is not huge.
ext {
lifecycle = '1.1.1'
}
dependencies {
implementation 'androidx.lifecycle:lifecycle-extensions:$lifecycle'
}
3) In some cases if you want to share variables between project_name/build.gradle and project_name/app/build.gradle use ext{}
in project_name/build.gradle you define kotlin_shared_variable:
buildscript {
ext.kotlin_shared_variable = '1.3.41'
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_shared_variable"
}
}
which you can use in project_name/app/build.gradle
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_shared_variable"
}
and of course you can combine them.
see here.
Double-quoted strings are plain java.lang.String if there’s no interpolated expression, but are groovy.lang.GString instances if interpolation is present.
Gradle uses Groovy as a DSL. Here "${springVersion}" is a placeholder, what you want is to interpolate, so you should use the double quote, only the double quote in GString has the capability to interpolate.
You can also define variables in the gradle.properties file at the root of your project. You don't have to use double quotes in that file. You would need to add the following line:
lifecycle=2.0.0

Make substitution reference on strong containing equals sign

I'm trying to use a Make substitution reference to alter a string. The problem being that the string happens to contain an equals = symbol.
For example:
INPUT = -switch1 -switch2=potato -switch3
OUTPUT = $(INPUT:-switch2=%=-switch2=turnip)
all:
#echo TEST : $(OUTPUT)
so in the form $(var:a=b), INPUT is var, -switch2=% is a and -switch2=turnip is b.
Obviously that doesn't work because = is a special character in this context, but I've no idea how to make it realize that this is part of string a.
I've tried quoting, backslashes, alternative escape characters and putting -switch2=% in a variable and using that instead. All to no avail.
I know I can use patsubst, but that'd be adding the first non-POSIX extension to the file and i'd prefer to not be that guy.
Any suggestions appreciated!
You'll have to use a full patsubst function. Substitution references are just a shortcut for patsubst:
OUTPUT = $(patsubst -switch2=%,-switch2=turnip,$(INPUT))

Replacing or substituting in a python string does not work

I could almost solve all of my python problems thanks to this great site, however, now I'm on a point where I need some more and specific help.
I have a string fetched from a database which looks like this:
u'\t\t\tcase <<<compute_type>>>:\n\t\t\t\t{\n\t\t\t\t\tif (curr_i <= 1) Messag...
the string is basically plain c code with unix line endings and supposed to be treated in a way that the values of some specific variables are replaced by something else gathered from a Qt UI.
I tried the following to do the replacing:
tmplt.replace(u"<<<compute_type>>>", str(led_coeffs.compute_type))
where 'led_coeffs' is a namedtuple and its value is an integer. I also tried this:
tmplt = Template(u'\t\t\tcase ${compute_type}:\n\t\t\t\t{\n\t\t\t\t\tif (curr_i <= 1) Messag...)
tmplt.substitute(compute_type = str(led_coeffs.compute_type))
however, both approaches do not work and I have no idea why. Finally I was hoping to get some input here. Maybe the whole approach is not right and any hint on how to achieve the replacing in a good manner is highly appreciated.
Thanks,
Ben
str.replace (and other string methods) don't work in-place (string in Python are immutable) - it returns a new string - you will need to assign the result back to the original name for the changes to take effect:
tmplt = tmplt.replace(u"<<<compute_type>>>", str(led_coeffs.compute_type))
You could also invent your own kind of templating:
import re
print re.sub('<<<(.*?)>>>', lambda L, nt=led_coeffs: str(getattr(nt, L.group(1))), your_string)
to automatically lookup attributes on your namedtuple...

Resources