use of org.eclipse.jgit.lib.Repository in project camel by apache.
the class GitProducerTest method remoteAddTest.
@Test
public void remoteAddTest() throws Exception {
Repository repository = getTestRepository();
File gitDir = new File(gitLocalRepo, ".git");
assertEquals(gitDir.exists(), true);
Git git = new Git(repository);
List<RemoteConfig> remoteConfigList = git.remoteList().call();
assertTrue(remoteConfigList.size() == 0);
Object result = template.requestBody("direct:remoteAdd", "");
assertTrue(result instanceof RemoteConfig);
RemoteConfig remoteConfig = (RemoteConfig) result;
remoteConfigList = git.remoteList().call();
assertTrue(remoteConfigList.size() == 1);
assertEquals(remoteConfigList.get(0).getName(), remoteConfig.getName());
assertEquals(remoteConfigList.get(0).getURIs(), remoteConfig.getURIs());
git.close();
}
use of org.eclipse.jgit.lib.Repository in project che by eclipse.
the class JGitConnection method commit.
@Override
public Revision commit(CommitParams params) throws GitException {
try {
// Check repository state
RepositoryState repositoryState = repository.getRepositoryState();
if (!repositoryState.canCommit()) {
throw new GitException(format(MESSAGE_COMMIT_NOT_POSSIBLE, repositoryState.getDescription()));
}
if (params.isAmend() && !repositoryState.canAmend()) {
throw new GitException(format(MESSAGE_COMMIT_AMEND_NOT_POSSIBLE, repositoryState.getDescription()));
}
// Check committer
GitUser committer = getUser();
if (committer == null) {
throw new GitException("Committer can't be null");
}
String committerName = committer.getName();
String committerEmail = committer.getEmail();
if (committerName == null || committerEmail == null) {
throw new GitException("Git user name and (or) email wasn't set", ErrorCodes.NO_COMMITTER_NAME_OR_EMAIL_DEFINED);
}
// Check commit message
String message = params.getMessage();
if (message == null) {
throw new GitException("Message wasn't set");
}
Status status = status(StatusFormat.SHORT);
List<String> specified = params.getFiles();
List<String> staged = new ArrayList<>();
staged.addAll(status.getAdded());
staged.addAll(status.getChanged());
staged.addAll(status.getRemoved());
List<String> changed = new ArrayList<>(staged);
changed.addAll(status.getModified());
changed.addAll(status.getMissing());
List<String> specifiedStaged = specified.stream().filter(path -> staged.stream().anyMatch(s -> s.startsWith(path))).collect(Collectors.toList());
List<String> specifiedChanged = specified.stream().filter(path -> changed.stream().anyMatch(c -> c.startsWith(path))).collect(Collectors.toList());
// Check that there are changes present for commit, if 'isAmend' is disabled
if (!params.isAmend()) {
// Check that there are staged changes present for commit, or any changes if 'isAll' is enabled
if (status.isClean()) {
throw new GitException("Nothing to commit, working directory clean");
} else if (!params.isAll() && (specified.isEmpty() ? staged.isEmpty() : specifiedStaged.isEmpty())) {
throw new GitException("No changes added to commit");
}
} else {
/*
By default Jgit doesn't allow to commit not changed specified paths. According to setAllowEmpty method documentation,
setting this flag to true must allow such commit, but it won't because Jgit has a bug:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=510685. As a workaround, specified paths of the commit command will contain
only changed and specified paths. If other changes are present, but the list of changed and specified paths is empty,
throw exception to prevent committing other paths. TODO Remove this check when the bug will be fixed.
*/
if (!specified.isEmpty() && !(params.isAll() ? changed.isEmpty() : staged.isEmpty()) && specifiedChanged.isEmpty()) {
throw new GitException(format("Changes are present but not changed path%s specified for commit.", specified.size() > 1 ? "s were" : " was"));
}
}
// TODO add 'setAllowEmpty(params.isAmend())' when https://bugs.eclipse.org/bugs/show_bug.cgi?id=510685 will be fixed
CommitCommand commitCommand = getGit().commit().setCommitter(committerName, committerEmail).setAuthor(committerName, committerEmail).setMessage(message).setAll(params.isAll()).setAmend(params.isAmend());
if (!params.isAll()) {
// TODO change to 'specified.forEach(commitCommand::setOnly)' when https://bugs.eclipse.org/bugs/show_bug.cgi?id=510685 will be fixed. See description above.
specifiedChanged.forEach(commitCommand::setOnly);
}
// Check if repository is configured with Gerrit Support
String gerritSupportConfigValue = repository.getConfig().getString(ConfigConstants.CONFIG_GERRIT_SECTION, null, ConfigConstants.CONFIG_KEY_CREATECHANGEID);
boolean isGerritSupportConfigured = gerritSupportConfigValue != null ? Boolean.valueOf(gerritSupportConfigValue) : false;
commitCommand.setInsertChangeId(isGerritSupportConfigured);
RevCommit result = commitCommand.call();
GitUser gitUser = newDto(GitUser.class).withName(committerName).withEmail(committerEmail);
return newDto(Revision.class).withBranch(getCurrentBranch()).withId(result.getId().getName()).withMessage(result.getFullMessage()).withCommitTime(MILLISECONDS.convert(result.getCommitTime(), SECONDS)).withCommitter(gitUser);
} catch (GitAPIException exception) {
throw new GitException(exception.getMessage(), exception);
}
}
use of org.eclipse.jgit.lib.Repository in project gerrit by GerritCodeReview.
the class RelatedChangesSorter method collectById.
private Map<String, PatchSetData> collectById(List<ChangeData> in) throws OrmException, IOException {
Project.NameKey project = in.get(0).change().getProject();
Map<String, PatchSetData> result = Maps.newHashMapWithExpectedSize(in.size() * 3);
try (Repository repo = repoManager.openRepository(project);
RevWalk rw = new RevWalk(repo)) {
rw.setRetainBody(true);
for (ChangeData cd : in) {
checkArgument(cd.change().getProject().equals(project), "Expected change %s in project %s, found %s", cd.getId(), project, cd.change().getProject());
for (PatchSet ps : cd.patchSets()) {
String id = ps.getRevision().get();
RevCommit c = rw.parseCommit(ObjectId.fromString(id));
PatchSetData psd = PatchSetData.create(cd, ps, c);
result.put(id, psd);
}
}
}
return result;
}
use of org.eclipse.jgit.lib.Repository in project gerrit by GerritCodeReview.
the class Revert method revert.
private Change.Id revert(BatchUpdate.Factory updateFactory, ChangeControl ctl, String message) throws OrmException, IOException, RestApiException, UpdateException {
Change.Id changeIdToRevert = ctl.getChange().getId();
PatchSet.Id patchSetId = ctl.getChange().currentPatchSetId();
PatchSet patch = psUtil.get(db.get(), ctl.getNotes(), patchSetId);
if (patch == null) {
throw new ResourceNotFoundException(changeIdToRevert.toString());
}
Project.NameKey project = ctl.getProject().getNameKey();
CurrentUser user = ctl.getUser();
try (Repository git = repoManager.openRepository(project);
ObjectInserter oi = git.newObjectInserter();
ObjectReader reader = oi.newReader();
RevWalk revWalk = new RevWalk(reader)) {
RevCommit commitToRevert = revWalk.parseCommit(ObjectId.fromString(patch.getRevision().get()));
if (commitToRevert.getParentCount() == 0) {
throw new ResourceConflictException("Cannot revert initial commit");
}
Timestamp now = TimeUtil.nowTs();
PersonIdent committerIdent = new PersonIdent(serverIdent, now);
PersonIdent authorIdent = user.asIdentifiedUser().newCommitterIdent(now, committerIdent.getTimeZone());
RevCommit parentToCommitToRevert = commitToRevert.getParent(0);
revWalk.parseHeaders(parentToCommitToRevert);
CommitBuilder revertCommitBuilder = new CommitBuilder();
revertCommitBuilder.addParentId(commitToRevert);
revertCommitBuilder.setTreeId(parentToCommitToRevert.getTree());
revertCommitBuilder.setAuthor(authorIdent);
revertCommitBuilder.setCommitter(authorIdent);
Change changeToRevert = ctl.getChange();
if (message == null) {
message = MessageFormat.format(ChangeMessages.get().revertChangeDefaultMessage, changeToRevert.getSubject(), patch.getRevision().get());
}
ObjectId computedChangeId = ChangeIdUtil.computeChangeId(parentToCommitToRevert.getTree(), commitToRevert, authorIdent, committerIdent, message);
revertCommitBuilder.setMessage(ChangeIdUtil.insertId(message, computedChangeId, true));
Change.Id changeId = new Change.Id(seq.nextChangeId());
ObjectId id = oi.insert(revertCommitBuilder);
RevCommit revertCommit = revWalk.parseCommit(id);
ChangeInserter ins = changeInserterFactory.create(changeId, revertCommit, ctl.getChange().getDest().get()).setTopic(changeToRevert.getTopic());
ins.setMessage("Uploaded patch set 1.");
Set<Account.Id> reviewers = new HashSet<>();
reviewers.add(changeToRevert.getOwner());
reviewers.addAll(approvalsUtil.getReviewers(db.get(), ctl.getNotes()).all());
reviewers.remove(user.getAccountId());
ins.setReviewers(reviewers);
try (BatchUpdate bu = updateFactory.create(db.get(), project, user, now)) {
bu.setRepository(git, revWalk, oi);
bu.insertChange(ins);
bu.addOp(changeId, new NotifyOp(ctl.getChange(), ins));
bu.addOp(changeToRevert.getId(), new PostRevertedMessageOp(computedChangeId));
bu.execute();
}
return changeId;
} catch (RepositoryNotFoundException e) {
throw new ResourceNotFoundException(changeIdToRevert.toString(), e);
}
}
use of org.eclipse.jgit.lib.Repository in project gerrit by GerritCodeReview.
the class WalkSorter method sortProject.
private List<PatchSetData> sortProject(Project.NameKey project, Collection<ChangeData> in) throws OrmException, IOException {
try (Repository repo = repoManager.openRepository(project);
RevWalk rw = new RevWalk(repo)) {
rw.setRetainBody(retainBody);
ListMultimap<RevCommit, PatchSetData> byCommit = byCommit(rw, in);
if (byCommit.isEmpty()) {
return ImmutableList.of();
} else if (byCommit.size() == 1) {
return ImmutableList.of(byCommit.values().iterator().next());
}
// Walk from all patch set SHA-1s, and terminate as soon as we've found
// everything we're looking for. This is equivalent to just sorting the
// list of commits by the RevWalk's configured order.
//
// Partially topo sort the list, ensuring no parent is emitted before a
// direct child that is also in the input set. This preserves the stable,
// expected sort in the case where many commits share the same timestamp,
// e.g. a quick rebase. It also avoids JGit's topo sort, which slurps all
// interesting commits at the beginning, which is a problem since we don't
// know which commits to mark as uninteresting. Finding a reasonable set
// of commits to mark uninteresting (the "rootmost" set) is at least as
// difficult as just implementing this partial topo sort ourselves.
//
// (This is slightly less efficient than JGit's topo sort, which uses a
// private in-degree field in RevCommit rather than multimaps. We assume
// the input size is small enough that this is not an issue.)
Set<RevCommit> commits = byCommit.keySet();
ListMultimap<RevCommit, RevCommit> children = collectChildren(commits);
ListMultimap<RevCommit, RevCommit> pending = MultimapBuilder.hashKeys().arrayListValues().build();
Deque<RevCommit> todo = new ArrayDeque<>();
RevFlag done = rw.newFlag("done");
markStart(rw, commits);
int expected = commits.size();
int found = 0;
RevCommit c;
List<PatchSetData> result = new ArrayList<>(expected);
while (found < expected && (c = rw.next()) != null) {
if (!commits.contains(c)) {
continue;
}
todo.clear();
todo.add(c);
int i = 0;
while (!todo.isEmpty()) {
// Sanity check: we can't pop more than N pending commits, otherwise
// we have an infinite loop due to programmer error or something.
checkState(++i <= commits.size(), "Too many pending steps while sorting %s", commits);
RevCommit t = todo.removeFirst();
if (t.has(done)) {
continue;
}
boolean ready = true;
for (RevCommit child : children.get(t)) {
if (!child.has(done)) {
pending.put(child, t);
ready = false;
}
}
if (ready) {
found += emit(t, byCommit, result, done);
todo.addAll(pending.get(t));
}
}
}
return result;
}
}
Aggregations