Search in sources :

Example 66 with RefUpdate

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

the class CreateProject method createProject.

private Project createProject(CreateProjectArgs args) throws BadRequestException, ResourceConflictException, IOException, ConfigInvalidException {
    final Project.NameKey nameKey = args.getProject();
    try {
        final String head = args.permissionsOnly ? RefNames.REFS_CONFIG : args.branch.get(0);
        try (Repository repo = repoManager.openRepository(nameKey)) {
            if (repo.getObjectDatabase().exists()) {
                throw new ResourceConflictException("project \"" + nameKey + "\" exists");
            }
        } catch (RepositoryNotFoundException e) {
        // It does not exist, safe to ignore.
        }
        try (Repository repo = repoManager.createRepository(nameKey)) {
            RefUpdate u = repo.updateRef(Constants.HEAD);
            u.disableRefLog();
            u.link(head);
            createProjectConfig(args);
            if (!args.permissionsOnly && args.createEmptyCommit) {
                createEmptyCommits(repo, nameKey, args.branch);
            }
            fire(nameKey, head);
            return projectCache.get(nameKey).getProject();
        }
    } catch (RepositoryCaseMismatchException e) {
        throw new ResourceConflictException("Cannot create " + nameKey.get() + " because the name is already occupied by another project." + " The other project has the same name, only spelled in a" + " different case.");
    } catch (RepositoryNotFoundException badName) {
        throw new BadRequestException("invalid project name: " + nameKey);
    } catch (ConfigInvalidException e) {
        String msg = "Cannot create " + nameKey;
        log.error(msg, e);
        throw e;
    }
}
Also used : Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) RepositoryCaseMismatchException(com.google.gerrit.server.git.RepositoryCaseMismatchException) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 67 with RefUpdate

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

the class DeleteRef method deleteSingleRef.

private void deleteSingleRef(Repository r) throws IOException, ResourceConflictException {
    String ref = refsToDelete.get(0);
    if (prefix != null && !ref.startsWith(prefix)) {
        ref = prefix + ref;
    }
    RefUpdate.Result result;
    RefUpdate u = r.updateRef(ref);
    u.setExpectedOldObjectId(r.exactRef(ref).getObjectId());
    u.setNewObjectId(ObjectId.zeroId());
    u.setForceUpdate(true);
    refDeletionValidator.validateRefOperation(resource.getName(), identifiedUser.get(), u);
    int remainingLockFailureCalls = MAX_LOCK_FAILURE_CALLS;
    for (; ; ) {
        try {
            result = u.delete();
        } catch (LockFailedException e) {
            result = RefUpdate.Result.LOCK_FAILURE;
        } catch (IOException e) {
            log.error("Cannot delete " + ref, e);
            throw e;
        }
        if (result == RefUpdate.Result.LOCK_FAILURE && --remainingLockFailureCalls > 0) {
            try {
                Thread.sleep(SLEEP_ON_LOCK_FAILURE_MS);
            } catch (InterruptedException ie) {
            // ignore
            }
        } else {
            break;
        }
    }
    switch(result) {
        case NEW:
        case NO_CHANGE:
        case FAST_FORWARD:
        case FORCED:
            referenceUpdated.fire(resource.getNameKey(), u, ReceiveCommand.Type.DELETE, identifiedUser.get().getAccount());
            break;
        case REJECTED_CURRENT_BRANCH:
            log.error("Cannot delete " + ref + ": " + result.name());
            throw new ResourceConflictException("cannot delete current branch");
        case IO_FAILURE:
        case LOCK_FAILURE:
        case NOT_ATTEMPTED:
        case REJECTED:
        case RENAMED:
        default:
            log.error("Cannot delete " + ref + ": " + result.name());
            throw new ResourceConflictException("cannot delete: " + result.name());
    }
}
Also used : ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) LockFailedException(org.eclipse.jgit.errors.LockFailedException) IOException(java.io.IOException) RefUpdate(org.eclipse.jgit.lib.RefUpdate) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate)

Example 68 with RefUpdate

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

the class AccountsUpdate method createUserBranch.

public static void createUserBranch(Repository repo, ObjectInserter oi, PersonIdent committerIdent, PersonIdent authorIdent, Account account) throws IOException {
    ObjectId id = createInitialEmptyCommit(oi, committerIdent, authorIdent, account.getRegisteredOn());
    String refName = RefNames.refsUsers(account.getId());
    RefUpdate ru = repo.updateRef(refName);
    ru.setExpectedOldObjectId(ObjectId.zeroId());
    ru.setNewObjectId(id);
    ru.setForceUpdate(true);
    ru.setRefLogIdent(committerIdent);
    ru.setRefLogMessage("Create Account", true);
    Result result = ru.update();
    if (result != Result.NEW) {
        throw new IOException(String.format("Failed to update ref %s: %s", refName, result.name()));
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) IOException(java.io.IOException) RefUpdate(org.eclipse.jgit.lib.RefUpdate) Result(org.eclipse.jgit.lib.RefUpdate.Result)

Example 69 with RefUpdate

use of org.eclipse.jgit.lib.RefUpdate in project blueocean-plugin by jenkinsci.

the class GitUtils method commit.

public static void commit(final Repository repo, final String refName, final String path, final byte[] contents, final String name, final String email, final String message, final TimeZone timeZone, final Date when) {
    final PersonIdent author = buildPersonIdent(repo, name, email, timeZone, when);
    try (final ObjectInserter odi = repo.newObjectInserter()) {
        // Create the in-memory index of the new/updated issue.
        final ObjectId headId = repo.resolve(refName + "^{commit}");
        final DirCache index = createTemporaryIndex(repo, headId, path, contents);
        final ObjectId indexTreeId = index.writeTree(odi);
        // Create a commit object
        final CommitBuilder commit = new CommitBuilder();
        commit.setAuthor(author);
        commit.setCommitter(author);
        commit.setEncoding(Constants.CHARACTER_ENCODING);
        commit.setMessage(message);
        // headId can be null if the repository has no commit yet
        if (headId != null) {
            commit.setParentId(headId);
        }
        commit.setTreeId(indexTreeId);
        // Insert the commit into the repository
        final ObjectId commitId = odi.insert(commit);
        odi.flush();
        try (RevWalk revWalk = new RevWalk(repo)) {
            final RevCommit revCommit = revWalk.parseCommit(commitId);
            final RefUpdate ru = repo.updateRef(refName);
            if (headId == null) {
                ru.setExpectedOldObjectId(ObjectId.zeroId());
            } else {
                ru.setExpectedOldObjectId(headId);
            }
            ru.setNewObjectId(commitId);
            ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
            final RefUpdate.Result rc = ru.forceUpdate();
            switch(rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    break;
                case REJECTED:
                case LOCK_FAILURE:
                    throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
                default:
                    throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, Constants.HEAD, commitId.toString(), rc));
            }
        }
    } catch (ConcurrentRefUpdateException | IOException | JGitInternalException ex) {
        throw new RuntimeException(ex);
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) DirCache(org.eclipse.jgit.dircache.DirCache) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) PersonIdent(org.eclipse.jgit.lib.PersonIdent) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) ConcurrentRefUpdateException(org.eclipse.jgit.api.errors.ConcurrentRefUpdateException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) RefUpdate(org.eclipse.jgit.lib.RefUpdate) RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate)

Example 70 with RefUpdate

use of org.eclipse.jgit.lib.RefUpdate in project egit by eclipse.

the class LocalRepositoryTestCase method createRemoteRepository.

protected File createRemoteRepository(File repositoryDir) throws Exception {
    Repository myRepository = lookupRepository(repositoryDir);
    File gitDir = new File(testDirectory, REPO2);
    Repository myRemoteRepository = FileRepositoryBuilder.create(gitDir);
    myRemoteRepository.create(true);
    // double-check that this is bare
    assertTrue(myRemoteRepository.isBare());
    createStableBranch(myRepository);
    // now we configure a pure push destination
    myRepository.getConfig().setString("remote", "push", "pushurl", "file:///" + myRemoteRepository.getDirectory().getPath());
    myRepository.getConfig().setString("remote", "push", "push", "+refs/heads/*:refs/heads/*");
    // and a pure fetch destination
    myRepository.getConfig().setString("remote", "fetch", "url", "file:///" + myRemoteRepository.getDirectory().getPath());
    myRepository.getConfig().setString("remote", "fetch", "fetch", "+refs/heads/*:refs/heads/*");
    // a destination with both fetch and push urls and specs
    myRepository.getConfig().setString("remote", "both", "pushurl", "file:///" + myRemoteRepository.getDirectory().getPath());
    myRepository.getConfig().setString("remote", "both", "push", "+refs/heads/*:refs/heads/*");
    myRepository.getConfig().setString("remote", "both", "url", "file:///" + myRemoteRepository.getDirectory().getPath());
    myRepository.getConfig().setString("remote", "both", "fetch", "+refs/heads/*:refs/heads/*");
    // a destination with only a fetch url and push and fetch specs
    myRepository.getConfig().setString("remote", "mixed", "push", "+refs/heads/*:refs/heads/*");
    myRepository.getConfig().setString("remote", "mixed", "url", "file:///" + myRemoteRepository.getDirectory().getPath());
    myRepository.getConfig().setString("remote", "mixed", "fetch", "+refs/heads/*:refs/heads/*");
    myRepository.getConfig().save();
    // and push
    PushOperationUI pa = new PushOperationUI(myRepository, "push", false);
    pa.execute(null);
    try {
        // delete the stable branch again
        RefUpdate op = myRepository.updateRef("refs/heads/stable");
        // $NON-NLS-1$
        op.setRefLogMessage(// $NON-NLS-1$
        "branch deleted", false);
        // we set the force update in order
        // to avoid having this rejected
        // due to minor issues
        op.setForceUpdate(true);
        op.delete();
    } catch (IOException ioe) {
        throw new InvocationTargetException(ioe);
    }
    return myRemoteRepository.getDirectory();
}
Also used : Repository(org.eclipse.jgit.lib.Repository) PushOperationUI(org.eclipse.egit.ui.internal.push.PushOperationUI) IOException(java.io.IOException) IFile(org.eclipse.core.resources.IFile) File(java.io.File) InvocationTargetException(java.lang.reflect.InvocationTargetException) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Aggregations

RefUpdate (org.eclipse.jgit.lib.RefUpdate)110 Repository (org.eclipse.jgit.lib.Repository)51 ObjectId (org.eclipse.jgit.lib.ObjectId)45 IOException (java.io.IOException)34 Test (org.junit.Test)32 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)27 TestRepository (org.eclipse.jgit.junit.TestRepository)26 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)24 RevWalk (org.eclipse.jgit.revwalk.RevWalk)23 Result (org.eclipse.jgit.lib.RefUpdate.Result)22 RevCommit (org.eclipse.jgit.revwalk.RevCommit)20 CommitBuilder (org.eclipse.jgit.lib.CommitBuilder)18 Ref (org.eclipse.jgit.lib.Ref)17 RemoteRefUpdate (org.eclipse.jgit.transport.RemoteRefUpdate)17 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)15 BatchRefUpdate (org.eclipse.jgit.lib.BatchRefUpdate)14 InMemoryRepository (org.eclipse.jgit.internal.storage.dfs.InMemoryRepository)12 LockFailureException (com.google.gerrit.git.LockFailureException)10 PersonIdent (org.eclipse.jgit.lib.PersonIdent)9 DirCache (org.eclipse.jgit.dircache.DirCache)8