Search in sources :

Example 21 with ProjectState

use of com.google.gerrit.server.project.ProjectState in project gerrit by GerritCodeReview.

the class CreateProject method apply.

@Override
public Response<ProjectInfo> apply(TopLevelResource resource, IdString id, ProjectInput input) throws RestApiException, IOException, ConfigInvalidException, PermissionBackendException {
    String name = id.get();
    if (input == null) {
        input = new ProjectInput();
    }
    if (input.name != null && !name.equals(input.name)) {
        throw new BadRequestException("name must match URL");
    }
    CreateProjectArgs args = new CreateProjectArgs();
    args.setProjectName(ProjectUtil.sanitizeProjectName(name));
    String parentName = MoreObjects.firstNonNull(Strings.emptyToNull(input.parent), allProjects.get());
    args.newParent = projectsCollection.get().parse(parentName, false).getNameKey();
    if (args.newParent.equals(allUsers)) {
        throw new ResourceConflictException(String.format("Cannot inherit from '%s' project", allUsers.get()));
    }
    args.createEmptyCommit = input.createEmptyCommit;
    args.permissionsOnly = input.permissionsOnly;
    args.projectDescription = Strings.emptyToNull(input.description);
    args.submitType = input.submitType;
    args.branch = normalizeBranchNames(input.branches);
    if (input.owners == null || input.owners.isEmpty()) {
        args.ownerIds = new ArrayList<>(projectOwnerGroups.create(args.getProject()).get());
    } else {
        args.ownerIds = Lists.newArrayListWithCapacity(input.owners.size());
        for (String owner : input.owners) {
            args.ownerIds.add(groupResolver.get().parse(owner).getGroupUUID());
        }
    }
    args.contributorAgreements = MoreObjects.firstNonNull(input.useContributorAgreements, InheritableBoolean.INHERIT);
    args.signedOffBy = MoreObjects.firstNonNull(input.useSignedOffBy, InheritableBoolean.INHERIT);
    args.contentMerge = input.submitType == SubmitType.FAST_FORWARD_ONLY ? InheritableBoolean.FALSE : MoreObjects.firstNonNull(input.useContentMerge, InheritableBoolean.INHERIT);
    args.newChangeForAllNotInTarget = MoreObjects.firstNonNull(input.createNewChangeForAllNotInTarget, InheritableBoolean.INHERIT);
    args.changeIdRequired = MoreObjects.firstNonNull(input.requireChangeId, InheritableBoolean.INHERIT);
    args.rejectEmptyCommit = MoreObjects.firstNonNull(input.rejectEmptyCommit, InheritableBoolean.INHERIT);
    args.enableSignedPush = MoreObjects.firstNonNull(input.enableSignedPush, InheritableBoolean.INHERIT);
    args.requireSignedPush = MoreObjects.firstNonNull(input.requireSignedPush, InheritableBoolean.INHERIT);
    try {
        args.maxObjectSizeLimit = ProjectConfig.validMaxObjectSizeLimit(input.maxObjectSizeLimit);
    } catch (ConfigInvalidException e) {
        throw new BadRequestException(e.getMessage());
    }
    Lock nameLock = lockManager.call(lockManager -> lockManager.getLock(args.getProject()));
    nameLock.lock();
    try {
        try {
            projectCreationValidationListeners.runEach(l -> l.validateNewProject(args), ValidationException.class);
        } catch (ValidationException e) {
            throw new ResourceConflictException(e.getMessage(), e);
        }
        ProjectState projectState = projectCreator.createProject(args);
        requireNonNull(projectState, () -> String.format("failed to create project %s", args.getProject().get()));
        if (input.pluginConfigValues != null) {
            ConfigInput in = new ConfigInput();
            in.pluginConfigValues = input.pluginConfigValues;
            in.description = args.projectDescription;
            putConfig.get().apply(projectState, in);
        }
        return Response.created(json.format(projectState));
    } finally {
        nameLock.unlock();
    }
}
Also used : ProjectInput(com.google.gerrit.extensions.api.projects.ProjectInput) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ValidationException(com.google.gerrit.server.validators.ValidationException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ConfigInput(com.google.gerrit.extensions.api.projects.ConfigInput) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ProjectState(com.google.gerrit.server.project.ProjectState) IdString(com.google.gerrit.extensions.restapi.IdString) CreateProjectArgs(com.google.gerrit.server.project.CreateProjectArgs) Lock(java.util.concurrent.locks.Lock)

Example 22 with ProjectState

use of com.google.gerrit.server.project.ProjectState in project gerrit by GerritCodeReview.

the class ChangeResource method prepareETag.

// This includes all information relevant for ETag computation
// unrelated to the UI.
public void prepareETag(Hasher h, CurrentUser user) {
    h.putInt(JSON_FORMAT_VERSION).putLong(getChange().getLastUpdatedOn().toEpochMilli()).putInt(user.isIdentifiedUser() ? user.getAccountId().get() : 0);
    if (user.isIdentifiedUser()) {
        for (AccountGroup.UUID uuid : user.getEffectiveGroups().getKnownGroups()) {
            h.putBytes(uuid.get().getBytes(UTF_8));
        }
    }
    byte[] buf = new byte[20];
    Set<Account.Id> accounts = new HashSet<>();
    accounts.add(getChange().getOwner());
    if (getChange().getAssignee() != null) {
        accounts.add(getChange().getAssignee());
    }
    try {
        patchSetUtil.byChange(getNotes()).stream().map(PatchSet::uploader).forEach(accounts::add);
        // It's intentional to include the states for *all* reviewers into the ETag computation.
        // We need the states of all current reviewers and CCs because they are part of ChangeInfo.
        // Including removed reviewers is a cheap way of making sure that the states of accounts that
        // posted a message on the change are included. Loading all change messages to find the exact
        // set of accounts that posted a message is too expensive. However everyone who posts a
        // message is automatically added as reviewer. Hence if we include removed reviewers we can
        // be sure that we have all accounts that posted messages on the change.
        accounts.addAll(approvalUtil.getReviewers(getNotes()).all());
    } catch (StorageException e) {
    // This ETag will be invalidated if it loads next time.
    }
    for (Account.Id accountId : accounts) {
        Optional<AccountState> accountState = accountCache.get(accountId);
        if (accountState.isPresent()) {
            hashAccount(h, accountState.get(), buf);
        } else {
            h.putInt(accountId.get());
        }
    }
    ObjectId noteId;
    try {
        noteId = getNotes().loadRevision();
    } catch (StorageException e) {
        // This ETag will be invalidated if it loads next time.
        noteId = null;
    }
    hashObjectId(h, noteId, buf);
    // TODO(dborowitz): Include more NoteDb and other related refs, e.g. drafts
    // and edits.
    Iterable<ProjectState> projectStateTree = projectCache.get(getProject()).orElseThrow(illegalState(getProject())).tree();
    for (ProjectState p : projectStateTree) {
        hashObjectId(h, p.getConfig().getRevision().orElse(null), buf);
    }
    changeETagComputation.runEach(c -> {
        String pluginETag = c.getETag(changeData.project(), changeData.getId());
        if (pluginETag != null) {
            h.putString(pluginETag, UTF_8);
        }
    });
}
Also used : Account(com.google.gerrit.entities.Account) ObjectId(org.eclipse.jgit.lib.ObjectId) AccountState(com.google.gerrit.server.account.AccountState) AccountGroup(com.google.gerrit.entities.AccountGroup) ProjectState(com.google.gerrit.server.project.ProjectState) ObjectId(org.eclipse.jgit.lib.ObjectId) StorageException(com.google.gerrit.exceptions.StorageException) HashSet(java.util.HashSet)

Example 23 with ProjectState

use of com.google.gerrit.server.project.ProjectState in project gerrit by GerritCodeReview.

the class TestSubmitRule method apply.

@Override
public Response<TestSubmitRuleInfo> apply(RevisionResource rsrc, TestSubmitRuleInput input) throws AuthException, PermissionBackendException, BadRequestException {
    if (input == null) {
        input = new TestSubmitRuleInput();
    }
    if (input.rule == null) {
        throw new BadRequestException("rule is required");
    }
    if (!rules.isProjectRulesEnabled()) {
        throw new AuthException("project rules are disabled");
    }
    input.filters = MoreObjects.firstNonNull(input.filters, filters);
    Project.NameKey name = rsrc.getProject();
    Optional<ProjectState> project = projectCache.get(name);
    if (!project.isPresent()) {
        throw new BadRequestException("project not found " + name);
    }
    ChangeData cd = changeDataFactory.create(rsrc.getNotes());
    SubmitRecord record = prologRule.evaluate(cd, PrologOptions.dryRunOptions(input.rule, input.filters == Filters.SKIP));
    AccountLoader accounts = accountInfoFactory.create(true);
    TestSubmitRuleInfo out = newSubmitRuleInfo(record, accounts);
    accounts.fill();
    return Response.ok(out);
}
Also used : Project(com.google.gerrit.entities.Project) SubmitRecord(com.google.gerrit.entities.SubmitRecord) TestSubmitRuleInput(com.google.gerrit.extensions.common.TestSubmitRuleInput) AccountLoader(com.google.gerrit.server.account.AccountLoader) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) AuthException(com.google.gerrit.extensions.restapi.AuthException) ProjectState(com.google.gerrit.server.project.ProjectState) ChangeData(com.google.gerrit.server.query.change.ChangeData) TestSubmitRuleInfo(com.google.gerrit.extensions.common.TestSubmitRuleInfo)

Example 24 with ProjectState

use of com.google.gerrit.server.project.ProjectState in project gerrit by GerritCodeReview.

the class RevertSubmission method getDescription.

@Override
public Description getDescription(ChangeResource rsrc) {
    Change change = rsrc.getChange();
    boolean projectStatePermitsWrite = false;
    try {
        projectStatePermitsWrite = projectCache.get(rsrc.getProject()).map(ProjectState::statePermitsWrite).orElse(false);
    } catch (StorageException e) {
        logger.atSevere().withCause(e).log("Failed to check if project state permits write: %s", rsrc.getProject());
    }
    return new UiAction.Description().setLabel("Revert submission").setTitle("Revert this change and all changes that have been submitted together with this change").setVisible(and(and(change.isMerged() && change.getSubmissionId() != null && isChangePartOfSubmission(change.getSubmissionId()) && projectStatePermitsWrite, permissionBackend.user(rsrc.getUser()).ref(change.getDest()).testCond(CREATE_CHANGE)), permissionBackend.user(rsrc.getUser()).change(rsrc.getNotes()).testCond(REVERT)));
}
Also used : ProjectState(com.google.gerrit.server.project.ProjectState) Change(com.google.gerrit.entities.Change) UiAction(com.google.gerrit.extensions.webui.UiAction) StorageException(com.google.gerrit.exceptions.StorageException)

Example 25 with ProjectState

use of com.google.gerrit.server.project.ProjectState in project gerrit by GerritCodeReview.

the class ListTasks method apply.

@Override
public Response<List<TaskInfo>> apply(ConfigResource resource) throws AuthException, PermissionBackendException {
    CurrentUser user = self.get();
    if (!user.isIdentifiedUser()) {
        throw new AuthException("Authentication required");
    }
    List<TaskInfo> allTasks = getTasks();
    try {
        permissionBackend.user(user).check(GlobalPermission.VIEW_QUEUE);
        return Response.ok(allTasks);
    } catch (AuthException e) {
    // Fall through to filter tasks.
    }
    Map<String, Boolean> visibilityCache = new HashMap<>();
    List<TaskInfo> visibleTasks = new ArrayList<>();
    for (TaskInfo task : allTasks) {
        if (task.projectName != null) {
            Boolean visible = visibilityCache.get(task.projectName);
            if (visible == null) {
                Project.NameKey nameKey = Project.nameKey(task.projectName);
                Optional<ProjectState> state = projectCache.get(nameKey);
                if (!state.isPresent() || !state.get().statePermitsRead()) {
                    visible = false;
                } else {
                    try {
                        permissionBackend.user(user).project(nameKey).check(ProjectPermission.ACCESS);
                        visible = true;
                    } catch (AuthException e) {
                        visible = false;
                    }
                }
                visibilityCache.put(task.projectName, visible);
            }
            if (visible) {
                visibleTasks.add(task);
            }
        }
    }
    return Response.ok(visibleTasks);
}
Also used : CurrentUser(com.google.gerrit.server.CurrentUser) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) AuthException(com.google.gerrit.extensions.restapi.AuthException) Project(com.google.gerrit.entities.Project) ProjectState(com.google.gerrit.server.project.ProjectState)

Aggregations

ProjectState (com.google.gerrit.server.project.ProjectState)86 Project (com.google.gerrit.entities.Project)20 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)19 IOException (java.io.IOException)18 Repository (org.eclipse.jgit.lib.Repository)18 AuthException (com.google.gerrit.extensions.restapi.AuthException)16 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)14 PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)14 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)13 Change (com.google.gerrit.entities.Change)13 ObjectId (org.eclipse.jgit.lib.ObjectId)13 Test (org.junit.Test)13 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)12 ChangeData (com.google.gerrit.server.query.change.ChangeData)11 Inject (com.google.inject.Inject)10 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)10 RepositoryNotFoundException (org.eclipse.jgit.errors.RepositoryNotFoundException)10 StorageException (com.google.gerrit.exceptions.StorageException)9 ProjectInfo (com.google.gerrit.extensions.common.ProjectInfo)9 ProjectResource (com.google.gerrit.server.project.ProjectResource)9