Search in sources :

Example 91 with Project

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

the class GitwebServlet method service.

@Override
protected void service(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
    if (req.getQueryString() == null || req.getQueryString().isEmpty()) {
        // No query string? They want the project list, which we don't
        // currently support. Return to Gerrit's own web UI.
        // 
        rsp.sendRedirect(req.getContextPath() + "/");
        return;
    }
    final Map<String, String> params = getParameters(req);
    String a = params.get("a");
    if (a != null) {
        if (deniedActions.contains(a)) {
            rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
        if (a.equals(PROJECT_LIST_ACTION)) {
            rsp.sendRedirect(req.getContextPath() + "/#" + PageLinks.ADMIN_PROJECTS + "?filter=" + Url.encode(params.get("pf") + "/"));
            return;
        }
    }
    String name = params.get("p");
    if (name == null) {
        rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    if (name.endsWith(".git")) {
        name = name.substring(0, name.length() - 4);
    }
    Project.NameKey nameKey = Project.nameKey(name);
    Optional<ProjectState> projectState;
    try {
        projectState = projectCache.get(nameKey);
        if (!projectState.isPresent()) {
            sendErrorOrRedirect(req, rsp, HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        projectState.get().checkStatePermitsRead();
        permissionBackend.user(userProvider.get()).project(nameKey).check(ProjectPermission.READ);
    } catch (AuthException e) {
        sendErrorOrRedirect(req, rsp, HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (IOException | PermissionBackendException err) {
        logger.atSevere().withCause(err).log("cannot load %s", name);
        rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    } catch (ResourceConflictException e) {
        sendErrorOrRedirect(req, rsp, HttpServletResponse.SC_CONFLICT);
        return;
    }
    try (Repository repo = repoManager.openRepository(nameKey)) {
        CacheHeaders.setNotCacheable(rsp);
        exec(req, rsp, projectState.get());
    } catch (RepositoryNotFoundException e) {
        getServletContext().log("Cannot open repository", e);
        rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
Also used : AuthException(com.google.gerrit.extensions.restapi.AuthException) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) IOException(java.io.IOException) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) Project(com.google.gerrit.entities.Project) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Repository(org.eclipse.jgit.lib.Repository) ProjectState(com.google.gerrit.server.project.ProjectState)

Example 92 with Project

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

the class ConsistencyChecker method openRepo.

private boolean openRepo() {
    Project.NameKey project = change().getDest().project();
    try {
        repo = repoManager.openRepository(project);
        oi = repo.newObjectInserter();
        rw = new RevWalk(oi.newReader());
        return true;
    } catch (RepositoryNotFoundException e) {
        ProblemInfo problem = problem("Destination repository not found: " + project);
        logger.atWarning().withCause(e).log("Error in consistency check of change %s: %s", notes.getChangeId(), problem);
        return false;
    } catch (IOException e) {
        ProblemInfo problem = problem("Failed to open repository: " + project);
        logger.atWarning().withCause(e).log("Error in consistency check of change %s: %s", notes.getChangeId(), problem);
        return false;
    }
}
Also used : Project(com.google.gerrit.entities.Project) ProblemInfo(com.google.gerrit.extensions.common.ProblemInfo) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk)

Example 93 with Project

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

the class CommentContextLoader method getContext.

/**
 * Load the comment context for multiple contextInputs at once. This method will open the
 * repository and read the source files for all necessary contextInputs' file paths.
 *
 * @param contextInputs a list of contextInputs.
 * @return a Map where all entries consist of the input contextInputs and the values are their
 *     corresponding {@link CommentContext}.
 */
public Map<ContextInput, CommentContext> getContext(Collection<ContextInput> contextInputs) throws IOException {
    ImmutableMap.Builder<ContextInput, CommentContext> result = ImmutableMap.builderWithExpectedSize(Iterables.size(contextInputs));
    // Group contextInputs by commit ID so that each commit is parsed only once
    Map<ObjectId, List<ContextInput>> commentsByCommitId = contextInputs.stream().collect(groupingBy(ContextInput::commitId));
    try (Repository repo = repoManager.openRepository(project);
        RevWalk rw = new RevWalk(repo)) {
        for (ObjectId commitId : commentsByCommitId.keySet()) {
            RevCommit commit;
            try {
                commit = rw.parseCommit(commitId);
            } catch (IncorrectObjectTypeException | MissingObjectException e) {
                logger.atWarning().log("Commit %s is missing or has an incorrect object type", commitId);
                commentsByCommitId.get(commitId).forEach(contextInput -> result.put(contextInput, CommentContext.empty()));
                continue;
            }
            for (ContextInput contextInput : commentsByCommitId.get(commitId)) {
                Optional<Range> range = getStartAndEndLines(contextInput);
                if (!range.isPresent()) {
                    result.put(contextInput, CommentContext.empty());
                    continue;
                }
                String filePath = contextInput.filePath();
                switch(filePath) {
                    case COMMIT_MSG:
                        result.put(contextInput, getContextForCommitMessage(rw.getObjectReader(), commit, range.get(), contextInput.contextPadding()));
                        break;
                    case MERGE_LIST:
                        result.put(contextInput, getContextForMergeList(rw.getObjectReader(), commit, range.get(), contextInput.contextPadding()));
                        break;
                    default:
                        result.put(contextInput, getContextForFilePath(repo, rw, commit, filePath, range.get(), contextInput.contextPadding()));
                }
            }
        }
        return result.build();
    }
}
Also used : Iterables(com.google.common.collect.Iterables) ComparisonType(com.google.gerrit.server.patch.ComparisonType) RevCommit(org.eclipse.jgit.revwalk.RevCommit) ProjectCache(com.google.gerrit.server.project.ProjectCache) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) SrcContentResolver(com.google.gerrit.server.patch.SrcContentResolver) Inject(com.google.inject.Inject) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) MERGE_LIST(com.google.gerrit.entities.Patch.MERGE_LIST) Comment(com.google.gerrit.entities.Comment) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) MimeType(eu.medsea.mimeutil.MimeType) Assisted(com.google.inject.assistedinject.Assisted) RevWalk(org.eclipse.jgit.revwalk.RevWalk) PatchScript(com.google.gerrit.common.data.PatchScript) ContextLineInfo(com.google.gerrit.extensions.common.ContextLineInfo) FileContentUtil(com.google.gerrit.server.change.FileContentUtil) Map(java.util.Map) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) ImmutableMap(com.google.common.collect.ImmutableMap) Text(com.google.gerrit.server.patch.Text) Collection(java.util.Collection) FileTypeRegistry(com.google.gerrit.server.mime.FileTypeRegistry) ProjectState(com.google.gerrit.server.project.ProjectState) IOException(java.io.IOException) CommentContext(com.google.gerrit.entities.CommentContext) COMMIT_MSG(com.google.gerrit.entities.Patch.COMMIT_MSG) ObjectId(org.eclipse.jgit.lib.ObjectId) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) AutoValue(com.google.auto.value.AutoValue) Project(com.google.gerrit.entities.Project) Optional(java.util.Optional) MimeUtil2(eu.medsea.mimeutil.MimeUtil2) ObjectReader(org.eclipse.jgit.lib.ObjectReader) FluentLogger(com.google.common.flogger.FluentLogger) Repository(org.eclipse.jgit.lib.Repository) ObjectId(org.eclipse.jgit.lib.ObjectId) CommentContext(com.google.gerrit.entities.CommentContext) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ImmutableMap(com.google.common.collect.ImmutableMap) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) Repository(org.eclipse.jgit.lib.Repository) List(java.util.List) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 94 with Project

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

the class RevisionJson method toRevisionInfo.

private RevisionInfo toRevisionInfo(AccountLoader accountLoader, ChangeData cd, PatchSet in, @Nullable Repository repo, @Nullable RevWalk rw, boolean fillCommit, @Nullable ChangeInfo changeInfo) throws PatchListNotAvailableException, GpgException, IOException, PermissionBackendException {
    Change c = cd.change();
    RevisionInfo out = new RevisionInfo();
    out.isCurrent = in.id().equals(c.currentPatchSetId());
    out._number = in.id().get();
    out.ref = in.refName();
    out.setCreated(in.createdOn());
    out.uploader = accountLoader.get(in.uploader());
    out.fetch = makeFetchMap(cd, in);
    out.kind = changeKindCache.getChangeKind(rw, repo != null ? repo.getConfig() : null, cd, in);
    out.description = in.description().orElse(null);
    boolean setCommit = has(ALL_COMMITS) || (out.isCurrent && has(CURRENT_COMMIT));
    boolean addFooters = out.isCurrent && has(COMMIT_FOOTERS);
    if (setCommit || addFooters) {
        checkState(rw != null);
        checkState(repo != null);
        Project.NameKey project = c.getProject();
        String rev = in.commitId().name();
        RevCommit commit = rw.parseCommit(ObjectId.fromString(rev));
        rw.parseBody(commit);
        String branchName = cd.change().getDest().branch();
        if (setCommit) {
            out.commit = getCommitInfo(project, rw, commit, has(WEB_LINKS), fillCommit, branchName);
        }
        if (addFooters) {
            Ref ref = repo.exactRef(branchName);
            RevCommit mergeTip = null;
            if (ref != null) {
                mergeTip = rw.parseCommit(ref.getObjectId());
                rw.parseBody(mergeTip);
            }
            out.commitWithFooters = mergeUtilFactory.create(projectCache.get(project).orElseThrow(illegalState(project))).createCommitMessageOnSubmit(commit, mergeTip, cd.notes(), in.id());
        }
    }
    if (has(ALL_FILES) || (out.isCurrent && has(CURRENT_FILES))) {
        try {
            out.files = fileInfoJson.getFileInfoMap(c, in);
            out.files.remove(Patch.COMMIT_MSG);
            out.files.remove(Patch.MERGE_LIST);
        } catch (ResourceConflictException e) {
            logger.atWarning().withCause(e).log("creating file list failed");
        }
    }
    if (out.isCurrent && has(CURRENT_ACTIONS) && userProvider.get().isIdentifiedUser()) {
        actionJson.addRevisionActions(changeInfo, out, new RevisionResource(changeResourceFactory.create(cd, userProvider.get()), in));
    }
    if (gpgApi.isEnabled() && has(PUSH_CERTIFICATES)) {
        if (in.pushCertificate().isPresent()) {
            out.pushCertificate = gpgApi.checkPushCertificate(in.pushCertificate().get(), userFactory.create(in.uploader()));
        } else {
            out.pushCertificate = new PushCertificateInfo();
        }
    }
    return out;
}
Also used : Project(com.google.gerrit.entities.Project) Ref(org.eclipse.jgit.lib.Ref) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) RevisionInfo(com.google.gerrit.extensions.common.RevisionInfo) Change(com.google.gerrit.entities.Change) PushCertificateInfo(com.google.gerrit.extensions.common.PushCertificateInfo) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 95 with Project

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

the class AllProjectsIndexer method reindexProjects.

private SiteIndexer.Result reindexProjects(ProjectIndex index, List<Project.NameKey> names, ProgressMonitor progress) {
    progress.beginTask("Reindexing projects", names.size());
    List<ListenableFuture<?>> futures = new ArrayList<>(names.size());
    AtomicBoolean ok = new AtomicBoolean(true);
    AtomicInteger done = new AtomicInteger();
    AtomicInteger failed = new AtomicInteger();
    Stopwatch sw = Stopwatch.createStarted();
    for (Project.NameKey name : names) {
        String desc = "project " + name;
        ListenableFuture<?> future = executor.submit(() -> {
            try {
                projectCache.evict(name);
                ProjectData projectData = projectCache.get(name).orElseThrow(illegalState(name)).toProjectData();
                if (isFirstInsertForEntry.equals(IsFirstInsertForEntry.YES)) {
                    index.insert(projectData);
                } else {
                    index.replace(projectData);
                }
                verboseWriter.println("Reindexed " + desc);
                done.incrementAndGet();
            } catch (Exception e) {
                failed.incrementAndGet();
                throw e;
            }
            return null;
        });
        addErrorListener(future, desc, progress, ok);
        futures.add(future);
    }
    try {
        Futures.successfulAsList(futures).get();
    } catch (ExecutionException | InterruptedException e) {
        logger.atSevere().withCause(e).log("Error waiting on project futures");
        return SiteIndexer.Result.create(sw, false, 0, 0);
    }
    progress.endTask();
    return SiteIndexer.Result.create(sw, ok.get(), done.get(), failed.get());
}
Also used : ArrayList(java.util.ArrayList) Stopwatch(com.google.common.base.Stopwatch) ExecutionException(java.util.concurrent.ExecutionException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Project(com.google.gerrit.entities.Project) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ExecutionException(java.util.concurrent.ExecutionException) ProjectData(com.google.gerrit.index.project.ProjectData)

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