Example usage for org.eclipse.jgit.lib Repository getRepositoryState

List of usage examples for org.eclipse.jgit.lib Repository getRepositoryState

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository getRepositoryState.

Prototype

@NonNull
public RepositoryState getRepositoryState() 

Source Link

Document

Get the repository state

Usage

From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java

License:Open Source License

@Override
public void saveReview(URI uri, ModelReview modelReview, User currentReviewer, IProgressMonitor monitor)
        throws InvalidReviewRepositoryException, InvalidReviewException, RepositoryIOException {

    monitor.beginTask("Connecting to repository", IProgressMonitor.UNKNOWN);

    String repoFileURI = COMMENTS_FILE_URI;

    try {/*from  ww  w . ja  v  a2 s.c o  m*/
        Git git = Git.open(new File(uri));
        Repository repository = git.getRepository();
        ObjectInserter objectInserter = repository.newObjectInserter();

        String commentRefName = getCommentRefName(modelReview);
        Ref commentRef = repository.exactRef(commentRefName);

        DirCache index = DirCache.newInCore();
        DirCacheBuilder dirCacheBuilder = index.builder();

        monitor.beginTask("Preparing commit...", IProgressMonitor.UNKNOWN);

        if (commentRef != null) {

            /*
             * The ref already exists so we have to copy the previous
             * RevTree to keep all already attached files
             */

            RevWalk revWalk = new RevWalk(repository);
            RevCommit prevCommit = revWalk.parseCommit(commentRef.getObjectId());
            RevTree tree = prevCommit.getTree();

            List<String> ignoredFiles = new ArrayList<>();
            /*
             * add file path of the new file to the ignored file paths, as
             * we don't want any already existing old file in our new tree
             */
            ignoredFiles.add(repoFileURI);
            buildDirCacheFromTree(tree, repository, dirCacheBuilder, ignoredFiles);

            revWalk.close();
        }

        monitor.beginTask("Writing comments file...", IProgressMonitor.UNKNOWN);

        ResourceSet resourceSet = new ResourceSetImpl();
        Resource resource = resourceSet.createResource(org.eclipse.emf.common.util.URI.createURI(repoFileURI));

        addCommentsToResource(modelReview, resource);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        resource.save(outputStream, null);

        // insert file as object
        byte[] content = outputStream.toByteArray();
        long length = content.length;
        InputStream inputStream = new ByteArrayInputStream(content);
        ObjectId objectId = objectInserter.insert(Constants.OBJ_BLOB, length, inputStream);
        inputStream.close();

        // create tree entry
        DirCacheEntry entry = new DirCacheEntry(repoFileURI);
        entry.setFileMode(FileMode.REGULAR_FILE);
        entry.setLastModified(System.currentTimeMillis());
        entry.setLength(length);
        entry.setObjectId(objectId);
        dirCacheBuilder.add(entry);

        dirCacheBuilder.finish();

        // write new tree in database
        ObjectId indexTreeId = index.writeTree(objectInserter);

        monitor.beginTask("Commiting comments...", IProgressMonitor.UNKNOWN);

        // create commit
        CommitBuilder commitBuilder = new CommitBuilder();
        PersonIdent personIdent = new PersonIdent("Mervin", "mervin@mervin.modelreview");
        commitBuilder.setCommitter(personIdent);
        commitBuilder.setAuthor(personIdent);
        commitBuilder.setMessage(
                MessageFormat.format("Updated comments by user \"{0}\"", currentReviewer.getName()));

        if (commentRef != null) {
            commitBuilder.setParentId(commentRef.getObjectId());
        }
        commitBuilder.setTreeId(indexTreeId);

        // commit
        ObjectId commitId = objectInserter.insert(commitBuilder);
        objectInserter.flush();

        RefUpdate refUpdate = repository.updateRef(commentRefName);
        refUpdate.setNewObjectId(commitId);
        if (commentRef != null)
            refUpdate.setExpectedOldObjectId(commentRef.getObjectId());
        else
            refUpdate.setExpectedOldObjectId(ObjectId.zeroId());

        /*
         * TODO the result handling below is copied from the CommitCommand
         * class, I don't know if this is really necessary in our case
         */
        Result result = refUpdate.forceUpdate();
        switch (result) {
        case NEW:
        case FORCED:
        case FAST_FORWARD: {
            if (repository.getRepositoryState() == RepositoryState.MERGING_RESOLVED) {
                /*
                 * Commit was successful. Now delete the files used for
                 * merge commits
                 */
                repository.writeMergeCommitMsg(null);
                repository.writeMergeHeads(null);
            } else if (repository.getRepositoryState() == RepositoryState.CHERRY_PICKING_RESOLVED) {
                repository.writeMergeCommitMsg(null);
                repository.writeCherryPickHead(null);
            } else if (repository.getRepositoryState() == RepositoryState.REVERTING_RESOLVED) {
                repository.writeMergeCommitMsg(null);
                repository.writeRevertHead(null);
            }
            break;
        }
        case REJECTED:
        case LOCK_FAILURE:
            throw new RepositoryIOException("Error occured during writing to the git repository",
                    new ConcurrentRefUpdateException("Could not lock ref " + refUpdate.getRef().getName(),
                            refUpdate.getRef(), result));
        default:
            throw new RepositoryIOException("Error occured during writing to the git repository",
                    new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            refUpdate.getRef().getName(), commitId.toString(), result)));
        }

    } catch (IOException e) {
        throw new InvalidReviewRepositoryException("Could not open local git repository", e);
    } finally {
        monitor.done();
    }

}

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;/*from   www  .j  a  v a  2s .  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:de.unihalle.informatik.Alida.version.ALDVersionProviderGit.java

License:Open Source License

/**
 * Returns information about current commit.
 * <p>/*from   w w  w  .j  ava 2 s  .  c  o  m*/
 * If no git repository is found, the method checks for a file 
 * "revision.txt" as it is present in Alida jar files. 
 * If the file does not exist or is empty, a dummy string is returned.
 * 
 * @return    Info string.
 */
private static String getRepositoryInfo() {

    ALDVersionProviderGit.localVersion = "Unknown";
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    try {
        Repository repo = null;
        try {
            repo = builder.readEnvironment().build();
        } catch (IllegalArgumentException e) {
            // problem accessing environment... fall back to default
            if (repo != null)
                repo.close();
            return ALDVersionProviderGit.localVersion;
        }

        // check if GIT_DIR is set
        if (!builder.getGitDir().isDirectory()) {
            if (repo != null)
                repo.close();
            return ALDVersionProviderGit.localVersion;
        }

        // extract the active branch
        String activeBranch = repo.getBranch();

        // extract last commit 
        Ref HEAD = repo.findRef(activeBranch);

        // safety check if everything is alright with repository
        if (HEAD == null) {
            repo.close();
            throw new IOException();
        }

        // extract state of repository
        String state = repo.getRepositoryState().toString();

        ALDVersionProviderGit.localVersion = activeBranch + " : " + HEAD.toString() + " ( " + state + " ) ";

        // clean-up
        repo.close();
    } catch (IOException e) {
        // accessing the Git repository failed, search for file
        InputStream is = null;
        BufferedReader br = null;
        String vLine = null;

        // initialize file reader and extract version information
        try {
            System.out.print("Searching for local revision file...");
            is = ALDVersionProviderGit.class.getResourceAsStream("/" + ALDVersionProviderGit.revFile);
            br = new BufferedReader(new InputStreamReader(is));
            vLine = br.readLine();
            if (vLine == null) {
                System.err.println("ALDVersionProviderGit: " + "revision file is empty...!?");
                br.close();
                is.close();
                return ALDVersionProviderGit.localVersion;
            }
            ALDVersionProviderGit.localVersion = vLine;
            br.close();
            is.close();
            return vLine;
        } catch (Exception ex) {
            try {
                if (br != null)
                    br.close();
                if (is != null)
                    is.close();
            } catch (IOException eo) {
                // nothing to do here
            }
            return ALDVersionProviderGit.localVersion;
        }
    }
    return ALDVersionProviderGit.localVersion;
}

From source file:net.erdfelt.android.sdkfido.git.internal.GitInfo.java

License:Apache License

public static void infoAll(Repository db) throws IOException {
    System.out.printf("Repository - %s%n", db.getDirectory());
    System.out.printf("      state: %s%n", db.getRepositoryState());
    System.out.printf("     branch: %s%n", db.getBranch());
    System.out.printf("full-branch: %s%n", db.getFullBranch());
    infoRefs(db);/*w ww  . j a va2 s  . c o  m*/
    infoBranches(db);
    infoTags(db);
}

From source file:net.tietema.versioning.GitJavaVersioning.java

License:Apache License

public String getRevision(File projectDir) throws MojoExecutionException {
    // XXX we use our own findGitDir because they JGit one doesn't find the git dir in a multi project build
    File gitDir = findGitDir(projectDir);
    String revision = "Unknown";
    if (gitDir == null)
        return revision;

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = null;
    try {/* w  ww . jav  a  2s  .co m*/
        repository = builder.setGitDir(gitDir).readEnvironment() // scan environment GIT_* variables
                .findGitDir(projectDir) // scan up the file system tree
                .build();

        log.info("Git dir: " + gitDir.toString());
        RepositoryState state = repository.getRepositoryState();
        log.info(state.getDescription());
        String branch = repository.getBranch();
        log.info("Branch is: " + branch);
        Git git = new Git(repository);
        String fullBranch = repository.getFullBranch();
        log.info("Full branch is: " + fullBranch);
        ObjectId id = repository.resolve(fullBranch);
        log.info("Branch " + repository.getBranch() + " points to " + id.name());

        Status status = git.status().call();
        boolean strictClean = status.isClean();
        // no untracked files
        boolean loseClean = status.getAdded().isEmpty() && status.getChanged().isEmpty()
                && status.getConflicting().isEmpty() && status.getMissing().isEmpty()
                && status.getModified().isEmpty() && status.getRemoved().isEmpty();

        StringWriter buffer = new StringWriter();
        JavaWriter writer = new JavaWriter(buffer);
        writer.emitPackage(packageName)
                .beginType(packageName + "." + className, "class", Modifier.PUBLIC | Modifier.FINAL)
                .emitField("String", "BRANCH", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC,
                        String.format(Locale.US, "\"%s\"", branch))
                .emitField("String", "REVISION", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC,
                        String.format(Locale.US, "\"%s\"", id.name()))
                .emitField("String", "REVISION_SHORT", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC,
                        String.format(Locale.US, "\"%s\"", id.name().substring(0, 8)))
                .emitJavadoc("Strict Clean means no changes, not even untracked files")
                .emitField("boolean", "STRICT_CLEAN", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC,
                        (strictClean ? "true" : "false"))
                .emitJavadoc("Lose Clean means no changes except untracked files.")
                .emitField("boolean", "LOSE_CLEAN", Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC,
                        (loseClean ? "true" : "false"))
                .endType();
        revision = buffer.toString();

        return revision;
    } catch (IOException e) {
        log.error(e);
        throw new MojoExecutionException(e.getMessage());
    } catch (GitAPIException e) {
        log.error(e);
        throw new MojoExecutionException(e.getMessage());
    } finally {
        if (repository != null)
            repository.close();
    }
}

From source file:org.eclipse.egit.core.internal.rebase.RebaseInteractivePlan.java

License:Open Source License

/**
 * @return true if repository state is/* w w w  . jav  a 2s . c om*/
 *         {@link RepositoryState#REBASING_INTERACTIVE}
 */
public boolean isRebasingInteractive() {
    Repository repository = getRepository();
    return repository != null && repository.getRepositoryState() == RepositoryState.REBASING_INTERACTIVE;
}

From source file:org.eclipse.egit.core.internal.rebase.RebaseInteractivePlan.java

License:Open Source License

/**
 * Writes the plan to the FS./*w  ww  . j a v a  2 s .  c  o m*/
 * <p>
 * Only {@link PlanElement Elements} of {@link ElementType#TODO} are
 * persisted.
 *
 * @param repository
 *            the plan belongs to
 *
 * @return true if the todo file has been written successfully, otherwise
 *         false
 */
private boolean persist(Repository repository) {
    if (repository == null || repository.getRepositoryState() != RepositoryState.REBASING_INTERACTIVE) {
        return false;
    }
    List<RebaseTodoLine> todoLines = new LinkedList<RebaseTodoLine>();
    for (PlanElement element : planList.getSecondList())
        todoLines.add(element.getRebaseTodoLine());
    try {
        repository.writeRebaseTodoFile(REBASE_TODO, todoLines, false);
    } catch (IOException e) {
        Activator.logError(CoreText.RebaseInteractivePlan_WriteRebaseTodoFailed, e);
        throw new RuntimeException(e);
    }
    return true;
}

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

License:Open Source License

@Override
public void execute(IAction action) throws InvocationTargetException, InterruptedException {
    final Repository repository = getRepository(true);
    if (repository == null)
        return;/*from   w w  w  .j  a  v a2s .  c o m*/

    if (!repository.getRepositoryState().canCheckout()) {
        MessageDialog.openError(getShell(), UIText.BranchAction_cannotCheckout, NLS
                .bind(UIText.BranchAction_repositoryState, repository.getRepositoryState().getDescription()));
        return;
    }

    BranchSelectionDialog dialog = new BranchSelectionDialog(getShell(), repository);
    if (dialog.open() != Window.OK) {
        return;
    }

    final String refName = dialog.getRefName();

    String jobname = NLS.bind(UIText.BranchAction_checkingOut, refName);
    Job job = new Job(jobname) {
        @Override
        protected IStatus run(IProgressMonitor monitor) {
            try {
                new BranchOperation(repository, refName).execute(monitor);
            } catch (CoreException e) {
                return Activator.createErrorStatus(UIText.BranchAction_branchFailed, e);
            } finally {
                GitLightweightDecorator.refresh();
            }
            return Status.OK_STATUS;
        }
    };
    job.setUser(true);
    job.schedule();
}

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

License:Open Source License

public Object execute(ExecutionEvent event) throws ExecutionException {
    final Repository repository = getRepository(true, event);
    if (repository == null)
        return null;

    if (!repository.getRepositoryState().canCheckout()) {
        MessageDialog.openError(getShell(event), UIText.BranchAction_cannotCheckout, NLS
                .bind(UIText.BranchAction_repositoryState, repository.getRepositoryState().getDescription()));
        return null;
    }/*from  w w  w.j  a v a  2s  .  com*/

    BranchSelectionDialog dialog = new BranchSelectionDialog(getShell(event), repository);
    if (dialog.open() != Window.OK) {
        return null;
    }

    final String refName = dialog.getRefName();

    String jobname = NLS.bind(UIText.BranchAction_checkingOut, refName);
    Job job = new Job(jobname) {
        @Override
        protected IStatus run(IProgressMonitor monitor) {
            try {
                new BranchOperation(repository, refName).execute(monitor);
            } catch (CoreException e) {
                return Activator.createErrorStatus(UIText.BranchAction_branchFailed, e);
            } finally {
                GitLightweightDecorator.refresh();
            }
            return Status.OK_STATUS;
        }
    };
    job.setUser(true);
    job.schedule();
    return null;
}

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

License:Open Source License

@Override
public void execute(IAction act) {
    // let's see if there is any dirty editor around and
    // ask the user if they want to save or abort
    if (!PlatformUI.getWorkbench().saveAllEditors(true)) {
        return;//from  w  ww  . ja va2 s .  co m
    }

    resetState();
    try {
        buildIndexHeadDiffList();
    } catch (IOException e) {
        handle(new TeamException(UIText.CommitAction_errorComputingDiffs, e),
                UIText.CommitAction_errorDuringCommit, UIText.CommitAction_errorComputingDiffs);
        return;
    } catch (CoreException e) {
        handle(new TeamException(UIText.CommitAction_errorComputingDiffs, e),
                UIText.CommitAction_errorDuringCommit, UIText.CommitAction_errorComputingDiffs);
        return;
    }

    Repository[] repos = getRepositoriesFor(getProjectsForSelectedResources());
    Repository repository = null;
    amendAllowed = repos.length == 1;
    for (Repository repo : repos) {
        repository = repo;
        RepositoryState state = repo.getRepositoryState();
        // currently we don't support committing a merge commit
        if (state == RepositoryState.MERGING_RESOLVED || !state.canCommit()) {
            MessageDialog.openError(getTargetPart().getSite().getShell(), UIText.CommitAction_cannotCommit,
                    NLS.bind(UIText.CommitAction_repositoryState, state.getDescription()));
            return;
        }
    }

    loadPreviousCommit();
    if (files.isEmpty()) {
        if (amendAllowed && previousCommit != null) {
            boolean result = MessageDialog.openQuestion(getTargetPart().getSite().getShell(),
                    UIText.CommitAction_noFilesToCommit, UIText.CommitAction_amendCommit);
            if (!result)
                return;
            amending = true;
        } else {
            MessageDialog.openWarning(getTargetPart().getSite().getShell(), UIText.CommitAction_noFilesToCommit,
                    UIText.CommitAction_amendNotPossible);
            return;
        }
    }

    String author = null;
    String committer = null;
    if (repository != null) {
        final RepositoryConfig config = repository.getConfig();
        author = config.getAuthorName();
        final String authorEmail = config.getAuthorEmail();
        author = author + " <" + authorEmail + ">"; //$NON-NLS-1$ //$NON-NLS-2$

        committer = config.getCommitterName();
        final String committerEmail = config.getCommitterEmail();
        committer = committer + " <" + committerEmail + ">"; //$NON-NLS-1$ //$NON-NLS-2$
    }

    CommitDialog commitDialog = new CommitDialog(getTargetPart().getSite().getShell());
    commitDialog.setAmending(amending);
    commitDialog.setAmendAllowed(amendAllowed);
    commitDialog.setFileList(files);
    commitDialog.setPreselectedFiles(getSelectedFiles());
    commitDialog.setAuthor(author);
    commitDialog.setCommitter(committer);

    if (previousCommit != null) {
        commitDialog.setPreviousCommitMessage(previousCommit.getMessage());
        PersonIdent previousAuthor = previousCommit.getAuthor();
        commitDialog
                .setPreviousAuthor(previousAuthor.getName() + " <" + previousAuthor.getEmailAddress() + ">"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    if (commitDialog.open() != IDialogConstants.OK_ID)
        return;

    final CommitOperation commitOperation = new CommitOperation(commitDialog.getSelectedFiles(), notIndexed,
            notTracked, commitDialog.getAuthor(), commitDialog.getCommitter(), commitDialog.getCommitMessage());
    if (commitDialog.isAmending()) {
        commitOperation.setAmending(true);
        commitOperation.setPreviousCommit(previousCommit);
        commitOperation.setRepos(repos);
    }
    String jobname = UIText.CommitAction_CommittingChanges;
    Job job = new Job(jobname) {
        @Override
        protected IStatus run(IProgressMonitor monitor) {
            try {
                commitOperation.execute(monitor);

                for (IProject proj : getProjectsForSelectedResources()) {
                    RepositoryMapping.getMapping(proj).fireRepositoryChanged();
                }
            } catch (CoreException e) {
                return Activator.createErrorStatus(UIText.CommitAction_CommittingFailed, e);
            } finally {
                GitLightweightDecorator.refresh();
            }
            return Status.OK_STATUS;
        }
    };
    job.setUser(true);
    job.schedule();
}