use of org.eclipse.jgit.lib.ObjectReader in project gerrit by GerritCodeReview.
the class ChangeNotesParser method parseNotes.
private void parseNotes() throws IOException, ConfigInvalidException {
ObjectReader reader = walk.getObjectReader();
ChangeNotesCommit tipCommit = walk.parseCommit(tip);
revisionNoteMap = RevisionNoteMap.parse(changeNoteJson, reader, NoteMap.read(reader, tipCommit), HumanComment.Status.PUBLISHED);
Map<ObjectId, ChangeRevisionNote> rns = revisionNoteMap.revisionNotes;
for (Map.Entry<ObjectId, ChangeRevisionNote> e : rns.entrySet()) {
for (HumanComment c : e.getValue().getEntities()) {
humanComments.put(e.getKey(), c);
}
}
// PS of them.
for (PatchSet.Builder ps : patchSets.values().stream().sorted(comparingInt((PatchSet.Builder p) -> p.id().get()).reversed()).collect(Collectors.toList())) {
Optional<ObjectId> maybePsCommitId = ps.commitId();
if (!maybePsCommitId.isPresent()) {
continue;
}
ObjectId psCommitId = maybePsCommitId.get();
if (rns.containsKey(psCommitId) && rns.get(psCommitId).getSubmitRequirementsResult() != null) {
rns.get(psCommitId).getSubmitRequirementsResult().forEach(sr -> submitRequirementResults.add(sr));
break;
}
}
for (PatchSet.Builder b : patchSets.values()) {
ObjectId commitId = b.commitId().orElseThrow(() -> new IllegalStateException("never parsed commit ID for patch set " + b.id()));
ChangeRevisionNote rn = rns.get(commitId);
if (rn != null && rn.getPushCert() != null) {
b.pushCertificate(Optional.of(rn.getPushCert()));
}
}
}
use of org.eclipse.jgit.lib.ObjectReader in project gerrit by GerritCodeReview.
the class CreateChange method createNewChange.
// TODO(issue-15517): Fix the JdkObsolete issue with Date once JGit's PersonIdent class supports
// Instants
@SuppressWarnings("JdkObsolete")
private ChangeInfo createNewChange(ChangeInput input, IdentifiedUser me, ProjectState projectState, BatchUpdate.Factory updateFactory) throws RestApiException, PermissionBackendException, IOException, ConfigInvalidException, UpdateException {
logger.atFine().log("Creating new change for target branch %s in project %s" + " (new branch = %s, base change = %s, base commit = %s)", input.branch, projectState.getName(), input.newBranch, input.baseChange, input.baseCommit);
try (Repository git = gitManager.openRepository(projectState.getNameKey());
ObjectInserter oi = git.newObjectInserter();
ObjectReader reader = oi.newReader();
CodeReviewRevWalk rw = CodeReviewCommit.newRevWalk(reader)) {
PatchSet basePatchSet = null;
List<String> groups = Collections.emptyList();
if (input.baseChange != null) {
ChangeNotes baseChange = getBaseChange(input.baseChange);
basePatchSet = psUtil.current(baseChange);
groups = basePatchSet.groups();
logger.atFine().log("base patch set = %s (groups = %s)", basePatchSet.id(), groups);
}
ObjectId parentCommit = getParentCommit(git, rw, input.branch, input.newBranch, basePatchSet, input.baseCommit, input.merge);
logger.atFine().log("parent commit = %s", parentCommit != null ? parentCommit.name() : "NULL");
RevCommit mergeTip = parentCommit == null ? null : rw.parseCommit(parentCommit);
Instant now = TimeUtil.now();
PersonIdent committer = me.newCommitterIdent(now, serverTimeZone);
PersonIdent author = input.author == null ? committer : new PersonIdent(input.author.name, input.author.email, Date.from(now), serverTimeZone);
String commitMessage = getCommitMessage(input.subject, me);
CodeReviewCommit c;
if (input.merge != null) {
// create a merge commit
c = newMergeCommit(git, oi, rw, projectState, mergeTip, input.merge, author, committer, commitMessage);
if (!c.getFilesWithGitConflicts().isEmpty()) {
logger.atFine().log("merge commit has conflicts in the following files: %s", c.getFilesWithGitConflicts());
}
} else {
// create an empty commit
c = newCommit(oi, rw, author, committer, mergeTip, commitMessage);
}
// Flush inserter so that commit becomes visible to validators
oi.flush();
Change.Id changeId = Change.id(seq.nextChangeId());
ChangeInserter ins = changeInserterFactory.create(changeId, c, input.branch);
ins.setMessage(messageForNewChange(ins.getPatchSetId(), c));
ins.setTopic(input.topic);
ins.setPrivate(input.isPrivate);
ins.setWorkInProgress(input.workInProgress || !c.getFilesWithGitConflicts().isEmpty());
ins.setGroups(groups);
if (input.validationOptions != null) {
ImmutableListMultimap.Builder<String, String> validationOptions = ImmutableListMultimap.builder();
input.validationOptions.entrySet().forEach(e -> validationOptions.put(e.getKey(), e.getValue()));
ins.setValidationOptions(validationOptions.build());
}
try (BatchUpdate bu = updateFactory.create(projectState.getNameKey(), me, now)) {
bu.setRepository(git, rw, oi);
bu.setNotify(notifyResolver.resolve(firstNonNull(input.notify, NotifyHandling.ALL), input.notifyDetails));
bu.insertChange(ins);
bu.execute();
}
ChangeInfo changeInfo = jsonFactory.noOptions().format(ins.getChange());
changeInfo.containsGitConflicts = !c.getFilesWithGitConflicts().isEmpty() ? true : null;
return changeInfo;
} catch (InvalidMergeStrategyException | MergeWithConflictsNotSupportedException e) {
throw new BadRequestException(e.getMessage());
}
}
use of org.eclipse.jgit.lib.ObjectReader in project gerrit by GerritCodeReview.
the class CreateMergePatchSet method apply.
// TODO(issue-15517): Fix the JdkObsolete issue with Date once JGit's PersonIdent class supports
// Instants
@SuppressWarnings("JdkObsolete")
@Override
public Response<ChangeInfo> apply(ChangeResource rsrc, MergePatchSetInput in) throws IOException, RestApiException, UpdateException, PermissionBackendException {
// Not allowed to create a new patch set if the current patch set is locked.
psUtil.checkPatchSetNotLocked(rsrc.getNotes());
rsrc.permissions().check(ChangePermission.ADD_PATCH_SET);
if (in.author != null) {
permissionBackend.currentUser().project(rsrc.getProject()).ref(rsrc.getChange().getDest().branch()).check(RefPermission.FORGE_AUTHOR);
}
ProjectState projectState = projectCache.get(rsrc.getProject()).orElseThrow(illegalState(rsrc.getProject()));
projectState.checkStatePermitsWrite();
MergeInput merge = in.merge;
if (merge == null || Strings.isNullOrEmpty(merge.source)) {
throw new BadRequestException("merge.source must be non-empty");
}
if (in.author != null && (Strings.isNullOrEmpty(in.author.email) || Strings.isNullOrEmpty(in.author.name))) {
throw new BadRequestException("Author must specify name and email");
}
in.baseChange = Strings.nullToEmpty(in.baseChange).trim();
PatchSet ps = psUtil.current(rsrc.getNotes());
Change change = rsrc.getChange();
Project.NameKey project = change.getProject();
BranchNameKey dest = change.getDest();
try (Repository git = gitManager.openRepository(project);
ObjectInserter oi = git.newObjectInserter();
ObjectReader reader = oi.newReader();
CodeReviewRevWalk rw = CodeReviewCommit.newRevWalk(reader)) {
RevCommit sourceCommit = MergeUtil.resolveCommit(git, rw, merge.source);
if (!commits.canRead(projectState, git, sourceCommit)) {
throw new ResourceNotFoundException("cannot find source commit: " + merge.source + " to merge.");
}
RevCommit currentPsCommit;
List<String> groups = null;
if (!in.inheritParent && !in.baseChange.isEmpty()) {
PatchSet basePS = findBasePatchSet(in.baseChange);
currentPsCommit = rw.parseCommit(basePS.commitId());
groups = basePS.groups();
} else {
currentPsCommit = rw.parseCommit(ps.commitId());
}
Instant now = TimeUtil.now();
IdentifiedUser me = user.get().asIdentifiedUser();
PersonIdent author = in.author == null ? me.newCommitterIdent(now, serverTimeZone) : new PersonIdent(in.author.name, in.author.email, Date.from(now), serverTimeZone);
CodeReviewCommit newCommit = createMergeCommit(in, projectState, dest, git, oi, rw, currentPsCommit, sourceCommit, author, ObjectId.fromString(change.getKey().get().substring(1)));
oi.flush();
PatchSet.Id nextPsId = ChangeUtil.nextPatchSetId(ps.id());
PatchSetInserter psInserter = patchSetInserterFactory.create(rsrc.getNotes(), nextPsId, newCommit);
try (BatchUpdate bu = updateFactory.create(project, me, now)) {
bu.setRepository(git, rw, oi);
bu.setNotify(NotifyResolver.Result.none());
psInserter.setMessage(messageForChange(nextPsId, newCommit)).setWorkInProgress(!newCommit.getFilesWithGitConflicts().isEmpty()).setCheckAddPatchSetPermission(false);
if (groups != null) {
psInserter.setGroups(groups);
}
bu.addOp(rsrc.getId(), psInserter);
bu.execute();
}
ChangeJson json = jsonFactory.create(ListChangesOption.CURRENT_REVISION);
ChangeInfo changeInfo = json.format(psInserter.getChange());
changeInfo.containsGitConflicts = !newCommit.getFilesWithGitConflicts().isEmpty() ? true : null;
return Response.ok(changeInfo);
} catch (InvalidMergeStrategyException | MergeWithConflictsNotSupportedException e) {
throw new BadRequestException(e.getMessage());
}
}
use of org.eclipse.jgit.lib.ObjectReader in project gerrit by GerritCodeReview.
the class CreateAccessChange method apply.
@Override
public Response<ChangeInfo> apply(ProjectResource rsrc, ProjectAccessInput input) throws PermissionBackendException, AuthException, IOException, ConfigInvalidException, InvalidNameException, UpdateException, RestApiException {
PermissionBackend.ForProject forProject = permissionBackend.user(rsrc.getUser()).project(rsrc.getNameKey());
if (!check(forProject, ProjectPermission.READ_CONFIG)) {
throw new AuthException(RefNames.REFS_CONFIG + " not visible");
}
if (!check(forProject, ProjectPermission.WRITE_CONFIG)) {
try {
forProject.ref(RefNames.REFS_CONFIG).check(RefPermission.CREATE_CHANGE);
} catch (AuthException denied) {
throw new AuthException("cannot create change for " + RefNames.REFS_CONFIG, denied);
}
}
projectCache.get(rsrc.getNameKey()).orElseThrow(illegalState(rsrc.getNameKey())).checkStatePermitsWrite();
MetaDataUpdate.User metaDataUpdateUser = metaDataUpdateFactory.get();
ImmutableList<AccessSection> removals = setAccess.getAccessSections(input.remove);
ImmutableList<AccessSection> additions = setAccess.getAccessSections(input.add);
Project.NameKey newParentProjectName = input.parent == null ? null : Project.nameKey(input.parent);
try (MetaDataUpdate md = metaDataUpdateUser.create(rsrc.getNameKey())) {
ProjectConfig config = projectConfigFactory.read(md);
ObjectId oldCommit = config.getRevision();
String oldCommitSha1 = oldCommit == null ? null : oldCommit.getName();
setAccess.validateChanges(config, removals, additions);
setAccess.applyChanges(config, removals, additions);
try {
setAccess.setParentName(rsrc.getUser().asIdentifiedUser(), config, rsrc.getNameKey(), newParentProjectName, false);
} catch (AuthException e) {
throw new IllegalStateException(e);
}
md.setMessage("Review access change");
md.setInsertChangeId(true);
Change.Id changeId = Change.id(seq.nextChangeId());
RevCommit commit = config.commitToNewRef(md, PatchSet.id(changeId, Change.INITIAL_PATCH_SET_ID).toRefName());
if (commit.name().equals(oldCommitSha1)) {
throw new BadRequestException("no change");
}
try (ObjectInserter objInserter = md.getRepository().newObjectInserter();
ObjectReader objReader = objInserter.newReader();
RevWalk rw = new RevWalk(objReader);
BatchUpdate bu = updateFactory.create(rsrc.getNameKey(), rsrc.getUser(), TimeUtil.now())) {
bu.setRepository(md.getRepository(), rw, objInserter);
ChangeInserter ins = newInserter(changeId, commit);
bu.insertChange(ins);
bu.execute();
return Response.created(jsonFactory.noOptions().format(ins.getChange()));
}
} catch (InvalidNameException e) {
throw new BadRequestException(e.toString());
}
}
use of org.eclipse.jgit.lib.ObjectReader in project gerrit by GerritCodeReview.
the class AccountIT method assertUserBranch.
private void assertUserBranch(Account.Id accountId, @Nullable String name, @Nullable String status) throws Exception {
try (Repository repo = repoManager.openRepository(allUsers);
RevWalk rw = new RevWalk(repo);
ObjectReader or = repo.newObjectReader()) {
Ref ref = repo.exactRef(RefNames.refsUsers(accountId));
assertThat(ref).isNotNull();
RevCommit c = rw.parseCommit(ref.getObjectId());
long timestampDiffMs = Math.abs(c.getCommitTime() * 1000L - getAccount(accountId).registeredOn().toEpochMilli());
assertThat(timestampDiffMs).isAtMost(SECONDS.toMillis(1));
// Check the 'account.config' file.
try (TreeWalk tw = TreeWalk.forPath(or, AccountProperties.ACCOUNT_CONFIG, c.getTree())) {
if (name != null || status != null) {
assertThat(tw).isNotNull();
Config cfg = new Config();
cfg.fromText(new String(or.open(tw.getObjectId(0), OBJ_BLOB).getBytes(), UTF_8));
assertThat(cfg).stringValue(AccountProperties.ACCOUNT, null, AccountProperties.KEY_FULL_NAME).isEqualTo(name);
assertThat(cfg).stringValue(AccountProperties.ACCOUNT, null, AccountProperties.KEY_STATUS).isEqualTo(status);
} else {
// No account properties were set, hence an 'account.config' file was not created.
assertThat(tw).isNull();
}
}
}
}
Aggregations