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);
}
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;
}
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;
}
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;
}
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;
}
Aggregations