Search in sources :

Example 41 with ConfigInvalidException

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

the class ChangeNotesParser method parseCopiedApproval.

/**
 * Parses copied {@link PatchSetApproval}.
 */
private void parseCopiedApproval(PatchSet.Id psId, Instant ts, String line) throws ConfigInvalidException {
    ParsedPatchSetApproval parsedPatchSetApproval = ChangeNoteUtil.parseCopiedApproval(line);
    checkFooter(parsedPatchSetApproval.accountIdent().isPresent(), FOOTER_COPIED_LABEL, parsedPatchSetApproval.footerLine());
    PersonIdent accountIdent = RawParseUtils.parsePersonIdent(parsedPatchSetApproval.accountIdent().get());
    checkFooter(accountIdent != null, FOOTER_COPIED_LABEL, parsedPatchSetApproval.footerLine());
    Account.Id accountId = parseIdent(accountIdent);
    Account.Id realAccountId = null;
    if (parsedPatchSetApproval.realAccountIdent().isPresent()) {
        PersonIdent realIdent = RawParseUtils.parsePersonIdent(parsedPatchSetApproval.realAccountIdent().get());
        checkFooter(realIdent != null, FOOTER_COPIED_LABEL, parsedPatchSetApproval.footerLine());
        realAccountId = parseIdent(realIdent);
    }
    LabelVote l;
    try {
        l = LabelVote.parseWithEquals(parsedPatchSetApproval.labelVote());
    } catch (IllegalArgumentException e) {
        ConfigInvalidException pe = parseException("invalid %s: %s", FOOTER_COPIED_LABEL, parsedPatchSetApproval.footerLine());
        pe.initCause(e);
        throw pe;
    }
    PatchSetApproval.Builder psa = PatchSetApproval.builder().key(PatchSetApproval.key(psId, accountId, LabelId.create(l.label()))).uuid(parsedPatchSetApproval.uuid().map(PatchSetApproval::uuid)).value(l.value()).granted(ts).tag(parsedPatchSetApproval.tag()).copied(true);
    if (realAccountId != null) {
        psa.realAccountId(realAccountId);
    }
    approvals.putIfAbsent(psa.key(), psa);
    bufferedApprovals.add(psa);
}
Also used : Account(com.google.gerrit.entities.Account) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) PersonIdent(org.eclipse.jgit.lib.PersonIdent) LabelVote(com.google.gerrit.server.util.LabelVote) ParsedPatchSetApproval(com.google.gerrit.server.notedb.ChangeNoteUtil.ParsedPatchSetApproval) PatchSetApproval(com.google.gerrit.entities.PatchSetApproval) ParsedPatchSetApproval(com.google.gerrit.server.notedb.ChangeNoteUtil.ParsedPatchSetApproval)

Example 42 with ConfigInvalidException

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

the class ChangeUpdate method applyImpl.

@Override
protected CommitBuilder applyImpl(RevWalk rw, ObjectInserter ins, ObjectId curr) throws IOException {
    checkState(deleteCommentRewriter == null && deleteChangeMessageRewriter == null, "cannot update and rewrite ref in one BatchUpdate");
    PatchSet.Id patchSetId = psId != null ? psId : getChange().currentPatchSetId();
    StringBuilder msg = new StringBuilder();
    if (commitSubject != null) {
        msg.append(commitSubject);
    } else {
        msg.append("Update patch set ").append(patchSetId.get());
    }
    msg.append("\n\n");
    if (changeMessage != null) {
        msg.append(changeMessage);
        msg.append("\n\n");
    }
    addPatchSetFooter(msg, patchSetId);
    if (currentPatchSet) {
        addFooter(msg, FOOTER_CURRENT, Boolean.TRUE);
    }
    if (psDescription != null) {
        addFooter(msg, FOOTER_PATCH_SET_DESCRIPTION, psDescription);
    }
    if (changeId != null) {
        addFooter(msg, FOOTER_CHANGE_ID, changeId);
    }
    if (subject != null) {
        addFooter(msg, FOOTER_SUBJECT, subject);
    }
    if (branch != null) {
        addFooter(msg, FOOTER_BRANCH, branch);
    }
    if (status != null) {
        addFooter(msg, FOOTER_STATUS, status.name().toLowerCase());
        if (status.equals(Change.Status.ABANDONED)) {
            clearAttentionSet("Change was abandoned");
        }
        if (status.equals(Change.Status.MERGED)) {
            clearAttentionSet("Change was submitted");
        }
    }
    if (topic != null) {
        addFooter(msg, FOOTER_TOPIC, topic);
    }
    if (commit != null) {
        addFooter(msg, FOOTER_COMMIT, commit);
    }
    if (assignee != null) {
        if (assignee.isPresent()) {
            addFooter(msg, FOOTER_ASSIGNEE);
            noteUtil.appendAccountIdIdentString(msg, assignee.get()).append('\n');
        } else {
            addFooter(msg, FOOTER_ASSIGNEE).append('\n');
        }
    }
    Joiner comma = Joiner.on(',');
    if (hashtags != null) {
        addFooter(msg, FOOTER_HASHTAGS, comma.join(hashtags));
    }
    if (tag != null) {
        addFooter(msg, FOOTER_TAG, tag);
    }
    if (groups != null) {
        addFooter(msg, FOOTER_GROUPS, comma.join(groups));
    }
    for (Map.Entry<Account.Id, ReviewerStateInternal> e : reviewers.entrySet()) {
        addFooter(msg, e.getValue().getFooterKey());
        noteUtil.appendAccountIdIdentString(msg, e.getKey()).append('\n');
    }
    applyReviewerUpdatesToAttentionSet();
    for (Map.Entry<Address, ReviewerStateInternal> e : reviewersByEmail.entrySet()) {
        addFooter(msg, e.getValue().getByEmailFooterKey(), e.getKey().toString());
    }
    for (Table.Cell<String, Account.Id, Optional<Short>> c : approvals.cellSet()) {
        addLabelFooter(msg, c, patchSetId);
    }
    for (PatchSetApproval patchSetApproval : copiedApprovals) {
        addCopiedLabelFooter(msg, patchSetApproval);
    }
    if (submissionId != null) {
        addFooter(msg, FOOTER_SUBMISSION_ID, submissionId);
    }
    if (submitRecords != null) {
        for (SubmitRecord rec : submitRecords) {
            addFooter(msg, FOOTER_SUBMITTED_WITH).append(rec.status);
            if (rec.errorMessage != null) {
                msg.append(' ').append(sanitizeFooter(rec.errorMessage));
            }
            msg.append('\n');
            if (rec.ruleName != null) {
                addFooter(msg, FOOTER_SUBMITTED_WITH).append("Rule-Name: ").append(rec.ruleName);
                msg.append('\n');
            }
            if (rec.labels != null) {
                for (SubmitRecord.Label label : rec.labels) {
                    // Label names/values are safe to append without sanitizing.
                    addFooter(msg, FOOTER_SUBMITTED_WITH).append(label.status).append(": ").append(label.label);
                    if (label.appliedBy != null) {
                        msg.append(": ");
                        noteUtil.appendAccountIdIdentString(msg, label.appliedBy);
                    }
                    msg.append('\n');
                }
            }
        }
    }
    if (!Objects.equals(accountId, realAccountId)) {
        addFooter(msg, FOOTER_REAL_USER);
        noteUtil.appendAccountIdIdentString(msg, realAccountId).append('\n');
    }
    if (isPrivate != null) {
        addFooter(msg, FOOTER_PRIVATE, isPrivate);
    }
    if (workInProgress != null) {
        addFooter(msg, FOOTER_WORK_IN_PROGRESS, workInProgress);
        if (workInProgress) {
            clearAttentionSet("Change was marked work in progress");
        } else {
            addAllReviewersToAttentionSet();
        }
    }
    if (revertOf != null) {
        addFooter(msg, FOOTER_REVERT_OF, revertOf);
    }
    if (cherryPickOf != null) {
        if (cherryPickOf.isPresent()) {
            addFooter(msg, FOOTER_CHERRY_PICK_OF, cherryPickOf.get());
        } else {
            // Update cherryPickOf with an empty value.
            addFooter(msg, FOOTER_CHERRY_PICK_OF).append('\n');
        }
    }
    updateAttentionSet(msg);
    CommitBuilder cb = new CommitBuilder();
    cb.setMessage(msg.toString());
    try {
        ObjectId treeId = storeRevisionNotes(rw, ins, curr);
        if (treeId != null) {
            cb.setTreeId(treeId);
        }
    } catch (ConfigInvalidException e) {
        throw new StorageException(e);
    }
    return cb;
}
Also used : Joiner(com.google.common.base.Joiner) TreeBasedTable(com.google.common.collect.TreeBasedTable) Table(com.google.common.collect.Table) Address(com.google.gerrit.entities.Address) Optional(java.util.Optional) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ObjectId(org.eclipse.jgit.lib.ObjectId) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) PatchSet(com.google.gerrit.entities.PatchSet) PatchSetApproval(com.google.gerrit.entities.PatchSetApproval) SubmitRecord(com.google.gerrit.entities.SubmitRecord) SubmissionId(com.google.gerrit.entities.SubmissionId) LabelId(com.google.gerrit.entities.LabelId) ObjectId(org.eclipse.jgit.lib.ObjectId) Map(java.util.Map) NoteMap(org.eclipse.jgit.notes.NoteMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) StorageException(com.google.gerrit.exceptions.StorageException)

Example 43 with ConfigInvalidException

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

the class ListGroups method filterGroupsOwnedBy.

private List<GroupInfo> filterGroupsOwnedBy(Predicate<GroupDescription.Internal> filter) throws IOException, ConfigInvalidException, PermissionBackendException {
    Pattern pattern = getRegexPattern();
    Stream<? extends GroupDescription.Internal> foundGroups = loadGroups(groups.getAllGroupReferences().filter(group -> isRelevant(pattern, group)).map(g -> g.getUUID()).collect(toImmutableSet())).stream().filter(this::isVisible).filter(filter).sorted(GROUP_COMPARATOR).skip(start);
    if (limit > 0) {
        foundGroups = foundGroups.limit(limit);
    }
    List<GroupDescription.Internal> ownedGroups = foundGroups.collect(toImmutableList());
    List<GroupInfo> groupInfos = new ArrayList<>(ownedGroups.size());
    for (GroupDescription.Internal group : ownedGroups) {
        groupInfos.add(json.addOptions(options).format(group));
    }
    return groupInfos;
}
Also used : GroupDescription(com.google.gerrit.entities.GroupDescription) InternalGroupDescription(com.google.gerrit.server.group.InternalGroupDescription) GroupBackend(com.google.gerrit.server.account.GroupBackend) GroupResolver(com.google.gerrit.server.group.GroupResolver) Groups(com.google.gerrit.server.group.db.Groups) Inject(com.google.inject.Inject) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) Locale(java.util.Locale) EnumSet(java.util.EnumSet) RestReadView(com.google.gerrit.extensions.restapi.RestReadView) Predicate(java.util.function.Predicate) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Collection(java.util.Collection) Account(com.google.gerrit.entities.Account) Set(java.util.Set) Option(org.kohsuke.args4j.Option) NavigableMap(java.util.NavigableMap) TopLevelResource(com.google.gerrit.extensions.restapi.TopLevelResource) GroupReference(com.google.gerrit.entities.GroupReference) List(java.util.List) Stream(java.util.stream.Stream) Url(com.google.gerrit.extensions.restapi.Url) Pattern(java.util.regex.Pattern) GroupCache(com.google.gerrit.server.account.GroupCache) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ListGroupsOption(com.google.gerrit.extensions.client.ListGroupsOption) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) Response(com.google.gerrit.extensions.restapi.Response) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) Lists(com.google.common.collect.Lists) GroupInfo(com.google.gerrit.extensions.common.GroupInfo) GroupDescription(com.google.gerrit.entities.GroupDescription) GetGroups(com.google.gerrit.server.restapi.account.GetGroups) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) InternalGroupDescription(com.google.gerrit.server.group.InternalGroupDescription) AccountGroup(com.google.gerrit.entities.AccountGroup) CurrentUser(com.google.gerrit.server.CurrentUser) GroupControl(com.google.gerrit.server.account.GroupControl) ListOption(com.google.gerrit.extensions.client.ListOption) AccountResource(com.google.gerrit.server.account.AccountResource) ProjectState(com.google.gerrit.server.project.ProjectState) MoreObjects(com.google.common.base.MoreObjects) IOException(java.io.IOException) Collectors.toList(java.util.stream.Collectors.toList) Provider(com.google.inject.Provider) TreeMap(java.util.TreeMap) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) Comparator(java.util.Comparator) Pattern(java.util.regex.Pattern) GroupInfo(com.google.gerrit.extensions.common.GroupInfo) ArrayList(java.util.ArrayList)

Example 44 with ConfigInvalidException

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

the class ListDashboards method scanDashboards.

private ImmutableList<DashboardInfo> scanDashboards(Project definingProject, Repository git, RevWalk rw, Ref ref, String project, boolean setDefault) throws IOException {
    ImmutableList.Builder<DashboardInfo> list = ImmutableList.builder();
    try (TreeWalk tw = new TreeWalk(rw.getObjectReader())) {
        tw.addTree(rw.parseTree(ref.getObjectId()));
        tw.setRecursive(true);
        while (tw.next()) {
            if (tw.getFileMode(0) == FileMode.REGULAR_FILE) {
                try {
                    list.add(DashboardsCollection.parse(definingProject, ref.getName().substring(REFS_DASHBOARDS.length()), tw.getPathString(), new BlobBasedConfig(null, git, tw.getObjectId(0)), project, setDefault));
                } catch (ConfigInvalidException e) {
                    logger.atWarning().log("Cannot parse dashboard %s:%s:%s: %s", definingProject.getName(), ref.getName(), tw.getPathString(), e.getMessage());
                }
            }
        }
    }
    return list.build();
}
Also used : ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ImmutableList(com.google.common.collect.ImmutableList) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) BlobBasedConfig(org.eclipse.jgit.lib.BlobBasedConfig) DashboardInfo(com.google.gerrit.extensions.api.projects.DashboardInfo)

Example 45 with ConfigInvalidException

use of org.eclipse.jgit.errors.ConfigInvalidException 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)

Aggregations

ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)158 IOException (java.io.IOException)95 Inject (com.google.inject.Inject)38 Repository (org.eclipse.jgit.lib.Repository)37 Provider (com.google.inject.Provider)34 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)31 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)30 ArrayList (java.util.ArrayList)30 Account (com.google.gerrit.entities.Account)27 List (java.util.List)26 Set (java.util.Set)26 ObjectId (org.eclipse.jgit.lib.ObjectId)26 AuthException (com.google.gerrit.extensions.restapi.AuthException)25 Config (org.eclipse.jgit.lib.Config)24 Singleton (com.google.inject.Singleton)23 OrmException (com.google.gwtorm.server.OrmException)22 AccountGroup (com.google.gerrit.entities.AccountGroup)21 RevWalk (org.eclipse.jgit.revwalk.RevWalk)21 StorageException (com.google.gerrit.exceptions.StorageException)20 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)20