hudson.plugins.git.Branch Java Examples

The following examples show how to use hudson.plugins.git.Branch. 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: GitAPITestCase.java    From git-client-plugin with MIT License 6 votes vote down vote up
public void test_revListFirstParent() throws Exception {
    w.init();
    w.launchCommand("git", "pull", localMirror());

    for (Branch b : w.git.getRemoteBranches()) {
        StringBuilder out = new StringBuilder();
        List<ObjectId> oidList = new ArrayList<>();

        RevListCommand revListCommand = w.git.revList_();
        revListCommand.firstParent(true);
        revListCommand.to(oidList);
        revListCommand.reference(b.getName());
        revListCommand.execute();

        for (ObjectId id : oidList) {
            out.append(id.name()).append('\n');
        }

        String all = w.launchCommand("git", "rev-list", "--first-parent",  b.getName());
        assertEquals(all,out.toString());
    }
}
 
Example #2
Source File: GitClientCloneTest.java    From git-client-plugin with MIT License 6 votes vote down vote up
@Test
public void test_clone_refspecs() throws Exception {
    List<RefSpec> refspecs = Arrays.asList(
            new RefSpec("+refs/heads/master:refs/remotes/origin/master"),
            new RefSpec("+refs/heads/1.4.x:refs/remotes/origin/1.4.x")
    );
    testGitClient.clone_().url(workspace.localMirror()).refspecs(refspecs).repositoryName("origin").execute();
    testGitClient.withRepository((Repository workRepo, VirtualChannel channel) -> {
        String[] fetchRefSpecs = workRepo.getConfig().getStringList(ConfigConstants.CONFIG_REMOTE_SECTION, Constants.DEFAULT_REMOTE_NAME, "fetch");
        assertThat(fetchRefSpecs.length, is(2));
        assertThat(fetchRefSpecs[0], is("+refs/heads/master:refs/remotes/origin/master"));
        assertThat(fetchRefSpecs[1], is("+refs/heads/1.4.x:refs/remotes/origin/1.4.x"));
        return null;
    });
    Set<Branch> remoteBranches = testGitClient.getRemoteBranches();
    assertBranchesExist(remoteBranches, "origin/master");
    assertBranchesExist(remoteBranches, "origin/1.4.x");
    assertThat(remoteBranches.size(), is(2));
}
 
Example #3
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/**
 * Returns the remote branches defined in this repository.
 *
 * @return {@link java.util.Set} of remote branches in this repository
 * @throws hudson.plugins.git.GitException if underlying git operation fails
 * @throws java.lang.InterruptedException if interrupted
 */
@Override
public Set<Branch> getRemoteBranches() throws GitException, InterruptedException {
    try (Repository db = getRepository()) {
        Map<String, Ref> refs = db.getAllRefs();
        Set<Branch> branches = new HashSet<>();

        for(Ref candidate : refs.values()) {
            if(candidate.getName().startsWith(Constants.R_REMOTES)) {
                Branch buildBranch = new Branch(candidate);
                if (!GitClient.quietRemoteBranches) {
                    listener.getLogger().println("Seen branch in repository " + buildBranch.getName());
                }
                branches.add(buildBranch);
            }
        }

        if (branches.size() == 1) {
            listener.getLogger().println("Seen 1 remote branch");
        } else {
            listener.getLogger().println(MessageFormat.format("Seen {0} remote branches", branches.size()));
        }

        return branches;
    }
}
 
Example #4
Source File: BuildUtil.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
public static Run<?, ?> getBuildByBranch(Job<?, ?> project, String branchName) {
    for (Run<?, ?> build : project.getBuilds()) {
        BuildData data = build.getAction(BuildData.class);
        MergeRecord merge = build.getAction(MergeRecord.class);
        if (hasLastBuild(data) && isNoMergeBuild(data, merge)) {    
            for (Branch branch : data.lastBuild.getRevision().getBranches()) {
                if (branch.getName().endsWith("/" + branchName)) {
                    return build;
                }
            }
        }
    }
    return null;
}
 
Example #5
Source File: GitClientCliCloneTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
private String checkoutRandomBranch() throws GitException, InterruptedException {
    String branchName = "rev-parse-branch-" + UUID.randomUUID().toString();
    testGitClient.checkout().ref("origin/master").branch(branchName).execute();
    Set<String> branchNames = testGitClient.getBranches().stream().map(Branch::getName).collect(Collectors.toSet());
    assertThat(branchNames, hasItem(branchName));
    return branchName;
}
 
Example #6
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
private String formatBranches(List<Branch> branches) {
    Set<String> names = new TreeSet<>();
    for (Branch b : branches) {
        names.add(b.getName());
    }
    return Util.join(names,",");
}
 
Example #7
Source File: GitClientTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
private boolean removeMatchingBranches(Set<Branch> filtered, Set<Branch> toRemove) {
    Set<ObjectId> objectIds = new HashSet<>();
    for (Branch removeBranch : toRemove) {
        objectIds.add(removeBranch.getSHA1());
    }
    boolean modified = false;
    for (Iterator<Branch> i = filtered.iterator(); i.hasNext();) {
        Branch checkBranch = i.next();
        if (objectIds.contains(checkBranch.getSHA1())) {
            modified = true;
            i.remove();
        }
    }
    return modified;
}
 
Example #8
Source File: GitClientTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
private void assertBranches(GitClient client, String... expectedBranchNames) throws GitException, InterruptedException {
    List<String> branchNames = new ArrayList<>(); // Arrays.asList(expectedBranchNames);
    for (Branch branch : client.getBranches()) {
        if (branch.getName().startsWith("remotes/")) {
            continue; // Ignore remote branches
        }
        branchNames.add(branch.getName());
    }
    assertThat(branchNames, containsInAnyOrder(expectedBranchNames));
}
 
Example #9
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
private List<Branch> getBranches(ObjectId objectId) throws GitException, InterruptedException
{
    List<Branch> matches = new ArrayList<>();
    Set<Branch> branches = w.git.getBranches();
    for(Branch branch : branches) {
        if(branch.getSHA1().equals(objectId)) matches.add(branch);
    }
    return unmodifiableList(matches);
}
 
Example #10
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
public void test_revList() throws Exception {
    w.init();
    w.launchCommand("git", "pull", localMirror());

    for (Branch b : w.git.getRemoteBranches()) {
        StringBuilder out = new StringBuilder();
        for (ObjectId id : w.git.revList(b.getName())) {
            out.append(id.name()).append('\n');
        }
        String all = w.launchCommand("git", "rev-list", b.getName());
        assertEquals(all,out.toString());
    }
}
 
Example #11
Source File: GitClientTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void test_git_branch_with_line_breaks_and_long_strings() {
    assumeThat(gitImplName, is("git"));
    String gitBranchOutput =
            "* (HEAD detached at b297853)  b297853e667d5989801937beea30fcec7d1d2595 Commit message with line breaks\r very-long-string-with-more-than-44-characters\n" +
                    "  remotes/origin/master       e0d3f46c4fdb8acd068b6b127356931411d16e23 Commit message with line breaks\r very-long-string-with-more-than-44-characters and some more text\n" +
                    "  remotes/origin/develop      fc8996efc1066d9dae529e5187800f84995ca56f Single-line commit message\n";

    cliGitAPIImplTest.setTimeoutVisibleInCurrentTest(false);
    CliGitAPIImpl git = new CliGitAPIImpl("git", new File("."), cliGitAPIImplTest.listener, cliGitAPIImplTest.env);
    Set<Branch> branches = git.parseBranches(gitBranchOutput);
    assertEquals("\"git branch -a -v --no-abbrev\" output correctly parsed", 2, branches.size());
}
 
Example #12
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public List<Branch> getBranchesContaining(String revspec, boolean allBranches)
        throws GitException, InterruptedException {
    final String commandOutput;
    if (allBranches) {
        commandOutput = launchCommand("branch", "-a", "-v", "--no-abbrev", "--contains", revspec);
    } else {
        commandOutput = launchCommand("branch", "-v", "--no-abbrev", "--contains", revspec);
    }
    return new ArrayList<>(parseBranches(commandOutput));
}
 
Example #13
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Deprecated
@Override
public List<Branch> getBranchesContaining(String revspec) throws GitException,
        InterruptedException {
    // For backward compatibility we do query remote branches here
    return getBranchesContaining(revspec, true);
}
 
Example #14
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-34309")
public void test_list_branches() throws Exception {
    w.init();
    Set<Branch> branches = w.git.getBranches();
    assertEquals(0, branches.size()); // empty repo should have 0 branches
    w.commitEmpty("init");

    w.git.branch("test");
    w.touch("test-branch.txt");
    w.git.add("test-branch.txt");
    // JGit commit doesn't end commit message with Ctrl-M, even when passed
    final String testBranchCommitMessage = "test branch commit ends in Ctrl-M";
    w.jgit().commit(testBranchCommitMessage + "\r");

    w.git.branch("another");
    w.touch("another-branch.txt");
    w.git.add("another-branch.txt");
    // CliGit commit doesn't end commit message with Ctrl-M, even when passed
    final String anotherBranchCommitMessage = "test branch commit ends in Ctrl-M";
    w.cgit().commit(anotherBranchCommitMessage + "\r");

    branches = w.git.getBranches();
    assertBranchesExist(branches, "master", "test", "another");
    assertEquals(3, branches.size());
    String output = w.launchCommand("git", "branch", "-v", "--no-abbrev");
    assertTrue("git branch -v --no-abbrev missing test commit msg: '" + output + "'", output.contains(testBranchCommitMessage));
    assertTrue("git branch -v --no-abbrev missing another commit msg: '" + output + "'", output.contains(anotherBranchCommitMessage));
    if (w.cgit().isAtLeastVersion(2, 13, 0, 0)) {
        assertTrue("git branch -v --no-abbrev missing Ctrl-M: '" + output + "'", output.contains("\r"));
        assertTrue("git branch -v --no-abbrev missing test commit msg Ctrl-M: '" + output + "'", output.contains(testBranchCommitMessage + "\r"));
        assertTrue("git branch -v --no-abbrev missing another commit msg Ctrl-M: '" + output + "'", output.contains(anotherBranchCommitMessage + "\r"));
    } else {
        assertFalse("git branch -v --no-abbrev contains Ctrl-M: '" + output + "'", output.contains("\r"));
        assertFalse("git branch -v --no-abbrev contains test commit msg Ctrl-M: '" + output + "'", output.contains(testBranchCommitMessage + "\r"));
        assertFalse("git branch -v --no-abbrev contains another commit msg Ctrl-M: '" + output + "'", output.contains(anotherBranchCommitMessage + "\r"));
    }
}
 
Example #15
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/**
 * Parse branch name and SHA1 from "fos" argument string.
 *
 * Argument content must match "git branch -v --no-abbrev".
 *
 * One branch per line, two leading characters ignored on each
 * line, the branch name (not allowed to contain spaces), one or
 * more spaces, and the 40 character SHA1 of the commit that is
 * the head of that branch. Text after the SHA1 is ignored.
 *
 * @param fos output of "git branch -v --no-abbrev"
 * @return a {@link java.util.Set} object.
 */
/*package*/ Set<Branch> parseBranches(String fos) {
    // JENKINS-34309 if the commit message contains line breaks,
    // "git branch -v --no-abbrev" output will include CR (Carriage Return) characters.
    // Replace all CR characters to avoid interpreting them as line endings
    fos = fos.replaceAll("\\r", "");

    Set<Branch> branches = new HashSet<>();
    BufferedReader rdr = new BufferedReader(new StringReader(fos));
    String line;
    try {
        while ((line = rdr.readLine()) != null) {
            if (line.length() < 44 || !line.contains(" ")) {
                // Line must contain 2 leading characters, branch
                // name (at least 1 character), a space, and 40
                // character SHA1.
                continue;
            }
            // Ignore leading 2 characters (marker for current branch)
            // Ignore line if second field is not SHA1 length (40 characters)
            // Split fields into branch name, SHA1, and rest of line
            // Fields are separated by one or more spaces
            String[] branchVerboseOutput = line.substring(2).split(" +", 3);
            if (branchVerboseOutput.length > 1 && branchVerboseOutput[1].length() == 40) {
                branches.add(new Branch(branchVerboseOutput[0], ObjectId.fromString(branchVerboseOutput[1])));
            }
        }
    } catch (IOException e) {
        throw new GitException("Error parsing branches", e);
    }

    return branches;
}
 
Example #16
Source File: PushTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
private ObjectId checkoutBranch(boolean useOldCommit) throws GitException, InterruptedException {
    /* Checkout branchName */
    workingGitClient.checkoutBranch(branchName, "origin/" + branchName + (useOldCommit ? "^" : ""));
    List<Branch> branches = workingGitClient.getBranchesContaining(branchName, false);
    assertThat(getBranchNames(branches), contains(branchName));
    return bareGitClient.getHeadRev(bareRepo.getAbsolutePath(), branchName);
}
 
Example #17
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
public void test_list_remote_branches() throws Exception {
    WorkingArea r = new WorkingArea();
    r.init();
    r.commitEmpty("init");
    r.git.branch("test");
    r.git.branch("another");

    w.init();
    w.launchCommand("git", "remote", "add", "origin", r.repoPath());
    w.launchCommand("git", "fetch", "origin");
    Set<Branch> branches = w.git.getRemoteBranches();
    assertBranchesExist(branches, "origin/master", "origin/test", "origin/another");
    assertEquals(3, branches.size());
}
 
Example #18
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
public Set<Branch> getBranchesInternal(ListBranchCommand.ListMode mode) throws GitException {
    try (Repository repo = getRepository()) {
        List<Ref> refs = git(repo).branchList().setListMode(mode).call();
        Set<Branch> branches = new HashSet<>(refs.size());
        for (Ref ref : refs) {
            branches.add(new Branch(ref));
        }
        return branches;
    } catch (GitAPIException e) {
        throw new GitException(e);
    }
}
 
Example #19
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
public void test_list_branches_containing_ref() throws Exception {
    w.init();
    w.commitEmpty("init");
    w.git.branch("test");
    w.git.branch("another");
    Set<Branch> branches = w.git.getBranches();
    assertBranchesExist(branches, "master", "test", "another");
    assertEquals(3, branches.size());
}
 
Example #20
Source File: GitClientTest.java    From git-client-plugin with MIT License 4 votes vote down vote up
@Test
public void testgetBranchesContainingTrue_existing_sha1() throws Exception {
    List<Branch> branches = srcGitClient.getBranchesContaining(TESTS_NOT_SUBMODULE_SHA1, true);
    assertThat(branches, is(not(empty())));
}
 
Example #21
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 4 votes vote down vote up
private Collection<String> getBranchNames(Collection<Branch> branches) {
    return branches.stream().map(Branch::getName).collect(toList());
}
 
Example #22
Source File: GitClientTest.java    From git-client-plugin with MIT License 4 votes vote down vote up
@Test
public void testgetBranchesContainingFalse_existing_sha1() throws Exception {
    List<Branch> branches = srcGitClient.getBranchesContaining(TESTS_NOT_SUBMODULE_SHA1, false);
    assertThat(branches, is(empty()));
}
 
Example #23
Source File: PushTest.java    From git-client-plugin with MIT License 4 votes vote down vote up
private Collection<String> getBranchNames(List<Branch> branches) {
    return branches.stream().map(Branch::getName).collect(toList());
}
 
Example #24
Source File: GitClientFetchTest.java    From git-client-plugin with MIT License 4 votes vote down vote up
/**
 * JGit 3.3.0 thru 4.5.4 "prune during fetch" prunes more remote
 * branches than command line git prunes during fetch.  JGit 5.0.2
 * fixes the problem.
 * Refer to https://bugs.eclipse.org/bugs/show_bug.cgi?id=533549
 * Refer to https://bugs.eclipse.org/bugs/show_bug.cgi?id=533806
 */
@Test
@Issue("JENKINS-26197")
public void test_fetch_with_prune() throws Exception {
    bareWorkspace = new WorkspaceWithRepo(secondRepo.getRoot(), gitImplName, TaskListener.NULL);
    bareWorkspace.initBareRepo(bareWorkspace.getGitClient(), true);
    /* Create a working repo containing three branches */
    /* master -> branch1 */
    /*        -> branch2 */
    testGitClient.init();
    testGitClient.setRemoteUrl("origin", bareWorkspace.getGitFileDir().getAbsolutePath());
    workspace.touch(testGitDir, "file-master", "file master content " + UUID.randomUUID().toString());
    testGitClient.add("file-master");
    testGitClient.commit("master-commit");
    assertThat("Wrong branch count", testGitClient.getBranches().size(), is(1));
    testGitClient.push("origin", "master"); /* master branch is now on bare repo */

    testGitClient.checkout().ref("master").execute();
    testGitClient.branch("branch1");
    workspace.touch(testGitDir, "file-branch1", "file branch1 content " + UUID.randomUUID().toString());
    testGitClient.add("file-branch1");
    testGitClient.commit("branch1-commit");
    assertThat(getBranchNames(testGitClient.getBranches()), containsInAnyOrder("master", "branch1"));
    testGitClient.push("origin", "branch1"); /* branch1 is now on bare repo */

    testGitClient.checkout().ref("master").execute();
    testGitClient.branch("branch2");
    workspace.touch(testGitDir, "file-branch2", "file branch2 content " + UUID.randomUUID().toString());
    testGitClient.add("file-branch2");
    testGitClient.commit("branch2-commit");
    assertThat(getBranchNames(testGitClient.getBranches()), containsInAnyOrder("master", "branch1", "branch2"));
    assertThat(testGitClient.getRemoteBranches(), is(empty()));
    testGitClient.push("origin", "branch2"); /* branch2 is now on bare repo */

    /* Clone new working repo from bare repo */
    newAreaWorkspace = new WorkspaceWithRepo(thirdRepo.getRoot(), gitImplName, TaskListener.NULL);
    newAreaWorkspace.cloneRepo(newAreaWorkspace, bareWorkspace.getGitFileDir().getAbsolutePath());
    ObjectId newAreaHead = newAreaWorkspace.getGitClient().revParse("HEAD");
    Set<Branch> remoteBranches = newAreaWorkspace.getGitClient().getRemoteBranches();
    assertThat(getBranchNames(remoteBranches), containsInAnyOrder("origin/master", "origin/branch1", "origin/branch2", "origin/HEAD"));

    /* Remove branch1 from bare repo using original repo */
    cliGitCommand.run("push", bareWorkspace.getGitFileDir().getAbsolutePath(), ":branch1");

    List<RefSpec> refSpecs = Arrays.asList(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));

    /* Fetch without prune should leave branch1 in newArea */
    newAreaWorkspace.launchCommand("git", "config", "fetch.prune", "false");
    newAreaWorkspace.getGitClient().fetch_().from(new URIish(bareWorkspace.getGitFileDir().toString()), refSpecs).execute();
    remoteBranches = newAreaWorkspace.getGitClient().getRemoteBranches();
    assertThat(getBranchNames(remoteBranches), containsInAnyOrder("origin/master", "origin/branch1", "origin/branch2", "origin/HEAD"));

    /* Fetch with prune should remove branch1 from newArea */
    newAreaWorkspace.getGitClient().fetch_().from(new URIish(bareWorkspace.getGitFileDir().toString()), refSpecs).prune(true).execute();
    remoteBranches = newAreaWorkspace.getGitClient().getRemoteBranches();

    /* Git older than 1.7.9 (like 1.7.1 on Red Hat 6) does not prune branch1, don't fail the test
     * on that old git version.
     */
    if (newAreaWorkspace.getGitClient() instanceof CliGitAPIImpl && !workspace.cgit().isAtLeastVersion(1, 7, 9, 0)) {
        assertThat(getBranchNames(remoteBranches), containsInAnyOrder("origin/master", "origin/branch1", "origin/branch2", "origin/HEAD"));
    } else {
        assertThat(getBranchNames(remoteBranches), containsInAnyOrder("origin/master", "origin/branch2", "origin/HEAD"));
    }
}
 
Example #25
Source File: GitClientFetchTest.java    From git-client-plugin with MIT License 4 votes vote down vote up
private Collection<String> getBranchNames(Collection<Branch> branches) {
    return branches.stream().map(Branch::getName).collect(toList());
}
 
Example #26
Source File: GitClientFetchTest.java    From git-client-plugin with MIT License 4 votes vote down vote up
private void assertBranchesExist(Set<Branch> branches, String... names) throws InterruptedException {
    Collection<String> branchNames = getBranchNames(branches);
    for (String name : names) {
        assertThat(branchNames, hasItem(name));
    }
}
 
Example #27
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 4 votes vote down vote up
private void assertBranchesNotExist(Set<Branch> branches, String ... names) throws InterruptedException {
    Collection<String> branchNames = getBranchNames(branches);
    for (String name : names) {
        assertThat(branchNames, not(hasItem(name)));
    }
}
 
Example #28
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 4 votes vote down vote up
private void assertBranchesExist(Set<Branch> branches, String ... names) throws InterruptedException {
    Collection<String> branchNames = getBranchNames(branches);
    for (String name : names) {
        assertThat(branchNames, hasItem(name));
    }
}
 
Example #29
Source File: GitClientCloneTest.java    From git-client-plugin with MIT License 4 votes vote down vote up
private void assertBranchesExist(Set<Branch> branches, String... names) throws InterruptedException {
    Collection<String> branchNames = getBranchNames(branches);
    for (String name : names) {
        assertThat(branchNames, hasItem(name));
    }
}
 
Example #30
Source File: GitClientCloneTest.java    From git-client-plugin with MIT License 4 votes vote down vote up
private Collection<String> getBranchNames(Collection<Branch> branches) {
    return branches.stream().map(Branch::getName).collect(toList());
}