Search in sources :

Example 86 with Repository

use of org.eclipse.jgit.lib.Repository in project gerrit by GerritCodeReview.

the class CheckMergeability method apply.

@Override
public MergeableInfo apply(BranchResource resource) throws IOException, BadRequestException, ResourceNotFoundException {
    if (!(submitType.equals(SubmitType.MERGE_ALWAYS) || submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
        throw new BadRequestException("Submit type: " + submitType + " is not supported");
    }
    MergeableInfo result = new MergeableInfo();
    result.submitType = submitType;
    result.strategy = strategy;
    try (Repository git = gitManager.openRepository(resource.getNameKey());
        RevWalk rw = new RevWalk(git);
        ObjectInserter inserter = new InMemoryInserter(git)) {
        Merger m = MergeUtil.newMerger(inserter, git.getConfig(), strategy);
        Ref destRef = git.getRefDatabase().exactRef(resource.getRef());
        if (destRef == null) {
            throw new ResourceNotFoundException(resource.getRef());
        }
        RevCommit targetCommit = rw.parseCommit(destRef.getObjectId());
        RevCommit sourceCommit = MergeUtil.resolveCommit(git, rw, source);
        if (!resource.getControl().canReadCommit(db.get(), git, sourceCommit)) {
            throw new BadRequestException("do not have read permission for: " + source);
        }
        if (rw.isMergedInto(sourceCommit, targetCommit)) {
            result.mergeable = true;
            result.commitMerged = true;
            result.contentMerged = true;
            return result;
        }
        if (m.merge(false, targetCommit, sourceCommit)) {
            result.mergeable = true;
            result.commitMerged = false;
            result.contentMerged = m.getResultTreeId().equals(targetCommit.getTree());
        } else {
            result.mergeable = false;
            if (m instanceof ResolveMerger) {
                result.conflicts = ((ResolveMerger) m).getUnmergedPaths();
            }
        }
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage());
    }
    return result;
}
Also used : Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) Merger(org.eclipse.jgit.merge.Merger) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) MergeableInfo(com.google.gerrit.extensions.common.MergeableInfo) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) InMemoryInserter(com.google.gerrit.server.git.InMemoryInserter) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 87 with Repository

use of org.eclipse.jgit.lib.Repository in project gerrit by GerritCodeReview.

the class CreateBranch method apply.

@Override
public BranchInfo apply(ProjectResource rsrc, BranchInput input) throws BadRequestException, AuthException, ResourceConflictException, IOException {
    if (input == null) {
        input = new BranchInput();
    }
    if (input.ref != null && !ref.equals(input.ref)) {
        throw new BadRequestException("ref must match URL");
    }
    if (input.revision == null) {
        input.revision = Constants.HEAD;
    }
    while (ref.startsWith("/")) {
        ref = ref.substring(1);
    }
    ref = RefNames.fullName(ref);
    if (!Repository.isValidRefName(ref)) {
        throw new BadRequestException("invalid branch name \"" + ref + "\"");
    }
    if (MagicBranch.isMagicBranch(ref)) {
        throw new BadRequestException("not allowed to create branches under \"" + MagicBranch.getMagicRefNamePrefix(ref) + "\"");
    }
    final Branch.NameKey name = new Branch.NameKey(rsrc.getNameKey(), ref);
    final RefControl refControl = rsrc.getControl().controlForRef(name);
    try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
        ObjectId revid = RefUtil.parseBaseRevision(repo, rsrc.getNameKey(), input.revision);
        RevWalk rw = RefUtil.verifyConnected(repo, revid);
        RevObject object = rw.parseAny(revid);
        if (ref.startsWith(Constants.R_HEADS)) {
            //
            try {
                object = rw.parseCommit(object);
            } catch (IncorrectObjectTypeException notCommit) {
                throw new BadRequestException("\"" + input.revision + "\" not a commit");
            }
        }
        if (!refControl.canCreate(db.get(), repo, object)) {
            throw new AuthException("Cannot create \"" + ref + "\"");
        }
        try {
            final RefUpdate u = repo.updateRef(ref);
            u.setExpectedOldObjectId(ObjectId.zeroId());
            u.setNewObjectId(object.copy());
            u.setRefLogIdent(identifiedUser.get().newRefLogIdent());
            u.setRefLogMessage("created via REST from " + input.revision, false);
            refCreationValidator.validateRefOperation(rsrc.getName(), identifiedUser.get(), u);
            final RefUpdate.Result result = u.update(rw);
            switch(result) {
                case FAST_FORWARD:
                case NEW:
                case NO_CHANGE:
                    referenceUpdated.fire(name.getParentKey(), u, ReceiveCommand.Type.CREATE, identifiedUser.get().getAccount());
                    break;
                case LOCK_FAILURE:
                    if (repo.getRefDatabase().exactRef(ref) != null) {
                        throw new ResourceConflictException("branch \"" + ref + "\" already exists");
                    }
                    String refPrefix = RefUtil.getRefPrefix(ref);
                    while (!Constants.R_HEADS.equals(refPrefix)) {
                        if (repo.getRefDatabase().exactRef(refPrefix) != null) {
                            throw new ResourceConflictException("Cannot create branch \"" + ref + "\" since it conflicts with branch \"" + refPrefix + "\".");
                        }
                        refPrefix = RefUtil.getRefPrefix(refPrefix);
                    }
                //$FALL-THROUGH$
                case FORCED:
                case IO_FAILURE:
                case NOT_ATTEMPTED:
                case REJECTED:
                case REJECTED_CURRENT_BRANCH:
                case RENAMED:
                default:
                    {
                        throw new IOException(result.name());
                    }
            }
            BranchInfo info = new BranchInfo();
            info.ref = ref;
            info.revision = revid.getName();
            info.canDelete = permissionBackend.user(identifiedUser).ref(name).testOrFalse(RefPermission.DELETE) ? true : null;
            return info;
        } catch (IOException err) {
            log.error("Cannot create branch \"" + name + "\"", err);
            throw err;
        }
    } catch (RefUtil.InvalidRevisionException e) {
        throw new BadRequestException("invalid revision \"" + input.revision + "\"");
    }
}
Also used : BranchInfo(com.google.gerrit.extensions.api.projects.BranchInfo) ObjectId(org.eclipse.jgit.lib.ObjectId) RevObject(org.eclipse.jgit.revwalk.RevObject) AuthException(com.google.gerrit.extensions.restapi.AuthException) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MagicBranch(com.google.gerrit.server.util.MagicBranch) Branch(com.google.gerrit.reviewdb.client.Branch) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) BranchInput(com.google.gerrit.extensions.api.projects.BranchInput) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 88 with Repository

use of org.eclipse.jgit.lib.Repository in project gerrit by GerritCodeReview.

the class GetReflog method apply.

@Override
public List<ReflogEntryInfo> apply(BranchResource rsrc) throws AuthException, ResourceNotFoundException, RepositoryNotFoundException, IOException {
    if (!rsrc.getControl().isOwner()) {
        throw new AuthException("not project owner");
    }
    try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
        ReflogReader r = repo.getReflogReader(rsrc.getRef());
        if (r == null) {
            throw new ResourceNotFoundException(rsrc.getRef());
        }
        List<ReflogEntry> entries;
        if (from == null && to == null) {
            entries = limit > 0 ? r.getReverseEntries(limit) : r.getReverseEntries();
        } else {
            entries = limit > 0 ? new ArrayList<>(limit) : new ArrayList<>();
            for (ReflogEntry e : r.getReverseEntries()) {
                Timestamp timestamp = new Timestamp(e.getWho().getWhen().getTime());
                if ((from == null || from.before(timestamp)) && (to == null || to.after(timestamp))) {
                    entries.add(e);
                }
                if (limit > 0 && entries.size() >= limit) {
                    break;
                }
            }
        }
        return Lists.transform(entries, ReflogEntryInfo::new);
    }
}
Also used : Repository(org.eclipse.jgit.lib.Repository) ReflogReader(org.eclipse.jgit.lib.ReflogReader) ReflogEntry(org.eclipse.jgit.lib.ReflogEntry) ArrayList(java.util.ArrayList) AuthException(com.google.gerrit.extensions.restapi.AuthException) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) Timestamp(java.sql.Timestamp)

Example 89 with Repository

use of org.eclipse.jgit.lib.Repository 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 90 with Repository

use of org.eclipse.jgit.lib.Repository 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)

Aggregations

Repository (org.eclipse.jgit.lib.Repository)326 IOException (java.io.IOException)103 RevWalk (org.eclipse.jgit.revwalk.RevWalk)102 Test (org.junit.Test)81 RevCommit (org.eclipse.jgit.revwalk.RevCommit)76 ObjectId (org.eclipse.jgit.lib.ObjectId)72 File (java.io.File)43 TestRepository (org.eclipse.jgit.junit.TestRepository)40 Change (com.google.gerrit.reviewdb.client.Change)39 OrmException (com.google.gwtorm.server.OrmException)39 Ref (org.eclipse.jgit.lib.Ref)35 Project (com.google.gerrit.reviewdb.client.Project)32 ArrayList (java.util.ArrayList)31 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)27 InMemoryRepository (org.eclipse.jgit.internal.storage.dfs.InMemoryRepository)26 PatchSet (com.google.gerrit.reviewdb.client.PatchSet)24 Map (java.util.Map)23 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)23 RepositoryModel (com.gitblit.models.RepositoryModel)20 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)20