Example usage for org.eclipse.jgit.lib Constants HEAD

List of usage examples for org.eclipse.jgit.lib Constants HEAD

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Constants HEAD.

Prototype

String HEAD

To view the source code for org.eclipse.jgit.lib Constants HEAD.

Click Source Link

Document

Special name for the "HEAD" symbolic-ref.

Usage

From source file:hudson.plugins.git.GitPublisherTest.java

License:Open Source License

/**
 * Fix push to remote when skipTag is enabled
 *//*w  w  w. j av a2 s  .c o m*/
@Issue("JENKINS-17769")
@Test
public void testMergeAndPushWithSkipTagEnabled() throws Exception {
    FreeStyleProject project = setupSimpleProject("master");

    GitSCM scm = new GitSCM(remoteConfigs(), Collections.singletonList(new BranchSpec("*")), false,
            Collections.<SubmoduleConfig>emptyList(), null, null, new ArrayList<GitSCMExtension>());
    scm.getExtensions().add(new PreBuildMerge(new UserMergeOptions("origin", "integration", null, null)));
    scm.getExtensions().add(new LocalBranch("integration"));
    project.setScm(scm);

    project.getPublishersList()
            .add(new GitPublisher(Collections.<TagToPush>emptyList(),
                    Collections.singletonList(new BranchToPush("origin", "integration")),
                    Collections.<NoteToPush>emptyList(), true, true, false));

    // create initial commit and then run the build against it:
    commitNewFile("commitFileBase");
    testGitClient.branch("integration");
    build(project, Result.SUCCESS, "commitFileBase");

    testGitClient.checkout(null, "topic1");
    final String commitFile1 = "commitFile1";
    commitNewFile(commitFile1);
    final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
    assertTrue(build1.getWorkspace().child(commitFile1).exists());

    String sha1 = getHeadRevision(build1, "integration");
    assertEquals(sha1, testGitClient.revParse(Constants.HEAD).name());
}

From source file:hudson.plugins.git.GitPublisherTest.java

License:Open Source License

private void checkEnvVar(FreeStyleProject project, String envName, String envValue) throws Exception {

    String envReference = "${" + envName + "}";

    List<GitSCMExtension> scmExtensions = new ArrayList<GitSCMExtension>();
    scmExtensions.add(new PreBuildMerge(new UserMergeOptions("origin", envReference, null, null)));
    scmExtensions.add(new LocalBranch(envReference));
    GitSCM scm = new GitSCM(remoteConfigs(), Collections.singletonList(new BranchSpec("*")), false,
            Collections.<SubmoduleConfig>emptyList(), null, null, scmExtensions);
    project.setScm(scm);//w w  w  . ja va 2 s . c o  m

    String tagNameReference = envReference + "-tag"; // ${BRANCH_NAME}-tag
    String tagNameValue = envValue + "-tag"; // master-tag
    String tagMessageReference = envReference + " tag message";
    String noteReference = "note for " + envReference;
    String noteValue = "note for " + envValue;
    GitPublisher publisher = new GitPublisher(
            Collections
                    .singletonList(new TagToPush("origin", tagNameReference, tagMessageReference, false, true)),
            Collections.singletonList(new BranchToPush("origin", envReference)),
            Collections
                    .singletonList(new NoteToPush("origin", noteReference, Constants.R_NOTES_COMMITS, false)),
            true, true, true);
    assertTrue(publisher.isForcePush());
    assertTrue(publisher.isPushBranches());
    assertTrue(publisher.isPushMerge());
    assertTrue(publisher.isPushNotes());
    assertTrue(publisher.isPushOnlyIfSuccess());
    assertTrue(publisher.isPushTags());
    project.getPublishersList().add(publisher);

    // create initial commit
    commitNewFile("commitFileBase");
    ObjectId initialCommit = testGitClient.getHeadRev(testGitDir.getAbsolutePath(), "master");
    assertTrue(testGitClient.isCommitInRepo(initialCommit));

    // Create branch in the test repo (pulled into the project workspace at build)
    assertFalse("Test repo has " + envValue + " branch", hasBranch(envValue));
    testGitClient.branch(envValue);
    assertTrue("Test repo missing " + envValue + " branch", hasBranch(envValue));
    assertFalse(tagNameValue + " in " + testGitClient, testGitClient.tagExists(tagNameValue));

    // Build the branch
    final FreeStyleBuild build0 = build(project, Result.SUCCESS, "commitFileBase");

    String build0HeadBranch = getHeadRevision(build0, envValue);
    assertEquals(build0HeadBranch, initialCommit.getName());
    assertTrue(tagNameValue + " not in " + testGitClient, testGitClient.tagExists(tagNameValue));
    assertTrue(tagNameValue + " not in build",
            build0.getWorkspace().child(".git/refs/tags/" + tagNameValue).exists());

    // Create a topic branch in the source repository and commit to topic branch
    String topicBranch = envValue + "-topic1";
    assertFalse("Test repo has " + topicBranch + " branch", hasBranch(topicBranch));
    testGitClient.checkout(null, topicBranch);
    assertTrue("Test repo has no " + topicBranch + " branch", hasBranch(topicBranch));
    final String commitFile1 = "commitFile1";
    commitNewFile(commitFile1);
    ObjectId topicCommit = testGitClient.getHeadRev(testGitDir.getAbsolutePath(), topicBranch);
    assertTrue(testGitClient.isCommitInRepo(topicCommit));

    // Run a build, should be on the topic branch, tagged, and noted
    final FreeStyleBuild build1 = build(project, Result.SUCCESS, commitFile1);
    FilePath myWorkspace = build1.getWorkspace();
    assertTrue(myWorkspace.child(commitFile1).exists());
    assertTrue("Tag " + tagNameValue + " not in build",
            myWorkspace.child(".git/refs/tags/" + tagNameValue).exists());

    String build1Head = getHeadRevision(build1, envValue);
    assertEquals(build1Head, testGitClient.revParse(Constants.HEAD).name());
    assertEquals("Wrong head commit in build1", topicCommit.getName(), build1Head);

}

From source file:it.com.atlassian.labs.speakeasy.util.jgit.FixedTransportHttp.java

License:Eclipse Distribution License

private FetchConnection newDumbConnection(InputStream in) throws IOException, PackProtocolException {
    HttpObjectDB d = new HttpObjectDB(objectsUrl);
    BufferedReader br = toBufferedReader(in);
    Map<String, Ref> refs;
    try {/*from  w  w  w  . jav a  2 s  .c  om*/
        refs = d.readAdvertisedImpl(br);
    } finally {
        br.close();
    }

    if (!refs.containsKey(Constants.HEAD)) {
        // If HEAD was not published in the info/refs file (it usually
        // is not there) download HEAD by itself as a loose file and do
        // the resolution by hand.
        //
        HttpURLConnection conn = httpOpen(new URL(baseUrl, Constants.HEAD));
        int status = HttpSupport.response(conn);
        switch (status) {
        case HttpURLConnection.HTTP_OK: {
            br = toBufferedReader(openInputStream(conn));
            try {
                String line = br.readLine();
                if (line != null && line.startsWith(RefDirectory.SYMREF)) {
                    String target = line.substring(RefDirectory.SYMREF.length());
                    Ref r = refs.get(target);
                    if (r == null)
                        r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
                    r = new SymbolicRef(Constants.HEAD, r);
                    refs.put(r.getName(), r);
                } else if (line != null && ObjectId.isId(line)) {
                    Ref r = new ObjectIdRef.Unpeeled(Ref.Storage.NETWORK, Constants.HEAD,
                            ObjectId.fromString(line));
                    refs.put(r.getName(), r);
                }
            } finally {
                br.close();
            }
            break;
        }

        case HttpURLConnection.HTTP_NOT_FOUND:
            break;

        default:
            throw new TransportException(uri,
                    MessageFormat.format(JGitText.get().cannotReadHEAD, status, conn.getResponseMessage()));
        }
    }

    WalkFetchConnection wfc = new WalkFetchConnection(this, d);
    wfc.available(refs);
    return wfc;
}

From source file:jbyoshi.gitupdate.processor.FastForward.java

License:Apache License

private static boolean tryFastForward(Repository repo, Ref ref, Ref target, Report report)
        throws GitAPIException, IOException {
    if (ref == null || target == null) {
        return false;
    }//from w w  w  .  j a  va  2  s. c o m
    target = repo.peel(target);
    if (!ref.equals(repo.getRef(Constants.HEAD).getTarget())) {
        try (RevWalk revWalk = new RevWalk(repo)) {
            ObjectId targetId = target.getPeeledObjectId();
            if (targetId == null) {
                targetId = target.getObjectId();
            }

            RevCommit targetCommit = revWalk.lookupCommit(targetId);
            ObjectId sourceId = ref.getObjectId();
            RevCommit sourceCommit = revWalk.lookupCommit(sourceId);
            if (revWalk.isMergedInto(sourceCommit, targetCommit)) {
                RefUpdate refUpdate = repo.updateRef(ref.getName());
                refUpdate.setNewObjectId(targetCommit);
                refUpdate.setRefLogMessage("Fast forward", false);
                refUpdate.setExpectedOldObjectId(sourceId);
                Result rc = refUpdate.update();
                switch (rc) {
                case NEW:
                case FAST_FORWARD:
                    report.newChild(ref.getName() + " -> " + target.getName()).modified();
                    return true;
                case REJECTED:
                case LOCK_FAILURE:
                    report.newErrorChild(new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD,
                            refUpdate.getRef(), rc));
                    break;
                case NO_CHANGE:
                    break;
                default:
                    report.newErrorChild(new JGitInternalException(MessageFormat
                            .format(JGitText.get().updatingRefFailed, ref.getName(), targetId.toString(), rc)));
                    break;
                }
            }
            return false;
        }
    }
    try {
        MergeResult result = Git.wrap(repo).merge().setFastForward(MergeCommand.FastForwardMode.FF_ONLY)
                .include(target.getTarget()).call();
        if (result.getMergeStatus() == MergeResult.MergeStatus.ALREADY_UP_TO_DATE) {
            // Ignore
        } else if (result.getMergeStatus() == MergeResult.MergeStatus.FAST_FORWARD) {
            report.newChild("Fast-forwarded " + ref.getName() + " to " + target.getName()).modified();
            return true;
        } else {
            report.newChild("Fast-forward failed: status " + result.getMergeStatus()).error();
        }
    } catch (NoHeadException e) {
        // Ignore
    }
    return false;
}

From source file:jbyoshi.gitupdate.processor.Fetch.java

License:Apache License

@Override
public void process(Repository repo, Git git, String remote, String fullRemote, Report report)
        throws GitAPIException, IOException {
    FetchResult result = git.fetch().setRemoveDeletedRefs(true).setCredentialsProvider(Prompts.INSTANCE)
            .setRemote(remote).call();//from   ww w . j  a  v a 2 s .  c  om
    for (TrackingRefUpdate update : result.getTrackingRefUpdates()) {
        if (update.getRemoteName().equals(Constants.R_HEADS + Constants.HEAD)) {
            continue;
        }
        StringBuilder text = new StringBuilder(Utils.getShortBranch(update.getRemoteName())).append(": ");
        String oldId = update.getOldObjectId().name();
        if (update.getOldObjectId().equals(ObjectId.zeroId())) {
            oldId = "new branch";
        }
        String newId = update.getNewObjectId().name();
        if (update.getNewObjectId().equals(ObjectId.zeroId())) {
            newId = "deleted";
            for (String branch : Utils.getLocalBranches(repo).keySet()) {
                if (update.getLocalName()
                        .equals(new BranchConfig(repo.getConfig(), branch).getRemoteTrackingBranch())) {
                    repo.getConfig().unset("branches", branch, "remote");
                    repo.getConfig().save();
                }
            }
        }
        text.append(oldId).append(" -> ").append(newId);
        report.newChild(text.toString()).modified();
    }
}

From source file:jenkins.plugins.git.GitSampleRepoRule.java

License:Open Source License

/** Returns the (full) commit hash of the current {@link Constants#HEAD} of the repository. */
public String head() throws Exception {
    return new RepositoryBuilder().setWorkTree(sampleRepo).build().resolve(Constants.HEAD).name();
}

From source file:jenkins.plugins.git.MergeWithGitSCMExtension.java

License:Open Source License

@Override
public Revision decorateRevisionToBuild(GitSCM scm, Run<?, ?> build, GitClient git, TaskListener listener,
        Revision marked, Revision rev) throws IOException, InterruptedException, GitException {
    ObjectId baseObjectId;//from   w  w w  .  j  a v  a2  s.com
    if (StringUtils.isBlank(baseHash)) {
        try {
            baseObjectId = git.revParse(Constants.R_REFS + baseName);
        } catch (GitException e) {
            listener.getLogger().printf("Unable to determine head revision of %s prior to merge with PR%n",
                    baseName);
            throw e;
        }
    } else {
        baseObjectId = ObjectId.fromString(baseHash);
    }
    listener.getLogger().printf("Merging %s commit %s into PR head commit %s%n", baseName, baseObjectId.name(),
            rev.getSha1String());
    checkout(scm, build, git, listener, rev);
    try {
        /* could parse out of JenkinsLocationConfiguration.get().getAdminAddress() but seems overkill */
        git.setAuthor("Jenkins", "nobody@nowhere");
        git.setCommitter("Jenkins", "nobody@nowhere");
        MergeCommand cmd = git.merge().setRevisionToMerge(baseObjectId);
        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 x) {
        // TODO clarify these TODO comments copied from GitHub Branch Source

        // Try to revert merge conflict markers.
        // TODO IGitAPI offers a reset(hard) method yet GitClient does not. Why?
        checkout(scm, build, git, listener, rev);
        // TODO would be nicer to throw an AbortException with just the message, but this is actually worse
        // until git-client 1.19.7+
        throw x;
    }
    build.addAction(new MergeRecord(baseName, baseObjectId.getName())); // 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
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.agent.command.impl.CleanCommandImpl.java

License:Apache License

@NotNull
private WorkingDirStatus getWorkingDirStatus(@NotNull Repository repo) {
    FileTreeIterator workingTreeIt = new FileTreeIterator(repo);
    try {/*from   w  w  w .j av a2 s  .  co m*/
        IndexDiff diff = new IndexDiff(repo, Constants.HEAD, workingTreeIt);
        diff.diff();
        return new WorkingDirStatus(diff);
    } catch (IOException e) {
        throw new JGitInternalException(e.getMessage(), e);
    }
}

From source file:kr.re.ec.grigit.graph.ui.RevWalker.java

License:Eclipse Distribution License

public void init() throws Exception {

    logger = LoggerFactory.getLogger(RevWalker.class);

    db = CurrentRepository.getInstance().getRepository();

    walk = createWalk();//from   ww w.  j  a  va 2 s  . c  o  m
    for (final RevSort s : sorting)
        walk.sort(s, true);
    /*
    if (pathFilter == TreeFilter.ALL) {
       if (followPath != null)
    walk.setTreeFilter(FollowFilter.create(followPath, db
          .getConfig().get(DiffConfig.KEY)));
    } else if (pathFilter != TreeFilter.ALL) {
       walk.setTreeFilter(AndTreeFilter.create(pathFilter,
       TreeFilter.ANY_DIFF));
    }*/

    if (revLimiter.size() == 1)
        walk.setRevFilter(revLimiter.get(0));
    else if (revLimiter.size() > 1)
        walk.setRevFilter(AndRevFilter.create(revLimiter));

    if (all) {
        Map<String, Ref> refs = db.getRefDatabase().getRefs(RefDatabase.ALL);
        for (Ref a : refs.values()) {
            ObjectId oid = a.getPeeledObjectId();
            if (oid == null)
                oid = a.getObjectId();
            try {
                commits.add(walk.parseCommit(oid));
            } catch (IncorrectObjectTypeException e) {
                // Ignore all refs which are not commits
            }
        }
    }

    if (commits.isEmpty()) {
        final ObjectId head = db.resolve(Constants.HEAD);
        if (head == null)
            //logger.info(MessageFormat.format(CLIText.get().cannotResolve,
            //   Constants.HEAD));
            commits.add(walk.parseCommit(head));
    }
    for (final RevCommit c : commits) {
        final RevCommit real = argWalk == walk ? c : walk.parseCommit(c);
        if (c.has(RevFlag.UNINTERESTING))
            walk.markUninteresting(real);
        else
            walk.markStart(real);
    }

    //final long start = System.currentTimeMillis();
    //logger.info("i'm here1");
    final int n = walkLoop();
    //logger.info("i'm here2");
    if (count) {
        //final long end = System.currentTimeMillis();
        logger.info("" + n);
        logger.info(" ");
        //   logger.info(MessageFormat.format(CLIText.get().timeInMilliSeconds,
        //      Long.valueOf(end - start)));
    }
}

From source file:me.cmoz.gradle.snapshot.GitSCMCommand.java

License:Apache License

@Override
@SneakyThrows(IOException.class)
public Commit getLatestCommit(@NonNull final String dateFormat) {
    if (repoDir == null) {
        throw new IllegalStateException("'.git' folder could not be found.");
    }/* ww  w. ja v  a2  s  .  c om*/

    final FileRepositoryBuilder builder = new FileRepositoryBuilder();

    final Repository repo = builder.setGitDir(repoDir).readEnvironment().build();
    final StoredConfig conf = repo.getConfig();

    int abbrev = Commit.ABBREV_LENGTH;
    if (conf != null) {
        abbrev = conf.getInt("core", "abbrev", abbrev);
    }

    final SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

    final Ref HEAD = repo.getRef(Constants.HEAD);
    if (HEAD.getObjectId() == null) {
        throw new RuntimeException("Could not find any commits from HEAD ref.");
    }

    final RevWalk revWalk = new RevWalk(repo);
    if (HEAD.getObjectId() == null) {
        throw new RuntimeException("Could not find any commits from HEAD ref.");
    }
    final RevCommit revCommit = revWalk.parseCommit(HEAD.getObjectId());
    revWalk.markStart(revCommit);

    try {
        // git commit time in sec and java datetime is in ms
        final Date commitTime = new Date(revCommit.getCommitTime() * 1000L);
        final PersonIdent ident = revCommit.getAuthorIdent();
        final UserConfig userConf = conf.get(UserConfig.KEY);

        return Commit.builder().buildTime(sdf.format(new Date())).buildAuthorName(userConf.getAuthorName())
                .buildAuthorEmail(userConf.getAuthorEmail()).branchName(repo.getBranch())
                .commitId(revCommit.getName()).commitTime(sdf.format(commitTime))
                .commitUserName(ident.getName()).commitUserEmail(ident.getEmailAddress())
                .commitMessage(revCommit.getFullMessage().trim()).build();
    } finally {
        revWalk.dispose();
        repo.close();
    }
}