use of org.eclipse.jgit.errors.MissingObjectException in project gerrit by GerritCodeReview.
the class CherryPickChange method getBaseCommit.
private RevCommit getBaseCommit(Ref destRef, String project, RevWalk revWalk, String base) throws RestApiException, IOException {
RevCommit destRefTip = revWalk.parseCommit(destRef.getObjectId());
// The tip commit of the destination ref is the default base for the newly created change.
if (Strings.isNullOrEmpty(base)) {
return destRefTip;
}
ObjectId baseObjectId;
try {
baseObjectId = ObjectId.fromString(base);
} catch (InvalidObjectIdException e) {
throw new BadRequestException(String.format("Base %s doesn't represent a valid SHA-1", base), e);
}
RevCommit baseCommit;
try {
baseCommit = revWalk.parseCommit(baseObjectId);
} catch (MissingObjectException e) {
throw new UnprocessableEntityException(String.format("Base %s doesn't exist", baseObjectId.name()), e);
}
InternalChangeQuery changeQuery = queryProvider.get();
changeQuery.enforceVisibility(true);
List<ChangeData> changeDatas = changeQuery.byBranchCommit(project, destRef.getName(), base);
if (changeDatas.isEmpty()) {
if (revWalk.isMergedInto(baseCommit, destRefTip)) {
// The base commit is a merged commit with no change associated.
return baseCommit;
}
throw new UnprocessableEntityException(String.format("Commit %s does not exist on branch %s", base, destRef.getName()));
} else if (changeDatas.size() != 1) {
throw new ResourceConflictException("Multiple changes found for commit " + base);
}
Change change = changeDatas.get(0).change();
if (!change.isAbandoned()) {
// The base commit is a valid change revision.
return baseCommit;
}
throw new ResourceConflictException(String.format("Change %s with commit %s is %s", change.getChangeId(), base, ChangeUtil.status(change)));
}
use of org.eclipse.jgit.errors.MissingObjectException in project gerrit by GerritCodeReview.
the class CommitsCollection method parse.
@Override
public CommitResource parse(ProjectResource parent, IdString id) throws RestApiException, IOException {
parent.getProjectState().checkStatePermitsRead();
ObjectId objectId;
try {
objectId = ObjectId.fromString(id.get());
} catch (IllegalArgumentException e) {
throw new ResourceNotFoundException(id, e);
}
try (Repository repo = repoManager.openRepository(parent.getNameKey());
RevWalk rw = new RevWalk(repo)) {
RevCommit commit = rw.parseCommit(objectId);
if (!canRead(parent.getProjectState(), repo, commit)) {
throw new ResourceNotFoundException(id);
}
// GetCommit depends on the body of both the commit and parent being parsed, to get the
// subject.
rw.parseBody(commit);
for (int i = 0; i < commit.getParentCount(); i++) {
rw.parseBody(rw.parseCommit(commit.getParent(i)));
}
return new CommitResource(parent, commit);
} catch (MissingObjectException | IncorrectObjectTypeException e) {
throw new ResourceNotFoundException(id, e);
}
}
use of org.eclipse.jgit.errors.MissingObjectException in project gerrit by GerritCodeReview.
the class ReceiveCommits method parseMagicBranch.
/**
* Parse the magic branch data (refs/for/BRANCH/OPTIONALTOPIC%OPTIONS) into the magicBranch
* member.
*
* <p>Assumes we are handling a magic branch here.
*/
private void parseMagicBranch(ReceiveCommand cmd) throws PermissionBackendException, IOException {
try (TraceTimer traceTimer = newTimer("parseMagicBranch")) {
logger.atFine().log("Found magic branch %s", cmd.getRefName());
MagicBranchInput magicBranch = new MagicBranchInput(user, projectState, cmd, labelTypes);
String ref;
magicBranch.cmdLineParser = optionParserFactory.create(magicBranch);
// Filter out plugin push options, as the parser would reject them as unknown.
ImmutableListMultimap<String, String> pushOptionsToParse = pushOptions.entries().stream().filter(e -> !isPluginPushOption(e.getKey())).collect(toImmutableListMultimap(e -> e.getKey(), e -> e.getValue()));
try {
ref = magicBranch.parse(pushOptionsToParse);
} catch (CmdLineException e) {
if (!magicBranch.cmdLineParser.wasHelpRequestedByOption()) {
logger.atFine().log("Invalid branch syntax");
reject(cmd, e.getMessage());
return;
}
// never happens
ref = null;
}
if (magicBranch.skipValidation) {
reject(cmd, String.format("\"--%s\" option is only supported for direct push", PUSH_OPTION_SKIP_VALIDATION));
return;
}
if (magicBranch.topic != null && magicBranch.topic.length() > ChangeUtil.TOPIC_MAX_LENGTH) {
reject(cmd, String.format("topic length exceeds the limit (%d)", ChangeUtil.TOPIC_MAX_LENGTH));
}
if (magicBranch.cmdLineParser.wasHelpRequestedByOption()) {
StringWriter w = new StringWriter();
w.write("\nHelp for refs/for/branch:\n\n");
magicBranch.cmdLineParser.printUsage(w, null);
String pluginPushOptionsHelp = StreamSupport.stream(pluginPushOptions.entries().spliterator(), /* parallel= */
false).map(e -> String.format("-o %s~%s: %s", e.getPluginName(), e.get().getName(), e.get().getDescription())).sorted().collect(joining("\n"));
if (!pluginPushOptionsHelp.isEmpty()) {
w.write("\nPlugin push options:\n" + pluginPushOptionsHelp);
}
addMessage(w.toString());
reject(cmd, "see help");
return;
}
if (projectState.isAllUsers() && RefNames.REFS_USERS_SELF.equals(ref)) {
logger.atFine().log("Handling %s", RefNames.REFS_USERS_SELF);
ref = RefNames.refsUsers(user.getAccountId());
}
// configuration.
if (receivePackRefCache.exactRef(ref) == null && !ref.equals(readHEAD(repo)) && !ref.equals(RefNames.REFS_CONFIG)) {
logger.atFine().log("Ref %s not found", ref);
if (ref.startsWith(Constants.R_HEADS)) {
String n = ref.substring(Constants.R_HEADS.length());
reject(cmd, "branch " + n + " not found");
} else {
reject(cmd, ref + " not found");
}
return;
}
magicBranch.dest = BranchNameKey.create(project.getNameKey(), ref);
magicBranch.perm = permissions.ref(ref);
Optional<AuthException> err = checkRefPermission(magicBranch.perm, RefPermission.READ).map(Optional::of).orElse(checkRefPermission(magicBranch.perm, RefPermission.CREATE_CHANGE));
if (err.isPresent()) {
rejectProhibited(cmd, err.get());
return;
}
if (magicBranch.isPrivate && magicBranch.removePrivate) {
reject(cmd, "the options 'private' and 'remove-private' are mutually exclusive");
return;
}
boolean privateByDefault = projectCache.get(project.getNameKey()).orElseThrow(illegalState(project.getNameKey())).is(BooleanProjectConfig.PRIVATE_BY_DEFAULT);
setChangeAsPrivate = magicBranch.isPrivate || (privateByDefault && !magicBranch.removePrivate);
if (receiveConfig.disablePrivateChanges && setChangeAsPrivate) {
reject(cmd, "private changes are disabled");
return;
}
if (magicBranch.workInProgress && magicBranch.ready) {
reject(cmd, "the options 'wip' and 'ready' are mutually exclusive");
return;
}
if (magicBranch.publishComments && magicBranch.noPublishComments) {
reject(cmd, "the options 'publish-comments' and 'no-publish-comments' are mutually exclusive");
return;
}
if (magicBranch.submit) {
err = checkRefPermission(magicBranch.perm, RefPermission.UPDATE_BY_SUBMIT);
if (err.isPresent()) {
rejectProhibited(cmd, err.get());
return;
}
}
RevWalk walk = receivePack.getRevWalk();
RevCommit tip;
try {
tip = walk.parseCommit(magicBranch.cmd.getNewId());
logger.atFine().log("Tip of push: %s", tip.name());
} catch (IOException ex) {
magicBranch.cmd.setResult(REJECTED_MISSING_OBJECT);
logger.atSevere().withCause(ex).log("Invalid pack upload; one or more objects weren't sent");
return;
}
String destBranch = magicBranch.dest.branch();
try {
if (magicBranch.merged) {
if (magicBranch.base != null) {
reject(cmd, "cannot use merged with base");
return;
}
Ref refTip = receivePackRefCache.exactRef(magicBranch.dest.branch());
if (refTip == null) {
reject(cmd, magicBranch.dest.branch() + " not found");
return;
}
RevCommit branchTip = receivePack.getRevWalk().parseCommit(refTip.getObjectId());
if (!walk.isMergedInto(tip, branchTip)) {
reject(cmd, "not merged into branch");
return;
}
}
// if %base or %merged was specified, ignore newChangeForAllNotInTarget.
if (tip.getParentCount() > 1 || magicBranch.base != null || magicBranch.merged || tip.getParentCount() == 0) {
logger.atFine().log("Forcing newChangeForAllNotInTarget = false");
newChangeForAllNotInTarget = false;
}
if (magicBranch.base != null) {
logger.atFine().log("Handling %%base: %s", magicBranch.base);
magicBranch.baseCommit = Lists.newArrayListWithCapacity(magicBranch.base.size());
for (ObjectId id : magicBranch.base) {
try {
magicBranch.baseCommit.add(walk.parseCommit(id));
} catch (IncorrectObjectTypeException notCommit) {
reject(cmd, "base must be a commit");
return;
} catch (MissingObjectException e) {
reject(cmd, "base not found");
return;
} catch (IOException e) {
throw new StorageException(String.format("Project %s cannot read %s", project.getName(), id.name()), e);
}
}
} else if (newChangeForAllNotInTarget) {
Ref refTip = receivePackRefCache.exactRef(magicBranch.dest.branch());
if (refTip != null) {
RevCommit branchTip = receivePack.getRevWalk().parseCommit(refTip.getObjectId());
magicBranch.baseCommit = Collections.singletonList(branchTip);
logger.atFine().log("Set baseCommit = %s", magicBranch.baseCommit.get(0).name());
} else {
// repository and to review an initial project configuration.
if (!ref.equals(readHEAD(repo)) && !ref.equals(RefNames.REFS_CONFIG)) {
reject(cmd, magicBranch.dest.branch() + " not found");
return;
}
}
}
} catch (IOException e) {
throw new StorageException(String.format("Error walking to %s in project %s", destBranch, project.getName()), e);
}
if (validateConnected(magicBranch.cmd, magicBranch.dest, tip)) {
this.magicBranch = magicBranch;
this.result.magicPush(true);
}
}
}
use of org.eclipse.jgit.errors.MissingObjectException in project gerrit by GerritCodeReview.
the class SubmitStrategyOp method getAlreadyMergedCommit.
private CodeReviewCommit getAlreadyMergedCommit(RepoContext ctx) throws IOException {
CodeReviewCommit tip = args.mergeTip.getInitialTip();
if (tip == null) {
return null;
}
CodeReviewRevWalk rw = (CodeReviewRevWalk) ctx.getRevWalk();
Change.Id id = getId();
String refPrefix = id.toRefPrefix();
Map<String, ObjectId> refs = ctx.getRepoView().getRefs(refPrefix);
List<CodeReviewCommit> commits = new ArrayList<>(refs.size());
for (Map.Entry<String, ObjectId> e : refs.entrySet()) {
PatchSet.Id psId = PatchSet.Id.fromRef(refPrefix + e.getKey());
if (psId == null) {
continue;
}
try {
CodeReviewCommit c = rw.parseCommit(e.getValue());
c.setPatchsetId(psId);
commits.add(c);
} catch (MissingObjectException | IncorrectObjectTypeException ex) {
// Bogus ref, can't be merged into tip so we don't care.
continue;
}
}
commits.sort(comparing((CodeReviewCommit c) -> c.getPatchsetId().get()).reversed());
CodeReviewCommit result = MergeUtil.findAnyMergedInto(rw, commits, tip);
if (result == null) {
return null;
}
// Some patch set of this change is actually merged into the target
// branch, most likely because a previous run of MergeOp failed after
// updateRepo, during updateChange.
//
// Do the best we can to clean this up: mark the change as merged and set
// the current patch set. Don't touch the dest branch at all. This can
// lead to some odd situations like another change in the set merging in
// a different patch set of this change, but that's unavoidable at this
// point. At least the change will end up in the right state.
//
// TODO(dborowitz): Consider deleting later junk patch set refs. They
// presumably don't have PatchSets pointing to them.
rw.parseBody(result);
result.add(args.canMergeFlag);
PatchSet.Id psId = result.getPatchsetId();
result.copyFrom(toMerge);
// Got overwriten by copyFrom.
result.setPatchsetId(psId);
result.setStatusCode(CommitMergeStatus.ALREADY_MERGED);
args.commitStatus.put(result);
return result;
}
use of org.eclipse.jgit.errors.MissingObjectException in project gitblit by gitblit.
the class JGitUtils method searchRevlogs.
/**
* Search the commit history for a case-insensitive match to the value.
* Search results require a specified SearchType of AUTHOR, COMMITTER, or
* COMMIT. Results may be paginated using offset and maxCount. If the
* repository does not exist or is empty, an empty list is returned.
*
* @param repository
* @param objectId
* if unspecified, HEAD is assumed.
* @param value
* @param type
* AUTHOR, COMMITTER, COMMIT
* @param offset
* @param maxCount
* if < 0, all matches are returned
* @return matching list of commits
*/
public static List<RevCommit> searchRevlogs(Repository repository, String objectId, String value, final com.gitblit.Constants.SearchType type, int offset, int maxCount) {
List<RevCommit> list = new ArrayList<RevCommit>();
if (StringUtils.isEmpty(value)) {
return list;
}
if (maxCount == 0) {
return list;
}
if (!hasCommits(repository)) {
return list;
}
final String lcValue = value.toLowerCase();
try {
// resolve branch
ObjectId branchObject;
if (StringUtils.isEmpty(objectId)) {
branchObject = getDefaultBranch(repository);
} else {
branchObject = repository.resolve(objectId);
}
RevWalk rw = new RevWalk(repository);
rw.setRevFilter(new RevFilter() {
@Override
public RevFilter clone() {
// This is part of JGit design and unrelated to Cloneable.
return this;
}
@Override
public boolean include(RevWalk walker, RevCommit commit) throws StopWalkException, MissingObjectException, IncorrectObjectTypeException, IOException {
boolean include = false;
switch(type) {
case AUTHOR:
include = (commit.getAuthorIdent().getName().toLowerCase().indexOf(lcValue) > -1) || (commit.getAuthorIdent().getEmailAddress().toLowerCase().indexOf(lcValue) > -1);
break;
case COMMITTER:
include = (commit.getCommitterIdent().getName().toLowerCase().indexOf(lcValue) > -1) || (commit.getCommitterIdent().getEmailAddress().toLowerCase().indexOf(lcValue) > -1);
break;
case COMMIT:
include = commit.getFullMessage().toLowerCase().indexOf(lcValue) > -1;
break;
}
return include;
}
});
rw.markStart(rw.parseCommit(branchObject));
Iterable<RevCommit> revlog = rw;
if (offset > 0) {
int count = 0;
for (RevCommit rev : revlog) {
count++;
if (count > offset) {
list.add(rev);
if (maxCount > 0 && list.size() == maxCount) {
break;
}
}
}
} else {
for (RevCommit rev : revlog) {
list.add(rev);
if (maxCount > 0 && list.size() == maxCount) {
break;
}
}
}
rw.dispose();
} catch (Throwable t) {
error(t, repository, "{0} failed to {1} search revlogs for {2}", type.name(), value);
}
return list;
}
Aggregations