How to get the current branch with LibGit2Sharp? - libgit2sharp

How do I get the branch for a specific directory even if this directory is not the root of the repo ? iow the equivalent of
git branch --show-current
(which works fine even in a subdirectory).
Following the answer to this similar question, I did as follows, which works only in the root dir of the repo:
using (var git = new Repository("repo_root\subdir")) // throws if subdir
{
return git.Head.FriendlyName;
}

Oops, found it:
using (var git = new Repository(
LibGit2Sharp.Repository.Discover(#"repo_root\subdir")))
{
return git.Head.FriendlyName;
}

Related

Jenkins Shared Library resource not found

I have just started looking into a shared libarary with jenkins in order to combine a load of scripts and pipelines across multiple repos that are pretty much identical.
I have the shared lib loaded and working but when tryign to execute the scripts i the resources folder i keep geting not found errors:
../releaseTagging-EO2DMYOPJ6JGB6JT5Q2RSFJWJWWPALA7F25H7CQNYBEV4ITTEB6Q#tmp/build.sh: not found
I am creating a copy of the file using the following:
createTempLocation(String path) {
String tmpDir = pwd tmp: true
return tmpDir + File.separator + new File(path).getName()
}
and
copyGlobalLibraryScriptcall(String srcPath, String destPath = null) {
destPath = destPath ?: createTempLocation(srcPath)
writeFile file: destPath, text: libraryResource(srcPath)
echo "copyGlobalLibraryScript: copied ${srcPath} to ${destPath}"
sh "chmod +x ${destPath}"
echo "added executable permissions to ${destPath}"
return destPath
}
I am then calling the last function thusly:
runBuild(Map config) {
def script = copyGlobalLibraryScript('build.sh')
sh script
}
(i realise i can collapse the above function in to one line)
This in turn then gets called via (trimed the whole file to relevent part):
pipeline {
agent any
stages {
stage('Build') {
steps {
timestamps {
checkout scm
bbNotify( key: buildKey, name: BuildName) {
runBuild()
}
stash includes: '**', name: 'RelToSTAN'
}
}
}
}
This all fails with the error at the top of the question, however when sshing on to the build server i can find that file int he location specified.
I dont understand why Jenkins cannot find it and execute it.
The issue will be the following:
When using a java File object it‘ll always refer to some location on the Jenkins master. And of course it usually cannot run inside the sandbox.
On the other hand the readFile and writeFile methods always refer to some path on the build agent reserved by the node block where the call is encapsulated.
Long story short: Do not use the File class. Unfortunately you’ll need to create the temp path manually. But that shouldn’t be too hard.

Jenkins's Pipeline File Param [duplicate]

I'm putting together a Jenkins pipeline job which will take a file parameter. I can trigger the job and point it at a file however I can't find where the file has ended up (In an ordinary freestyle job it would be in the workspace).
Where has the uploaded file gone? Or do file parameters not currently work with pipelines?
There is currently an issue with pipeline and file parameter
(https://issues.jenkins-ci.org/browse/JENKINS-27413).
Solved it the following way:
node {
deleteDir()
stage("upload") {
def inputFile = input message: 'Upload file', parameters: [file(name: 'data.zip')]
new hudson.FilePath(new File("$workspace/data.zip")).copyFrom(inputFile)
inputFile.delete()
}
stage("checkout") {
echo fileExists('data.zip').toString()
}
}
I know the solution is not that beautiful because the pipeline gets interrupted for the upload but it works.
Further the "copyFrom" is necessary, because the input stores the "data.zip" in the jobs directory and not in the workspace (don't know why)
Found a WA (Strictly for text based file input)
We can use Jenkins multi-line string parameter and ask user to paste file contents to it.
And in our pipeline, write contents of this parameter using pipeline step writeFile, as :
stage('File Param WA') {
writeFile file: 'demo.yaml', text: params.DEMO_YAML
}
I tried using the solution provided by #Christoph Forster , but the input File was not getting copied anywhere in the workspace .
So I used the workaround as provided in
https://bitbucket.org/janvrany/jenkins-27413-workaround-library/src/6b7dada8ea37?at=default
The library provides a new library - unstashParam - that saves the file build parameter into a workspace. Works fine with text and yaml file .
I also tried using the solution by #Christoph Forster but I received a script security error when Groovy Sandbox is enable
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use new hudson.FilePath java.io.File
However, it seems we can skip the file copying and deleting actions (and bypass the Groovy sandbox restriction) by simply requiring that the file is uploaded to the job workspace. Just add the workspace variable to the file name as follows:
stage("upload") {
def inputFile = input message: 'Upload file', parameters: [file(name: "$workspace/data.zip")]
}
I found a solution in the form of a global library here:
https://bitbucket.org/janvrany/jenkins-27413-workaround-library/src/default/
It contains calls to inner methods of Jenkins which are deprecated (I guess).
So I made my own version like this:
import hudson.FilePath
import hudson.model.ParametersAction
import hudson.model.FileParameterValue
import hudson.model.Executor
def call(String name, String fname = null) {
def paramsAction = currentBuild.rawBuild.getAction(ParametersAction.class);
if (paramsAction == null) {
error "unstashParam: No file parameter named '${name}'"
}
for (param in paramsAction.getParameters()) {
if (param.getName().equals(name)) {
if (! param instanceof FileParameterValue) {
error "unstashParam: not a file parameter: ${name}"
}
if (env['NODE_NAME'] == null) {
error "unstashParam: no node in current context"
}
if (env['WORKSPACE'] == null) {
error "unstashParam: no workspace in current context"
}
workspace = new FilePath(getComputer(env['NODE_NAME']), env['WORKSPACE'])
filename = fname == null ? param.getOriginalFileName() : fname
file = workspace.child(filename)
file.copyFrom(param.getFile())
return filename;
}
}
}
def getComputer(name){
for(computer in Jenkins.getInstance().getComputers()){
if(computer.getDisplayName() == name){
return computer.getChannel()
}
}
error "Cannot find computer for file parameter workaround"
}
You can insert it in a global library and then use it like:
library "file-workaround"
node {
def file_in_workspace = unstashParam "myFile"
sh "cat ${file_in_workspace}"
}
It's not pretty but it's working and as long as there is no official fix, it's my best shot.
Update
Turns out you might run into "No such file or directory". That's because nothing in the workaround triggers Jenkins to create the workspace directory. If that was triggered somewhere else in the pipeline good, otherwise you'll be scratching your head.
You might wanna throw a
touch "thisIsAFile"
in there
To handle an optional file parameter in pipeline (to handle the use case where no file should be accepted) you could use jenkinsci-unstashParam-library (add it in Jenkins>Manage Jenkins>Configure System>Global Pipeline Libraries https://github.com/janvrany/jenkinsci-unstashParam-library) with a try/catch in a script as this sample stage:
stage('upload') {
steps {
// delete workspace
cleanWs()
// handle file parameters in pipeline (JENKINS-27413)
script {
try {
// force workspace directory creation
sh "touch emptyFileToCreateWorkspace"
// https://stackoverflow.com/questions/59468464/fetching-uploaded-files-in-jenkins
def file_in_workspace = unstashParam 'MY_FILE.xlsx'
// https://unix.stackexchange.com/questions/125776/error-with-a-file-name-containing-parentheses
sh "mv '${file_in_workspace}' MY_FILE.xlsx"
}
catch (Exception e) {
echo e.getMessage()
echo "No file parameter, we will continue.."
}
}
}
}
File parameters provides 2 alternative parameters types for files (stashed for large files and base64 for small files).
Example, for base64File:
node {
sh 'echo $FILE | base64 -d'
withFileParameter('FILE') {
sh 'cat $FILE'
}
}
and stashedFile:
node {
unstash 'FILE'
sh 'cat FILE'
}
Tried what Christoph suggested and it didnt work for me. Here is what worked for me and the setup which I have, his should help others figure out what to do.
Problem:
I am executing my pipeline on dedicated nodes and use sanitized workspaces. After some research and troubleshooting I found out that by default the file upload only works with Master node. I realized this after digging through the file system and finding the file I am uploading in the workspace on the master
Solution:
stage('Upload Key') {
agent { label 'master' }
steps {
script {
// Uploads file via master node and stases it for other nodes to access
def inputFile = input message: 'Upload file', parameters: [file(name: "key.p12")]
new hudson.FilePath(new File("${workspace}/key.p12")).copyFrom(inputFile)
inputFile.delete()
}
stash name: 'key.p12' , includes: "key.p12"
}
}
stage('Register') {
steps {
ws (sanitizedWorkspaceName) {
echo "Registering"
unstash 'key.p12'
}
}
}
Execute the suggested file copy solution by Christoph. This stores the file in the job workspace on the master node
Allow the scripts in Manage Jenkins > In Process Script approval
use the stash step to stash the uploaded file
In the target stage "running on a different node" use the unstash
Hope this helps
I wasn't able to make Christoph's solution working if the file was uploaded on master node and needed on slave. The solution was to stash it on master and later unstash it on slave. Don't forget to remove the uploaded file on master node.
It's supported by the latest File Parameters plugin now. Please refer to: How to pass a file parameter to another build job in jenkins pipeline?

File operations in Jenkins Pipeline

I have a pipeline flow defined as:
node("linux_label") {
println("hostname".execute().txt)
def filename = "${WORKSPACE}/submoduleinfo.txt"
stage("Submodule info") {
def submoduleString = sh script: "git -C ${WORKSPACE} submodule status > ${filename}", returnStdout: true
}
String fileContents = new File("$filename}").text
operateOnFile(fileContents)
}
At "new File" I will get an error saying no such file exists. after some troublehshooting I see that the hostname printout will output the jenkins master and not the node "linux_label" where the workspace resides.
Is this how Piepeline should work, i.e. all code that is not part of stage/steps/etc are executed on the jenkins master and not on the wanted node?
What would be a good workaround where I do an operation in one stage and want to operate on the file in the node {} domain?
That is how pipeline works. You can use readFile to read file from a workspace. Since you are using just a content of the file for your processing, this will work.
From tutorial:
readFile step loads a text file from the workspace and returns its
content (do not try to use java.io.File methods — these will refer to
files on the master where Jenkins is running, not in the current
workspace).
In one of our use case, we added some additional functions using Shared pipeline library.
Try this:
if (env['NODE_NAME'].equals("master")) {
return new hudson.FilePath(path);
} else {
return new hudson.FilePath(Jenkins.getInstance().getComputer(env['NODE_NAME']).getChannel(), path);
}

How to call external Groovy files from Jenkins Build Flow Plugin script?

A JobDSL script can use a Groovy file in the same directory. For example, Git.groovy with contents like:
class Git extends Closure<Void> {
final String git
def Git(final String git = '/usr/bin/git') {
super(null)
this.git = git
}
def call(ArrayList<String> command, File dir = null) {
final gitCommand = [git, *command].execute(null, dir)
gitCommand.waitFor()
}
}
can be used by a JobDSL script:
final git = new Git()
git(['clone', ...])
But when the same thing is tried in a Build Flow script, it emits something like:
Script1.groovy: 49: unable to resolve class Git
This happens even if the Build Flow script has Flow run needs a workspace set.
How can a Build Flow script re-use common code?

How to upload artifact to network drive using gradle?

I am reading this:
http://www.gradle.org/docs/current/userguide/artifact_management.html
to understand how to publish/upload my artifact to a network drive/fileshare which is a requirement (we have a maven repo up and running but some artifacts needs to be dumped on a fileshare). The examples I have found are more focused on deploying to repositories, maven, ivy, etc.
I have a simple eclipse java project that I build using gradle 1.2 with the following build.gradle file:
apply plugin: 'java'
sourceSets {
main {
java {
srcDir 'src'
}
}
test {
java {
srcDir 'test'
}
}
}
repositories {
flatDir {
name "fileRepo"
dirs "file://internal.newtwork.drive/folder/test"
}
}
uploadArchives {
repositories {
add project.repositories.fileRepo
}
}
Where in the gradle docs can I read about how to copy resources to a remote fileshare?
I have tried to update the protocol and the dir attribute based on the below answers but I get this error:
What went wrong:
Execution failed for task ':uploadArchives'.
Could not publish configuration ':archives'.
java.io.FileNotFoundException: /internal.newtwork.drive/folder/test/sample-gradle-java-unspecified.jar (No such file or directory)
The destination is correct so does the flatDir repo not support networkdrives?
You should define the following parameters:
archivesBaseName = 'yourappname'
group = 'your.app.package'
version = '1.0.0'
Your URL doesn't mention a scheme (http:, file:, etc.). I don't know if you can get away with using a file: URL, or whether you need to us a different syntax to specify a directory rather than an HTTP URL, but either way, you'll need to correctly form the URI for the Windows UNC path.
See this question for more details.
It looks like you're crossing your wires. The url would only be part of that ivy repository declaration which you're apparently not using. The filesystem repository would be handled by the flatDir block which is then referenced by the add project.repositories.fileRepo statement. I'd suggest trying the full path in the flatDir dir variable, otherwise the path of least resistance may just be to throw together a simple manual file copy (or other transfer) task which is then added on to the main deploy task you're using.
//Try this,
apply plugin: 'java'
apply plugin: 'maven'
repositories {
maven {
url "$archivaUrl"`enter code here`
credentials {
username = "$userName"
password = "$passWord"
}
}
}
// Dependencies
dependencies {
// specify the lib files at compile and run time
compile fileTree(dir: 'lib', include: ['**/*.jar','*.jar'])
runtime fileTree(dir: 'lib', include: ['**/*.jar','*.jar'])
}
// source path
sourceSets {
main {
java {
srcDirs 'src'
}
}
}
uploadArchives {
repositories {
mavenDeployer {
repository(url: "$archivaUrl") {
authentication(userName: "$userName", password: "$passWord")
}
pom.version = "1.0-SNAPSHOT"
pom.artifactId = "fd-common"
pom.groupId = "com.somename.common"
}
}
}

Resources