Search in sources :

Example 6 with Result

use of org.eclipse.jgit.lib.RefUpdate.Result in project gitblit by gitblit.

the class JGitUtils method setBranchRef.

/**
	 * Sets the local branch ref to point to the specified commit id.
	 *
	 * @param repository
	 * @param branch
	 * @param commitId
	 * @return true if successful
	 */
public static boolean setBranchRef(Repository repository, String branch, String commitId) {
    String branchName = branch;
    if (!branchName.startsWith(Constants.R_REFS)) {
        branchName = Constants.R_HEADS + branch;
    }
    try {
        RefUpdate refUpdate = repository.updateRef(branchName, false);
        refUpdate.setNewObjectId(ObjectId.fromString(commitId));
        RefUpdate.Result result = refUpdate.forceUpdate();
        switch(result) {
            case NEW:
            case FORCED:
            case NO_CHANGE:
            case FAST_FORWARD:
                return true;
            default:
                LOGGER.error(MessageFormat.format("{0} {1} update to {2} returned result {3}", repository.getDirectory().getAbsolutePath(), branchName, commitId, result));
        }
    } catch (Throwable t) {
        error(t, repository, "{0} failed to set {1} to {2}", branchName, commitId);
    }
    return false;
}
Also used : Result(org.eclipse.jgit.lib.RefUpdate.Result) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 7 with Result

use of org.eclipse.jgit.lib.RefUpdate.Result in project gitblit by gitblit.

the class JGitUtils method deleteBranchRef.

/**
	 * Deletes the specified branch ref.
	 *
	 * @param repository
	 * @param branch
	 * @return true if successful
	 */
public static boolean deleteBranchRef(Repository repository, String branch) {
    try {
        RefUpdate refUpdate = repository.updateRef(branch, false);
        refUpdate.setForceUpdate(true);
        RefUpdate.Result result = refUpdate.delete();
        switch(result) {
            case NEW:
            case FORCED:
            case NO_CHANGE:
            case FAST_FORWARD:
                return true;
            default:
                LOGGER.error(MessageFormat.format("{0} failed to delete to {1} returned result {2}", repository.getDirectory().getAbsolutePath(), branch, result));
        }
    } catch (Throwable t) {
        error(t, repository, "{0} failed to delete {1}", branch);
    }
    return false;
}
Also used : Result(org.eclipse.jgit.lib.RefUpdate.Result) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 8 with Result

use of org.eclipse.jgit.lib.RefUpdate.Result in project gitblit by gitblit.

the class NewRepositoryPage method initialCommit.

/**
	 * Prepare the initial commit for the repository.
	 *
	 * @param repository
	 * @param addReadme
	 * @param gitignore
	 * @param addGitFlow
	 * @return true if an initial commit was created
	 */
protected boolean initialCommit(RepositoryModel repository, boolean addReadme, String gitignore, boolean addGitFlow) {
    boolean initialCommit = addReadme || !StringUtils.isEmpty(gitignore) || addGitFlow;
    if (!initialCommit) {
        return false;
    }
    // build an initial commit
    boolean success = false;
    Repository db = app().repositories().getRepository(repositoryModel.name);
    ObjectInserter odi = db.newObjectInserter();
    try {
        UserModel user = GitBlitWebSession.get().getUser();
        String email = Optional.fromNullable(user.emailAddress).or(user.username + "@" + "gitblit");
        PersonIdent author = new PersonIdent(user.getDisplayName(), email);
        DirCache newIndex = DirCache.newInCore();
        DirCacheBuilder indexBuilder = newIndex.builder();
        if (addReadme) {
            // insert a README
            String title = StringUtils.stripDotGit(StringUtils.getLastPathElement(repositoryModel.name));
            String description = repositoryModel.description == null ? "" : repositoryModel.description;
            String readme = String.format("## %s\n\n%s\n\n", title, description);
            byte[] bytes = readme.getBytes(Constants.ENCODING);
            DirCacheEntry entry = new DirCacheEntry("README.md");
            entry.setLength(bytes.length);
            entry.setLastModified(System.currentTimeMillis());
            entry.setFileMode(FileMode.REGULAR_FILE);
            entry.setObjectId(odi.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes));
            indexBuilder.add(entry);
        }
        if (!StringUtils.isEmpty(gitignore)) {
            // insert a .gitignore file
            File dir = app().runtime().getFileOrFolder(Keys.git.gitignoreFolder, "${baseFolder}/gitignore");
            File file = new File(dir, gitignore + ".gitignore");
            if (file.exists() && file.length() > 0) {
                byte[] bytes = FileUtils.readContent(file);
                if (!ArrayUtils.isEmpty(bytes)) {
                    DirCacheEntry entry = new DirCacheEntry(".gitignore");
                    entry.setLength(bytes.length);
                    entry.setLastModified(System.currentTimeMillis());
                    entry.setFileMode(FileMode.REGULAR_FILE);
                    entry.setObjectId(odi.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes));
                    indexBuilder.add(entry);
                }
            }
        }
        if (addGitFlow) {
            // insert a .gitflow file
            Config config = new Config();
            config.setString("gitflow", null, "masterBranch", Constants.MASTER);
            config.setString("gitflow", null, "developBranch", Constants.DEVELOP);
            config.setString("gitflow", null, "featureBranchPrefix", "feature/");
            config.setString("gitflow", null, "releaseBranchPrefix", "release/");
            config.setString("gitflow", null, "hotfixBranchPrefix", "hotfix/");
            config.setString("gitflow", null, "supportBranchPrefix", "support/");
            config.setString("gitflow", null, "versionTagPrefix", "");
            byte[] bytes = config.toText().getBytes(Constants.ENCODING);
            DirCacheEntry entry = new DirCacheEntry(".gitflow");
            entry.setLength(bytes.length);
            entry.setLastModified(System.currentTimeMillis());
            entry.setFileMode(FileMode.REGULAR_FILE);
            entry.setObjectId(odi.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, bytes));
            indexBuilder.add(entry);
        }
        indexBuilder.finish();
        if (newIndex.getEntryCount() == 0) {
            // nothing to commit
            return false;
        }
        ObjectId treeId = newIndex.writeTree(odi);
        // Create a commit object
        CommitBuilder commit = new CommitBuilder();
        commit.setAuthor(author);
        commit.setCommitter(author);
        commit.setEncoding(Constants.ENCODING);
        commit.setMessage("Initial commit");
        commit.setTreeId(treeId);
        // Insert the commit into the repository
        ObjectId commitId = odi.insert(commit);
        odi.flush();
        // set the branch refs
        RevWalk revWalk = new RevWalk(db);
        try {
            // set the master branch
            RevCommit revCommit = revWalk.parseCommit(commitId);
            RefUpdate masterRef = db.updateRef(Constants.R_MASTER);
            masterRef.setNewObjectId(commitId);
            masterRef.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
            Result masterRC = masterRef.update();
            switch(masterRC) {
                case NEW:
                    success = true;
                    break;
                default:
                    success = false;
            }
            if (addGitFlow) {
                // set the develop branch for git-flow
                RefUpdate developRef = db.updateRef(Constants.R_DEVELOP);
                developRef.setNewObjectId(commitId);
                developRef.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result developRC = developRef.update();
                switch(developRC) {
                    case NEW:
                        success = true;
                        break;
                    default:
                        success = false;
                }
            }
        } finally {
            revWalk.close();
        }
    } catch (UnsupportedEncodingException e) {
        logger().error(null, e);
    } catch (IOException e) {
        logger().error(null, e);
    } finally {
        odi.close();
        db.close();
    }
    return success;
}
Also used : DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) ObjectId(org.eclipse.jgit.lib.ObjectId) Config(org.eclipse.jgit.lib.Config) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Result(org.eclipse.jgit.lib.RefUpdate.Result) UserModel(com.gitblit.models.UserModel) DirCache(org.eclipse.jgit.dircache.DirCache) Repository(org.eclipse.jgit.lib.Repository) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) PersonIdent(org.eclipse.jgit.lib.PersonIdent) File(java.io.File) RevCommit(org.eclipse.jgit.revwalk.RevCommit) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 9 with Result

use of org.eclipse.jgit.lib.RefUpdate.Result in project gerrit by GerritCodeReview.

the class AccountsUpdate method deleteUserBranch.

public static void deleteUserBranch(Repository repo, PersonIdent refLogIdent, Account.Id accountId) throws IOException {
    String refName = RefNames.refsUsers(accountId);
    Ref ref = repo.exactRef(refName);
    if (ref == null) {
        return;
    }
    RefUpdate ru = repo.updateRef(refName);
    ru.setExpectedOldObjectId(ref.getObjectId());
    ru.setNewObjectId(ObjectId.zeroId());
    ru.setForceUpdate(true);
    ru.setRefLogIdent(refLogIdent);
    ru.setRefLogMessage("Delete Account", true);
    Result result = ru.delete();
    if (result != Result.FORCED) {
        throw new IOException(String.format("Failed to delete ref %s: %s", refName, result.name()));
    }
}
Also used : Ref(org.eclipse.jgit.lib.Ref) IOException(java.io.IOException) RefUpdate(org.eclipse.jgit.lib.RefUpdate) Result(org.eclipse.jgit.lib.RefUpdate.Result)

Example 10 with Result

use of org.eclipse.jgit.lib.RefUpdate.Result in project gerrit by GerritCodeReview.

the class CreateProject method createEmptyCommits.

private void createEmptyCommits(Repository repo, Project.NameKey project, List<String> refs) throws IOException {
    try (ObjectInserter oi = repo.newObjectInserter()) {
        CommitBuilder cb = new CommitBuilder();
        cb.setTreeId(oi.insert(Constants.OBJ_TREE, new byte[] {}));
        cb.setAuthor(metaDataUpdateFactory.getUserPersonIdent());
        cb.setCommitter(serverIdent);
        cb.setMessage("Initial empty repository\n");
        ObjectId id = oi.insert(cb);
        oi.flush();
        for (String ref : refs) {
            RefUpdate ru = repo.updateRef(ref);
            ru.setNewObjectId(id);
            Result result = ru.update();
            switch(result) {
                case NEW:
                    referenceUpdated.fire(project, ru, ReceiveCommand.Type.CREATE, identifiedUser.get().getAccount());
                    break;
                case FAST_FORWARD:
                case FORCED:
                case IO_FAILURE:
                case LOCK_FAILURE:
                case NOT_ATTEMPTED:
                case NO_CHANGE:
                case REJECTED:
                case REJECTED_CURRENT_BRANCH:
                case RENAMED:
                default:
                    {
                        throw new IOException(String.format("Failed to create ref \"%s\": %s", ref, result.name()));
                    }
            }
        }
    } catch (IOException e) {
        log.error("Cannot create empty commit for " + project.get(), e);
        throw e;
    }
}
Also used : ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ObjectId(org.eclipse.jgit.lib.ObjectId) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) IOException(java.io.IOException) RefUpdate(org.eclipse.jgit.lib.RefUpdate) Result(org.eclipse.jgit.lib.RefUpdate.Result)

Aggregations

Result (org.eclipse.jgit.lib.RefUpdate.Result)19 RefUpdate (org.eclipse.jgit.lib.RefUpdate)17 IOException (java.io.IOException)11 ObjectId (org.eclipse.jgit.lib.ObjectId)9 RevCommit (org.eclipse.jgit.revwalk.RevCommit)8 CommitBuilder (org.eclipse.jgit.lib.CommitBuilder)7 PersonIdent (org.eclipse.jgit.lib.PersonIdent)7 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)6 Ref (org.eclipse.jgit.lib.Ref)5 RevWalk (org.eclipse.jgit.revwalk.RevWalk)5 FetchResult (org.eclipse.jgit.transport.FetchResult)4 RefModel (com.gitblit.models.RefModel)3 DirCache (org.eclipse.jgit.dircache.DirCache)3 File (java.io.File)2 ArrayList (java.util.ArrayList)2 GitException (org.eclipse.che.api.git.exception.GitException)2 MergeResult (org.eclipse.che.api.git.shared.MergeResult)2 RebaseResult (org.eclipse.jgit.api.RebaseResult)2 ConcurrentRefUpdateException (org.eclipse.jgit.api.errors.ConcurrentRefUpdateException)2 RefRename (org.eclipse.jgit.lib.RefRename)2