Search in sources :

Example 1 with CommitAction

use of org.gitlab4j.api.models.CommitAction in project legend-sdlc by finos.

the class GitLabWorkspaceApi method createConflictResolution.

/**
 * This method will mark create a conflict resolution branch from a given workspace branch. Assume we have workspace branch `w1`, this method will:
 * 1. Create resolution branch from `master` branch (check if that's the latest)
 * 2. Get all the changes of workspace branch `w1`
 * 3. Copy and replace those changes to resolution branch `w1` and create a new commit out of that.
 */
private WorkspaceUpdateReport createConflictResolution(String projectId, String workspaceId, WorkspaceType workspaceType, String masterRevisionId) {
    // Check if conflict resolution is happening, if it is, it means conflict resolution branch already existed, so we will
    // scrap that branch and create a new one.
    GitLabProjectId gitLabProjectId = parseProjectId(projectId);
    RepositoryApi repositoryApi = getGitLabApi(gitLabProjectId.getGitLabMode()).getRepositoryApi();
    Branch previousConflictResolutionBranch = null;
    ProjectFileAccessProvider.WorkspaceAccessType conflictResolutionWorkspaceType = ProjectFileAccessProvider.WorkspaceAccessType.CONFLICT_RESOLUTION;
    try {
        previousConflictResolutionBranch = withRetries(() -> repositoryApi.getBranch(gitLabProjectId.getGitLabId(), getWorkspaceBranchName(workspaceId, workspaceType, conflictResolutionWorkspaceType)));
    } catch (Exception e) {
        if (!GitLabApiTools.isNotFoundGitLabApiException(e)) {
            LOGGER.error("Error updating {} {} in project {}", workspaceType.getLabel() + " " + conflictResolutionWorkspaceType.getLabel(), workspaceId, projectId);
        }
    }
    // Delete conflict resolution workspace
    if (previousConflictResolutionBranch != null) {
        LOGGER.debug("Conflict resolution already happened in workspace {} in project {}, but we will recreate this conflict resolution workspace to make sure it's up to date", workspaceId, projectId);
        boolean conflictResolutionBranchDeleted;
        try {
            conflictResolutionBranchDeleted = GitLabApiTools.deleteBranchAndVerify(repositoryApi, gitLabProjectId.getGitLabId(), getWorkspaceBranchName(workspaceId, workspaceType, conflictResolutionWorkspaceType), 20, 1_000);
        } catch (Exception e) {
            throw buildException(e, () -> "User " + getCurrentUser() + " is not allowed to delete " + workspaceType.getLabel() + " " + conflictResolutionWorkspaceType.getLabel() + " " + workspaceId + " in project " + projectId, () -> "Unknown " + workspaceType.getLabel() + " " + conflictResolutionWorkspaceType.getLabel() + " (" + workspaceId + ") or project (" + projectId + ")", () -> "Error deleting " + workspaceType.getLabel() + " " + conflictResolutionWorkspaceType.getLabel() + " " + workspaceId + " in project " + projectId);
        }
        if (!conflictResolutionBranchDeleted) {
            throw new LegendSDLCServerException("Failed to delete " + workspaceType.getLabel() + " " + conflictResolutionWorkspaceType.getLabel() + " " + workspaceId + " in project " + projectId);
        }
    }
    // Create conflict resolution workspace
    Branch conflictResolutionBranch;
    try {
        conflictResolutionBranch = GitLabApiTools.createBranchFromSourceBranchAndVerify(repositoryApi, gitLabProjectId.getGitLabId(), getWorkspaceBranchName(workspaceId, workspaceType, conflictResolutionWorkspaceType), MASTER_BRANCH, 30, 1_000);
    } catch (Exception e) {
        throw buildException(e, () -> "User " + getCurrentUser() + " is not allowed to create workspace " + workspaceId + " in project " + projectId, () -> "Unknown project: " + projectId, () -> "Error creating workspace " + workspaceId + " in project " + projectId);
    }
    if (conflictResolutionBranch == null) {
        throw new LegendSDLCServerException("Failed to create " + workspaceType.getLabel() + " " + conflictResolutionWorkspaceType.getLabel() + " " + workspaceId + " in project " + projectId);
    }
    // Get the changes of the current workspace
    String currentWorkspaceRevisionId = this.revisionApi.getWorkspaceRevisionContext(projectId, workspaceId, workspaceType).getCurrentRevision().getId();
    String workspaceCreationRevisionId;
    try {
        workspaceCreationRevisionId = withRetries(() -> repositoryApi.getMergeBase(gitLabProjectId.getGitLabId(), Arrays.asList(MASTER_BRANCH, currentWorkspaceRevisionId)).getId());
    } catch (Exception e) {
        throw buildException(e, () -> "User " + getCurrentUser() + " is not allowed to get merged base revision for revisions " + MASTER_BRANCH + ", " + currentWorkspaceRevisionId + " from project " + projectId, () -> "Could not find revisions " + MASTER_BRANCH + ", " + currentWorkspaceRevisionId + " from project " + projectId, () -> "Failed to fetch merged base information for revisions " + MASTER_BRANCH + ", " + currentWorkspaceRevisionId + " from project " + projectId);
    }
    CompareResults comparisonResult;
    try {
        comparisonResult = withRetries(() -> repositoryApi.compare(gitLabProjectId.getGitLabId(), workspaceCreationRevisionId, currentWorkspaceRevisionId, true));
    } catch (Exception e) {
        throw buildException(e, () -> "User " + getCurrentUser() + " is not allowed to get comparison information from revision " + workspaceCreationRevisionId + "  to revision " + currentWorkspaceRevisionId + " on project" + projectId, () -> "Could not find revisions " + workspaceCreationRevisionId + " ," + currentWorkspaceRevisionId + " on project" + projectId, () -> "Failed to fetch comparison information from revision " + workspaceCreationRevisionId + "  to revision " + currentWorkspaceRevisionId + " on project" + projectId);
    }
    List<Diff> diffs = comparisonResult.getDiffs();
    // Create a new commit on conflict resolution branch
    CommitsApi commitsApi = getGitLabApi(gitLabProjectId.getGitLabMode()).getCommitsApi();
    ProjectFileAccessProvider.FileAccessContext projectFileAccessContext = getProjectFileAccessProvider().getProjectFileAccessContext(projectId);
    ProjectFileAccessProvider.WorkspaceAccessType workspaceAccessType = ProjectFileAccessProvider.WorkspaceAccessType.WORKSPACE;
    ProjectFileAccessProvider.FileAccessContext workspaceFileAccessContext = getProjectFileAccessProvider().getWorkspaceFileAccessContext(projectId, workspaceId, workspaceType, workspaceAccessType);
    try {
        List<CommitAction> commitActions = Lists.mutable.empty();
        // NOTE: we are bringing the diffs from the workspace and applying those diffs to the project HEAD. Now, the project
        // HEAD could potentially differ greatly from the workspace base revision. This means that when we create the commit
        // action from the diff, we must be careful about the action type.
        // Take for example DELETE: if according to the diff, we delete file A, but at project HEAD, A is already deleted
        // in one of the commits between workspace base and project HEAD, such DELETE commit action will fail, this should then be
        // a NO_OP. Then again, we will have to be careful when CREATE, MOVE, and UPDATE.
        diffs.forEach(diff -> {
            if (diff.getDeletedFile()) {
                // Ensure the file to delete exists at project HEAD
                ProjectFileAccessProvider.ProjectFile fileToDelete = projectFileAccessContext.getFile(diff.getOldPath());
                if (fileToDelete != null) {
                    commitActions.add(new CommitAction().withAction(CommitAction.Action.DELETE).withFilePath(diff.getOldPath()));
                }
            } else if (diff.getRenamedFile()) {
                // split a MOVE into a DELETE followed by an CREATE/UPDATE to handle cases when
                // file to be moved is already deleted at project HEAD
                // and file to be moved to is already created at project HEAD
                ProjectFileAccessProvider.ProjectFile fileToDelete = projectFileAccessContext.getFile(diff.getOldPath());
                ProjectFileAccessProvider.ProjectFile fileToReplace = projectFileAccessContext.getFile(diff.getNewPath());
                if (fileToDelete != null) {
                    commitActions.add(new CommitAction().withAction(CommitAction.Action.DELETE).withFilePath(diff.getOldPath()));
                }
                commitActions.add(new CommitAction().withAction(fileToReplace == null ? CommitAction.Action.CREATE : CommitAction.Action.UPDATE).withFilePath(diff.getNewPath()).withEncoding(Constants.Encoding.BASE64).withContent(encodeBase64(workspaceFileAccessContext.getFile(diff.getNewPath()).getContentAsBytes())));
            } else if (diff.getNewFile()) {
                // If the file to be created already exists at project HEAD, change this to an UPDATE
                ProjectFileAccessProvider.ProjectFile fileToCreate = projectFileAccessContext.getFile(diff.getOldPath());
                commitActions.add(new CommitAction().withAction(fileToCreate == null ? CommitAction.Action.CREATE : CommitAction.Action.UPDATE).withFilePath(diff.getNewPath()).withEncoding(Constants.Encoding.BASE64).withContent(encodeBase64(workspaceFileAccessContext.getFile(diff.getNewPath()).getContentAsBytes())));
            } else {
                // File was updated
                // If the file to be updated is deleted at project HEAD, change this to a CREATE
                ProjectFileAccessProvider.ProjectFile fileToUpdate = projectFileAccessContext.getFile(diff.getOldPath());
                commitActions.add(new CommitAction().withAction(fileToUpdate == null ? CommitAction.Action.CREATE : CommitAction.Action.UPDATE).withFilePath(diff.getOldPath()).withEncoding(Constants.Encoding.BASE64).withContent(encodeBase64(workspaceFileAccessContext.getFile(diff.getOldPath()).getContentAsBytes())));
            }
        });
        commitsApi.createCommit(gitLabProjectId.getGitLabId(), this.getWorkspaceBranchName(workspaceId, workspaceType, conflictResolutionWorkspaceType), "aggregated changes for conflict resolution", null, null, getCurrentUser(), commitActions);
    } catch (Exception e) {
        throw buildException(e, () -> "User " + getCurrentUser() + " is not allowed to create commit on " + workspaceType.getLabel() + " " + conflictResolutionWorkspaceType.getLabel() + workspaceId + " of project " + projectId, () -> "Unknown project: " + projectId + " or " + workspaceType.getLabel() + " " + conflictResolutionWorkspaceType.getLabel() + " " + workspaceId, () -> "Failed to create commit in " + workspaceType.getLabel() + " " + conflictResolutionWorkspaceType.getLabel() + workspaceId + " of project" + projectId);
    }
    return createWorkspaceUpdateReport(WorkspaceUpdateReportStatus.CONFLICT, masterRevisionId, conflictResolutionBranch.getCommit().getId());
}
Also used : CompareResults(org.gitlab4j.api.models.CompareResults) Diff(org.gitlab4j.api.models.Diff) LegendSDLCServerException(org.finos.legend.sdlc.server.error.LegendSDLCServerException) GitLabApiException(org.gitlab4j.api.GitLabApiException) CommitsApi(org.gitlab4j.api.CommitsApi) ProjectFileAccessProvider(org.finos.legend.sdlc.server.project.ProjectFileAccessProvider) LegendSDLCServerException(org.finos.legend.sdlc.server.error.LegendSDLCServerException) GitLabProjectId(org.finos.legend.sdlc.server.gitlab.GitLabProjectId) Branch(org.gitlab4j.api.models.Branch) RepositoryApi(org.gitlab4j.api.RepositoryApi) CommitAction(org.gitlab4j.api.models.CommitAction)

Example 2 with CommitAction

use of org.gitlab4j.api.models.CommitAction in project legend-sdlc by finos.

the class GitLabWorkspaceApi method attemptToSquashAndRebaseWorkspace.

/**
 * This method is called when we failed to rebase the workspace branch on top of master branch. This implies that either
 * the whole change is causing a merge conflict or one of the intermediate commits have conflicts with the change in master branch
 * <p>
 * To handle the latter case, this method will squash all commits on the workspace branch and attempt rebase again.
 * If this fails, it implies that rebase fails because of merge conflicts, which means we have to enter conflict resolution route.
 * <p>
 * NOTE: based on the nature of this method, we have an optimization here where we check for the number of commits on the current
 * branch, if it is less than 2 (not counting the base), it means no squashing is needed and we can just immediately tell that there
 * is merge conflict and the workspace update should enter conflict resolution route
 * <p>
 * So following is the summary of this method:
 * 1. Create a temp branch to do the squashing on that branch
 * 3. Attempt to rebase the temp branch on master:
 * - If succeeded: re-create current workspace branch on top of the temp branch
 * - If failed -> implies conflict resolution is needed
 *
 * @return a workspace update report that might have status as UPDATED or CONFLICT.
 */
private WorkspaceUpdateReport attemptToSquashAndRebaseWorkspace(String projectId, String workspaceId, WorkspaceType workspaceType, String masterRevisionId, String currentWorkspaceRevisionId, String workspaceCreationRevisionId) {
    GitLabProjectId gitLabProjectId = parseProjectId(projectId);
    RepositoryApi repositoryApi = getGitLabApi(gitLabProjectId.getGitLabMode()).getRepositoryApi();
    // Create temp branch for rebasing
    String tempBranchName = newUserTemporaryBranchName();
    Branch tempBranch;
    try {
        tempBranch = GitLabApiTools.createBranchAndVerify(repositoryApi, gitLabProjectId.getGitLabId(), tempBranchName, workspaceCreationRevisionId, 30, 1_000);
    } catch (Exception e) {
        throw buildException(e, () -> "User " + getCurrentUser() + " is not allowed to create temporary workspace " + tempBranchName + " in project " + projectId, () -> "Unknown project: " + projectId, () -> "Error creating temporary workspace " + tempBranchName + " in project " + projectId);
    }
    if (tempBranch == null) {
        throw new LegendSDLCServerException("Failed to create temporary workspace " + tempBranchName + " in project " + projectId + " from revision " + workspaceCreationRevisionId);
    }
    CompareResults comparisonResult;
    try {
        comparisonResult = withRetries(() -> repositoryApi.compare(gitLabProjectId.getGitLabId(), workspaceCreationRevisionId, currentWorkspaceRevisionId, true));
    } catch (Exception e) {
        throw buildException(e, () -> "User " + getCurrentUser() + " is not allowed to get comparison information from revision " + workspaceCreationRevisionId + "  to revision " + currentWorkspaceRevisionId + " on project" + projectId, () -> "Could not find revisions " + workspaceCreationRevisionId + " ," + currentWorkspaceRevisionId + " on project" + projectId, () -> "Failed to fetch comparison information from revision " + workspaceCreationRevisionId + "  to revision " + currentWorkspaceRevisionId + " on project" + projectId);
    }
    // Create a new commit on temp branch that squashes all changes on the concerned workspace branch
    CommitsApi commitsApi = getGitLabApi(gitLabProjectId.getGitLabMode()).getCommitsApi();
    ProjectFileAccessProvider.WorkspaceAccessType workspaceAccessType = ProjectFileAccessProvider.WorkspaceAccessType.WORKSPACE;
    ProjectFileAccessProvider.FileAccessContext workspaceFileAccessContext = getProjectFileAccessProvider().getWorkspaceFileAccessContext(projectId, workspaceId, workspaceType, workspaceAccessType);
    Commit squashedCommit;
    try {
        List<CommitAction> commitActions = Lists.mutable.empty();
        comparisonResult.getDiffs().forEach(diff -> {
            if (diff.getDeletedFile()) {
                // DELETE
                commitActions.add(new CommitAction().withAction(CommitAction.Action.DELETE).withFilePath(diff.getOldPath()));
            } else if (diff.getRenamedFile()) {
                // MOVE
                // 
                // tl;dr;
                // split this into a delete and a create to make sure the moved entity has the content of the entity
                // in workspace HEAD revision
                // 
                // Since we use comparison API to compute the diff, Git has a smart algorithm to calculate file move
                // as it is a heuristics such that if file content is only slightly different, Git can conclude that the
                // diff was of type RENAME.
                // 
                // The problem with this is when we compare the workspace BASE revision and workspace HEAD revision
                // Assume that we actually renamed an entity, we also want to update the entity path, not just its location
                // the location part is correctly identified by Git, and the change in content is captured as a diff string
                // in comparison result (which shows the change in the path)
                // but when we create CommitAction, there is no way for us to apply this patch on top of the entity content
                // so if we just create action of type MOVE for CommitAction, we will have the content of the old entity
                // which has the wrong path, and thus this entity if continue to exist in the workspace will throw off
                // our path and entity location validation check
                commitActions.add(new CommitAction().withAction(CommitAction.Action.DELETE).withFilePath(diff.getOldPath()));
                commitActions.add(new CommitAction().withAction(CommitAction.Action.CREATE).withFilePath(diff.getNewPath()).withEncoding(Constants.Encoding.BASE64).withContent(encodeBase64(workspaceFileAccessContext.getFile(diff.getNewPath()).getContentAsBytes())));
            } else if (diff.getNewFile()) {
                // CREATE
                commitActions.add(new CommitAction().withAction(CommitAction.Action.CREATE).withFilePath(diff.getNewPath()).withEncoding(Constants.Encoding.BASE64).withContent(encodeBase64(workspaceFileAccessContext.getFile(diff.getNewPath()).getContentAsBytes())));
            } else {
                // UPDATE
                commitActions.add(new CommitAction().withAction(CommitAction.Action.UPDATE).withFilePath(diff.getOldPath()).withEncoding(Constants.Encoding.BASE64).withContent(encodeBase64(workspaceFileAccessContext.getFile(diff.getOldPath()).getContentAsBytes())));
            }
        });
        squashedCommit = commitsApi.createCommit(gitLabProjectId.getGitLabId(), tempBranchName, "aggregated changes for workspace " + workspaceId, null, null, getCurrentUser(), commitActions);
    } catch (Exception e) {
        throw buildException(e, () -> "User " + getCurrentUser() + " is not allowed to create commit on temporary workspace " + tempBranchName + " of project " + projectId, () -> "Unknown project: " + projectId + " or temporary workspace " + tempBranchName, () -> "Failed to create commit in temporary workspace " + tempBranchName + " of project " + projectId);
    }
    // Attempt to rebase the temporary branch on top of master
    boolean attemptRebaseResult = this.attemptToRebaseWorkspaceUsingTemporaryBranch(projectId, workspaceId, workspaceType, tempBranchName, masterRevisionId);
    // If rebasing failed, this implies there are conflicts, otherwise, the workspace should be updated
    if (!attemptRebaseResult) {
        return createWorkspaceUpdateReport(WorkspaceUpdateReportStatus.CONFLICT, null, null);
    }
    return createWorkspaceUpdateReport(WorkspaceUpdateReportStatus.UPDATED, masterRevisionId, squashedCommit.getId());
}
Also used : CompareResults(org.gitlab4j.api.models.CompareResults) LegendSDLCServerException(org.finos.legend.sdlc.server.error.LegendSDLCServerException) GitLabApiException(org.gitlab4j.api.GitLabApiException) CommitsApi(org.gitlab4j.api.CommitsApi) ProjectFileAccessProvider(org.finos.legend.sdlc.server.project.ProjectFileAccessProvider) LegendSDLCServerException(org.finos.legend.sdlc.server.error.LegendSDLCServerException) Commit(org.gitlab4j.api.models.Commit) GitLabProjectId(org.finos.legend.sdlc.server.gitlab.GitLabProjectId) Branch(org.gitlab4j.api.models.Branch) RepositoryApi(org.gitlab4j.api.RepositoryApi) CommitAction(org.gitlab4j.api.models.CommitAction)

Aggregations

LegendSDLCServerException (org.finos.legend.sdlc.server.error.LegendSDLCServerException)2 GitLabProjectId (org.finos.legend.sdlc.server.gitlab.GitLabProjectId)2 ProjectFileAccessProvider (org.finos.legend.sdlc.server.project.ProjectFileAccessProvider)2 CommitsApi (org.gitlab4j.api.CommitsApi)2 GitLabApiException (org.gitlab4j.api.GitLabApiException)2 RepositoryApi (org.gitlab4j.api.RepositoryApi)2 Branch (org.gitlab4j.api.models.Branch)2 CommitAction (org.gitlab4j.api.models.CommitAction)2 CompareResults (org.gitlab4j.api.models.CompareResults)2 Commit (org.gitlab4j.api.models.Commit)1 Diff (org.gitlab4j.api.models.Diff)1