use of com.google.gerrit.server.project.ProjectState in project gerrit by GerritCodeReview.
the class ChildProjectsCollection method parse.
@Override
public ChildProjectResource parse(ProjectResource parent, IdString id) throws RestApiException, IOException, PermissionBackendException {
parent.getProjectState().checkStatePermitsRead();
ProjectResource p = projectsCollection.parse(TopLevelResource.INSTANCE, id);
for (ProjectState pp : p.getProjectState().parents()) {
if (parent.getNameKey().equals(pp.getProject().getNameKey())) {
return new ChildProjectResource(parent, p.getProjectState());
}
}
throw new ResourceNotFoundException(id);
}
use of com.google.gerrit.server.project.ProjectState in project gerrit by GerritCodeReview.
the class CommitsCollection method canRead.
/**
* Returns true if {@code commit} is visible to the caller.
*/
public boolean canRead(ProjectState state, Repository repo, RevCommit commit) throws IOException {
Project.NameKey project = state.getNameKey();
if (indexes.getSearchIndex() == null) {
// as the commit might be a patchset of a not yet submitted change.
return reachable.fromRefs(project, repo, commit, repo.getRefDatabase().getRefs());
}
// Check first if any patchset of any change references the commit in question. This is much
// cheaper than ref visibility filtering and reachability computation.
List<ChangeData> changes = retryHelper.changeIndexQuery("queryChangesByProjectCommitWithLimit1", q -> q.enforceVisibility(true).setLimit(1).byProjectCommit(project, commit)).call();
if (!changes.isEmpty()) {
return true;
}
// Maybe the commit was a merge commit of a change. Try to find promising candidates for
// branches to check, by seeing if its parents were associated to changes.
Predicate<ChangeData> pred = Predicate.and(ChangePredicates.project(project), Predicate.or(Arrays.stream(commit.getParents()).map(parent -> ChangePredicates.commitPrefix(parent.getId().getName())).collect(toImmutableList())));
changes = retryHelper.changeIndexQuery("queryChangesByProjectCommit", q -> q.enforceVisibility(true).query(pred)).call();
Set<Ref> branchesForCommitParents = new HashSet<>(changes.size());
for (ChangeData cd : changes) {
Ref ref = repo.exactRef(cd.change().getDest().branch());
if (ref != null) {
branchesForCommitParents.add(ref);
}
}
if (reachable.fromRefs(project, repo, commit, branchesForCommitParents.stream().collect(Collectors.toList()))) {
return true;
}
// If we have already checked change refs using the change index, spare any further checks for
// changes.
List<Ref> refs = repo.getRefDatabase().getRefsByPrefixWithExclusions(RefDatabase.ALL, ImmutableSet.of(RefNames.REFS_CHANGES));
return reachable.fromRefs(project, repo, commit, refs);
}
use of com.google.gerrit.server.project.ProjectState in project gerrit by GerritCodeReview.
the class PRED_project_default_submit_type_1 method exec.
@Override
public Operation exec(Prolog engine) throws PrologException {
engine.setB0();
Term a1 = arg1.dereference();
ProjectState projectState = StoredValues.PROJECT_STATE.get(engine);
SubmitType submitType = projectState.getSubmitType();
if (!a1.unify(term[submitType.ordinal()], engine.trail)) {
return engine.fail();
}
return cont;
}
use of com.google.gerrit.server.project.ProjectState in project gerrit by GerritCodeReview.
the class FixReplacementInterpreter method toCommitModification.
/**
* Transforms the given {@code FixReplacement}s into {@code TreeModification}s.
*
* @param repository the affected Git repository
* @param projectState the affected project
* @param patchSetCommitId the patch set which should be modified
* @param fixReplacements the replacements which should be applied
* @return a list of {@code TreeModification}s representing the given replacements
* @throws ResourceNotFoundException if a file to which one of the replacements refers doesn't
* exist
* @throws ResourceConflictException if the replacements can't be transformed into {@code
* TreeModification}s
*/
public CommitModification toCommitModification(Repository repository, ProjectState projectState, ObjectId patchSetCommitId, List<FixReplacement> fixReplacements) throws BadRequestException, ResourceNotFoundException, IOException, ResourceConflictException {
requireNonNull(fixReplacements, "Fix replacements must not be null");
Map<String, List<FixReplacement>> fixReplacementsPerFilePath = fixReplacements.stream().collect(groupingBy(fixReplacement -> fixReplacement.path));
CommitModification.Builder modificationBuilder = CommitModification.builder();
for (Map.Entry<String, List<FixReplacement>> entry : fixReplacementsPerFilePath.entrySet()) {
if (Objects.equals(entry.getKey(), Patch.COMMIT_MSG)) {
String newCommitMessage = getNewCommitMessage(repository, patchSetCommitId, entry.getValue());
modificationBuilder.newCommitMessage(newCommitMessage);
} else {
TreeModification treeModification = toTreeModification(repository, projectState, patchSetCommitId, entry.getKey(), entry.getValue());
modificationBuilder.addTreeModification(treeModification);
}
}
return modificationBuilder.build();
}
use of com.google.gerrit.server.project.ProjectState 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);
}
}
}
Aggregations