Publishing to Github Packages from Jenkins Using Cake - cakebuild

I'm having an issue publishing to Github Packages from Jenkins using Cake.
The push task looks like this:
Task(nugetPushTask)
.WithCriteria(() => isPublishBranch)
.IsDependentOn(packTask)
.Does(() => {
foreach(var file in GetFiles(nugetFilesPath)) {
DotNetNuGetPush(file, new DotNetNuGetPushSettings {
ApiKey = "key_gdhsjgjhjkeykeykey",
Source = "https://nuget.pkg.github.com/yourOrganizationOrAccount/index.json"
});
}
});
Interestingly, I can successfully push the package with the following command:
dotnet nuget push nameofpackage.1.0.0.nupkg --source github --api-key key_gdhsjgjhjkeykeykey
using a shell prompt.
The error which I see in the build log for that step is:
An error occurred when executing task 'PublishGithub'.
System.Exception: Github Package Key Environment Variable is not set
correctly.
at Submission#0.<>b__0_7(ICakeContext context)
at
Cake.Core.CakeTaskBuilderExtensions.<>c__DisplayClass39_0.b__0(ICakeContext
context) in
C:\projects\cake\src\Cake.Core\CakeTaskBuilder.Execution.cs:line 81
at Cake.Core.CakeTask.Execute(ICakeContext context) in
C:\projects\cake\src\Cake.Core\CakeTask.cs:line 119
at Cake.Core.DefaultExecutionStrategy.ExecuteAsync(CakeTask task,
ICakeContext context) in
C:\projects\cake\src\Cake.Core\DefaultExecutionStrategy.cs:line 69
at Cake.Core.CakeEngine.ExecuteTaskAsync(ICakeContext context,
IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task,
CakeReport report) in
C:\projects\cake\src\Cake.Core\CakeEngine.cs:line 318
Can anyone advise how to get Cake to do what the CLI command is doing.
Thanks

Related

Can't run flutter build from Jenkins

I tried to run a flutter build from jenkins using the following pipeline code :
pipeline {
agent any
stages {
stage('build') {
steps {
bat 'C:\\path_to_doc\\flutter_dev\\flutter\\bin\\flutter.bat build web -t "C:\\path_to_doc\\lib\\src\\main\\main.dart"'
}
}
}
post{
always {
archiveArtifacts artifacts: 'C:\\path_to_doc\\build\\web\\index.html', fingerprint: true, followSymlinks: false
}
}
}
I got this error in jenkins :
I tried to write the flutter build code in a bat file in the root of my flutter project, and then execute this file on the pipeline code, got the same error.
What is the correct way to proceed to avoid this error ?
Jenkins has a habit of reverting to the initial workspace directory for each separate command. Try setting the directory after your steps{ line:
dir('C:\\path_to_doc\\flutter_dev\\flutter\\bin\\') {
bat 'flutter.bat build web -t "C:\\path_to_doc\\lib\\src\\main\\main.dart"'
}
This will ensure that your script will run in this location. So if your pubspec.yaml is in this location, it should be able to find it. In any case, this is a problem with the directory, so if this doesn't work, some manual debugging would be necessary to see what went wrong.

Display jest warning as a warning in the Azure DevOps pipeline build results page

We have an Azure DevOps pipeline which uses self hosted Windows agents with Azure DevOps server 2019. The pipeline runs our front-end tests. For this we use the following command line to run the tests:
npm run jest -- --ci --reporters=default --reporters=jest-junit. Then we use the publish test results task to publish the results.
This all works just fine. However, we noticed recently that the runtime warnings in the tests aren't being displayed anywhere. We have our linter warnings displayed in the build results page by adding the vso formatter like this: npm run nx run-many -- --target="lint" --all --skip-nx-cache=true --parallel --format=vso. However, it doesn't seem jest has any kind of format argument we can use.
Is it possible to take the warnings that display in the jest tests and log them in the results page of the build? Thank you for any help, please let me know if I can provide additional information.
So I ended up using the following PowerShell task to append a version of what #PerryQian-MSFT posted into my jest-setup.js file.
- task: PowerShell#2
displayName: Make test log warnings
inputs:
targetType: 'inline'
script: |
Add-Content -path config/jest-setup.js -value #"
import { command, log } from "azure-pipelines-logging";
const { error, warn } = console;
global.console.error = (...args) => {
error(...args);
log(command("task", "logissue", { type: "error" })(...args));
};
global.console.warn = (...args) => {
warn(...args);
log(command("task", "logissue", { type: "warning" })(...args));
};
"#
I had to change the solution from the GitHub post because I didn't want the tests to fail if they hit a warning, the pipeline should still succeed, just with issues. To fix this I included azure-pipelines-logging as a dependency. Then I was able to use log(command("task", "logissue", { type: "warning" })(...args)); to log in the pipeline whenever a warning is called.

How do you get a grunt error to return on a VSTS hosted build agent

I'm trying to run grunt tasks through a batch script and am calling grunt as follows:
call npm install
call npm install grunt
However, if this returns an error, then the VSTS build on the hosted build agent still shows up as successful (even with a logged error in the script). Does anyone have any good examples of how to get it to return an error to the build?
I've been looking at using powershell, but without any luck so far, with code as follows:
In gruntfile.js:
grunt.initConfig({
shell: {
ps: {
options: {
stdout: true
},
command: 'powershell ../../errors.ps1'
}
}
});
grunt.registerTask('default', function() {
try {
grunt.task.run([
'less:desktop',
'less:tablet',
'less:smartphone',
'less:homepage_desktop',
'less:homepage_tablet']);
} catch(e) {
grunt.task.run([
'shell:ps']);
throw e;
}
});
In errors.ps1:
$URL_Format_Error = [string]"Error found in running grunt. Please investigate grunt logs"
Write-Error $URL_Format_Error -ErrorAction:Stop
return
The code run in the exception handler never gets called, and a warning is output with a compilation error in the .less file, but the powershell is never run. Is there a way I can hook into the warning perhaps, and run my powershell then?
As an alternative, when I try to add a grunt task to the VSTS build definition after a batch script to run the NPM install, I just keep getting the following error (even after seeing a successful NPM installation in the batch script):
Fatal error: Unable to find local grunt
Hence, I'm not sure if I can run the grunt task in a separate task the VSTS build definition, if I'm using a hosted build agent. I'm inclined to think that would only work if I had my own build server.
Just try to use Write-Error in combination with an exit 1 in your script.
Write-Error ("Some error")
exit 1
Reference this thread : How to fail the build from a PowerShell task in TFS 2015

Jenkins publish changes in repository to github using pipeline and groovy

I have a jenkins organization pipeline job that executes on all repositories that have "Jenkinsfile" defined. The job clones the repository from github, then runs the powershell script that increments the version number in the file. I'm now trying to publish that updated file back to the original repository on github, so when developer pulls the changes he gets the latest version number.
I tried using the script (inside "jenkinsfile") as suggested in jenkins JIRA (https://issues.jenkins-ci.org/browse/JENKINS-28335), but to no avail. Any suggestions will be appreciated. Basically need to execute "git commit" and "git push" using the same parameters defined for a job.
Just as a reference, here is a previous solution used for free style (not pipeline job): How to push changes to github after jenkins build completes?.
Actually found couple solutions, first I modied script from Jenkins like this (some objects changed in workflow pipeline):
import hudson.FilePath
import org.eclipse.jgit.transport.URIish
node {
env.WORKSPACE = pwd()
stage 'Checkout'
checkout scm
def build = manager.build
def listener = manager.listener
def workspace = new FilePath(new File(env.WORKSPACE))
def environment = build.getEnvironment(listener)
final def project = build.getParent()
final def gitScm = project.getTypicalSCM()
final def gitClient = gitScm.createClient(listener, environment, build, workspace);
final def gitTagName = "TAG_NAME"
final def comment = "COMMENT"
final def remoteURI = new URIish("origin")
gitClient.tag(gitTagName, comment)
gitClient.push().tags(true).to(remoteURI).execute()
}
You need to run the script multiple times and then allow code execution in jenkins (manage jenkins->in process script approval).
Another solution, much simpler (using this one for now):
bat "\"${tool 'Git'}\" config user.email \"ci#virtocommerce.com\""
bat "\"${tool 'Git'}\" config user.name \"Virto Jenkins\""
bat "\"${tool 'Git'}\" commit -am \"Updated version number\""
bat "\"${tool 'Git'}\" push origin HEAD:master -f"
You have to have Git tool with a name "Git" configured in Jenkins.

Stop the pipeline when stage is unstable

I have a Jenkins build pipeline created using workflow plugin. At the beginning the pipeline runs a gulp build inside of the docker container and then archives test results using the following code
step([$class: 'JUnitResultArchiver', testResults: 'build/test-results/*.xml'])
In the following steps I package up the artifacts and ship them to the binary repository.
When unit tests are not passing Jenkins understands the build is unstable and marks it yellow. However it still continues with subsequent steps in the pipeline. Is there any way make the pipeline stop when unit tests are failing?
the JUnitResultArchiver will cause this condition to be true when the build is unstable:
currentBuild.result != null.
If I remember correctly it sets it to UNSTABLE, but it is enough to check that is different than null.
So you could do something like
step([$class: 'JUnitResultArchiver', testResults: 'build/test-results/*.xml'])
if (currentBuild.result == null) {
//contintue with your pipeline
} else {
//notify that the build is unstable. //or just do nothing
}
There is nothing to do at Jenkins side but at Gulp side. The call to gulp CLI needs to return a proper error value to have the sh step failing correctly.
Jenkins just interprets what the shell is returning, so you juts need to make Gulp to return a fail when tests fail (see this blog post, it seems to achieve exactly that).