Search in sources :

Example 6 with RepositoryNotFoundException

use of org.eclipse.jgit.errors.RepositoryNotFoundException in project gerrit by GerritCodeReview.

the class GetAccess method apply.

@Override
public ProjectAccessInfo apply(ProjectResource rsrc) throws ResourceNotFoundException, ResourceConflictException, IOException {
    // Load the current configuration from the repository, ensuring it's the most
    // recent version available. If it differs from what was in the project
    // state, force a cache flush now.
    //
    Project.NameKey projectName = rsrc.getNameKey();
    ProjectAccessInfo info = new ProjectAccessInfo();
    ProjectConfig config;
    ProjectControl pc = createProjectControl(projectName);
    RefControl metaConfigControl = pc.controlForRef(RefNames.REFS_CONFIG);
    try (MetaDataUpdate md = metaDataUpdateFactory.create(projectName)) {
        config = ProjectConfig.read(md);
        if (config.updateGroupNames(groupBackend)) {
            md.setMessage("Update group names\n");
            config.commit(md);
            projectCache.evict(config.getProject());
            pc = createProjectControl(projectName);
        } else if (config.getRevision() != null && !config.getRevision().equals(pc.getProjectState().getConfig().getRevision())) {
            projectCache.evict(config.getProject());
            pc = createProjectControl(projectName);
        }
    } catch (ConfigInvalidException e) {
        throw new ResourceConflictException(e.getMessage());
    } catch (RepositoryNotFoundException e) {
        throw new ResourceNotFoundException(rsrc.getName());
    }
    info.local = new HashMap<>();
    info.ownerOf = new HashSet<>();
    Map<AccountGroup.UUID, Boolean> visibleGroups = new HashMap<>();
    for (AccessSection section : config.getAccessSections()) {
        String name = section.getName();
        if (AccessSection.GLOBAL_CAPABILITIES.equals(name)) {
            if (pc.isOwner()) {
                info.local.put(name, createAccessSection(section));
                info.ownerOf.add(name);
            } else if (metaConfigControl.isVisible()) {
                info.local.put(section.getName(), createAccessSection(section));
            }
        } else if (RefConfigSection.isValid(name)) {
            RefControl rc = pc.controlForRef(name);
            if (rc.isOwner()) {
                info.local.put(name, createAccessSection(section));
                info.ownerOf.add(name);
            } else if (metaConfigControl.isVisible()) {
                info.local.put(name, createAccessSection(section));
            } else if (rc.isVisible()) {
                // Filter the section to only add rules describing groups that
                // are visible to the current-user. This includes any group the
                // user is a member of, as well as groups they own or that
                // are visible to all users.
                AccessSection dst = null;
                for (Permission srcPerm : section.getPermissions()) {
                    Permission dstPerm = null;
                    for (PermissionRule srcRule : srcPerm.getRules()) {
                        AccountGroup.UUID group = srcRule.getGroup().getUUID();
                        if (group == null) {
                            continue;
                        }
                        Boolean canSeeGroup = visibleGroups.get(group);
                        if (canSeeGroup == null) {
                            try {
                                canSeeGroup = groupControlFactory.controlFor(group).isVisible();
                            } catch (NoSuchGroupException e) {
                                canSeeGroup = Boolean.FALSE;
                            }
                            visibleGroups.put(group, canSeeGroup);
                        }
                        if (canSeeGroup) {
                            if (dstPerm == null) {
                                if (dst == null) {
                                    dst = new AccessSection(name);
                                    info.local.put(name, createAccessSection(dst));
                                }
                                dstPerm = dst.getPermission(srcPerm.getName(), true);
                            }
                            dstPerm.add(srcRule);
                        }
                    }
                }
            }
        }
    }
    if (info.ownerOf.isEmpty() && pc.isOwnerAnyRef()) {
        // Special case: If the section list is empty, this project has no current
        // access control information. Rely on what ProjectControl determines
        // is ownership, which probably means falling back to site administrators.
        info.ownerOf.add(AccessSection.ALL);
    }
    if (config.getRevision() != null) {
        info.revision = config.getRevision().name();
    }
    ProjectState parent = Iterables.getFirst(pc.getProjectState().parents(), null);
    if (parent != null) {
        info.inheritsFrom = projectJson.format(parent.getProject());
    }
    if (pc.getProject().getNameKey().equals(allProjectsName)) {
        if (pc.isOwner()) {
            info.ownerOf.add(AccessSection.GLOBAL_CAPABILITIES);
        }
    }
    info.isOwner = toBoolean(pc.isOwner());
    info.canUpload = toBoolean(pc.isOwner() || (metaConfigControl.isVisible() && metaConfigControl.canUpload()));
    info.canAdd = toBoolean(pc.canAddRefs());
    info.configVisible = pc.isOwner() || metaConfigControl.isVisible();
    return info;
}
Also used : ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) HashMap(java.util.HashMap) PermissionRule(com.google.gerrit.common.data.PermissionRule) ProjectAccessInfo(com.google.gerrit.extensions.api.access.ProjectAccessInfo) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) AccessSection(com.google.gerrit.common.data.AccessSection) NoSuchGroupException(com.google.gerrit.common.errors.NoSuchGroupException) ProjectConfig(com.google.gerrit.server.git.ProjectConfig) Project(com.google.gerrit.reviewdb.client.Project) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Permission(com.google.gerrit.common.data.Permission) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) MetaDataUpdate(com.google.gerrit.server.git.MetaDataUpdate)

Example 7 with RepositoryNotFoundException

use of org.eclipse.jgit.errors.RepositoryNotFoundException in project gerrit by GerritCodeReview.

the class ListBranches method allBranches.

private List<BranchInfo> allBranches(ProjectResource rsrc) throws IOException, ResourceNotFoundException {
    List<Ref> refs;
    try (Repository db = repoManager.openRepository(rsrc.getNameKey())) {
        Collection<Ref> heads = db.getRefDatabase().getRefs(Constants.R_HEADS).values();
        refs = new ArrayList<>(heads.size() + 3);
        refs.addAll(heads);
        refs.addAll(db.getRefDatabase().exactRef(Constants.HEAD, RefNames.REFS_CONFIG, RefNames.REFS_USERS_DEFAULT).values());
    } catch (RepositoryNotFoundException noGitRepository) {
        throw new ResourceNotFoundException();
    }
    Set<String> targets = Sets.newHashSetWithExpectedSize(1);
    for (Ref ref : refs) {
        if (ref.isSymbolic()) {
            targets.add(ref.getTarget().getName());
        }
    }
    ProjectControl pctl = rsrc.getControl();
    PermissionBackend.ForProject perm = permissionBackend.user(user).project(rsrc.getNameKey());
    List<BranchInfo> branches = new ArrayList<>(refs.size());
    for (Ref ref : refs) {
        if (ref.isSymbolic()) {
            // A symbolic reference to another branch, instead of
            // showing the resolved value, show the name it references.
            //
            String target = ref.getTarget().getName();
            RefControl targetRefControl = pctl.controlForRef(target);
            if (!targetRefControl.isVisible()) {
                continue;
            }
            if (target.startsWith(Constants.R_HEADS)) {
                target = target.substring(Constants.R_HEADS.length());
            }
            BranchInfo b = new BranchInfo();
            b.ref = ref.getName();
            b.revision = target;
            branches.add(b);
            if (!Constants.HEAD.equals(ref.getName())) {
                b.canDelete = perm.ref(ref.getName()).testOrFalse(RefPermission.DELETE) ? true : null;
            }
            continue;
        }
        if (pctl.controlForRef(ref.getName()).isVisible()) {
            branches.add(createBranchInfo(perm.ref(ref.getName()), ref, pctl, targets));
        }
    }
    Collections.sort(branches, new BranchComparator());
    return branches;
}
Also used : BranchInfo(com.google.gerrit.extensions.api.projects.BranchInfo) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ArrayList(java.util.ArrayList) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) Ref(org.eclipse.jgit.lib.Ref) Repository(org.eclipse.jgit.lib.Repository) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Example 8 with RepositoryNotFoundException

use of org.eclipse.jgit.errors.RepositoryNotFoundException in project gerrit by GerritCodeReview.

the class ListProjects method display.

public SortedMap<String, ProjectInfo> display(@Nullable OutputStream displayOutputStream) throws BadRequestException, PermissionBackendException {
    if (groupUuid != null) {
        try {
            if (!groupControlFactory.controlFor(groupUuid).isVisible()) {
                return Collections.emptySortedMap();
            }
        } catch (NoSuchGroupException ex) {
            return Collections.emptySortedMap();
        }
    }
    PrintWriter stdout = null;
    if (displayOutputStream != null) {
        stdout = new PrintWriter(new BufferedWriter(new OutputStreamWriter(displayOutputStream, UTF_8)));
    }
    if (type == FilterType.PARENT_CANDIDATES) {
        // Historically, PARENT_CANDIDATES implied showDescription.
        showDescription = true;
    }
    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 {
        for (final Project.NameKey projectName : filter(perm)) {
            final ProjectState e = projectCache.get(projectName);
            if (e == null || (!all && e.getProject().getState() == HIDDEN)) {
                // If all wasn't selected, and its HIDDEN, pretend its not present.
                continue;
            }
            final ProjectControl pctl = e.controlFor(currentUser);
            if (groupUuid != null && !pctl.getLocalGroups().contains(GroupReference.forGroup(groupsCollection.parseId(groupUuid.get())))) {
                continue;
            }
            ProjectInfo info = new ProjectInfo();
            if (showTree && !format.isJson()) {
                treeMap.put(projectName, projectNodeFactory.create(pctl.getProject(), true));
                continue;
            }
            info.name = projectName.get();
            if (showTree && format.isJson()) {
                ProjectState parent = Iterables.getFirst(e.parents(), null);
                if (parent != null) {
                    if (isParentAccessible(accessibleParents, perm, parent)) {
                        info.parent = parent.getProject().getName();
                    } else {
                        info.parent = hiddenNames.get(parent.getProject().getName());
                        if (info.parent == null) {
                            info.parent = "?-" + (hiddenNames.size() + 1);
                            hiddenNames.put(parent.getProject().getName(), info.parent);
                        }
                    }
                }
            }
            if (showDescription) {
                info.description = Strings.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 = getBranchRefs(projectName, pctl);
                        if (!hasValidRef(refs)) {
                            continue;
                        }
                        for (int i = 0; i < showBranch.size(); i++) {
                            Ref ref = refs.get(i);
                            if (ref != null && ref.getObjectId() != null) {
                                if (info.branches == null) {
                                    info.branches = new LinkedHashMap<>();
                                }
                                info.branches.put(showBranch.get(i), ref.getObjectId().name());
                            }
                        }
                    }
                } 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) {
                log.warn("Unexpected error reading " + projectName, err);
                continue;
            }
            if (type != FilterType.PARENT_CANDIDATES) {
                List<WebLinkInfo> links = webLinks.getProjectLinks(projectName.get());
                info.webLinks = links.isEmpty() ? null : links;
            }
            if (foundIndex++ < start) {
                continue;
            }
            if (limit > 0 && ++found > limit) {
                break;
            }
            if (stdout == null || format.isJson()) {
                output.put(info.name, info);
                continue;
            }
            if (!showBranch.isEmpty()) {
                for (String name : showBranch) {
                    String ref = info.branches != null ? info.branches.get(name) : null;
                    if (ref == null) {
                        // Print stub (forty '-' symbols)
                        ref = "----------------------------------------";
                    }
                    stdout.print(ref);
                    stdout.print(' ');
                }
            }
            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.common.errors.NoSuchGroupException) BufferedWriter(java.io.BufferedWriter) ProjectInfo(com.google.gerrit.extensions.common.ProjectInfo) PrintWriter(java.io.PrintWriter) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) IOException(java.io.IOException) TreeMap(java.util.TreeMap) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) WebLinkInfo(com.google.gerrit.extensions.common.WebLinkInfo) OutputStreamWriter(java.io.OutputStreamWriter) Map(java.util.Map) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap)

Example 9 with RepositoryNotFoundException

use of org.eclipse.jgit.errors.RepositoryNotFoundException in project gerrit by GerritCodeReview.

the class ProjectCacheImpl method checkedGet.

@Override
public ProjectState checkedGet(Project.NameKey projectName) throws IOException {
    if (projectName == null) {
        return null;
    }
    try {
        ProjectState state = byName.get(projectName.get());
        if (state != null && state.needsRefresh(clock.read())) {
            byName.invalidate(projectName.get());
            state = byName.get(projectName.get());
        }
        return state;
    } catch (ExecutionException e) {
        if (!(e.getCause() instanceof RepositoryNotFoundException)) {
            log.warn(String.format("Cannot read project %s", projectName.get()), e);
            Throwables.throwIfInstanceOf(e.getCause(), IOException.class);
            throw new IOException(e);
        }
        return null;
    }
}
Also used : RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Example 10 with RepositoryNotFoundException

use of org.eclipse.jgit.errors.RepositoryNotFoundException in project gerrit by GerritCodeReview.

the class PutDescription method apply.

@Override
public Response<String> apply(ProjectResource resource, DescriptionInput input) throws AuthException, ResourceConflictException, ResourceNotFoundException, IOException {
    if (input == null) {
        // Delete would set description to null.
        input = new DescriptionInput();
    }
    ProjectControl ctl = resource.getControl();
    IdentifiedUser user = ctl.getUser().asIdentifiedUser();
    if (!ctl.isOwner()) {
        throw new AuthException("not project owner");
    }
    try (MetaDataUpdate md = updateFactory.create(resource.getNameKey())) {
        ProjectConfig config = ProjectConfig.read(md);
        Project project = config.getProject();
        project.setDescription(Strings.emptyToNull(input.description));
        String msg = MoreObjects.firstNonNull(Strings.emptyToNull(input.commitMessage), "Updated description.\n");
        if (!msg.endsWith("\n")) {
            msg += "\n";
        }
        md.setAuthor(user);
        md.setMessage(msg);
        config.commit(md);
        cache.evict(ctl.getProject());
        md.getRepository().setGitwebDescription(project.getDescription());
        return Strings.isNullOrEmpty(project.getDescription()) ? Response.<String>none() : Response.ok(project.getDescription());
    } catch (RepositoryNotFoundException notFound) {
        throw new ResourceNotFoundException(resource.getName());
    } catch (ConfigInvalidException e) {
        throw new ResourceConflictException(String.format("invalid project.config: %s", e.getMessage()));
    }
}
Also used : ProjectConfig(com.google.gerrit.server.git.ProjectConfig) Project(com.google.gerrit.reviewdb.client.Project) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) DescriptionInput(com.google.gerrit.extensions.api.projects.DescriptionInput) AuthException(com.google.gerrit.extensions.restapi.AuthException) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) MetaDataUpdate(com.google.gerrit.server.git.MetaDataUpdate)

Aggregations

RepositoryNotFoundException (org.eclipse.jgit.errors.RepositoryNotFoundException)36 Repository (org.eclipse.jgit.lib.Repository)20 IOException (java.io.IOException)17 Project (com.google.gerrit.reviewdb.client.Project)14 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)11 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)9 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)8 MetaDataUpdate (com.google.gerrit.server.git.MetaDataUpdate)7 ProjectConfig (com.google.gerrit.server.git.ProjectConfig)7 AuthException (com.google.gerrit.extensions.restapi.AuthException)5 Change (com.google.gerrit.reviewdb.client.Change)5 Ref (org.eclipse.jgit.lib.Ref)5 RevWalk (org.eclipse.jgit.revwalk.RevWalk)5 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)4 PatchSet (com.google.gerrit.reviewdb.client.PatchSet)4 NoSuchChangeException (com.google.gerrit.server.project.NoSuchChangeException)4 File (java.io.File)4 ObjectId (org.eclipse.jgit.lib.ObjectId)4 ProjectControl (com.google.gerrit.server.project.ProjectControl)3 ArrayList (java.util.ArrayList)3