Example usage for org.eclipse.jgit.lib RepositoryState SAFE

List of usage examples for org.eclipse.jgit.lib RepositoryState SAFE

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib RepositoryState SAFE.

Prototype

RepositoryState SAFE

To view the source code for org.eclipse.jgit.lib RepositoryState SAFE.

Click Source Link

Document

A safe state for working normally

Usage

From source file:com.genuitec.eclipse.gerrit.tools.internal.fbranches.commands.MergeStableIntoCurrentBranchCommand.java

License:Open Source License

private boolean canMerge(final Repository repository) {
    String message = null;//w  w w  . j  a  va  2 s.c o  m
    Exception ex = null;
    try {
        Ref head = repository.getRef(Constants.HEAD);
        if (head == null || !head.isSymbolic())
            message = UIText.MergeAction_HeadIsNoBranch;
        else if (!repository.getRepositoryState().equals(RepositoryState.SAFE))
            message = NLS.bind(UIText.MergeAction_WrongRepositoryState, repository.getRepositoryState());
        else if (!head.getLeaf().getName().startsWith("refs/heads/features")) { //$NON-NLS-1$
            message = "Current branch is not a feature branch.";
        }
    } catch (IOException e) {
        message = e.getMessage();
        ex = e;
    }

    if (message != null)
        org.eclipse.egit.ui.Activator.handleError(message, ex, true);
    return (message == null);
}

From source file:com.mangosolutions.rcloud.rawgist.repository.git.BareCommitCommand.java

/**
 * Sets default values for not explicitly specified options. Then validates
 * that all required data has been provided.
 *
 * @param state//from  w  ww .  java  2  s  .  c  om
 *            the state of the repository we are working on
 * @param rw
 *            the RevWalk to use
 *
 * @throws NoMessageException
 *             if the commit message has not been specified
 */
private void processOptions(RepositoryState state, RevWalk rw) throws NoMessageException {
    if (committer == null) {
        committer = new PersonIdent(repo);
    }
    if (author == null && !amend) {
        author = committer;
    }
    if (allowEmpty == null) {
        // JGit allows empty commits by default. Only when pathes are
        // specified the commit should not be empty. This behaviour differs
        // from native git but can only be adapted in the next release.
        // TODO(ch) align the defaults with native git
        allowEmpty = (only.isEmpty()) ? Boolean.TRUE : Boolean.FALSE;
    }
    // when doing a merge commit parse MERGE_HEAD and MERGE_MSG files
    if (state == RepositoryState.MERGING_RESOLVED || isMergeDuringRebase(state)) {
        try {
            parents = repo.readMergeHeads();
            if (parents != null) {
                for (int i = 0; i < parents.size(); i++) {
                    RevObject ro = rw.parseAny(parents.get(i));
                    if (ro instanceof RevTag)
                        parents.set(i, rw.peel(ro));
                }
            }
        } catch (IOException e) {
            throw new JGitInternalException(MessageFormat.format(
                    JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR, Constants.MERGE_HEAD, e), e);
        }
        if (message == null) {
            try {
                message = repo.readMergeCommitMsg();
            } catch (IOException e) {
                throw new JGitInternalException(MessageFormat.format(
                        JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR, Constants.MERGE_MSG, e), e);
            }
        }
    } else if (state == RepositoryState.SAFE && message == null) {
        try {
            message = repo.readSquashCommitMsg();
            if (message != null) {
                repo.writeSquashCommitMsg(null /* delete */);
            }
        } catch (IOException e) {
            throw new JGitInternalException(MessageFormat
                    .format(JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR, Constants.MERGE_MSG, e), e);
        }

    }
    if (message == null) {
        // as long as we don't support -C option we have to have
        // an explicit message
        throw new NoMessageException(JGitText.get().commitMessageNotSpecified);
    }
}

From source file:com.microsoft.gittf.core.tasks.PullTaskTest.java

License:Open Source License

private void runPullRebaseTask() throws IOException {
    // Run the pull task
    PullTask pullTask = new PullTask(repository, mockVersionControlService);
    pullTask.setRebase(true);//w w  w.  java  2  s  .  com

    TaskStatus pullTaskStatus = pullTask.run(new NullTaskProgressMonitor());

    // Verify task completed without errors
    assertTrue(pullTaskStatus.isOK());

    // Verify that the repo is in a good state
    assertTrue(repository.getRepositoryState() == RepositoryState.SAFE);

    // Verify rebase happened
    ObjectId fetchedCommitId = pullTask.getCommitId();

    Ref head = repository.getRef(Constants.HEAD);
    RevWalk revWalk = new RevWalk(repository);
    RevCommit headCommit = revWalk.parseCommit(head.getObjectId());

    assertEquals(headCommit.getParentCount(), 1);

    RevCommit parent = headCommit.getParents()[0];

    assertTrue(parent.getId().equals(fetchedCommitId));
}

From source file:de.blizzy.documentr.page.PageStore.java

License:Open Source License

private MergeConflict savePageInternal(String projectName, String branchName, String path, String suffix,
        Page page, String baseCommit, String rootDir, User user, ILockedRepository repo, boolean push)
        throws IOException, GitAPIException {

    Git git = Git.wrap(repo.r());/*from w  w w. j a  v  a 2 s .c om*/

    String headCommit = CommitUtils.getHead(repo.r()).getName();
    if ((baseCommit != null) && headCommit.equals(baseCommit)) {
        baseCommit = null;
    }

    String editBranchName = "_edit_" + String.valueOf((long) (Math.random() * Long.MAX_VALUE)); //$NON-NLS-1$
    if (baseCommit != null) {
        git.branchCreate().setName(editBranchName).setStartPoint(baseCommit).call();

        git.checkout().setName(editBranchName).call();
    }

    Map<String, Object> metaMap = new HashMap<String, Object>();
    metaMap.put(TITLE, page.getTitle());
    metaMap.put(CONTENT_TYPE, page.getContentType());
    if (!page.getTags().isEmpty()) {
        metaMap.put(TAGS, page.getTags());
    }
    metaMap.put(VIEW_RESTRICTION_ROLE, page.getViewRestrictionRole());
    Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
    String json = gson.toJson(metaMap);
    File workingDir = RepositoryUtil.getWorkingDir(repo.r());
    File pagesDir = new File(workingDir, rootDir);
    File workingFile = Util.toFile(pagesDir, path + DocumentrConstants.META_SUFFIX);
    FileUtils.write(workingFile, json, Charsets.UTF_8);

    PageData pageData = page.getData();
    if (pageData != null) {
        workingFile = Util.toFile(pagesDir, path + suffix);
        FileUtils.writeByteArrayToFile(workingFile, pageData.getData());
    }

    AddCommand addCommand = git.add().addFilepattern(rootDir + "/" + path + DocumentrConstants.META_SUFFIX); //$NON-NLS-1$
    if (pageData != null) {
        addCommand.addFilepattern(rootDir + "/" + path + suffix); //$NON-NLS-1$
    }
    addCommand.call();

    PersonIdent ident = new PersonIdent(user.getLoginName(), user.getEmail());
    git.commit().setAuthor(ident).setCommitter(ident).setMessage(rootDir + "/" + path + suffix).call(); //$NON-NLS-1$

    MergeConflict conflict = null;

    if (baseCommit != null) {
        git.rebase().setUpstream(branchName).call();

        if (repo.r().getRepositoryState() != RepositoryState.SAFE) {
            String text = FileUtils.readFileToString(workingFile, Charsets.UTF_8);
            conflict = new MergeConflict(text, headCommit);

            git.rebase().setOperation(RebaseCommand.Operation.ABORT).call();
        }

        git.checkout().setName(branchName).call();

        if (conflict == null) {
            git.merge().include(repo.r().resolve(editBranchName)).call();
        }

        git.branchDelete().setBranchNames(editBranchName).setForce(true).call();
    }

    if (push && (conflict == null)) {
        git.push().call();
    }

    page.setParentPagePath(getParentPagePath(path, repo.r()));

    if (conflict == null) {
        PageUtil.updateProjectEditTime(projectName);
    }

    return conflict;
}

From source file:edu.wustl.lookingglass.community.CommunityRepository.java

License:Open Source License

private void resolveMerge() throws NoWorkTreeException, GitAPIException, IOException {
    assert this.username != null;
    assert this.email != null;

    Status status = this.git.status().call();
    Map<String, StageState> conflicting = status.getConflictingStageState();

    for (String path : conflicting.keySet()) {
        StageState stageState = conflicting.get(path);
        switch (stageState) {
        case BOTH_MODIFIED: // UU
        case BOTH_ADDED: // AA
        case ADDED_BY_US: // AU
        case ADDED_BY_THEM: // UA
            // Both the local and server version have been modified
            File conflictingFile = new File(this.repoDir, path);
            String fullPath = conflictingFile.getAbsolutePath();

            // Since the local copy was modified it probably makes sense to leave it
            // since that's the copy the user has been working on. Here's my assumption...
            // a sync didn't happen, so the user opens their project and sees it's not their
            // latest changes, they accept the failure and start to fix it... finally a sync
            // happens... at this point they are probably editing this world, so when they save
            // they wouldn't even load the new file, so we should just keep the old file.

            // TODO: we should really prompt the user to resolve this conflict.
            // but that's kinda hard with the singletons... because you probably just want
            // to open both files in two different windows (editors) but we can't do that. :(

            // Recover server version
            this.git.checkout().setStage(Stage.THEIRS).addPath(path).call();

            // Append a timestamp
            LocalDateTime date = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-mm-dd+HH'h'MM'm'");
            String timestamp = date.format(formatter);
            File theirFile = new File(FilenameUtils.getFullPath(fullPath), FilenameUtils.getBaseName(path)
                    + " (" + timestamp + ")." + FilenameUtils.getExtension(path));

            if (conflictingFile.exists() && !theirFile.exists()) {
                Files.move(conflictingFile.toPath(), theirFile.toPath());

                String relativePath = this.repoDir.toURI().relativize(theirFile.toURI()).getPath();
                this.git.add().addFilepattern(relativePath).call();
            }/*from  w  w w .  j  a v a  2  s.  c  om*/

            // Recover local version
            this.git.checkout().setStage(Stage.OURS).addPath(path).call();
            this.git.add().addFilepattern(path).call();
            break;

        case DELETED_BY_US: // DU
            // The modified local version is already in the checkout, so it just needs to be added.
            // We need to specifically mention the file, so we can't reuse the Add () method
            this.git.add().addFilepattern(path).call();
            break;
        case DELETED_BY_THEM: // UD
            // Recover server version
            this.git.checkout().setStage(Stage.THEIRS).addPath(path).call();
            this.git.add().addFilepattern(path).call();
            break;
        case BOTH_DELETED: // DD
            break;
        default:
            throw new IllegalArgumentException("Unknown StageState: " + stageState);
        }
    }

    RepositoryState resolvedState = this.git.getRepository().getRepositoryState();
    assert resolvedState == RepositoryState.MERGING_RESOLVED;

    // we are done resolving the merge!
    this.git.commit().setAuthor(this.username, this.email).call();

    RepositoryState safeState = this.git.getRepository().getRepositoryState();
    assert safeState == RepositoryState.SAFE;
}

From source file:net.erdfelt.android.sdkfido.git.GitAssert.java

License:Apache License

public static void assertCheckoutRef(String repoId, String expectedGitRef, File repoDir) throws IOException {
    FileRepository repository = assertGitRepo(repoId, repoDir);
    Assert.assertThat(repoId + " - current branch ref", repository.getFullBranch(), is(expectedGitRef));
    Assert.assertThat(repoId + " - state", repository.getRepositoryState(), is(RepositoryState.SAFE));
}

From source file:net.morimekta.gittool.cmd.Status.java

License:Apache License

@Override
public void execute(GitTool gt) throws IOException {
    try (Repository repository = gt.getRepository()) {
        RepositoryState state = repository.getRepositoryState();
        if (state != RepositoryState.SAFE) {
            System.out.println(WARN + "Repository not in a safe state" + CLEAR + ": " + state.getDescription());
        }//from ww  w . jav  a2s.  c o m

        Git git = new Git(repository);
        String currentBranch = repository.getBranch();
        String diffWithBranch = branch != null ? branch : gt.getDiffbase(currentBranch);

        this.root = gt.getRepositoryRoot().getCanonicalFile().getAbsolutePath();

        Ref currentRef = repository.getRef(gt.refName(currentBranch));
        Ref diffWithRef = repository.getRef(gt.refName(diffWithBranch));
        if (diffWithRef == null) {
            System.out.println(format("No such branch %s%s%s", BOLD, diffWithBranch, CLEAR));
            return;
        }

        ObjectId currentHead = currentRef.getObjectId();
        ObjectId diffWithHead = diffWithRef.getObjectId();

        // RevCommit currentCommit = commitOf(repository, currentHead);

        if (!currentHead.equals(diffWithHead)) {
            String stats = "";
            String diff = gt.isRemote(diffWithBranch) ? format("[->%s%s%s] ", DIM, diffWithBranch, CLEAR)
                    : format("[d:%s%s%s] ", CLR_BASE_BRANCH, diffWithBranch, CLEAR);

            List<RevCommit> localCommits = ImmutableList
                    .copyOf(git.log().addRange(diffWithHead, currentHead).call());
            List<RevCommit> remoteCommits = ImmutableList
                    .copyOf(git.log().addRange(currentHead, diffWithHead).call());

            localCommits = Lists.reverse(localCommits);
            remoteCommits = Lists.reverse(remoteCommits);

            int commits = localCommits.size();
            int missing = remoteCommits.size();

            RevCommit ancestor, local;
            if (remoteCommits.size() > 0) {
                List<RevCommit> sub2 = Lists.reverse(
                        ImmutableList.copyOf(git.log().add(remoteCommits.get(0)).setMaxCount(2).call()));
                ancestor = sub2.get(0);
            } else {
                ancestor = gt.commitOf(repository, diffWithBranch)
                        .orElseThrow(() -> new IOException("No commit on " + diffWithBranch));
            }
            if (localCommits.size() > 0) {
                local = localCommits.get(localCommits.size() - 1);
            } else {
                local = gt.commitOf(repository, currentBranch)
                        .orElseThrow(() -> new IOException("No commit on " + currentBranch));
            }

            if (commits > 0 || missing > 0) {
                if (commits == 0) {
                    stats = format(" [%s-%d%s]", CLR_SUBS, missing, CLEAR);
                } else if (missing == 0) {
                    stats = format(" [%s+%d%s]", CLR_ADDS, commits, CLEAR);
                } else {
                    stats = format(" [%s+%d%s,%s-%d%s]", CLR_ADDS, commits, CLEAR, CLR_SUBS, missing, CLEAR);
                }
            }

            System.out.println(format("Commits on %s%s%s%s since %s -- %s%s%s%s", CLR_UPDATED_BRANCH,
                    currentBranch, CLEAR, stats, date(ancestor), diff, DIM, ancestor.getShortMessage(), CLEAR));

            if (files) {
                ObjectReader reader = repository.newObjectReader();
                CanonicalTreeParser ancestorTreeIter = new CanonicalTreeParser();
                ancestorTreeIter.reset(reader, ancestor.getTree());
                CanonicalTreeParser localTreeIter = new CanonicalTreeParser();
                localTreeIter.reset(reader, local.getTree());

                // finally get the list of changed files
                List<DiffEntry> diffs = git.diff().setShowNameAndStatusOnly(true).setOldTree(ancestorTreeIter)
                        .setNewTree(localTreeIter).call();
                for (DiffEntry entry : diffs) {
                    switch (entry.getChangeType()) {
                    case RENAME:
                        System.out.println(format(" R %s%s%s <- %s%s%s", new Color(YELLOW, DIM),
                                entry.getNewPath(), CLEAR, DIM, path(entry.getOldPath()), CLEAR));
                        break;
                    case MODIFY:
                        System.out.println(format("   %s", path(entry.getOldPath())));
                        break;
                    case ADD:
                        System.out.println(format(" A %s%s%s", GREEN, path(entry.getNewPath()), CLEAR));
                        break;
                    case DELETE:
                        System.out.println(format(" D %s%s%s", YELLOW, path(entry.getOldPath()), CLEAR));
                        break;
                    case COPY:
                        System.out.println(format(" C %s%s%s <- %s%s%s", new Color(YELLOW, DIM),
                                path(entry.getNewPath()), CLEAR, DIM, path(entry.getOldPath()), CLEAR));
                        break;
                    }
                }
            } else {
                for (RevCommit localCommit : localCommits) {
                    System.out.println(format("+ %s%s%s (%s)", GREEN, localCommit.getShortMessage(), CLEAR,
                            date(localCommit)));
                }
                for (RevCommit remoteCommit : remoteCommits) {
                    System.out.println(format("- %s%s%s (%s)", RED, remoteCommit.getShortMessage(), CLEAR,
                            date(remoteCommit)));
                }
            }
        } else {
            RevCommit diffWithCommit = gt.commitOf(repository, diffWithBranch)
                    .orElseThrow(() -> new IOException("No commit in " + diffWithBranch));
            System.out.println(format("No commits on %s%s%s since %s -- %s%s%s", GREEN, currentBranch, CLEAR,
                    date(diffWithCommit), DIM, diffWithCommit.getShortMessage(), CLEAR));
        }

        // Check for staged and unstaged changes.
        if (files) {
            List<DiffEntry> staged = git.diff().setCached(true).call();
            List<DiffEntry> unstaged = git.diff().setCached(false).call();

            if (staged.size() > 0 || unstaged.size() > 0) {
                System.out.println();
                System.out.println(format("%sUncommitted%s changes on %s%s%s:", RED, CLEAR, CLR_UPDATED_BRANCH,
                        currentBranch, CLEAR));

                Map<String, FileStatus> st = unstaged.stream().map(d -> new FileStatus(relative, root, d))
                        .collect(Collectors.toMap(FileStatus::getNewestPath, fs -> fs));
                staged.forEach(d -> {
                    if (d.getNewPath() != null) {
                        if (st.containsKey(d.getNewPath())) {
                            st.get(d.getNewPath()).setStaged(d);
                            return;
                        }
                    }
                    if (d.getOldPath() != null) {
                        if (st.containsKey(d.getOldPath())) {
                            st.get(d.getOldPath()).setStaged(d);
                            return;
                        }
                    }
                    FileStatus fs = new FileStatus(relative, root, null).setStaged(d);

                    st.put(fs.getNewestPath(), fs);
                });

                for (FileStatus fs : new TreeMap<>(st).values()) {
                    System.out.println(fs.statusLine());
                }
            }
        } else {
            List<DiffEntry> staged = git.diff().setShowNameAndStatusOnly(true).setCached(true).call();
            List<DiffEntry> unstaged = git.diff().setShowNameAndStatusOnly(true).setCached(false).call();

            if (staged.size() > 0 || unstaged.size() > 0) {
                System.out.println(
                        format("Uncommitted changes on %s%s%s:", CLR_UPDATED_BRANCH, currentBranch, CLEAR));

                if (staged.size() > 0) {
                    long adds = staged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.ADD)
                            .count();
                    long dels = staged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.DELETE)
                            .count();
                    long mods = staged.size() - adds - dels;

                    System.out.print(format(" - %sStaged files%s   :", new Color(YELLOW, DIM), CLEAR));
                    if (adds > 0) {
                        System.out.print(format(" %s+%d%s", GREEN, adds, CLEAR));
                    }
                    if (dels > 0) {
                        System.out.print(format(" %s-%d%s", RED, dels, CLEAR));
                    }
                    if (mods > 0) {
                        System.out.print(format(" %s/%d%s", DIM, mods, CLEAR));
                    }
                    System.out.println();
                }
                if (unstaged.size() > 0) {
                    long adds = unstaged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.ADD)
                            .count();
                    long dels = unstaged.stream().filter(e -> e.getChangeType() == DiffEntry.ChangeType.DELETE)
                            .count();
                    long mods = unstaged.size() - adds - dels;

                    System.out.print(format(" - %sUnstaged files%s :", YELLOW, CLEAR));
                    if (adds > 0) {
                        System.out.print(format(" %s+%d%s", GREEN, adds, CLEAR));
                    }
                    if (dels > 0) {
                        System.out.print(format(" %s-%d%s", RED, dels, CLEAR));
                    }
                    if (mods > 0) {
                        System.out.print(format(" %s/%d%s", DIM, mods, CLEAR));
                    }
                    System.out.println();
                }
            }
        }
    } catch (GitAPIException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:org.eclipse.egit.ui.internal.actions.DiscardChangesAction.java

License:Open Source License

@Override
public boolean isEnabled() {
    for (IResource res : getSelectedResources()) {
        IProject[] proj = new IProject[] { res.getProject() };
        Repository repository = getRepositoriesFor(proj)[0];
        if (!repository.getRepositoryState().equals(RepositoryState.SAFE)) {
            return false;
        }//ww w.  j a v a2 s . com
    }
    return true;
}

From source file:org.eclipse.egit.ui.internal.actions.DiscardChangesActionHandler.java

License:Open Source License

@Override
public boolean isEnabled() {
    for (IResource res : getSelectedResources()) {
        IProject[] proj = new IProject[] { res.getProject() };
        Repository[] repositories = getRepositoriesFor(proj);
        if (repositories.length == 0)
            return false;
        Repository repository = repositories[0];
        if (!repository.getRepositoryState().equals(RepositoryState.SAFE)) {
            return false;
        }/*www.j a  v a  2s. c  om*/
    }
    return true;
}

From source file:org.eclipse.egit.ui.internal.actions.MergeAction.java

License:Open Source License

private boolean canMerge(final Repository repository) {
    String message = null;/*from  w ww . jav a2s .  com*/
    try {
        Ref head = repository.getRef(Constants.HEAD);
        if (head == null || !head.isSymbolic())
            message = UIText.MergeAction_HeadIsNoBranch;
        else if (!repository.getRepositoryState().equals(RepositoryState.SAFE))
            message = NLS.bind(UIText.MergeAction_WrongRepositoryState, repository.getRepositoryState());
    } catch (IOException e) {
        Activator.logError(e.getMessage(), e);
        message = e.getMessage();
    }

    if (message != null) {
        MessageDialog.openError(getShell(), UIText.MergeAction_CannotMerge, message);
    }
    return (message == null);
}