Jenkins Git Plugin

repository·master·Indexed 20 days ago

https://github.com/jenkinsci/git-plugin

Provides core Git SCM integration for Jenkins, supporting operations such as polling, fetching, checking out, branching, merging, tagging, and pushing. It includes the scmGit parameter for Jenkins Pipelines, a base implementation for Multibranch Pipelines and Organization Folders, and advanced checkout extensions for shallow clones, Git LFS, sparse checkouts, and submodule management. It also features repository browser integration, webhook-based commit notifications via the notifyCommit endpoint, and a Git Publisher for Freestyle projects.

Tokens
5.4K
Snippets
7
Records
18
Agent score
22%

What's inside git-plugin

  1. Configure Multibranch Pipelines with Git

    master

    The git plugin includes a multibranch provider for Jenkins Multibranch Pipelines and Organization Folders.

    Note: This is a 'base implementation' that uses command line git. If your git provider (e.g., GitHub, Bitbucket, GitLab, Gitea, or Tuleap) has a dedicated branch source plugin, you should prefer that implementation as it uses REST APIs for a better experience and additional capabilities.

  2. Use Git Publisher (Freestyle Projects Only)

    master

    The Git Publisher is a post-build action that allows pushing commits or tags from a Freestyle project workspace to a remote repository. Note: This is NOT available for Pipeline, Multibranch Pipeline, or Organization Folder projects.

    General Options

    • Push Only If Build Succeeds: Only pushes if the build status is successful (not unstable, failed, or canceled).
    • Merge Results: If merge extensions were used during the build, this pushes the merge results to the remote.
    • Force Push: Allows overwriting remote history if the remote repository refuses to replace a commit.

    Tagging Options

    • Tag to push: The name of the tag (supports Jenkins environment variables like $BUILD_TAG).
    • Tag message: The message associated with the tag.
    • Create new tag: Creates a new tag; the job fails if the tag already exists.
    • Update new tag: Modifies an existing tag to point to the most recent commit. Warning: Git documentation strongly advises against updating tags.
    • Tag remote name: The short name of the remote (e.g., origin).

    Branch Options

    • Branch to push: The name of the remote branch to receive the commits.
    • Target remote name: The short name of the remote (e.g., origin).
    • Rebase before push: Fetches the latest commits from the remote and applies local changes on top using git rebase. Warning: This creates a configuration of commits that has not been evaluated by any Jenkins job.
  3. Configure Push Notifications via Webhooks

    master

    To minimize delay between a push and a build, configure your Git provider to use a Webhook to notify Jenkins via the notifyCommit endpoint.

    For custom Git servers, you can use a post-receive hook that executes a curl command:

    curl "http://yourserver/git/notifyCommit?url=<URL_OF_REPO>&token=<ACCESS_TOKEN>"

    Parameters:

    • url (required): The URL used to clone the repository.
    • branches (optional): Comma-separated list of branches.
    • sha1 (optional): The commit hash.
    • token (optional): A secret token generated in Jenkins Global Security.

    Security Note: The token is required by default. You can change this via the system property hudson.plugins.git.GitStatus.NOTIFY_COMMIT_ACCESS_CONTROL using values disabled-for-polling or disabled (not recommended).

    curl "http://yourserver/git/notifyCommit?url=<URL of the Git repository>&token=<Access token>"
  4. Checkout git repositories with various configurations

    master

    The scmGit step supports several advanced checkout behaviors via the extensions parameter:

    • Specific Branch: Use branches: [[name: 'branch-name']].
    • SSH with Private Key: Use userRemoteConfigs: [[credentialsId: 'id', url: 'ssh://...']].
    • HTTPS with Credentials: Use userRemoteConfigs: [[credentialsId: 'id', url: 'https://...']].
    • Git LFS: Add extensions: [ lfs() ].
    • No Tags: Add extensions: [ cloneOption(noTags: true) ] to save time/space.
    • Shallow Clone: Add extensions: [ cloneOption(shallow: true) ] to request only a limited number of commits.
    • Narrow Refspec: Use extensions: [ cloneOption(honorRefspec: true) ] combined with a specific refspec in userRemoteConfigs to limit fetched branches.
    • Prune Stale Branches/Tags: Add extensions: [ pruneStaleBranch(), pruneTags(true) ] to remove local references that no longer exist on the remote.
    // Example: Shallow clone
    checkout scmGit(
        branches: [[name: '*/master']],
        extensions: [ cloneOption(shallow: true) ],
        userRemoteConfigs: [[url: 'https://github.com/jenkinsci/ws-cleanup-plugin.git']])
    
    // Example: Checkout and prune stale remote branches
    checkout scmGit(
        branches: [[name: 'master']],
        extensions: [ pruneStaleBranch(), pruneTags(true) ],
        userRemoteConfigs: [[url: 'https://github.com/jenkinsci/ws-cleanup-plugin.git']])
  5. Use the git plugin in Jenkins Pipelines

    master

    The git plugin provides the scmGit parameter, which is used with the Pipeline checkout step to pull git repositories into a workspace. You can use the Pipeline Syntax Snippet Generator to generate specific checkout commands based on your requirements.

    checkout scmGit(
        branches: [[name: 'master']],
        userRemoteConfigs: [[url: 'https://github.com/jenkinsci/git-plugin.git']])
  6. Configure Git Checkout Extensions

    master

    Checkout extensions modify how Git operations place files in the workspace. They can adjust timeouts, submodule behavior, workspace location, and more.

    Advanced Checkout Behaviors

    Modifies the git checkout command:

    • Timeout (in minutes) for checkout operation: Stops the checkout if it exceeds this duration. Useful for slow file systems or large repositories.

    Advanced Sub-modules Behaviors

    Modifies git submodule commands. Controls:

    • Disable submodules processing: Ignores submodules in the repository.
    • Recursively update submodules: Retrieves all submodules recursively (without this, submodules containing other submodules are ignored).
    • Update tracking submodules to tip of branch: Retrieves the tip of the configured branch in .gitmodules.
    • Use credentials from default remote of parent repository: Provides parent repository credentials to each submodule. Note: The submodule must accept the same credential type (e.g., if parent uses https, submodules must use https).
    • Path of the reference repo to use during submodule update: A folder containing a repository used as a reference during submodule clone operations.
    • Timeout (in minutes) for submodule operations: Overrides the default timeout.
    • Number of threads to use when updating submodules: Number of parallel processes (default is 1).
    • Shallow clone: Performs a shallow clone of submodules to save time/space.
    • Shallow clone depth: Sets the specific depth for the shallow clone.

    Checkout to a Sub-directory

    Checks out to a subdirectory of the workspace instead of the root. Warning: Do NOT use this in Jenkins Pipeline. Use ws or dir instead.

    • Local subdirectory for repo: The relative path from the workspace root.

    Checkout to Specific Local Branch

    • Branch name: If provided, checks out the revision as HEAD on the named branch. If set to "" or "**", the branch name is computed from the remote (e.g., origin/master becomes master). If a specific revision is checked out, the local branch name becomes detached.
  7. Configure Workspace Cleaning (Before or After Checkout)

    master

    Both 'Clean before checkout' and 'Clean after checkout' delete untracked files and directories (including those in .gitignore) and reset tracked files to their versioned state. This ensures the workspace is in a clean state, similar to a fresh clone.

    Options for both:

    • Delete untracked nested repositories: Removes subdirectories containing .git subdirectories (implements git clean -xffd).

    Note: Neither option removes files outside the workspace or files in the .git directory.

  8. Configure Git Repository settings

    master

    When configuring a Git repository in a Jenkins job, the following parameters are available:

    • Repository URL: The remote URL (supports https, ssh, scp, git, local file, etc.).
    • Credentials: Selected from the Jenkins credentials plugin.
    • Name: A short name for the remote (defaults to origin).
    • Refspec: Maps remote branches to local references. If left blank, it defaults to retrieving all branches. A restrictive refspec like +refs/heads/master:refs/remotes/origin/master can reduce data transfer.
  9. Configure Changelog Extensions

    master

    Changelog extensions adapt how the plugin calculates source code differences between builds.

    • Calculate changelog against a specific branch: Uses a specified branch (e.g., origin/master) for comparison instead of the previous build. Useful for environments without a formal 'pull request' concept.
      • Name of repository: The remote name (e.g., origin).
      • Name of branch: The branch name to use for calculation.
    • Use commit author in changelog: By default, the plugin uses the Git 'Committer' value. Enabling this uses the Git 'Author' value instead.
  10. Configure Global Git Plugin settings

    master

    Global settings can be managed via the Jenkins 'Configure System' page or via Configuration as Code (JCasC).

    Key Global Settings:

    • user.name / user.email: Default identity for commits made by Jenkins.
    • hideCredentials: Hides the credential identifier in console logs.
    • disablePerformanceEnhancements: Disables the automatic selection between JGit and command-line git based on repository size.
    • addGitTagAction: Controls whether the git tag action is automatically added to jobs.
    unclassified:
      scmGit:
        addGitTagAction: false
        allowSecondFetch: false
        createAccountBasedOnEmail: false
        disableGitToolChooser: false
        globalConfigEmail: "jenkins-user@example.com"
        globalConfigName: "jenkins-user"
        hideCredentials: false
        showEntireCommitSummaryInChanges: true
        useExistingAccountWithSameEmail: false
  11. Configure Build Initiation and Polling

    master

    Control how and when builds are triggered by Git changes.

    Build Initiation

    • Don't trigger a build on commit notifications: If checked, the repository is ignored when the notifyCommit URL is accessed.
    • Force polling using workspace: Instead of using ls-remote, polling is performed from a cloned copy of the workspace. This is required if using certain exclusion filters.

    Polling Filters

    These options require a workspace (disabling the faster ls-remote mechanism):

    • Polling ignores commits from certain users: Ignores revisions committed by users in a provided list (exact string match, one per line).
    • Polling ignores commits in certain paths: Uses Java regular expressions to include or exclude specific files/folders from triggering a build.
      • Included Regions: Java regex patterns (empty list = include everything).
      • Excluded Regions: Java regex patterns (empty list = exclude nothing).
    • Polling ignores commits with certain messages: Ignores revisions where the commit message matches a provided Java regular expression pattern.
  12. Remove Git build data via Groovy script workaround

    master

    If you encounter issues with Git build data stored in build records, you can use a system Groovy script to remove the BuildsByBranch static list. This workaround removes the action.buildsByBranchName array action from each build to clean up the data.

    Requirements:

    • You must have Administrator permission to run system Groovy scripts.
    • The script must be executed from the Jenkins Administrator's Script Console (e.g., https://jenkins.example.com/script).

    What the script does:

    1. Iterates through all jobs in the Jenkins instance.
    2. Identifies builds containing hudson.plugins.git.util.BuildData actions.
    3. Resets the buildsByBranchName map to an empty HashMap while preserving the last built revision information.
    4. Handles both standard jobs and MatrixProject runs by cleaning up both the main build and its individual runs.
    import hudson.matrix.*
    import hudson.model.*
    import static hudson.Util.fixNull
    
    hudsonInstance = hudson.model.Hudson.instance
    jobNames = hudsonInstance.getJobNames()
    allItems = []
    for (name in jobNames) {
      allItems += hudsonInstance.getItemByFullName(name)
    }
    
    // Iterate over all jobs and find the ones that have a hudson.plugins.git.util.BuildData
    // as an action.
    //
    // We then clean it by removing the useless array action.buildsByBranchName
    
    for (job in allItems) {
      println("job: " + job.name);
      def counter = 0;
      for (build in job.getBuilds()) {
        // It is possible for a build to have multiple BuildData actions
        // since we can use the Multiple SCM plugin.
        def gitActions = build.getActions(hudson.plugins.git.util.BuildData.class)
        if (gitActions != null) {
          for (action in gitActions) {
            action.buildsByBranchName = new HashMap<String, Build>();
            hudson.plugins.git.Revision r = action.getLastBuiltRevision();
            if (r != null) {
              for (branch in r.getBranches()) {
                action.buildsByBranchName.put(fixNull((String) branch.getName()), action.lastBuild)
              }
            }
            build.actions.remove(action)
            build.actions.add(action)
            build.save();
            counter++;
          }
        }
        if (job instanceof MatrixProject) {
          def runcounter = 0;
          for (run in build.getRuns()) {
            gitActions = run.getActions(hudson.plugins.git.util.BuildData.class)
            if (gitActions != null) {
              for (action in gitActions) {
                action.buildsByBranchName = new HashMap<String, Build>();
                hudson.plugins.git.Revision r = action.getLastBuiltRevision();
                if (r != null) {
                  for (branch in r.getBranches()) {
                    action.buildsByBranchName.put(fixNull((String) branch.getName()), action.lastBuild)
                  }
                }
                run.actions.remove(action)
                run.actions.add(action)
                run.save();
                runcounter++;
              }
            }
          }
          if (runcounter > 0) {
            println(" -->> cleaned: " + runcounter + " runs");
          }
        }
      }
      if (counter > 0) {
        println("-- cleaned: " + counter + " builds");
      }
    }