org.jenkinsci.plugins.gitclient.Git Java Examples

The following examples show how to use org.jenkinsci.plugins.gitclient.Git. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ListGitBranchesParameterDefinition.java    From list-git-branches-parameter-plugin with MIT License 6 votes vote down vote up
private GitClient createGitClient(Job job) throws IOException, InterruptedException {
    EnvVars env = Objects.requireNonNull(Objects.requireNonNull(Jenkins.getInstance()).toComputer()).getEnvironment();
    Git git = Git.with(TaskListener.NULL, env);

    GitClient c = git.getClient();
    List<StandardUsernameCredentials> urlCredentials = CredentialsProvider.lookupCredentials(
            StandardUsernameCredentials.class, job, ACL.SYSTEM, URIRequirementBuilder.fromUri(remoteURL).build()
    );
    CredentialsMatcher ucMatcher = CredentialsMatchers.withId(credentialsId);
    CredentialsMatcher idMatcher = CredentialsMatchers.allOf(ucMatcher, GitClient.CREDENTIALS_MATCHER);
    StandardUsernameCredentials credentials = CredentialsMatchers.firstOrNull(urlCredentials, idMatcher);

    if (credentials != null) {
        c.addCredentials(remoteURL, credentials);
        if (job != null && job.getLastBuild() != null) {
            CredentialsProvider.track(job.getLastBuild(), credentials);
        }
    }
    return c;
}
 
Example #2
Source File: GitUtils.java    From blueocean-plugin with MIT License 6 votes vote down vote up
public static void fetch(final Repository repo, final StandardCredentials credential) {
    try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
        FetchCommand fetchCommand = git.fetch();

        addCredential(repo, fetchCommand, credential);

        fetchCommand.setRemote("origin")
            .setRemoveDeletedRefs(true)
            .setRefSpecs(new RefSpec("+refs/heads/*:refs/remotes/origin/*"))
            .call();
    } catch (GitAPIException ex) {
        if (ex.getMessage().contains("Auth fail")) {
            throw new ServiceException.UnauthorizedException("Not authorized", ex);
        }
        throw new RuntimeException(ex);
    }
}
 
Example #3
Source File: GitClientFetchBenchmark.java    From git-client-plugin with MIT License 6 votes vote down vote up
/**
 * We want to create a temporary local git repository after each iteration of the benchmark, works just like
 * "before" and "after" JUnit annotations.
 */
@Setup(Level.Iteration)
public void doSetup() throws Exception {
    tmp.before();
    gitDir = tmp.newFolder();

    gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using(gitExe).getClient();

    // fetching all branches
    refSpecs.add(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));

    // initialize the test folder for git fetch
    gitClient.init();

    System.out.println("Do Setup for: " + gitExe);
}
 
Example #4
Source File: TestGitRepo.java    From flaky-test-handler-plugin with Apache License 2.0 6 votes vote down vote up
public TestGitRepo(String name, File tmpDir, TaskListener listener) throws IOException, InterruptedException {
  this.name = name;
  this.listener = listener;

  envVars = new EnvVars();

  gitDir = tmpDir;
  User john = User.get(johnDoe.getName(), true);
  UserProperty johnsMailerProperty = new Mailer.UserProperty(johnDoe.getEmailAddress());
  john.addProperty(johnsMailerProperty);

  User jane = User.get(janeDoe.getName(), true);
  UserProperty janesMailerProperty = new Mailer.UserProperty(janeDoe.getEmailAddress());
  jane.addProperty(janesMailerProperty);

  // initialize the git interface.
  gitDirPath = new FilePath(gitDir);
  git = Git.with(listener, envVars).in(gitDir).getClient();

  // finally: initialize the repo
  git.init();
}
 
Example #5
Source File: GitUtils.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 *  Attempts to push to a non-existent branch to validate the user actually has push access
 *
 * @param repo local repository
 * @param remoteUrl git repo url
 * @param credential credential to use when accessing git
 */
public static void validatePushAccess(@Nonnull Repository repo, @Nonnull String remoteUrl, @Nullable StandardCredentials credential) throws GitException {
    try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
        // we need to perform an actual push, so we try a deletion of a very-unlikely-to-exist branch
        // which needs to have push permissions in order to get a 'branch not found' message
        String pushSpec = ":this-branch-is-only-to-test-if-jenkins-has-push-access";
        PushCommand pushCommand = git.push();

        addCredential(repo, pushCommand, credential);

        Iterable<PushResult> resultIterable = pushCommand
            .setRefSpecs(new RefSpec(pushSpec))
            .setRemote(remoteUrl)
            .setDryRun(true) // we only want to test
            .call();
        PushResult result = resultIterable.iterator().next();
        if (result.getRemoteUpdates().isEmpty()) {
            System.out.println("No remote updates occurred");
        } else {
            for (RemoteRefUpdate update : result.getRemoteUpdates()) {
                if (!RemoteRefUpdate.Status.NON_EXISTING.equals(update.getStatus()) && !RemoteRefUpdate.Status.OK.equals(update.getStatus())) {
                    throw new ServiceException.UnexpectedErrorException("Expected non-existent ref but got: " + update.getStatus().name() + ": " + update.getMessage());
                }
            }
        }
    } catch (GitAPIException e) {
        if (e.getMessage().toLowerCase().contains("auth")) {
            throw new ServiceException.UnauthorizedException(e.getMessage(), e);
        }
        throw new ServiceException.UnexpectedErrorException("Unable to access and push to: " + remoteUrl + " - " + e.getMessage(), e);
    }
}
 
Example #6
Source File: GitClientFetchBenchmark.java    From git-client-plugin with MIT License 5 votes vote down vote up
private File cloneUpstreamRepositoryLocally(File parentDir, String repoUrl) throws Exception {
            String repoName = repoUrl.split("/")[repoUrl.split("/").length - 1];
            File gitRepoDir = new File(parentDir, repoName);
            gitRepoDir.mkdir();
            GitClient cloningGitClient = Git.with(TaskListener.NULL, new EnvVars()).in(gitRepoDir).using("git").getClient();
            cloningGitClient.clone_().url(repoUrl).execute();
//            assertTrue("Unable to create git repo", gitRepoDir.exists());
            return gitRepoDir;
        }
 
Example #7
Source File: GitClientInitBenchmark.java    From git-client-plugin with MIT License 5 votes vote down vote up
/**
 * We want to create a temporary local git repository after each iteration of the benchmark, similar to
 * "before" and "after" JUnit annotations.
 */
@Setup(Level.Iteration)
public void doSetup() throws Exception {
    tmp.before();
    gitDir = tmp.newFolder();

    gitClient = Git.with(TaskListener.NULL, new EnvVars()).in(gitDir).using(gitExe).getClient();

    System.out.println("Do Setup");
}
 
Example #8
Source File: GitExceptionTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void initJGitImplCollisionThrowsGitException() throws GitAPIException, IOException, InterruptedException {
    File dir = folder.getRoot();
    File dotGit = folder.newFile(".git");
    Files.write(dotGit.toPath(), "file named .git".getBytes("UTF-8"), APPEND);
    GitClient defaultClient = Git.with(TaskListener.NULL, new EnvVars()).in(dir).using("jgit").getClient();
    JGitInternalException e = assertThrows(JGitInternalException.class,
                                           () -> {
                                               defaultClient.init_().workspace(dir.getAbsolutePath()).execute();
                                           });
    assertThat(e.getCause(), isA(IOException.class));
}
 
Example #9
Source File: GitExceptionTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void initCliImplCollisionThrowsGitException() throws GitAPIException, IOException, InterruptedException {
    File dir = folder.getRoot();
    File dotGit = folder.newFile(".git");
    Files.write(dotGit.toPath(), "file named .git".getBytes("UTF-8"), APPEND);
    GitClient defaultClient = Git.with(TaskListener.NULL, new EnvVars()).in(dir).using("git").getClient();
    assertThrows(GitException.class,
                 () -> {
                     defaultClient.init_().workspace(dir.getAbsolutePath()).execute();
                 });
}
 
Example #10
Source File: GitExceptionTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void initJGitImplThrowsGitException() throws GitAPIException, IOException, InterruptedException {
    String fileName = isWindows() ? "\\\\badserver\\badshare\\bad\\dir" : "/this/is/a/bad/dir";
    final File badDirectory = new File(fileName);
    assumeFalse("running as root?", new File("/").canWrite());
    GitClient defaultClient = Git.with(TaskListener.NULL, new EnvVars()).in(badDirectory).using("jgit").getClient();
    assertNotNull(defaultClient);
    JGitInternalException e = assertThrows(JGitInternalException.class,
                                           () -> {
                                               defaultClient.init_().workspace(badDirectory.getAbsolutePath()).execute();
                                           });
    assertThat(e.getCause(), isA(IOException.class));
}
 
Example #11
Source File: GitExceptionTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void initCliImplThrowsGitException() throws GitAPIException, IOException, InterruptedException {
    String fileName = isWindows() ? "\\\\badserver\\badshare\\bad\\dir" : "/this/is/a/bad/dir";
    final File badDirectory = new File(fileName);
    assumeFalse("running as root?", new File("/").canWrite());
    GitClient defaultClient = Git.with(TaskListener.NULL, new EnvVars()).in(badDirectory).using("git").getClient();
    assertNotNull(defaultClient);
    assertThrows(GitException.class,
                 () -> {
                     defaultClient.init_().workspace(badDirectory.getAbsolutePath()).execute();
                 });
}
 
Example #12
Source File: GitAPI.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
public void commit(String message, PersonIdent author, PersonIdent committer) throws GitException, InterruptedException {
    if (Git.USE_CLI) {
        super.setAuthor(author);
        super.setCommitter(committer);
        super.commit(message);
    } else {
        jgit.setAuthor(author);
        jgit.setCommitter(committer);
        jgit.commit(message);
    }
}
 
Example #13
Source File: GitUtils.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Determines if the repository is using an SSH URL
 * @param repo repository to
 * @return true if there appears to be an SSH style remote URL
 */
private static boolean isSshUrl(Repository repo) {
    try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
        return isSshUrl(git.remoteList().call().get(0).getURIs().get(0).toString());
    } catch (IndexOutOfBoundsException | GitAPIException e) {
        return false;
    }
}
 
Example #14
Source File: GitUtils.java    From blueocean-plugin with MIT License 5 votes vote down vote up
public static void push(String remoteUrl, Repository repo, StandardCredentials credential, String localBranchRef, String remoteBranchRef) {
    try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
        String pushSpec = "+" + localBranchRef + ":" + remoteBranchRef;
        PushCommand pushCommand = git.push();

        addCredential(repo, pushCommand, credential);

        Iterable<PushResult> resultIterable = pushCommand
            .setRefSpecs(new RefSpec(pushSpec))
            .setRemote(remoteUrl)
            .call();
        PushResult result = resultIterable.iterator().next();
        if (result.getRemoteUpdates().isEmpty()) {
            throw new RuntimeException("No remote updates occurred");
        } else {
            for (RemoteRefUpdate update : result.getRemoteUpdates()) {
                if (!RemoteRefUpdate.Status.OK.equals(update.getStatus())) {
                    throw new ServiceException.UnexpectedErrorException("Remote update failed: " + update.getStatus().name() + ": " + update.getMessage());
                }
            }
        }
    } catch (GitAPIException e) {
        if (e.getMessage().toLowerCase().contains("auth")) {
            throw new ServiceException.UnauthorizedException(e.getMessage(), e);
        }
        throw new ServiceException.UnexpectedErrorException("Unable to save and push to: " + remoteUrl + " - " + e.getMessage(), e);
    }
}
 
Example #15
Source File: ApplyStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
public GitConfig getGitConfig() throws AbortException {
    try {
        GitClient client = Git.with(listener, env).in(workspace).getClient();
        return client.withRepository(new GitInfoCallback(listener));
    } catch (Exception e) {
        throw new AbortException("Error getting git config " + e);
    }
}
 
Example #16
Source File: AbstractGitTestCase.java    From flaky-test-handler-plugin with Apache License 2.0 5 votes vote down vote up
protected String getHeadRevision(AbstractBuild build, final String branch) throws IOException, InterruptedException {
  return build.getWorkspace().act(new MasterToSlaveFileCallable<String>() {
    public String invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
      try {
        ObjectId oid = Git.with(null, null).in(f).getClient().getRepository().resolve("refs/heads/" + branch);
        return oid.name();
      } catch (GitException e) {
        throw new RuntimeException(e);
      }
    }
  });
}
 
Example #17
Source File: GitAPI.java    From git-client-plugin with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@NonNull
public Repository getRepository() throws GitException {
    return Git.USE_CLI ? super.getRepository() :  jgit.getRepository();
}
 
Example #18
Source File: GitCloneReadSaveRequest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
GitClient cloneRepo() throws InterruptedException, IOException {
    EnvVars environment = new EnvVars();
    TaskListener taskListener = new LogTaskListener(Logger.getAnonymousLogger(), Level.ALL);
    String gitExe = gitTool.getGitExe();
    GitClient git = Git.with(taskListener, environment)
            .in(repositoryPath)
            .using(gitExe)
            .getClient();

    git.addCredentials(gitSource.getRemote(), getCredential());

    try {
        git.clone(gitSource.getRemote(), "origin", true, null);

        log.fine("Repository " + gitSource.getRemote() + " cloned to: " + repositoryPath.getCanonicalPath());
    } catch(GitException e) {
        // check if this is an empty repository
        boolean isEmptyRepo = false;
        try {
            if (git.getRemoteReferences(gitSource.getRemote(), null, true, false).isEmpty()) {
                isEmptyRepo = true;
            }
        } catch(GitException ge) {
            // *sigh* @ this necessary hack; {@link org.jenkinsci.plugins.gitclient.CliGitAPIImpl#getRemoteReferences}
            if ("unexpected ls-remote output ".equals(ge.getMessage())) { // blank line, command succeeded
                isEmptyRepo = true;
            }
            // ignore other reasons
        }

        if(isEmptyRepo) {
            git.init();
            git.addRemoteUrl("origin", gitSource.getRemote());

            log.fine("Repository " + gitSource.getRemote() + " not found, created new to: " + repositoryPath.getCanonicalPath());
        } else {
            throw e;
        }
    }

    return git;
}
 
Example #19
Source File: GitAPI.java    From git-client-plugin with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
public void add(String filePattern) throws GitException, InterruptedException {
    if (Git.USE_CLI) super.add(filePattern); else  jgit.add(filePattern);
}
 
Example #20
Source File: GitAPI.java    From git-client-plugin with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
public void branch(String name) throws GitException, InterruptedException {
    if (Git.USE_CLI) super.branch(name); else  jgit.branch(name);
}
 
Example #21
Source File: GitAPI.java    From git-client-plugin with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
public ObjectId revParse(String revName) throws GitException, InterruptedException {
    return Git.USE_CLI ? super.revParse(revName) :  jgit.revParse(revName);
}
 
Example #22
Source File: GitAPI.java    From git-client-plugin with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
public void clean() throws GitException, InterruptedException {
    if (Git.USE_CLI) super.clean(); else  jgit.clean();
}
 
Example #23
Source File: GitAPI.java    From git-client-plugin with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
public boolean tagExists(String tagName) throws GitException, InterruptedException {
    return Git.USE_CLI ? super.tagExists(tagName) :  jgit.tagExists(tagName);
}
 
Example #24
Source File: GitAPI.java    From git-client-plugin with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
public void fetch(String remoteName, RefSpec... refspec) throws GitException, InterruptedException {
    if (Git.USE_CLI) super.fetch(remoteName, refspec); else  jgit.fetch(remoteName, refspec);
}
 
Example #25
Source File: GitAPI.java    From git-client-plugin with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
public void fetch(URIish url, List<RefSpec> refspecs) throws GitException, InterruptedException {
    if (Git.USE_CLI) super.fetch_().from(url, refspecs).execute(); else  jgit.fetch_().from(url, refspecs).execute();
}
 
Example #26
Source File: GitAPI.java    From git-client-plugin with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
public void tag(String tagName, String comment) throws GitException, InterruptedException {
    if (Git.USE_CLI) super.tag(tagName, comment); else  jgit.tag(tagName, comment);
}
 
Example #27
Source File: GitAPI.java    From git-client-plugin with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
public void push(String remoteName, String refspec) throws GitException, InterruptedException {
    if (Git.USE_CLI) super.push(remoteName, refspec); else  jgit.push(remoteName, refspec);
}
 
Example #28
Source File: GitAPI.java    From git-client-plugin with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
public void deleteTag(String tagName) throws GitException, InterruptedException {
    if (Git.USE_CLI) super.deleteTag(tagName); else  jgit.deleteTag(tagName);
}
 
Example #29
Source File: GitAPI.java    From git-client-plugin with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
public void checkout(String ref) throws GitException, InterruptedException {
    if (Git.USE_CLI) super.checkout().ref(ref).execute(); else  jgit.checkout().ref(ref).execute();
}
 
Example #30
Source File: GitAPI.java    From git-client-plugin with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
public String getRemoteUrl(String name) throws GitException, InterruptedException {
    return Git.USE_CLI ? super.getRemoteUrl(name) :  jgit.getRemoteUrl(name);
}