org.jenkinsci.plugins.gitclient.GitClient Java Examples

The following examples show how to use org.jenkinsci.plugins.gitclient.GitClient. 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: GerritSCMSource.java    From gerrit-code-review-plugin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
public ListBoxModel doFillCredentialsIdItems(
    @AncestorInPath Item context,
    @QueryParameter String remote,
    @QueryParameter String credentialsId) {
  if (context == null && !Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER)
      || context != null && !context.hasPermission(Item.EXTENDED_READ)) {
    return new StandardListBoxModel().includeCurrentValue(credentialsId);
  }
  return new StandardListBoxModel()
      .includeEmptyValue()
      .includeMatchingAs(
          context instanceof Queue.Task
              ? Tasks.getAuthenticationOf((Queue.Task) context)
              : ACL.SYSTEM,
          context,
          StandardUsernameCredentials.class,
          URIRequirementBuilder.fromUri(remote).build(),
          GitClient.CREDENTIALS_MATCHER)
      .includeCurrentValue(credentialsId);
}
 
Example #2
Source File: GitCacheCloneReadSaveRequest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
<T> T invokeOnScm(final GitSCMFileSystem.FSFunction<T> function) throws IOException {
    try {
        GitSCMFileSystem fs = getFilesystem();
        if (fs == null) {
            // Fall back to a git clone if we can't get the repository filesystem
            GitCloneReadSaveRequest gitClone = new GitCloneReadSaveRequest(gitSource, branch, commitMessage, sourceBranch, filePath, contents);
            GitClient git = gitClone.cloneRepo();
            try {
                return git.withRepository(new RepositoryCallbackToFSFunctionAdapter<>(function));
            } finally {
                gitClone.cleanupRepo();
            }
        }
        return fs.invoke(function);
    } catch (InterruptedException ex) {
        throw new ServiceException.UnexpectedErrorException("Unable to save " + filePath, ex);
    }
}
 
Example #3
Source File: Connector.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Populates a {@link ListBoxModel} with the checkout credentials appropriate for the supplied context against the
 * supplied API endpoint.
 *
 * @param context the context.
 * @param apiUri  the api endpoint.
 * @return a {@link ListBoxModel}.
 */
@NonNull
public static ListBoxModel listCheckoutCredentials(@CheckForNull Item context, String apiUri) {
    StandardListBoxModel result = new StandardListBoxModel();
    result.includeEmptyValue();
    result.add("- same as scan credentials -", GitHubSCMSource.DescriptorImpl.SAME);
    result.add("- anonymous -", GitHubSCMSource.DescriptorImpl.ANONYMOUS);
    return result.includeMatchingAs(
            context instanceof Queue.Task
                    ? ((Queue.Task) context).getDefaultAuthentication()
                    : ACL.SYSTEM,
            context,
            StandardUsernameCredentials.class,
            githubDomainRequirements(apiUri),
            GitClient.CREDENTIALS_MATCHER
    );
}
 
Example #4
Source File: GitCloneReadSaveRequest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
byte[] read() throws IOException {
    try {
        GitClient git = cloneRepo();
        try {
            // thank you test for how to use something...
            // https://github.com/jenkinsci/git-client-plugin/blob/master/src/test/java/org/jenkinsci/plugins/gitclient/GitClientTest.java#L1108
            git.checkoutBranch(branch, "origin/" + branch);
        } catch(Exception e) {
            throw new RuntimeException("Branch not found: " + branch);
        }
        File f = new File(repositoryPath, filePath);
        if (f.canRead()) {
            return FileUtils.readFileToByteArray(f);
        }
        return null;
    } catch (InterruptedException ex) {
        throw new ServiceException.UnexpectedErrorException("Unable to read " + filePath, ex);
    } finally {
        cleanupRepo();
    }
}
 
Example #5
Source File: DeflakeGitBuildChooser.java    From flaky-test-handler-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Get failing build revision if this is a deflake build, otherwise use the default build chooser
 */
@Override
public Collection<Revision> getCandidateRevisions(boolean isPollCall, String singleBranch, GitClient git,
    TaskListener listener, BuildData buildData, BuildChooserContext context)
    throws GitException, IOException, InterruptedException {

  // Not sure why it cannot be inferred and we have to put cast here
  DeflakeCause cause = (DeflakeCause) context.getBuild().getCause(DeflakeCause.class);

  if (cause != null) {
    BuildData gitBuildData = gitSCM.getBuildData(cause.getUpstreamRun(), true);
    Revision revision = gitBuildData.getLastBuiltRevision();
    if (revision != null) {
      return Collections.singletonList(revision);
    }
  }

  // If it is not a deflake run, then use the default git checkout strategy
  defaultBuildChooser.gitSCM = this.gitSCM;
  return defaultBuildChooser.getCandidateRevisions(isPollCall, singleBranch, git, listener, buildData, context);
}
 
Example #6
Source File: GitLabSCMSourceSettings.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 6 votes vote down vote up
@Restricted(NoExternalUse.class)
public ListBoxModel doFillCheckoutCredentialsIdItems(@AncestorInPath SCMSourceOwner context, @QueryParameter String connectionName, @QueryParameter String checkoutCredentialsId) {
    if (context == null && !Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER) ||
            context != null && !context.hasPermission(Item.EXTENDED_READ)) {
        return new StandardListBoxModel().includeCurrentValue(checkoutCredentialsId);
    }

    StandardListBoxModel result = new StandardListBoxModel();
    result.add("- anonymous -", CHECKOUT_CREDENTIALS_ANONYMOUS);
    return result.includeMatchingAs(
            context instanceof Queue.Task
                    ? Tasks.getDefaultAuthenticationOf((Queue.Task) context)
                    : ACL.SYSTEM,
            context,
            StandardUsernameCredentials.class,
            SettingsUtils.gitLabConnectionRequirements(connectionName),
            GitClient.CREDENTIALS_MATCHER
    );
}
 
Example #7
Source File: GitLabSCMMergeRequestHead.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Revision decorateRevisionToBuild(GitSCM scm, Run<?, ?> build, GitClient git, TaskListener listener, Revision marked, Revision rev) throws IOException, InterruptedException, GitException {
    listener.getLogger().println("Merging " + targetBranch.getName() + " commit " + targetBranch.getRevision().getHash() + " into merge-request head commit " + rev.getSha1String());
    checkout(scm, build, git, listener, rev);
    try {
        git.setAuthor("Jenkins", /* could parse out of JenkinsLocationConfiguration.get().getAdminAddress() but seems overkill */"nobody@nowhere");
        git.setCommitter("Jenkins", "nobody@nowhere");
        MergeCommand cmd = git.merge().setRevisionToMerge(ObjectId.fromString(targetBranch.getRevision().getHash()));
        for (GitSCMExtension ext : scm.getExtensions()) {
            // By default we do a regular merge, allowing it to fast-forward.
            ext.decorateMergeCommand(scm, build, git, listener, cmd);
        }
        cmd.execute();
    } catch (GitException e) {
        // Try to revert merge conflict markers.
        checkout(scm, build, git, listener, rev);
        throw e;
    }
    build.addAction(new MergeRecord(targetBranch.getRefSpec().destinationRef(targetBranch.getName()), targetBranch.getRevision().getHash())); // does not seem to be used, but just in case
    ObjectId mergeRev = git.revParse(Constants.HEAD);
    listener.getLogger().println("Merge succeeded, producing " + mergeRev.name());
    return new Revision(mergeRev, rev.getBranches()); // note that this ensures Build.revision != Build.marked
}
 
Example #8
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 #9
Source File: ListGitBranchesParameterDefinition.java    From list-git-branches-parameter-plugin with MIT License 6 votes vote down vote up
@Nonnull
private Map<String, String> generateContents(Job job) throws IOException, InterruptedException {
    Map<String, String> paramList = new LinkedHashMap<String, String>();
    GitClient gitClient = createGitClient(job);
    try {
        if (isTagType()) {
            Set<String> tagSet = getTag(gitClient, remoteURL);
            sortAndPutToParam(tagSet, paramList);
        }
        if (isBranchType()) {
            Set<String> branchSet = getBranch(gitClient, remoteURL);
            sortAndPutToParam(branchSet, paramList);
        }

    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        paramList.clear();
        paramList.put(e.getMessage(), e.getMessage());
    }
    return paramList;
}
 
Example #10
Source File: ListGitBranchesParameterDefinition.java    From list-git-branches-parameter-plugin with MIT License 6 votes vote down vote up
private Set<String> getBranch(GitClient gitClient, String gitUrl) throws InterruptedException {
    Set<String> branchSet = new HashSet<>();
    String remoteName = "origin";
    Pattern branchFilterPattern = compileBranchFilterPattern();

    Map<String, ObjectId> branches = gitClient.getRemoteReferences(gitUrl, null, true, false);
    Iterator<String> remoteBranchesName = branches.keySet().iterator();
    while (remoteBranchesName.hasNext()) {
        //String branchName = strip(remoteBranchesName.next(), remoteName);
        String branchName = remoteBranchesName.next();
        Matcher matcher = branchFilterPattern.matcher(branchName);
        if (matcher.matches()) {
            if (matcher.groupCount() == 1) {
                branchSet.add(matcher.group(1));
            } else {
                branchSet.add(branchName);
            }
        }
    }
    return branchSet;
}
 
Example #11
Source File: GitLabSCMSource.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath SCMSourceOwner context,
        @QueryParameter String serverName, @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (context == null) {
        // must have admin if you want the list without a context
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            result.includeCurrentValue(credentialsId);
            return result;
        }
    } else {
        if (!context.hasPermission(Item.EXTENDED_READ)
                && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
            // must be able to read the configuration or use the item credentials if you
            // want the list
            result.includeCurrentValue(credentialsId);
            return result;
        }
    }
    result.includeEmptyValue();
    result.includeMatchingAs(
            context instanceof Queue.Task ? ((Queue.Task) context).getDefaultAuthentication() : ACL.SYSTEM,
            context, StandardUsernameCredentials.class, fromUri(getServerUrlFromName(serverName)).build(),
            GitClient.CREDENTIALS_MATCHER);
    return result;
}
 
Example #12
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 #13
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 #14
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 #15
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 #16
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 #17
Source File: GitAPIBadInitTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testInitExistingFile() throws Exception {
    File existingFile = new File(tempDir, "file-exists");
    FileUtils.writeStringToFile(existingFile, "git init should fail due to this file", "UTF-8");
    GitClient git = new GitAPI("git", existingFile, listener, env);
    GitException e = assertThrows(GitException.class,
                                  () -> {
                                      git.init();
                                  });
    assertThat(e.getMessage(), is("Could not init " + existingFile.getAbsolutePath()));
}
 
Example #18
Source File: GitAPIBadInitTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testInitExistingDirectory() throws Exception {
    GitClient git = new GitAPI("git", tempDir, listener, env);
    git.init();
    File gitDir = new File(tempDir, ".git");
    assertTrue(gitDir + " not created", gitDir.exists());
    assertTrue(gitDir + " not a directory", gitDir.isDirectory());
}
 
Example #19
Source File: GitLabSCMNavigator.java    From gitlab-branch-source-plugin with MIT License 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath SCMSourceOwner context,
    @QueryParameter String serverName,
    @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (context == null) {
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            // must have admin if you want the list without a context
            result.includeCurrentValue(credentialsId);
            return result;
        }
    } else {
        if (!context.hasPermission(Item.EXTENDED_READ)
            && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
            // must be able to read the configuration or use the item credentials if you want the list
            result.includeCurrentValue(credentialsId);
            return result;
        }
    }
    result.includeEmptyValue();
    result.includeMatchingAs(
        context instanceof Queue.Task
            ? ((Queue.Task) context).getDefaultAuthentication()
            : ACL.SYSTEM,
        context,
        StandardUsernameCredentials.class,
        fromUri(getServerUrlFromName(serverName)).build(),
        GitClient.CREDENTIALS_MATCHER
    );
    return result;
}
 
Example #20
Source File: GitCloneReadSaveRequest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
void save() throws IOException {
    try {
        GitClient git = cloneRepo();
        try {
            git.checkoutBranch(sourceBranch, "origin/" + sourceBranch);
        } catch(Exception e) {
            throw new RuntimeException("Branch not found: " + sourceBranch);
        }
        if (!sourceBranch.equals(branch)) {
            //git.branch(branch);
            git.checkoutBranch(branch, "origin/" + sourceBranch);
        }
        File f = new File(repositoryPath, filePath);
        // commit will fail if the contents hasn't changed
        if (!f.exists() || !Arrays.equals(FileUtils.readFileToByteArray(f), contents)) {
            FileUtils.writeByteArrayToFile(f, contents);
            git.add(filePath);
            git.commit(commitMessage);
        }
        git.push().ref(branch).to(new URIish(gitSource.getRemote())).execute();
    } catch (InterruptedException | GitException | URISyntaxException ex) {
        throw new ServiceException.UnexpectedErrorException("Unable to save " + filePath, ex);
    } finally {
        cleanupRepo();
    }
}
 
Example #21
Source File: ListGitBranchesParameterDefinition.java    From list-git-branches-parameter-plugin with MIT License 5 votes vote down vote up
private Set<String> getTag(GitClient gitClient, String gitUrl) throws InterruptedException {
    Set<String> tagSet = new HashSet<>();
    try {
        Map<String, ObjectId> tags = gitClient.getRemoteReferences(gitUrl, tagFilter, false, true);
        for (String tagName : tags.keySet()) {
            tagSet.add(tagName.replaceFirst(REFS_TAGS_PATTERN, ""));
        }
    } catch (GitException e) {
        LOGGER.log(Level.WARNING, e.getMessage(), e);
    }
    return tagSet;
}
 
Example #22
Source File: AbstractGerritSCMSource.java    From gerrit-code-review-plugin with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Nonnull
@Override
protected List<Action> retrieveActions(
    @CheckForNull SCMSourceEvent event, @Nonnull TaskListener listener)
    throws IOException, InterruptedException {
  return doRetrieve(
      null,
      new Retriever<List<Action>>() {
        @Override
        public List<Action> run(
            GitClient client,
            GerritSCMSourceContext context,
            String remoteName,
            Changes.QueryRequest queryRequest)
            throws IOException, InterruptedException {
          Map<String, String> symrefs = client.getRemoteSymbolicReferences(getRemote(), null);
          if (symrefs.containsKey(Constants.HEAD)) {
            // Hurrah! The Server is Git 1.8.5 or newer and our client has symref reporting
            String target = symrefs.get(Constants.HEAD);
            if (target.startsWith(Constants.R_HEADS)) {
              // shorten standard names
              target = target.substring(Constants.R_HEADS.length());
            }
            List<Action> result = new ArrayList<>();
            if (StringUtils.isNotBlank(target)) {
              result.add(new GitRemoteHeadRefAction(getRemote(), target));
            }
            result.add(new GerritLogo());
            return result;
          }

          // Give up, there's no way to get the primary branch
          return new ArrayList<>();
        }
      },
      new GerritSCMSourceContext(null, SCMHeadObserver.none()).withTraits(getTraits()),
      listener,
      false);
}
 
Example #23
Source File: GitLabSCMMergeRequestHead.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
private void checkout(GitSCM scm, Run<?, ?> build, GitClient git, TaskListener listener, Revision rev) throws InterruptedException, IOException, GitException {
    CheckoutCommand checkoutCommand = git.checkout().ref(rev.getSha1String());
    for (GitSCMExtension ext : scm.getExtensions()) {
        ext.decorateCheckoutCommand(scm, build, git, listener, checkoutCommand);
    }
    checkoutCommand.execute();
}
 
Example #24
Source File: GitUtils.java    From blueocean-plugin with MIT License 5 votes vote down vote up
static StandardCredentials getCredentials(ItemGroup owner, String uri, String credentialId){
    StandardCredentials standardCredentials =  CredentialsUtils.findCredential(credentialId, StandardCredentials.class, new BlueOceanDomainRequirement());
    if(standardCredentials == null){
        standardCredentials = CredentialsMatchers
                .firstOrNull(
                        CredentialsProvider.lookupCredentials(StandardCredentials.class, owner,
                                ACL.SYSTEM, URIRequirementBuilder.fromUri(uri).build()),
                        CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialId),
                                GitClient.CREDENTIALS_MATCHER));
    }

    return standardCredentials;
}
 
Example #25
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 #26
Source File: GitHubSCMBuilderTest.java    From github-branch-source-plugin with MIT License 4 votes vote down vote up
@Test
public void given__cloud_pullMerge_rev_anon__when__build__then__scmBuilt() throws Exception {
    createGitHubSCMSourceForTest(false, null);
    PullRequestSCMHead head = new PullRequestSCMHead("PR-1", "qa", "qa-repo", "qa-branch", 1,
            new BranchSCMHead("test-branch"), new SCMHeadOrigin.Fork("qa/qa-repo"),
            ChangeRequestCheckoutStrategy.MERGE);
    PullRequestSCMRevision revision = new PullRequestSCMRevision(
            head,
            "deadbeefcafebabedeadbeefcafebabedeadbeef",
            "cafebabedeadbeefcafebabedeadbeefcafebabe"
    );
    source.setCredentialsId(null);
    GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, revision);
    assertThat(instance.credentialsId(), is(nullValue()));
    assertThat(instance.head(), is(head));
    assertThat(instance.revision(), is(revision));
    assertThat(instance.refSpecs(), contains("+refs/pull/1/head:refs/remotes/@{remote}/PR-1"));
    assertThat("expecting guess value until withGitHubRemote called",
            instance.remote(), is("https://github.com/tester/test-repo.git"));
    assertThat(instance.browser(), instanceOf(GithubWeb.class));
    assertThat(instance.browser().getRepoUrl(), is("https://github.com/qa/qa-repo"));

    instance.withGitHubRemote();
    assertThat(instance.remote(), is("https://github.com/tester/test-repo.git"));

    GitSCM actual = instance.build();
    assertThat(actual.getBrowser(), instanceOf(GithubWeb.class));
    assertThat(actual.getBrowser().getRepoUrl(), is("https://github.com/qa/qa-repo"));
    assertThat(actual.getGitTool(), nullValue());
    assertThat(actual.getUserRemoteConfigs(), hasSize(1));
    UserRemoteConfig config = actual.getUserRemoteConfigs().get(0);
    assertThat(config.getName(), is("origin"));
    assertThat(config.getRefspec(), is("+refs/pull/1/head:refs/remotes/origin/PR-1 "
            + "+refs/heads/test-branch:refs/remotes/origin/test-branch"));
    assertThat(config.getUrl(), is("https://github.com/tester/test-repo.git"));
    assertThat(config.getCredentialsId(), is(nullValue()));
    RemoteConfig origin = actual.getRepositoryByName("origin");
    assertThat(origin, notNullValue());
    assertThat(origin.getURIs(), hasSize(1));
    assertThat(origin.getURIs().get(0).toString(), is("https://github.com/tester/test-repo.git"));
    assertThat(origin.getFetchRefSpecs(), hasSize(2));
    assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/pull/1/head"));
    assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/PR-1"));
    assertThat(origin.getFetchRefSpecs().get(0).isForceUpdate(), is(true));
    assertThat(origin.getFetchRefSpecs().get(0).isWildcard(), is(false));
    assertThat(origin.getFetchRefSpecs().get(1).getSource(), is("refs/heads/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(1).getDestination(), is("refs/remotes/origin/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(1).isForceUpdate(), is(true));
    assertThat(origin.getFetchRefSpecs().get(1).isWildcard(), is(false));
    assertThat(actual.getExtensions(), containsInAnyOrder(
            instanceOf(GitSCMSourceDefaults.class),
            instanceOf(BuildChooserSetting.class),
            instanceOf(MergeWithGitSCMExtension.class)
    ));
    BuildChooserSetting chooser = getExtension(actual, BuildChooserSetting.class);
    assertThat(chooser, notNullValue());
    assertThat(chooser.getBuildChooser(), instanceOf(AbstractGitSCMSource.SpecificRevisionBuildChooser.class));
    AbstractGitSCMSource.SpecificRevisionBuildChooser revChooser =
            (AbstractGitSCMSource.SpecificRevisionBuildChooser) chooser.getBuildChooser();
    Collection<Revision> revisions = revChooser
            .getCandidateRevisions(false, "test-branch", Mockito.mock(GitClient.class), new LogTaskListener(
                    Logger.getAnonymousLogger(), Level.FINEST), null, null);
    assertThat(revisions, hasSize(1));
    assertThat(revisions.iterator().next().getSha1String(), is("cafebabedeadbeefcafebabedeadbeefcafebabe"));
    MergeWithGitSCMExtension merge = getExtension(actual, MergeWithGitSCMExtension.class);
    assertThat(merge, notNullValue());
    assertThat(merge.getBaseName(), is("remotes/origin/test-branch"));
    assertThat(merge.getBaseHash(), is("deadbeefcafebabedeadbeefcafebabedeadbeef"));
}
 
Example #27
Source File: AbstractGerritSCMSource.java    From gerrit-code-review-plugin with Apache License 2.0 4 votes vote down vote up
T run(
GitClient client,
GerritSCMSourceContext context,
String remoteName,
Changes.QueryRequest changeQuery)
throws IOException, InterruptedException;
 
Example #28
Source File: GitHubSCMBuilderTest.java    From github-branch-source-plugin with MIT License 4 votes vote down vote up
@Test
public void given__cloud_branch_rev_anon__when__build__then__scmBuilt() throws Exception {
    createGitHubSCMSourceForTest(false, null);
    BranchSCMHead head = new BranchSCMHead("test-branch");
    SCMRevisionImpl revision =
            new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe");
    source.setCredentialsId(null);
    GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, revision);
    assertThat(instance.credentialsId(), is(nullValue()));
    assertThat(instance.head(), is(head));
    assertThat(instance.revision(), is(revision));
    assertThat(instance.refSpecs(), contains("+refs/heads/test-branch:refs/remotes/@{remote}/test-branch"));
    assertThat("expecting guess value until withGitHubRemote called",
            instance.remote(), is("https://github.com/tester/test-repo.git"));
    assertThat(instance.browser(), instanceOf(GithubWeb.class));
    assertThat(instance.browser().getRepoUrl(), is("https://github.com/tester/test-repo"));

    instance.withGitHubRemote();
    assertThat(instance.remote(), is("https://github.com/tester/test-repo.git"));

    GitSCM actual = instance.build();
    assertThat(actual.getBrowser(), instanceOf(GithubWeb.class));
    assertThat(actual.getBrowser().getRepoUrl(), is("https://github.com/tester/test-repo"));
    assertThat(actual.getGitTool(), nullValue());
    assertThat(actual.getUserRemoteConfigs(), hasSize(1));
    UserRemoteConfig config = actual.getUserRemoteConfigs().get(0);
    assertThat(config.getName(), is("origin"));
    assertThat(config.getRefspec(), is("+refs/heads/test-branch:refs/remotes/origin/test-branch"));
    assertThat(config.getUrl(), is("https://github.com/tester/test-repo.git"));
    assertThat(config.getCredentialsId(), is(nullValue()));
    RemoteConfig origin = actual.getRepositoryByName("origin");
    assertThat(origin, notNullValue());
    assertThat(origin.getURIs(), hasSize(1));
    assertThat(origin.getURIs().get(0).toString(), is("https://github.com/tester/test-repo.git"));
    assertThat(origin.getFetchRefSpecs(), hasSize(1));
    assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/heads/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).isForceUpdate(), is(true));
    assertThat(origin.getFetchRefSpecs().get(0).isWildcard(), is(false));
    assertThat(actual.getExtensions(), containsInAnyOrder(
            instanceOf(BuildChooserSetting.class),
            instanceOf(GitSCMSourceDefaults.class))
    );
    BuildChooserSetting chooser = getExtension(actual, BuildChooserSetting.class);
    assertThat(chooser.getBuildChooser(), instanceOf(SpecificRevisionBuildChooser.class));
    SpecificRevisionBuildChooser revChooser =
            (SpecificRevisionBuildChooser) chooser.getBuildChooser();
    Collection<Revision> revisions = revChooser
            .getCandidateRevisions(false, "test-branch", mock(GitClient.class), new LogTaskListener(
                    getAnonymousLogger(), FINEST), null, null);
    assertThat(revisions, hasSize(1));
    assertThat(revisions.iterator().next().getSha1String(), is("cafebabedeadbeefcafebabedeadbeefcafebabe"));
}
 
Example #29
Source File: AbstractGerritSCMSource.java    From gerrit-code-review-plugin with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@NonNull
@Override
protected List<Action> retrieveActions(
    @NonNull SCMHead head, @CheckForNull SCMHeadEvent event, @NonNull TaskListener listener)
    throws IOException, InterruptedException {
  final List<Action> actions =
      doRetrieve(
          head,
          (GitClient client,
              GerritSCMSourceContext context,
              String remoteName,
              Changes.QueryRequest changeQuery) -> {
            SCMSourceOwner owner = getOwner();
            if (owner instanceof Actionable && head instanceof ChangeSCMHead) {
              final Actionable actionableOwner = (Actionable) owner;
              final ChangeSCMHead change = (ChangeSCMHead) head;
              String gerritBaseUrl = getGerritBaseUrl();

              return actionableOwner
                  .getActions(GitRemoteHeadRefAction.class)
                  .stream()
                  .filter(action -> action.getRemote().equals(getRemote()))
                  .map(
                      action ->
                          new ObjectMetadataAction(
                              change.getName(),
                              change.getId(),
                              String.format("%s%d", gerritBaseUrl, change.getChangeNumber())))
                  .collect(Collectors.toList());
            } else {
              return Collections.emptyList();
            }
          },
          new GerritSCMSourceContext(null, SCMHeadObserver.none()).withTraits(getTraits()),
          listener,
          false);

  final ImmutableList.Builder<Action> resultBuilder = new ImmutableList.Builder<>();
  resultBuilder.addAll(super.retrieveActions(head, event, listener));
  resultBuilder.addAll(actions);
  return resultBuilder.build();
}
 
Example #30
Source File: GerritSCMSource.java    From gerrit-code-review-plugin with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
public FormValidation doCheckCredentialsId(
    @AncestorInPath Item context, @QueryParameter String remote, @QueryParameter String value) {
  if (context == null && !Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER)
      || context != null && !context.hasPermission(Item.EXTENDED_READ)) {
    return FormValidation.ok();
  }

  value = Util.fixEmptyAndTrim(value);
  if (value == null) {
    return FormValidation.ok();
  }

  remote = Util.fixEmptyAndTrim(remote);
  if (remote == null)
  // not set, can't check
  {
    return FormValidation.ok();
  }

  for (ListBoxModel.Option o :
      CredentialsProvider.listCredentials(
          StandardUsernameCredentials.class,
          context,
          context instanceof Queue.Task
              ? Tasks.getAuthenticationOf((Queue.Task) context)
              : ACL.SYSTEM,
          URIRequirementBuilder.fromUri(remote).build(),
          GitClient.CREDENTIALS_MATCHER)) {
    if (StringUtils.equals(value, o.value)) {
      // TODO check if this type of credential is acceptable to the Git client or does it merit
      // warning
      // NOTE: we would need to actually lookup the credential to do the check, which may
      // require
      // fetching the actual credential instance from a remote credentials store. Perhaps this
      // is
      // not required
      return FormValidation.ok();
    }
  }
  // no credentials available, can't check
  return FormValidation.warning("Cannot find any credentials with id " + value);
}