Example usage for org.eclipse.jgit.lib Repository updateRef

List of usage examples for org.eclipse.jgit.lib Repository updateRef

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository updateRef.

Prototype

@NonNull
public RefUpdate updateRef(String ref) throws IOException 

Source Link

Document

Create a command to update, create or delete a ref in this repository.

Usage

From source file:com.microsoft.gittf.core.util.StashUtil.java

License:Open Source License

/**
 * Creates a stash//from w w  w . jav  a2 s  . c  o  m
 * 
 * @param repository
 *        the git repository
 * @param repositoryInserter
 *        the repository inserter object to use
 * @param rootBaseTree
 *        the tree id for the base commit of the stash
 * @param rootStashTree
 *        the tree id for the commit of the stash
 * @param rootIndexTree
 *        the tree id for the index commit of the stash
 * @param baseParentId
 *        the parent of the base tree commit
 * @param ownerDisplayName
 *        the owner display name of the stash
 * @param ownerName
 *        the owner name of the stash
 * @param stashComment
 *        the comment used to for the stash
 * @param stashName
 *        the stash name
 * @return
 * @throws IOException
 */
public static final ObjectId create(final Repository repository, final ObjectInserter repositoryInserter,
        final ObjectId rootBaseTree, final ObjectId rootStashTree, final ObjectId rootIndexTree,
        final ObjectId baseParentId, final String ownerDisplayName, final String ownerName,
        final String stashComment, final String stashName) throws IOException {
    Check.notNull(repository, "repository"); //$NON-NLS-1$
    Check.notNull(repositoryInserter, "repositoryInserter"); //$NON-NLS-1$
    Check.notNull(rootBaseTree, "rootBaseTree"); //$NON-NLS-1$
    Check.notNull(rootStashTree, "rootStashTree"); //$NON-NLS-1$
    Check.notNull(rootIndexTree, "rootIndexTree"); //$NON-NLS-1$

    /* identifies the head and the branch we are creating the stash for */
    Ref headReference = repository.getRef(Constants.HEAD);
    RevCommit headCommit = new RevWalk(repository).parseCommit(headReference.getObjectId());
    String currentBranchName = Repository.shortenRefName(headReference.getTarget().getName());

    PersonIdent author = new PersonIdent(ownerDisplayName, ownerName);

    /* create the base commit */
    CommitBuilder commitBuilder = new CommitBuilder();
    commitBuilder.setTreeId(rootBaseTree);
    if (baseParentId != null) {
        commitBuilder.setParentId(baseParentId);
    }
    commitBuilder.setMessage(stashComment);
    commitBuilder.setAuthor(author);
    commitBuilder.setCommitter(author);

    ObjectId baseCommit = repositoryInserter.insert(commitBuilder);

    /* create the index commit */
    commitBuilder.setTreeId(rootIndexTree);
    commitBuilder.setParentId(baseCommit);
    commitBuilder.setMessage(MessageFormat.format(STASH_INDEX_COMMENT, currentBranchName,
            headCommit.abbreviate(7).name(), stashName));
    commitBuilder.setAuthor(author);
    commitBuilder.setCommitter(author);

    ObjectId indexCommit = repositoryInserter.insert(commitBuilder);

    /* create the stash commit */
    commitBuilder.setTreeId(rootStashTree);
    commitBuilder.setParentId(baseCommit);
    commitBuilder.addParentId(indexCommit);

    String stashRefLogComment = MessageFormat.format(STASH_COMMENT, currentBranchName,
            headCommit.abbreviate(7).name(), stashName);
    commitBuilder.setMessage(stashRefLogComment);

    ObjectId stashCommit = repositoryInserter.insert(commitBuilder);

    repositoryInserter.flush();

    /* Update the stash reference and ref log */
    RefUpdate stashReferenceUpdate = repository.updateRef(Constants.R_STASH);
    stashReferenceUpdate.setNewObjectId(stashCommit);
    stashReferenceUpdate.setRefLogIdent(author);
    stashReferenceUpdate.setRefLogMessage(stashRefLogComment, false);

    Ref currentStashRef = repository.getRef(Constants.R_STASH);
    if (currentStashRef != null) {
        stashReferenceUpdate.setExpectedOldObjectId(currentStashRef.getObjectId());
    } else {
        stashReferenceUpdate.setExpectedOldObjectId(ObjectId.zeroId());
    }

    stashReferenceUpdate.forceUpdate();

    return stashCommit;
}

From source file:com.microsoft.gittf.core.util.TfsBranchUtil.java

License:Open Source License

/**
 * Updates the remote tracking branch and branch to point at the commit
 * specified./*from   www  . ja va  2 s . c om*/
 * 
 * @param repository
 * @param commitId
 * @throws IOException
 * @throws RefAlreadyExistsException
 * @throws RefNotFoundException
 * @throws InvalidRefNameException
 * @throws GitAPIException
 */
public static void update(Repository repository, ObjectId commitId) throws IOException,
        RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException, GitAPIException {
    if (repository.isBare()) {
        Ref tfsBranchRef = repository.getRef(Constants.R_HEADS + GitTFConstants.GIT_TF_BRANCHNAME);
        if (tfsBranchRef == null) {
            create(repository);
        }

        RefUpdate ref = repository.updateRef(Constants.R_HEADS + GitTFConstants.GIT_TF_BRANCHNAME);
        ref.setNewObjectId(commitId);
        ref.setForceUpdate(true);
        ref.update();
    }

    TfsRemoteReferenceUpdate remoteRefUpdate = new TfsRemoteReferenceUpdate(repository, commitId.name());
    remoteRefUpdate.update();

}

From source file:com.palantir.gerrit.gerritci.servlets.JobsServlet.java

License:Apache License

public static void updateProjectRef(ObjectId treeId, ObjectInserter objectInserter, Repository repository,
        CurrentUser currentUser) throws IOException, NoFilepatternException, GitAPIException {
    // Create a branch
    Ref gerritCiRef = repository.getRef("refs/meta/gerrit-ci");
    CommitBuilder commitBuilder = new CommitBuilder();
    commitBuilder.setTreeId(treeId);/*from  w  ww  .  j av a  2  s .c o  m*/
    logger.info("treeId: " + treeId);

    if (gerritCiRef != null) {
        ObjectId prevCommit = gerritCiRef.getObjectId();
        logger.info("prevCommit: " + prevCommit);
        commitBuilder.setParentId(prevCommit);
    }
    // build commit
    logger.info("Adding git tree : " + treeId);
    commitBuilder.setMessage("Modify project build rules.");
    final IdentifiedUser iUser = (IdentifiedUser) currentUser;
    PersonIdent user = new PersonIdent(currentUser.getUserName(), iUser.getEmailAddresses().iterator().next());
    commitBuilder.setAuthor(user);
    commitBuilder.setCommitter(user);
    ObjectId commitId = objectInserter.insert(commitBuilder);
    objectInserter.flush();
    logger.info(" Making new commit: " + commitId);
    RefUpdate newRef = repository.updateRef("refs/meta/gerrit-ci");
    newRef.setNewObjectId(commitId);
    newRef.update();
    repository.close();
}

From source file:io.jenkins.blueocean.blueocean_git_pipeline.GitBareRepoReadSaveRequest.java

License:Open Source License

@Override
void save() throws IOException {
    invokeOnScm(new GitSCMFileSystem.FSFunction<Void>() {
        @Override/*from  w ww  .ja  v a  2 s .com*/
        public Void invoke(Repository repo) throws IOException, InterruptedException {
            String localBranchRef = LOCAL_REF_BASE + sourceBranch;

            ObjectId branchHead = repo.resolve(localBranchRef);

            try {
                // Get committer info
                User user = User.current();
                if (user == null) {
                    throw new ServiceException.UnauthorizedException("Not authenticated");
                }
                String mailAddress = MailAddressResolver.resolve(user);
                StandardCredentials credential = getCredential();

                // Make sure up-to-date and credentials work
                GitUtils.fetch(repo, credential);

                GitUtils.commit(repo, localBranchRef, filePath, contents, user.getId(), mailAddress,
                        commitMessage, TimeZone.getDefault(), new Date());

                GitUtils.push(gitSource.getRemote(), repo, credential, localBranchRef,
                        REMOTE_REF_BASE + branch);
                return null;
            } finally {
                // always roll back to undo our local changes
                try {
                    if (branchHead != null) { // branchHead may be null if this was an empty repo
                        RefUpdate rollback = repo.updateRef(localBranchRef);
                        rollback.setNewObjectId(branchHead);
                        rollback.forceUpdate();
                    }
                } catch (Exception ex) {
                    log.log(Level.SEVERE, "Unable to roll back repo after save failure", ex);
                }
            }
        }
    });
}

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  . ja v  a 2  s  .c  om*/
    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:jetbrains.buildServer.buildTriggers.vcs.git.tests.AgentVcsSupportTest.java

License:Apache License

@TestFor(issues = "TW-46854")
@Test(dataProvider = "mirrors")
public void should_update_remote_tracking_branch_in_case_of_fast_forward_update(boolean useMirrors)
        throws Exception {
    File remoteRepo = myTempFiles.createTempDir();

    copyRepository(dataFile("repo_for_fetch.2"), remoteRepo);
    VcsRootImpl root = vcsRoot().withAgentGitPath(getGitPath()).withFetchUrl(remoteRepo)
            .withUseMirrors(useMirrors).build();
    String buildBranchParam = GitUtils.getGitRootBranchParamName(root);

    //run build in master branch
    AgentRunningBuild build = createRunningBuild(map(buildBranchParam, "refs/heads/master"));
    myVcsSupport.updateSources(root, CheckoutRules.DEFAULT, "d47dda159b27b9a8c4cee4ce98e4435eb5b17168",
            myCheckoutDir, build, false);

    //fast-forward update master to point to the same commit as master
    Repository remote = new RepositoryBuilder().setGitDir(remoteRepo).build();
    RefUpdate refUpdate = remote.updateRef("refs/heads/personal");
    refUpdate.setNewObjectId(ObjectId.fromString("add81050184d3c818560bdd8839f50024c188586"));
    refUpdate.update();//from   www  .j a v a  2  s  .  c om

    //run build in personal branch
    build = createRunningBuild(map(buildBranchParam, "refs/heads/personal"));
    myVcsSupport.updateSources(root, CheckoutRules.DEFAULT, "add81050184d3c818560bdd8839f50024c188586",
            myCheckoutDir, build, false);

    //fast-forward update personal branch to point to the same commit as master
    refUpdate = remote.updateRef("refs/heads/personal");
    refUpdate.setNewObjectId(ObjectId.fromString("d47dda159b27b9a8c4cee4ce98e4435eb5b17168"));
    refUpdate.update();

    //run build on updated personal branch
    build = createRunningBuild(map(buildBranchParam, "refs/heads/personal"));
    myVcsSupport.updateSources(root, CheckoutRules.DEFAULT, "d47dda159b27b9a8c4cee4ce98e4435eb5b17168",
            myCheckoutDir, build, false);

    //both branch and its remote-tracking branch should be updated
    Repository r = new RepositoryBuilder().setWorkTree(myCheckoutDir).build();
    then(r.getAllRefs().get("refs/heads/personal").getObjectId().name())
            .isEqualTo("d47dda159b27b9a8c4cee4ce98e4435eb5b17168");
    then(r.getAllRefs().get("refs/remotes/origin/personal").getObjectId().name())
            .isEqualTo("d47dda159b27b9a8c4cee4ce98e4435eb5b17168");
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.AgentVcsSupportTest.java

License:Apache License

public void when_fetch_for_mirror_failed_remove_it_and_try_again() throws Exception {
    File repo = dataFile("repo_for_fetch.1");
    File remoteRepo = myTempFiles.createTempDir();
    copyRepository(repo, remoteRepo);/*from w  w w.  jav a 2s .c o m*/

    VcsRootImpl root = vcsRoot().withAgentGitPath(getGitPath()).withFetchUrl(GitUtils.toURL(remoteRepo))
            .build();

    AgentRunningBuild buildWithMirrors = createRunningBuild(true);
    myVcsSupport.updateSources(root, CheckoutRules.DEFAULT, "add81050184d3c818560bdd8839f50024c188586",
            myCheckoutDir, buildWithMirrors, false);

    //create branch tmp in the mirror
    File mirror = myBuilder.getMirrorManager().getMirrorDir(GitUtils.toURL(remoteRepo));
    Repository r = new RepositoryBuilder().setBare().setGitDir(mirror).build();
    RefUpdate update = r.updateRef("refs/heads/tmp");
    update.setNewObjectId(ObjectId.fromString("add81050184d3c818560bdd8839f50024c188586"));
    update.update();

    //update remote repo
    delete(remoteRepo);
    File updatedRepo = dataFile("repo_for_fetch.2.personal");
    copyRepository(updatedRepo, remoteRepo);

    //create branch tmp/1 in remote repo, so fetch will fail
    r = new RepositoryBuilder().setBare().setGitDir(remoteRepo).build();
    update = r.updateRef("refs/heads/tmp/1");
    update.setNewObjectId(ObjectId.fromString("d47dda159b27b9a8c4cee4ce98e4435eb5b17168"));
    update.update();

    //update succeeds
    myVcsSupport.updateSources(root, CheckoutRules.DEFAULT, "d47dda159b27b9a8c4cee4ce98e4435eb5b17168",
            myCheckoutDir, buildWithMirrors, false);
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.CollectChangesTest.java

License:Apache License

@TestFor(issues = { "TW-36080", "TW-35700" })
@Test(dataProvider = "separateProcess,newConnectionForPrune")
public void branch_turned_into_dir(boolean fetchInSeparateProcess, boolean newConnectionForPrune)
        throws Exception {
    myConfig.setSeparateProcessForFetch(fetchInSeparateProcess).setNewConnectionForPrune(newConnectionForPrune);
    VcsRoot root = vcsRoot().withFetchUrl(myRepo).withBranch("master").build();
    RepositoryStateData s1 = createVersionState("refs/heads/master",
            map("refs/heads/master", "f3f826ce85d6dad25156b2d7550cedeb1a422f4c", "refs/heads/patch-tests",
                    "a894d7d58ffde625019a9ecf8267f5f1d1e5c341"));
    RepositoryStateData s2 = createVersionState("refs/heads/master",
            map("refs/heads/master", "3b9fbfbb43e7edfad018b482e15e7f93cca4e69f", "refs/heads/patch-tests",
                    "a894d7d58ffde625019a9ecf8267f5f1d1e5c341"));

    git().getCollectChangesPolicy().collectChanges(root, s1, s2, CheckoutRules.DEFAULT);

    //rename refs/heads/patch-tests to refs/heads/patch-tests/a and make it point to commit not yet fetched by TC, so the fetch is required
    Repository r = new RepositoryBuilder().setGitDir(myRepo).build();
    r.getRefDatabase().newRename("refs/heads/patch-tests", "refs/heads/patch-tests/a").rename();
    RefUpdate refUpdate = r.updateRef("refs/heads/patch-tests/a");
    refUpdate.setForceUpdate(true);/*from  ww  w  .j a va 2 s  .  c  om*/
    refUpdate.setNewObjectId(ObjectId.fromString("39679cc440c83671fbf6ad8083d92517f9602300"));
    refUpdate.update();

    RepositoryStateData s3 = createVersionState("refs/heads/master",
            map("refs/heads/master", "3b9fbfbb43e7edfad018b482e15e7f93cca4e69f", "refs/heads/patch-tests/a",
                    "39679cc440c83671fbf6ad8083d92517f9602300"));
    git().getCollectChangesPolicy().collectChanges(root, s2, s3, CheckoutRules.DEFAULT);
}

From source file:net.polydawn.mdm.Plumbing.java

License:Open Source License

/**
 * Create a new "empty" commit in a new branch. If the branch name already exists,
 * a forced update will be performed.// w ww .java  2 s.  c o  m
 *
 * @return result of the branch update.
 * @throws IOException
 */
public static RefUpdate.Result createOrphanBranch(Repository repo, String branchName) throws IOException {
    ObjectInserter odi = repo.newObjectInserter();
    try {
        // Create an (empty) tree object to reference from a commit.
        TreeFormatter tree = new TreeFormatter();
        ObjectId treeId = odi.insert(tree);

        // Create a commit object... most data is nulls or silly placeholders; I expect you'll amend this commit.
        CommitBuilder commit = new CommitBuilder();
        PersonIdent author = new PersonIdent("mdm", "");
        commit.setAuthor(author);
        commit.setCommitter(author);
        commit.setMessage("");
        commit.setTreeId(treeId);

        // Insert the commit into the repository.
        ObjectId commitId = odi.insert(commit);
        odi.flush();

        // (Re)extract the commit we just flushed, and update a new branch ref to point to it.
        RevWalk revWalk = new RevWalk(repo);
        try {
            RevCommit revCommit = revWalk.parseCommit(commitId);
            if (!branchName.startsWith("refs/"))
                branchName = "refs/heads/" + branchName;
            RefUpdate ru = repo.updateRef(branchName);
            ru.setNewObjectId(commitId);
            ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
            return ru.forceUpdate();
        } finally {
            revWalk.release();
        }
    } finally {
        odi.release();
    }
}

From source file:org.eclipse.egit.core.op.CommitOperation.java

License:Open Source License

private void doCommits(String actMessage, HashMap<Repository, Tree> treeMap) throws IOException, TeamException {

    String commitMessage = actMessage;
    final Date commitDate = new Date();
    final TimeZone timeZone = TimeZone.getDefault();

    final PersonIdent authorIdent = RawParseUtils.parsePersonIdent(author);
    final PersonIdent committerIdent = RawParseUtils.parsePersonIdent(committer);

    for (java.util.Map.Entry<Repository, Tree> entry : treeMap.entrySet()) {
        Tree tree = entry.getValue();/*from   w w w  .  ja va2s .co  m*/
        Repository repo = tree.getRepository();
        repo.getIndex().write();
        writeTreeWithSubTrees(tree);

        ObjectId currentHeadId = repo.resolve(Constants.HEAD);
        ObjectId[] parentIds;
        if (amending) {
            RevCommit[] parents = previousCommit.getParents();
            parentIds = new ObjectId[parents.length];
            for (int i = 0; i < parents.length; i++)
                parentIds[i] = parents[i].getId();
        } else {
            if (currentHeadId != null)
                parentIds = new ObjectId[] { currentHeadId };
            else
                parentIds = new ObjectId[0];
        }
        if (createChangeId) {
            ObjectId parentId;
            if (parentIds.length > 0)
                parentId = parentIds[0];
            else
                parentId = null;
            ObjectId changeId = ChangeIdUtil.computeChangeId(tree.getId(), parentId, authorIdent,
                    committerIdent, commitMessage);
            commitMessage = ChangeIdUtil.insertId(commitMessage, changeId);
            if (changeId != null)
                commitMessage = commitMessage.replaceAll(
                        "\nChange-Id: I0000000000000000000000000000000000000000\n", //$NON-NLS-1$
                        "\nChange-Id: I" + changeId.getName() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        }
        CommitBuilder commit = new CommitBuilder();
        commit.setTreeId(tree.getTreeId());
        commit.setParentIds(parentIds);
        commit.setMessage(commitMessage);
        commit.setAuthor(new PersonIdent(authorIdent, commitDate, timeZone));
        commit.setCommitter(new PersonIdent(committerIdent, commitDate, timeZone));

        ObjectInserter inserter = repo.newObjectInserter();
        ObjectId commitId;
        try {
            commitId = inserter.insert(commit);
            inserter.flush();
        } finally {
            inserter.release();
        }

        final RefUpdate ru = repo.updateRef(Constants.HEAD);
        ru.setNewObjectId(commitId);
        ru.setRefLogMessage(buildReflogMessage(commitMessage), false);
        if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE) {
            throw new TeamException(NLS.bind(CoreText.CommitOperation_failedToUpdate, ru.getName(), commitId));
        }
    }
}