Search in sources :

Example 56 with Project

use of com.google.gerrit.entities.Project in project gerrit by GerritCodeReview.

the class PutConfig method apply.

public ConfigInfo apply(ProjectState projectState, ConfigInput input) throws ResourceNotFoundException, BadRequestException, ResourceConflictException {
    Project.NameKey projectName = projectState.getNameKey();
    if (input == null) {
        throw new BadRequestException("config is required");
    }
    try (MetaDataUpdate md = metaDataUpdateFactory.get().create(projectName)) {
        ProjectConfig projectConfig = projectConfigFactory.read(md);
        projectConfig.updateProject(p -> {
            p.setDescription(Strings.emptyToNull(input.description));
            for (BooleanProjectConfig cfg : BooleanProjectConfig.values()) {
                InheritableBoolean val = BooleanProjectConfigTransformations.get(cfg, input);
                if (val != null) {
                    p.setBooleanConfig(cfg, val);
                }
            }
            if (input.maxObjectSizeLimit != null) {
                p.setMaxObjectSizeLimit(input.maxObjectSizeLimit);
            }
            if (input.submitType != null) {
                p.setSubmitType(input.submitType);
            }
            if (input.state != null) {
                p.setState(input.state);
            }
        });
        if (input.pluginConfigValues != null) {
            setPluginConfigValues(projectState, projectConfig, input.pluginConfigValues);
        }
        if (input.commentLinks != null) {
            updateCommentLinks(projectConfig, input.commentLinks);
        }
        md.setMessage("Modified project settings\n");
        try {
            projectConfig.commit(md);
            projectCache.evictAndReindex(projectConfig.getProject());
            md.getRepository().setGitwebDescription(projectConfig.getProject().getDescription());
        } catch (IOException e) {
            if (e.getCause() instanceof ConfigInvalidException) {
                throw new ResourceConflictException("Cannot update " + projectName + ": " + e.getCause().getMessage());
            }
            logger.atWarning().withCause(e).log("Failed to update config of project %s.", projectName);
            throw new ResourceConflictException("Cannot update " + projectName);
        }
        ProjectState state = projectStateFactory.create(projectConfigFactory.read(md).getCacheable());
        return ConfigInfoCreator.constructInfo(serverEnableSignedPush, state, user.get(), pluginConfigEntries, cfgFactory, allProjects, uiActions, views);
    } catch (RepositoryNotFoundException notFound) {
        throw new ResourceNotFoundException(projectName.get(), notFound);
    } catch (ConfigInvalidException err) {
        throw new ResourceConflictException("Cannot read project " + projectName, err);
    } catch (IOException err) {
        throw new ResourceConflictException("Cannot update project " + projectName, err);
    }
}
Also used : ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) InheritableBoolean(com.google.gerrit.extensions.client.InheritableBoolean) IOException(java.io.IOException) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) ProjectConfig(com.google.gerrit.server.project.ProjectConfig) BooleanProjectConfig(com.google.gerrit.entities.BooleanProjectConfig) Project(com.google.gerrit.entities.Project) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ProjectState(com.google.gerrit.server.project.ProjectState) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) MetaDataUpdate(com.google.gerrit.server.git.meta.MetaDataUpdate) BooleanProjectConfig(com.google.gerrit.entities.BooleanProjectConfig)

Example 57 with Project

use of com.google.gerrit.entities.Project in project gerrit by GerritCodeReview.

the class IndexChanges method apply.

@Override
public Response.Accepted apply(ProjectResource resource, Input input) {
    Project.NameKey project = resource.getNameKey();
    Task mpt = multiProgressMonitorFactory.create(ByteStreams.nullOutputStream(), TaskKind.INDEXING, "Reindexing project").beginSubTask("", MultiProgressMonitor.UNKNOWN);
    AllChangesIndexer allChangesIndexer = allChangesIndexerProvider.get();
    allChangesIndexer.setVerboseOut(NullOutputStream.INSTANCE);
    // The REST call is just a trigger for async reindexing, so it is safe to ignore the future's
    // return value.
    @SuppressWarnings("unused") Future<?> possiblyIgnoredError = executor.submit(allChangesIndexer.reindexProject(indexer, project, mpt, mpt));
    return Response.accepted("Project " + project + " submitted for reindexing");
}
Also used : Project(com.google.gerrit.entities.Project) Task(com.google.gerrit.server.git.MultiProgressMonitor.Task) AllChangesIndexer(com.google.gerrit.server.index.change.AllChangesIndexer)

Example 58 with Project

use of com.google.gerrit.entities.Project in project gerrit by GerritCodeReview.

the class ListProjects method display.

@Nullable
public SortedMap<String, ProjectInfo> display(@Nullable PrintWriter stdout) throws BadRequestException, PermissionBackendException {
    if (all && state != null) {
        throw new BadRequestException("'all' and 'state' may not be used together");
    }
    if (groupUuid != null) {
        try {
            if (!groupControlFactory.controlFor(groupUuid).isVisible()) {
                return Collections.emptySortedMap();
            }
        } catch (NoSuchGroupException ex) {
            return Collections.emptySortedMap();
        }
    }
    int foundIndex = 0;
    int found = 0;
    TreeMap<String, ProjectInfo> output = new TreeMap<>();
    Map<String, String> hiddenNames = new HashMap<>();
    Map<Project.NameKey, Boolean> accessibleParents = new HashMap<>();
    PermissionBackend.WithUser perm = permissionBackend.user(currentUser);
    final TreeMap<Project.NameKey, ProjectNode> treeMap = new TreeMap<>();
    try {
        Iterator<ProjectState> projectStatesIt = filter(perm).iterator();
        while (projectStatesIt.hasNext()) {
            ProjectState e = projectStatesIt.next();
            Project.NameKey projectName = e.getNameKey();
            if (e.getProject().getState() == HIDDEN && !all && state != HIDDEN) {
                // If state HIDDEN wasn't selected, and it's HIDDEN, pretend it's not present.
                continue;
            }
            if (state != null && e.getProject().getState() != state) {
                continue;
            }
            if (groupUuid != null && !e.getLocalGroups().contains(GroupReference.forGroup(groupResolver.parseId(groupUuid.get())))) {
                continue;
            }
            if (showTree && !format.isJson()) {
                treeMap.put(projectName, projectNodeFactory.create(e.getProject(), true));
                continue;
            }
            if (foundIndex++ < start) {
                continue;
            }
            if (limit > 0 && ++found > limit) {
                break;
            }
            ProjectInfo info = new ProjectInfo();
            info.name = projectName.get();
            if (showTree && format.isJson()) {
                addParentProjectInfo(hiddenNames, accessibleParents, perm, e, info);
            }
            if (showDescription) {
                info.description = emptyToNull(e.getProject().getDescription());
            }
            info.state = e.getProject().getState();
            try {
                if (!showBranch.isEmpty()) {
                    try (Repository git = repoManager.openRepository(projectName)) {
                        if (!type.matches(git)) {
                            continue;
                        }
                        List<Ref> refs = retrieveBranchRefs(e, git);
                        if (!hasValidRef(refs)) {
                            continue;
                        }
                        addProjectBranchesInfo(info, refs);
                    }
                } else if (!showTree && type.useMatch()) {
                    try (Repository git = repoManager.openRepository(projectName)) {
                        if (!type.matches(git)) {
                            continue;
                        }
                    }
                }
            } catch (RepositoryNotFoundException err) {
                // If the Git repository is gone, the project doesn't actually exist anymore.
                continue;
            } catch (IOException err) {
                logger.atWarning().withCause(err).log("Unexpected error reading %s", projectName);
                continue;
            }
            ImmutableList<WebLinkInfo> links = webLinks.getProjectLinks(projectName.get());
            info.webLinks = links.isEmpty() ? null : links;
            if (stdout == null || format.isJson()) {
                output.put(info.name, info);
                continue;
            }
            if (!showBranch.isEmpty()) {
                printProjectBranches(stdout, info);
            }
            stdout.print(info.name);
            if (info.description != null) {
                // We still want to list every project as one-liners, hence escaping \n.
                stdout.print(" - " + StringUtil.escapeString(info.description));
            }
            stdout.print('\n');
        }
        for (ProjectInfo info : output.values()) {
            info.id = Url.encode(info.name);
            info.name = null;
        }
        if (stdout == null) {
            return output;
        } else if (format.isJson()) {
            format.newGson().toJson(output, new TypeToken<Map<String, ProjectInfo>>() {
            }.getType(), stdout);
            stdout.print('\n');
        } else if (showTree && treeMap.size() > 0) {
            printProjectTree(stdout, treeMap);
        }
        return null;
    } finally {
        if (stdout != null) {
            stdout.flush();
        }
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) ProjectInfo(com.google.gerrit.extensions.common.ProjectInfo) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) IOException(java.io.IOException) TreeMap(java.util.TreeMap) Project(com.google.gerrit.entities.Project) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) WebLinkInfo(com.google.gerrit.extensions.common.WebLinkInfo) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ProjectState(com.google.gerrit.server.project.ProjectState) Map(java.util.Map) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ImmutableSortedMap(com.google.common.collect.ImmutableSortedMap) TreeMap(java.util.TreeMap) Nullable(com.google.gerrit.common.Nullable)

Example 59 with Project

use of com.google.gerrit.entities.Project in project gerrit by GerritCodeReview.

the class ListProjects method isParentAccessible.

private boolean isParentAccessible(Map<Project.NameKey, Boolean> checked, PermissionBackend.WithUser perm, ProjectState state) throws PermissionBackendException {
    Project.NameKey name = state.getNameKey();
    Boolean b = checked.get(name);
    if (b == null) {
        try {
            // Hidden projects(permitsRead = false) should only be accessible by the project owners.
            // READ_CONFIG is checked here because it's only allowed to project owners(ACCESS may also
            // be allowed for other users). Allowing project owners to access here will help them to
            // view
            // and update the config of hidden projects easily.
            ProjectPermission permissionToCheck = state.statePermitsRead() ? ProjectPermission.ACCESS : ProjectPermission.READ_CONFIG;
            perm.project(name).check(permissionToCheck);
            b = true;
        } catch (AuthException denied) {
            b = false;
        }
        checked.put(name, b);
    }
    return b;
}
Also used : Project(com.google.gerrit.entities.Project) ProjectPermission(com.google.gerrit.server.permissions.ProjectPermission) AuthException(com.google.gerrit.extensions.restapi.AuthException)

Example 60 with Project

use of com.google.gerrit.entities.Project in project gerrit by GerritCodeReview.

the class SubmitRequirementIT method submitRequirement_storedForClosedChanges.

@Test
public void submitRequirement_storedForClosedChanges() throws Exception {
    for (SubmitType submitType : SubmitType.values()) {
        Project.NameKey project = createProjectForPush(submitType);
        TestRepository<InMemoryRepository> repo = cloneProject(project);
        configSubmitRequirement(project, SubmitRequirement.builder().setName("Code-Review").setSubmittabilityExpression(SubmitRequirementExpression.maxCodeReview()).setAllowOverrideInChildProjects(false).build());
        PushOneCommit.Result r = createChange(repo, "master", "Add a file", "foo", "content", "topic");
        String changeId = r.getChangeId();
        voteLabel(changeId, "Code-Review", 2);
        ChangeInfo change = gApi.changes().id(changeId).get();
        assertThat(change.submitRequirements).hasSize(1);
        assertSubmitRequirementStatus(change.submitRequirements, "Code-Review", Status.SATISFIED, /* isLegacy= */
        false);
        RevisionApi revision = gApi.changes().id(r.getChangeId()).current();
        revision.review(ReviewInput.approve());
        revision.submit();
        ChangeNotes notes = notesFactory.create(project, r.getChange().getId());
        SubmitRequirementResult result = notes.getSubmitRequirementsResult().stream().collect(MoreCollectors.onlyElement());
        assertThat(result.status()).isEqualTo(SubmitRequirementResult.Status.SATISFIED);
        assertThat(result.submittabilityExpressionResult().get().status()).isEqualTo(SubmitRequirementExpressionResult.Status.PASS);
        assertThat(result.submittabilityExpressionResult().get().expression().expressionString()).isEqualTo("label:Code-Review=MAX");
    }
}
Also used : Project(com.google.gerrit.entities.Project) InMemoryRepository(org.eclipse.jgit.internal.storage.dfs.InMemoryRepository) ChangeInfo(com.google.gerrit.extensions.common.ChangeInfo) RevisionApi(com.google.gerrit.extensions.api.changes.RevisionApi) SubmitType(com.google.gerrit.extensions.client.SubmitType) SubmitRequirementResult(com.google.gerrit.entities.SubmitRequirementResult) VerifyNoPiiInChangeNotes(com.google.gerrit.acceptance.VerifyNoPiiInChangeNotes) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Aggregations

Project (com.google.gerrit.entities.Project)184 Test (org.junit.Test)109 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)67 Change (com.google.gerrit.entities.Change)43 Repository (org.eclipse.jgit.lib.Repository)34 ChangeInfo (com.google.gerrit.extensions.common.ChangeInfo)33 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)32 InMemoryRepository (org.eclipse.jgit.internal.storage.dfs.InMemoryRepository)31 BranchNameKey (com.google.gerrit.entities.BranchNameKey)30 Config (org.eclipse.jgit.lib.Config)26 ObjectId (org.eclipse.jgit.lib.ObjectId)26 IOException (java.io.IOException)25 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)24 ProjectState (com.google.gerrit.server.project.ProjectState)23 Inject (com.google.inject.Inject)23 List (java.util.List)23 AuthException (com.google.gerrit.extensions.restapi.AuthException)22 ChangeData (com.google.gerrit.server.query.change.ChangeData)22 RevCommit (org.eclipse.jgit.revwalk.RevCommit)22 PatchSet (com.google.gerrit.entities.PatchSet)20