Grep xcov result into variable at fastfile - grep

I'm using fastlane but I don't want to use xcov slack feature, I'm compiling all the info onto the same slack notification further sent.
lane :run_my_stuff do
xcov(project: "my-app.xcodeproj",
scheme: "my_scheme",
output_directory: "xcov_output",
only_project_targets: true)
$coverage=sh("grep \"(\d+.\d+\%)\"")
slack(message: "🍏",
success: true,
slack_url: "https://hooks.slack.com/services/xxxxxxxx...",
default_payloads: [],
link_names: true,
attachment_properties: {
fields: [{
title: "Coverage",
value: $coverage
}
]
})
end
This doesn't work but I believe it shows what I'm trying to achieve. I also tried to use:
$coverage=sh("cat xcov_report/index.html | grep '\d\+.\d\+\%' | head -1")

I figured out what was wrong w/ my code. Several things (sigh)
There is no need for dollar sign
coverage=sh("cat xcov_output/index.html | grep '\\d\\+.\\d\\+\\%' -o | head -1")
The folder in which I was wasn't the same I thought. So I changed the output path to fastlane/xcov_output
The escaping at the regular expression was not enough. So I doubled it
End
xcov(project: "my-app.xcodeproj",
scheme: "MOCK",
output_directory: "fastlane/xcov_output",
only_project_targets: true)
release_notes=sh("git tag -l --format='%(contents)' $(git describe $(git rev-list --tags --max-count=1))")
coverage=sh("cat xcov_output/index.html | grep '\\d\\+.\\d\\+\\%' -o | head -1")
slack(message: "🍏 b(#{number_of_commits}) <#XXXXX>",
success: true,
slack_url: "https://hooks.slack.com/services/...",
default_payloads: [],
link_names: true,
attachment_properties: {
fields: [
{
title: "Release notes",
value: release_notes
},
{
title: "Environment",
value: environment.capitalize
},
{
title: "Coverage",
value: coverage
}
]
}
)

Related

How to extract a variable(username,ID) from Jenkins output

This is the output I got:
"Successfully created scratch org: oopopoooppooop, username: test+color#example.com"
when I run the following script:
echo "1. Creating Scratch Org"
def orgStatus = bat returnStdout: true, script: "sfdx force:org:create --definitionfile ${PROJECT_SCRATCH_PATH} --durationdays 30 --setalias ${SCRATCH_ORG_NAME} -v DevHub "
if (!orgStatus.contains("Successfully created scratch org")) {
error "Scratch Org creation failed"
} else {
echo orgStatus
}
Now I need to extract scratch org ID and username from the output separately and store it.
You can use a regular expression:
def regEx = 'Successfully created scratch org: (.*?), username: (.*)'
def match = orgStatus =~ regEx
if( match ) {
println "ID: " + match[0][1]
println "username: " + match[0][2]
}
Here the operator =~ applies the regular expression to the input and the result is stored in match.
Live Demo

How to get input steps ouput in jenkins-pipeline

I used in my pipeline a input steps as you can see below :
input(
message : "some message",
parameters: [
[$class: 'ChoiceParameterDefinition',
choices: string ,
description: 'description',
name:'input'
]
]
)
I wanted to use the name input that I configure to get the value put in the input like this ${input}, but it didn't work. I also tried to put it in a var like this :
def reg = input : messages : "", paramaters: [...]
But It doesn't work either, so I don't understand how I can get the param that the user chose and didn't find how to do in the do.
Regards,
When using ChoiceParameterDefinition remember to define choices as string delimited with \n. You can assign value returned by input(...) step to a variable and use it later on. Take a look at following example:
node {
stage('Test') {
def reg = input(
message: 'What is the reg value?',
parameters: [
[$class: 'ChoiceParameterDefinition',
choices: 'Choice 1\nChoice 2\nChoice 3',
name: 'input',
description: 'A select box option']
])
echo "Reg is ${reg}"
}
}
In this example I define a single select with 3 options. When I run this pipeline, I get this popup to select one of three options:
I pick the first one and pipeline finishes with following console output:
[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/test-pipeline
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] input
Input requested
Approved by admin
[Pipeline] echo
Reg is Choice 1
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Try use this code:
def userInput = input(id: 'userInput', message: 'some message', parameters: [
[$class: 'ChoiceParameterDefinition', choices: string, description: 'description', name:'input'],
])
VARAIBLE = userInput
It's work For me.
If you need add more ChoiceParameterDefinition code should look like that:
def userInput = input(id: 'userInput', message: 'some message', parameters: [
[$class: 'ChoiceParameterDefinition', choices: string, description: 'description1', name:'input1'],
[$class: 'ChoiceParameterDefinition', choices: string, description: 'description2', name:'input2'],
])
VARAIBLE1 = userInput['input1']
VARAIBLE2 = userInput['input2']

Jenkinsfile Groovy Pipeline Text Parameter Whitespace

currently I wish to added a multliline text parmeter to a groovy pipeline. If the text parameter is not left column alighed (no space before paramter), then whitespace is injected into the text parameter list.
Any ideas on how to resolve this?
Here is the code
#!/usr/bin/env groovy
node {
def startTime = new Date()
println "Build start time : " + startTime
// Load system parameters
def projectProperties = [
[$class: 'EnvInjectJobProperty', info: [loadFilesFromMaster: false, secureGroovyScript: [classpath: [], sandbox: false, script: '']], keepBuildVariables: true, keepJenkinsSystemVariables: true, on: true]
]
// Set project parameters
projectProperties.add(parameters([
string(name: 'infraRepo', description: 'Repo Name', defaultValue: 'my-infrastructure' ),
string(name: 'infraBranch', description: 'Repo Branch', defaultValue: 'develop' ),
string(name: 'projectName', description: 'Project name', defaultValue: 'think-more' ),
// Text field not left side aligned now whitespace will be injected
text(name: 'ecrRepoAndVersion', description: 'ECR Docker name and version number',
defaultValue:'''address=3.0.1
address-details=3.0.1
auth=3.2.1'''),
choice(name: 'clusterName', description: 'Ecs cluster name', choices: '---Select---\nblue-ci\ngreen-ci', defaultValue: '---Select---'),
]))
properties(projectProperties)
// Print system variables
sh 'env | sort'
}
And here is an image of how the Jenkins Job UI looks after this pipeline is executed. Note the whitespace in the ecrRepoAndVersion field.
Thank you - that worked perfectly.
text(name: 'ecrRepoAndVersion', description: 'ECR Docker name and
version number',defaultValue:"""address=3.0.7-RC\n
address-details=3.0.3-RC\nauth=3.2.3-RC""")
Setting aside the need for this logic, I would add a bit more readability and ease of maintenance by joining a list of items, instead of verbatim specification:
def ecrRepoAndVersionItemsDefault = [
"address=3.0.7-RC",
"address-details=3.0.3-RC",
"auth=3.2.3-RC",
]
...
// then construct an ArrayList
def jobParams = []
jobParams << ...
...
jobParams << text(
name: 'ecrRepoAndVersion',
description: 'ECR Docker name and version number',
defaultValue: ecrRepoAndVersionItemsDefault.join('\n')
)
// then add the properties
...
projectProperties.add(parameters(jobParams))
...
properties(projectProperties)
...
// etc.

mosquitto with PAHO publishing and subscribing

I want to send a command line by MQTT from raspberry pi to my laptop. After search i found MQTT launcher 1 ,i want to send python simple_stream.py to run simple_stream script in windows ,but i don't know how to put the program and arguments of my command line ( python simple_stream.py) in launcher.conf file instead of the examples of author , this is launcher.conf file of author
logfile = 'logfile'
mqtt_broker = 'localhost' # default: 'localhost'
mqtt_port = 1883 # default: 1883
mqtt_clientid = 'mqtt-launcher-1'
# mqtt_username = 'jane'
# mqtt_password = 'secret'
topiclist = {
# topic payload value program & arguments
"sys/file" : {
'create' : [ '/usr/bin/touch', '/tmp/file.one' ],
'false' : [ '/bin/rm', '-f', '/tmp/file.one' ],
'info' : [ '/bin/ls', '-l', '/tmp/file.one' ],
},
"prog/pwd" : {
None : [ 'pwd' ],
},
"dev/1" : {
None : [ 'ls', '-l', '/' ],
},
"dev/2" : {
None : [ "/bin/echo", "111", "*", "#!#", "222", "#!#", "333" ],
},
}
can you please help me
Add a line to the sys/file, right after info, that says the following:
'launch' : [ '/usr/bin/python', 'simple_stream.py' ],
This way, when you send the payload 'launch' (without quotes) to the topic sys/file, it will execute the desired python script. Please adjust with the path of your python executable (in linux: 'which python' will tell you the path).
Hope this helps.

Jenkins-pipeline Extract and Set variables from properties file in groovy

To begin i'm writing the pipeline entirely as groovy to be checked in to git. Please do not provide any gui necessary solutions. My Problem statement is:
Extract a variable from a file and set it equal to a groovy object.
What i've tried
def SERVICE_MAJOR_VERSION
node {
runGitClone(GIT_REPO_URL, GIT_HASH)
def conf = readFile("gradle.properties")
echo conf
//THE BELOW COMMENT DOESN'T WORK
//SERVICE_MAJOR_VERSION = loadEnvFromFile("SERVICE_VERSION_MAJOR", "gradle.properties", true, SERVICE_VERSION_MAJOR)
}
def runGitClone(git_repo_url, git_hash) {
checkout changelog: false, poll: false, scm: [$class: 'GitSCM', branches: [[name: git_hash]], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'WipeWorkspace']], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '85572032-4284-4095-9eec-4df70ddfdb68', url: git_repo_url]]]
}
def loadEnvFromFile(string_name, file_path, should_print_load) {
def par1 = null
def content = readFile file_path
def matcher = content =~ /${string_name}\=(.+)/
if (matcher) {
par1 = string_name + "='" + matcher[0][1] + "'"
new GroovyShell(this.binding).evaluate(par1)
if (should_print_load) {
println par1
}
}
return par1
}
I've tried other suggestions to no avail. Particularly the below two.
Get values from properties file using Groovy
Parsing string as properties
If you have a working example of extracting a variable from a file and setting it equal to a groovy object it would solve my problem.
SOLVED:
def content = readFile 'gradle.properties'
Properties properties = new Properties()
InputStream is = new ByteArrayInputStream(content.getBytes());
properties.load(is)
def runtimeString = 'SERVICE_VERSION_MINOR'
echo properties."$runtimeString"
SERVICE_VERSION_MINOR = properties."$runtimeString"
echo SERVICE_VERSION_MINOR

Resources