7

How to get the absolute path of a file (from workspace) in Jenkins pipeline script (in windows environment)

File locations (The files are checked-out from Git and Jenkinsfile2.nprd will have the groovy pipeline script):

C:/Program Files (x86)/Jenkins/workspace/dev-my-api/my-data-api/my-data-api/pom.xml C:/Program Files (x86)/Jenkins/workspace/dev-my-api/my-data-api/Jenkinsfile2.nprd

Script:

 stages {
        stage('Setup')  {
            steps {
                script {
                  pomPath = findFiles(glob: "**/pom.xml")[0].path
                  env.WORKSPACE = pwd()
                  pomDir = bat(script: "for %%F in ($pomPath) do set dirname=%%~dpF", returnStdout: true).trim()
                  echo "env.WORKSPACE:" + env.WORKSPACE
                  echo "pom file path:" + pomPath
                  echo "pom directory****:" + pomDir
                }
            }
        }
}

Output:

env.WORKSPACE:C:\Program Files (x86)\Jenkins\workspace\dev-my-api
pom file path:my-data-api\pom.xml
pom directory****:C:\Program Files (x86)\Jenkins\workspace\my-data-api>for %F in (my-data-api\pom.xml) do set dirname=%~dpF 

Requried path:

C:/Program Files (x86)/Jenkins/workspace/dev-my-api/my-data-api

How to get the above required path in Jenkins pipeline script without hard coding?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Thiagarajan Ramanathan
  • 1,035
  • 5
  • 24
  • 32

2 Answers2

0
pomPath = findFiles(glob: "**/$pomFile")[0].path
env.WORKSPACE = pwd()
def projectName = new File(pomPath).parent
baseDir = "${env.WORKSPACE}/$projectName"

I am able to get the required path. But looking for a cleaner solution.

Thiagarajan Ramanathan
  • 1,035
  • 5
  • 24
  • 32
0

Try out the following (find pom.xml relative path & get the full path)

 def pomPath = findFiles(glob: "**/pom.xml")[0].path
 echo new File(env.WORKSPACE, pomPath).getParent() +"\pom.xml"
CGS
  • 2,782
  • 18
  • 25
  • 1
    Shouldn't that require script approvals? `new File()` and `File.getParent()` both? `pomPath` will be a [`FileWrapper`](https://github.com/jenkinsci/pipeline-utility-steps-plugin/blob/master/src/main/java/org/jenkinsci/plugins/pipeline/utility/steps/fs/FileWrapper.java) instance. – Craig Ringer Jan 24 '19 at 04:00
  • 1
    beware of using File object. The CPS groovy executes some portions on master which won't have the file on it if you run on a node. It can be useful for constructing and decomposing paths but beyond that it can yield failures – Peter Kahn Aug 01 '19 at 15:41