Search in sources :

Example 1 with JGitInternalException

use of org.eclipse.jgit.api.errors.JGitInternalException in project bazel by bazelbuild.

the class GitCloner method clone.

public static SkyValue clone(Rule rule, Path outputDirectory, ExtendedEventHandler eventHandler, Map<String, String> clientEnvironment) throws RepositoryFunctionException {
    WorkspaceAttributeMapper mapper = WorkspaceAttributeMapper.of(rule);
    if (mapper.isAttributeValueExplicitlySpecified("commit") == mapper.isAttributeValueExplicitlySpecified("tag")) {
        throw new RepositoryFunctionException(new EvalException(rule.getLocation(), "One of either commit or tag must be defined"), Transience.PERSISTENT);
    }
    GitRepositoryDescriptor descriptor;
    String startingPoint;
    try {
        if (mapper.isAttributeValueExplicitlySpecified("commit")) {
            startingPoint = mapper.get("commit", Type.STRING);
        } else {
            startingPoint = "tags/" + mapper.get("tag", Type.STRING);
        }
        descriptor = new GitRepositoryDescriptor(mapper.get("remote", Type.STRING), startingPoint, mapper.get("init_submodules", Type.BOOLEAN), outputDirectory);
    } catch (EvalException e) {
        throw new RepositoryFunctionException(e, Transience.PERSISTENT);
    }
    // Setup proxy if remote is http or https
    if (descriptor.remote != null && Ascii.toLowerCase(descriptor.remote).startsWith("http")) {
        try {
            new ProxyHelper(clientEnvironment).createProxyIfNeeded(new URL(descriptor.remote));
        } catch (IOException ie) {
            throw new RepositoryFunctionException(ie, Transience.TRANSIENT);
        }
    }
    Git git = null;
    try {
        if (descriptor.directory.exists()) {
            if (isUpToDate(descriptor)) {
                return new HttpDownloadValue(descriptor.directory);
            }
            try {
                FileSystemUtils.deleteTree(descriptor.directory);
            } catch (IOException e) {
                throw new RepositoryFunctionException(e, Transience.TRANSIENT);
            }
        }
        git = Git.cloneRepository().setURI(descriptor.remote).setCredentialsProvider(new NetRCCredentialsProvider()).setDirectory(descriptor.directory.getPathFile()).setCloneSubmodules(false).setNoCheckout(true).setProgressMonitor(new GitProgressMonitor(descriptor.remote, "Cloning " + descriptor.remote, eventHandler)).call();
        git.checkout().setCreateBranch(true).setName("bazel-checkout").setStartPoint(descriptor.checkout).call();
        // the first level.
        if (descriptor.initSubmodules && !git.submoduleInit().call().isEmpty()) {
            git.submoduleUpdate().setProgressMonitor(new GitProgressMonitor(descriptor.remote, "Cloning submodules for " + descriptor.remote, eventHandler)).call();
        }
    } catch (InvalidRemoteException e) {
        throw new RepositoryFunctionException(new IOException("Invalid Git repository URI: " + e.getMessage()), Transience.PERSISTENT);
    } catch (RefNotFoundException | InvalidRefNameException e) {
        throw new RepositoryFunctionException(new IOException("Invalid branch, tag, or commit: " + e.getMessage()), Transience.PERSISTENT);
    } catch (GitAPIException e) {
        // This is a sad attempt to actually get a useful error message out of jGit, which will bury
        // the actual (useful) cause of the exception under several throws.
        StringBuilder errmsg = new StringBuilder();
        errmsg.append(e.getMessage());
        Throwable throwable = e;
        while (throwable.getCause() != null) {
            throwable = throwable.getCause();
            errmsg.append(" caused by " + throwable.getMessage());
        }
        throw new RepositoryFunctionException(new IOException("Error cloning repository: " + errmsg), Transience.PERSISTENT);
    } catch (JGitInternalException e) {
        // caller of the command can handle them effectively." Thanks, jgit.
        throw new RepositoryFunctionException(new IOException(e.getMessage()), Transience.PERSISTENT);
    } finally {
        if (git != null) {
            git.close();
        }
    }
    return new HttpDownloadValue(descriptor.directory);
}
Also used : ProxyHelper(com.google.devtools.build.lib.bazel.repository.downloader.ProxyHelper) EvalException(com.google.devtools.build.lib.syntax.EvalException) IOException(java.io.IOException) URL(java.net.URL) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.eclipse.jgit.api.Git) RefNotFoundException(org.eclipse.jgit.api.errors.RefNotFoundException) InvalidRefNameException(org.eclipse.jgit.api.errors.InvalidRefNameException) InvalidRemoteException(org.eclipse.jgit.api.errors.InvalidRemoteException) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) NetRCCredentialsProvider(org.eclipse.jgit.transport.NetRCCredentialsProvider) WorkspaceAttributeMapper(com.google.devtools.build.lib.rules.repository.WorkspaceAttributeMapper) RepositoryFunctionException(com.google.devtools.build.lib.rules.repository.RepositoryFunction.RepositoryFunctionException)

Example 2 with JGitInternalException

use of org.eclipse.jgit.api.errors.JGitInternalException in project gitblit by gitblit.

the class RefLogUtils method updateRefLog.

/**
	 * Updates the reflog with the received commands.
	 *
	 * @param user
	 * @param repository
	 * @param commands
	 * @return true, if the update was successful
	 */
public static boolean updateRefLog(UserModel user, Repository repository, Collection<ReceiveCommand> commands) {
    // only track branches and tags
    List<ReceiveCommand> filteredCommands = new ArrayList<ReceiveCommand>();
    for (ReceiveCommand cmd : commands) {
        if (!cmd.getRefName().startsWith(Constants.R_HEADS) && !cmd.getRefName().startsWith(Constants.R_TAGS)) {
            continue;
        }
        filteredCommands.add(cmd);
    }
    if (filteredCommands.isEmpty()) {
        // nothing to log
        return true;
    }
    RefModel reflogBranch = getRefLogBranch(repository);
    if (reflogBranch == null) {
        JGitUtils.createOrphanBranch(repository, GB_REFLOG, null);
    }
    boolean success = false;
    String message = "push";
    try {
        ObjectId headId = repository.resolve(GB_REFLOG + "^{commit}");
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create the in-memory index of the reflog log entry
            DirCache index = createIndex(repository, headId, commands);
            ObjectId indexTreeId = index.writeTree(odi);
            PersonIdent ident;
            if (UserModel.ANONYMOUS.equals(user)) {
                // anonymous push
                ident = new PersonIdent(user.username + "/" + user.username, user.username);
            } else {
                // construct real pushing account
                ident = new PersonIdent(MessageFormat.format("{0}/{1}", user.getDisplayName(), user.username), user.emailAddress == null ? user.username : user.emailAddress);
            }
            // Create a commit object
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(ident);
            commit.setCommitter(ident);
            commit.setEncoding(Constants.ENCODING);
            commit.setMessage(message);
            commit.setParentId(headId);
            commit.setTreeId(indexTreeId);
            // Insert the commit into the repository
            ObjectId commitId = odi.insert(commit);
            odi.flush();
            RevWalk revWalk = new RevWalk(repository);
            try {
                RevCommit revCommit = revWalk.parseCommit(commitId);
                RefUpdate ru = repository.updateRef(GB_REFLOG);
                ru.setNewObjectId(commitId);
                ru.setExpectedOldObjectId(headId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result rc = ru.forceUpdate();
                switch(rc) {
                    case NEW:
                    case FORCED:
                    case FAST_FORWARD:
                        success = true;
                        break;
                    case REJECTED:
                    case LOCK_FAILURE:
                        throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
                    default:
                        throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, GB_REFLOG, commitId.toString(), rc));
                }
            } finally {
                revWalk.close();
            }
        } finally {
            odi.close();
        }
    } catch (Throwable t) {
        error(t, repository, "Failed to commit reflog entry to {0}");
    }
    return success;
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) RefModel(com.gitblit.models.RefModel) ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Result(org.eclipse.jgit.lib.RefUpdate.Result) 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)

Example 3 with JGitInternalException

use of org.eclipse.jgit.api.errors.JGitInternalException in project gitblit by gitblit.

the class JGitUtils method commitIndex.

public static boolean commitIndex(Repository db, String branch, DirCache index, ObjectId parentId, boolean forceCommit, String author, String authorEmail, String message) throws IOException, ConcurrentRefUpdateException {
    boolean success = false;
    ObjectId headId = db.resolve(branch + "^{commit}");
    ObjectId baseId = parentId;
    if (baseId == null || headId == null) {
        return false;
    }
    ObjectInserter odi = db.newObjectInserter();
    try {
        // Create the in-memory index of the new/updated ticket
        ObjectId indexTreeId = index.writeTree(odi);
        // Create a commit object
        PersonIdent ident = new PersonIdent(author, authorEmail);
        if (forceCommit == false) {
            ThreeWayMerger merger = MergeStrategy.RECURSIVE.newMerger(db, true);
            merger.setObjectInserter(odi);
            merger.setBase(baseId);
            boolean mergeSuccess = merger.merge(indexTreeId, headId);
            if (mergeSuccess) {
                indexTreeId = merger.getResultTreeId();
            } else {
                //Manual merge required
                return false;
            }
        }
        CommitBuilder commit = new CommitBuilder();
        commit.setAuthor(ident);
        commit.setCommitter(ident);
        commit.setEncoding(com.gitblit.Constants.ENCODING);
        commit.setMessage(message);
        commit.setParentId(headId);
        commit.setTreeId(indexTreeId);
        // Insert the commit into the repository
        ObjectId commitId = odi.insert(commit);
        odi.flush();
        RevWalk revWalk = new RevWalk(db);
        try {
            RevCommit revCommit = revWalk.parseCommit(commitId);
            RefUpdate ru = db.updateRef(branch);
            ru.setForceUpdate(forceCommit);
            ru.setNewObjectId(commitId);
            ru.setExpectedOldObjectId(headId);
            ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
            Result rc = ru.update();
            switch(rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    success = true;
                    break;
                case REJECTED:
                case LOCK_FAILURE:
                    throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
                default:
                    throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, branch, commitId.toString(), rc));
            }
        } finally {
            revWalk.close();
        }
    } finally {
        odi.close();
    }
    return success;
}
Also used : ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) AnyObjectId(org.eclipse.jgit.lib.AnyObjectId) ObjectId(org.eclipse.jgit.lib.ObjectId) PersonIdent(org.eclipse.jgit.lib.PersonIdent) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) ThreeWayMerger(org.eclipse.jgit.merge.ThreeWayMerger) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ConcurrentRefUpdateException(org.eclipse.jgit.api.errors.ConcurrentRefUpdateException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) RefUpdate(org.eclipse.jgit.lib.RefUpdate) FetchResult(org.eclipse.jgit.transport.FetchResult) Result(org.eclipse.jgit.lib.RefUpdate.Result)

Example 4 with JGitInternalException

use of org.eclipse.jgit.api.errors.JGitInternalException in project indy by Commonjava.

the class GitManager method deleteAndCommitPaths.

public GitManager deleteAndCommitPaths(final ChangeSummary summary, final Collection<String> paths) throws GitSubsystemException {
    lockAnd(me -> {
        try {
            RmCommand rm = git.rm();
            CommitCommand commit = git.commit();
            for (final String path : paths) {
                rm = rm.addFilepattern(path);
                commit = commit.setOnly(path);
            }
            logger.info("Deleting:\n  " + join(paths, "\n  ") + "\n\nSummary: " + summary);
            rm.call();
            commit.setMessage(buildMessage(summary, paths)).setAuthor(summary.getUser(), email).call();
        } catch (final NoFilepatternException e) {
            throw new GitSubsystemException("Cannot remove from git: " + e.getMessage(), e);
        } catch (final JGitInternalException | GitAPIException e) {
            throw new GitSubsystemException("Cannot remove from git: " + e.getMessage(), e);
        }
        return me;
    });
    return this;
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) NoFilepatternException(org.eclipse.jgit.api.errors.NoFilepatternException) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) RmCommand(org.eclipse.jgit.api.RmCommand) CommitCommand(org.eclipse.jgit.api.CommitCommand) JoinString(org.commonjava.maven.atlas.ident.util.JoinString)

Example 5 with JGitInternalException

use of org.eclipse.jgit.api.errors.JGitInternalException in project bndtools by bndtools.

the class GitUtils method getRepository.

public static synchronized Repository getRepository(File gitRoot, String branch, String gitUrl, String gitPushUrl) throws IOException, ConfigInvalidException, JGitInternalException, GitAPIException {
    File dotGit;
    if (gitRoot.getName().equals(Constants.DOT_GIT)) {
        dotGit = gitRoot;
    } else {
        dotGit = new File(gitRoot, Constants.DOT_GIT);
    }
    Repository repository = localRepos.get(dotGit);
    if (repository != null && dotGit.exists()) {
        return repository;
    }
    if (!dotGit.exists()) {
        Git.cloneRepository().setDirectory(gitRoot).setCloneAllBranches(true).setURI(gitUrl).call();
        FileBasedConfig config = new FileBasedConfig(new File(dotGit, "config"), FS.DETECTED);
        config.load();
        if (gitPushUrl != null) {
            config.setString(ConfigConstants.CONFIG_REMOTE_SECTION, "origin", "pushurl", gitPushUrl);
        }
        config.save();
    }
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    repository = builder.setGitDir(dotGit).readEnvironment().findGitDir().build();
    localRepos.put(dotGit, repository);
    try {
        repository.incrementOpen();
        Git git = Git.wrap(repository);
        // Check branch
        boolean pull = true;
        String currentBranch = repository.getBranch();
        if (branch != null && !branch.equals(currentBranch)) {
            CheckoutCommand checkout = git.checkout();
            if (!branchExists(git, branch)) {
                checkout.setCreateBranch(true);
                pull = false;
            }
            checkout.setName(branch);
            checkout.call();
        }
        if (pull) {
            git.pull().call();
        } else {
            git.fetch().call();
        }
    } catch (Exception e) {
        if (!(e.getCause() instanceof TransportException)) {
            throw new RuntimeException(e);
        }
    } finally {
        if (repository != null) {
            repository.close();
        }
    }
    return repository;
}
Also used : Repository(org.eclipse.jgit.lib.Repository) CheckoutCommand(org.eclipse.jgit.api.CheckoutCommand) Git(org.eclipse.jgit.api.Git) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) File(java.io.File) FileRepositoryBuilder(org.eclipse.jgit.storage.file.FileRepositoryBuilder) TransportException(org.eclipse.jgit.errors.TransportException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException) TransportException(org.eclipse.jgit.errors.TransportException) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException)

Aggregations

JGitInternalException (org.eclipse.jgit.api.errors.JGitInternalException)6 IOException (java.io.IOException)3 Git (org.eclipse.jgit.api.Git)3 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)3 File (java.io.File)2 CheckoutCommand (org.eclipse.jgit.api.CheckoutCommand)2 ConcurrentRefUpdateException (org.eclipse.jgit.api.errors.ConcurrentRefUpdateException)2 CommitBuilder (org.eclipse.jgit.lib.CommitBuilder)2 ObjectId (org.eclipse.jgit.lib.ObjectId)2 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)2 PersonIdent (org.eclipse.jgit.lib.PersonIdent)2 RefUpdate (org.eclipse.jgit.lib.RefUpdate)2 Result (org.eclipse.jgit.lib.RefUpdate.Result)2 RevCommit (org.eclipse.jgit.revwalk.RevCommit)2 RevWalk (org.eclipse.jgit.revwalk.RevWalk)2 RefModel (com.gitblit.models.RefModel)1 ProxyHelper (com.google.devtools.build.lib.bazel.repository.downloader.ProxyHelper)1 RepositoryFunctionException (com.google.devtools.build.lib.rules.repository.RepositoryFunction.RepositoryFunctionException)1 WorkspaceAttributeMapper (com.google.devtools.build.lib.rules.repository.WorkspaceAttributeMapper)1 EvalException (com.google.devtools.build.lib.syntax.EvalException)1