Search in sources :

Example 16 with InvalidChangeOperationException

use of com.google.gerrit.server.project.InvalidChangeOperationException in project gerrit by GerritCodeReview.

the class ChangeEditModifier method createNewTree.

private static ObjectId createNewTree(Repository repository, RevCommit baseCommit, List<TreeModification> treeModifications) throws BadRequestException, IOException, InvalidChangeOperationException {
    if (treeModifications.isEmpty()) {
        return baseCommit.getTree();
    }
    ObjectId newTreeId;
    try {
        TreeCreator treeCreator = TreeCreator.basedOn(baseCommit);
        treeCreator.addTreeModifications(treeModifications);
        newTreeId = treeCreator.createNewTreeAndGetId(repository);
    } catch (InvalidPathException e) {
        throw new BadRequestException(e.getMessage());
    }
    if (ObjectId.isEqual(newTreeId, baseCommit.getTree())) {
        throw new InvalidChangeOperationException("no changes were made");
    }
    return newTreeId;
}
Also used : InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) TreeCreator(com.google.gerrit.server.edit.tree.TreeCreator) ObjectId(org.eclipse.jgit.lib.ObjectId) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) InvalidPathException(org.eclipse.jgit.dircache.InvalidPathException)

Example 17 with InvalidChangeOperationException

use of com.google.gerrit.server.project.InvalidChangeOperationException in project gerrit by GerritCodeReview.

the class ChangeEditModifier method createEdit.

/**
 * Creates a new change edit.
 *
 * @param repository the affected Git repository
 * @param notes the {@link ChangeNotes} of the change for which the change edit should be created
 * @throws AuthException if the user isn't authenticated or not allowed to use change edits
 * @throws InvalidChangeOperationException if a change edit already existed for the change
 */
public void createEdit(Repository repository, ChangeNotes notes) throws AuthException, IOException, InvalidChangeOperationException, PermissionBackendException, ResourceConflictException {
    assertCanEdit(notes);
    Optional<ChangeEdit> changeEdit = lookupChangeEdit(notes);
    if (changeEdit.isPresent()) {
        throw new InvalidChangeOperationException(String.format("A change edit already exists for change %s", notes.getChangeId()));
    }
    PatchSet currentPatchSet = lookupCurrentPatchSet(notes);
    ObjectId patchSetCommitId = currentPatchSet.commitId();
    noteDbEdits.createEdit(repository, notes, currentPatchSet, patchSetCommitId, TimeUtil.now());
}
Also used : InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) ObjectId(org.eclipse.jgit.lib.ObjectId) PatchSet(com.google.gerrit.entities.PatchSet)

Example 18 with InvalidChangeOperationException

use of com.google.gerrit.server.project.InvalidChangeOperationException in project gerrit by GerritCodeReview.

the class SubmitWithStickyApprovalDiff method apply.

public String apply(ChangeNotes notes, CurrentUser currentUser) throws AuthException, IOException, PermissionBackendException, InvalidChangeOperationException {
    PatchSet currentPatchset = notes.getCurrentPatchSet();
    PatchSet.Id latestApprovedPatchsetId = getLatestApprovedPatchsetId(notes);
    if (latestApprovedPatchsetId.get() == currentPatchset.id().get()) {
        // If the latest approved patchset is the current patchset, no need to return anything.
        return "";
    }
    StringBuilder diff = new StringBuilder(String.format("\n\n%d is the latest approved patch-set.\n", latestApprovedPatchsetId.get()));
    Map<String, FileDiffOutput> modifiedFiles = listModifiedFiles(notes.getProjectName(), currentPatchset, notes.getPatchSets().get(latestApprovedPatchsetId));
    // To make the message a bit more concise, we skip the magic files.
    List<FileDiffOutput> modifiedFilesList = modifiedFiles.values().stream().filter(p -> !Patch.isMagic(p.newPath().orElse(""))).collect(Collectors.toList());
    if (modifiedFilesList.isEmpty()) {
        diff.append("No files were changed between the latest approved patch-set and the submitted one.\n");
        return diff.toString();
    }
    diff.append("The change was submitted with unreviewed changes in the following files:\n\n");
    TemporaryBuffer.Heap buffer = new TemporaryBuffer.Heap(Math.min(HEAP_EST_SIZE, DEFAULT_POST_SUBMIT_SIZE_LIMIT), DEFAULT_POST_SUBMIT_SIZE_LIMIT);
    try (Repository repository = repositoryManager.openRepository(notes.getProjectName());
        DiffFormatter formatter = new DiffFormatter(buffer)) {
        formatter.setRepository(repository);
        formatter.setDetectRenames(true);
        boolean isDiffTooLarge = false;
        List<String> formatterResult = null;
        try {
            formatter.format(modifiedFilesList.get(0).oldCommitId(), modifiedFilesList.get(0).newCommitId());
            // This returns the diff for all the files.
            formatterResult = Arrays.stream(RawParseUtils.decode(buffer.toByteArray()).split("\n")).collect(Collectors.toList());
        } catch (IOException e) {
            if (JGitText.get().inMemoryBufferLimitExceeded.equals(e.getMessage())) {
                isDiffTooLarge = true;
            } else {
                throw e;
            }
        }
        if (formatterResult != null) {
            int addedBytes = formatterResult.stream().mapToInt(String::length).sum();
            if (!CommentCumulativeSizeValidator.isEnoughSpace(notes, addedBytes, maxCumulativeSize)) {
                isDiffTooLarge = true;
            }
        }
        for (FileDiffOutput fileDiff : modifiedFilesList) {
            diff.append(getDiffForFile(notes, currentPatchset.id(), latestApprovedPatchsetId, fileDiff, currentUser, formatterResult, isDiffTooLarge));
        }
    }
    return diff.toString();
}
Also used : Patch(com.google.gerrit.entities.Patch) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) Arrays(java.util.Arrays) LabelId(com.google.gerrit.entities.LabelId) Whitespace(com.google.gerrit.extensions.client.DiffPreferencesInfo.Whitespace) ProjectCache(com.google.gerrit.server.project.ProjectCache) Inject(com.google.inject.Inject) JGitText(org.eclipse.jgit.internal.JGitText) ArrayList(java.util.ArrayList) PatchSetApproval(com.google.gerrit.entities.PatchSetApproval) Config(org.eclipse.jgit.lib.Config) PatchScript(com.google.gerrit.common.data.PatchScript) ChangeType(com.google.gerrit.entities.Patch.ChangeType) CommentCumulativeSizeValidator(com.google.gerrit.server.git.validators.CommentCumulativeSizeValidator) FileDiffOutput(com.google.gerrit.server.patch.filediff.FileDiffOutput) InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) LabelType(com.google.gerrit.entities.LabelType) Map(java.util.Map) AuthException(com.google.gerrit.extensions.restapi.AuthException) PatchSet(com.google.gerrit.entities.PatchSet) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) DiffPreferencesInfo(com.google.gerrit.extensions.client.DiffPreferencesInfo) CurrentUser(com.google.gerrit.server.CurrentUser) TemporaryBuffer(org.eclipse.jgit.util.TemporaryBuffer) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) LargeObjectException(com.google.gerrit.server.git.LargeObjectException) StorageException(com.google.gerrit.exceptions.StorageException) ProjectState(com.google.gerrit.server.project.ProjectState) RawParseUtils(org.eclipse.jgit.util.RawParseUtils) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) DiffInfoCreator(com.google.gerrit.server.diff.DiffInfoCreator) Project(com.google.gerrit.entities.Project) Optional(java.util.Optional) Repository(org.eclipse.jgit.lib.Repository) PatchSet(com.google.gerrit.entities.PatchSet) IOException(java.io.IOException) FileDiffOutput(com.google.gerrit.server.patch.filediff.FileDiffOutput) Repository(org.eclipse.jgit.lib.Repository) TemporaryBuffer(org.eclipse.jgit.util.TemporaryBuffer) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter)

Example 19 with InvalidChangeOperationException

use of com.google.gerrit.server.project.InvalidChangeOperationException in project gerrit by GerritCodeReview.

the class GetFixPreview method apply.

@Override
public Response<Map<String, DiffInfo>> apply(FixResource resource) throws PermissionBackendException, ResourceNotFoundException, ResourceConflictException, AuthException, IOException, InvalidChangeOperationException {
    Map<String, DiffInfo> result = new HashMap<>();
    PatchSet patchSet = resource.getRevisionResource().getPatchSet();
    ChangeNotes notes = resource.getRevisionResource().getNotes();
    Change change = notes.getChange();
    ProjectState state = projectCache.get(change.getProject()).orElseThrow(illegalState(change.getProject()));
    Map<String, List<FixReplacement>> fixReplacementsPerFilePath = resource.getFixReplacements().stream().collect(groupingBy(fixReplacement -> fixReplacement.path));
    try {
        try (Repository git = repoManager.openRepository(notes.getProjectName())) {
            for (Map.Entry<String, List<FixReplacement>> entry : fixReplacementsPerFilePath.entrySet()) {
                String fileName = entry.getKey();
                DiffInfo diffInfo = getFixPreviewForSingleFile(git, patchSet, state, notes, fileName, ImmutableList.copyOf(entry.getValue()));
                result.put(fileName, diffInfo);
            }
        }
    } catch (NoSuchChangeException e) {
        throw new ResourceNotFoundException(e.getMessage(), e);
    } catch (LargeObjectException e) {
        throw new ResourceConflictException(e.getMessage(), e);
    }
    return Response.ok(result);
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) DiffInfo(com.google.gerrit.extensions.common.DiffInfo) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ProjectCache(com.google.gerrit.server.project.ProjectCache) Inject(com.google.inject.Inject) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) HashMap(java.util.HashMap) Response(com.google.gerrit.extensions.restapi.Response) PatchScriptFactoryForAutoFix(com.google.gerrit.server.patch.PatchScriptFactoryForAutoFix) PatchScript(com.google.gerrit.common.data.PatchScript) ImmutableList(com.google.common.collect.ImmutableList) InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) Map(java.util.Map) AuthException(com.google.gerrit.extensions.restapi.AuthException) NoSuchChangeException(com.google.gerrit.server.project.NoSuchChangeException) Change(com.google.gerrit.entities.Change) PatchSet(com.google.gerrit.entities.PatchSet) FixReplacement(com.google.gerrit.entities.FixReplacement) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) DiffPreferencesInfo(com.google.gerrit.extensions.client.DiffPreferencesInfo) RestReadView(com.google.gerrit.extensions.restapi.RestReadView) LargeObjectException(com.google.gerrit.server.git.LargeObjectException) ProjectState(com.google.gerrit.server.project.ProjectState) MoreObjects(com.google.common.base.MoreObjects) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) DiffSide(com.google.gerrit.server.diff.DiffSide) DiffWebLinksProvider(com.google.gerrit.server.diff.DiffWebLinksProvider) WebLinkInfo(com.google.gerrit.extensions.common.WebLinkInfo) List(java.util.List) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) DiffWebLinkInfo(com.google.gerrit.extensions.common.DiffWebLinkInfo) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) DiffInfoCreator(com.google.gerrit.server.diff.DiffInfoCreator) FixResource(com.google.gerrit.server.change.FixResource) Repository(org.eclipse.jgit.lib.Repository) Singleton(com.google.inject.Singleton) HashMap(java.util.HashMap) PatchSet(com.google.gerrit.entities.PatchSet) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) Change(com.google.gerrit.entities.Change) LargeObjectException(com.google.gerrit.server.git.LargeObjectException) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) NoSuchChangeException(com.google.gerrit.server.project.NoSuchChangeException) ProjectState(com.google.gerrit.server.project.ProjectState) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) HashMap(java.util.HashMap) Map(java.util.Map) DiffInfo(com.google.gerrit.extensions.common.DiffInfo)

Example 20 with InvalidChangeOperationException

use of com.google.gerrit.server.project.InvalidChangeOperationException in project gerrit by GerritCodeReview.

the class BatchUpdate method wrapAndThrowException.

private static void wrapAndThrowException(Exception e) throws UpdateException, RestApiException {
    // exception types.
    if (e instanceof InvalidChangeOperationException || e instanceof LimitExceededException) {
        throw new ResourceConflictException(e.getMessage(), e);
    } else if (e instanceof NoSuchChangeException || e instanceof NoSuchRefException || e instanceof NoSuchProjectException) {
        throw new ResourceNotFoundException(e.getMessage(), e);
    } else if (e instanceof CommentsRejectedException) {
        // status code and it's isolated in monitoring.
        throw new BadRequestException(e.getMessage(), e);
    }
    Throwables.throwIfUnchecked(e);
    // Propagate REST API exceptions thrown by operations; they commonly throw exceptions like
    // ResourceConflictException to indicate an atomic update failure.
    Throwables.throwIfInstanceOf(e, UpdateException.class);
    Throwables.throwIfInstanceOf(e, RestApiException.class);
    // Otherwise, wrap in a generic UpdateException, which does not include a user-visible message.
    throw new UpdateException(e);
}
Also used : InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) NoSuchChangeException(com.google.gerrit.server.project.NoSuchChangeException) NoSuchProjectException(com.google.gerrit.server.project.NoSuchProjectException) NoSuchRefException(com.google.gerrit.server.project.NoSuchRefException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) LimitExceededException(com.google.gerrit.server.notedb.LimitExceededException) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Aggregations

InvalidChangeOperationException (com.google.gerrit.server.project.InvalidChangeOperationException)20 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)8 ObjectId (org.eclipse.jgit.lib.ObjectId)8 PatchSet (com.google.gerrit.entities.PatchSet)7 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)7 Repository (org.eclipse.jgit.lib.Repository)7 ProjectState (com.google.gerrit.server.project.ProjectState)6 AuthException (com.google.gerrit.extensions.restapi.AuthException)5 Change (com.google.gerrit.entities.Change)4 Project (com.google.gerrit.entities.Project)4 NoSuchChangeException (com.google.gerrit.server.project.NoSuchChangeException)4 ChangeData (com.google.gerrit.server.query.change.ChangeData)4 MergeConflictException (com.google.gerrit.extensions.restapi.MergeConflictException)3 PatchSet (com.google.gerrit.reviewdb.client.PatchSet)3 GerritPersonIdent (com.google.gerrit.server.GerritPersonIdent)3 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)3 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)3 PersonIdent (org.eclipse.jgit.lib.PersonIdent)3 RevCommit (org.eclipse.jgit.revwalk.RevCommit)3 Nullable (com.google.gerrit.common.Nullable)2