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

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

Introduction

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

Prototype

public abstract String getDescription();

Source Link

Usage

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 . j  a v  a 2 s  . com

        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: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;//from www.j  av  a 2  s  . c om
    try {
        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.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;/*www . ja va 2  s. c  o 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();
}

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

License:Open Source License

public Object execute(final ExecutionEvent event) throws ExecutionException {
    // 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 null;
    }//from  w w  w . j a  v  a2 s  .  c om

    resetState();
    final IProject[] projects = getProjectsInRepositoryOfSelectedResources(event);
    try {
        PlatformUI.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() {

            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                try {
                    buildIndexHeadDiffList(projects, monitor);
                } catch (IOException e) {
                    throw new InvocationTargetException(e);
                }
            }
        });
    } catch (InvocationTargetException e) {
        Activator.handleError(UIText.CommitAction_errorComputingDiffs, e.getCause(), true);
        return null;
    } catch (InterruptedException e) {
        return null;
    }

    Repository[] repos = getRepositoriesFor(getProjectsForSelectedResources(event));
    Repository repository = null;
    Repository mergeRepository = null;
    amendAllowed = repos.length == 1;
    boolean isMergedResolved = false;
    for (Repository repo : repos) {
        repository = repo;
        RepositoryState state = repo.getRepositoryState();
        if (!state.canCommit()) {
            MessageDialog.openError(getShell(event), UIText.CommitAction_cannotCommit,
                    NLS.bind(UIText.CommitAction_repositoryState, state.getDescription()));
            return null;
        } else if (state.equals(RepositoryState.MERGING_RESOLVED)) {
            isMergedResolved = true;
            mergeRepository = repo;
        }
    }

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

    String author = null;
    String committer = null;
    if (repository != null) {
        final UserConfig config = repository.getConfig().get(UserConfig.KEY);
        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(getShell(event));
    commitDialog.setAmending(amending);
    commitDialog.setAmendAllowed(amendAllowed);
    commitDialog.setFileList(files, indexDiffs);
    commitDialog.setPreselectedFiles(getSelectedFiles(event));
    commitDialog.setAuthor(author);
    commitDialog.setCommitter(committer);
    commitDialog.setAllowToChangeSelection(!isMergedResolved);

    if (previousCommit != null) {
        commitDialog.setPreviousCommitMessage(previousCommit.getFullMessage());
        PersonIdent previousAuthor = previousCommit.getAuthorIdent();
        commitDialog
                .setPreviousAuthor(previousAuthor.getName() + " <" + previousAuthor.getEmailAddress() + ">"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    if (isMergedResolved) {
        commitDialog.setCommitMessage(getMergeResolveMessage(mergeRepository, event));
    }

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

    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);
    }
    commitOperation.setComputeChangeId(commitDialog.getCreateChangeId());
    commitOperation.setCommitAll(isMergedResolved);
    if (isMergedResolved)
        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(event)) {
                    RepositoryMapping.getMapping(proj).fireRepositoryChanged();
                }
            } catch (CoreException e) {
                return Activator.createErrorStatus(UIText.CommitAction_CommittingFailed, e);
            } catch (ExecutionException e) {
                return Activator.createErrorStatus(UIText.CommitAction_CommittingFailed, e);
            } finally {
                GitLightweightDecorator.refresh();
            }
            return Status.OK_STATUS;
        }

        @Override
        public boolean belongsTo(Object family) {
            if (family.equals(JobFamilies.COMMIT))
                return true;
            return super.belongsTo(family);
        }

    };
    job.setUser(true);
    job.schedule();
    return null;
}

From source file:org.eclipse.egit.ui.internal.commit.CommitHelper.java

License:Open Source License

private void calculateCommitInfo() {
    Repository mergeRepository = null;/*from w  w  w  .j av a2 s .com*/
    isMergedResolved = false;
    isCherryPickResolved = false;
    RepositoryState state = repository.getRepositoryState();
    canCommit = state.canCommit();
    if (!canCommit) {
        cannotCommitMessage = NLS.bind(UIText.CommitAction_repositoryState, state.getDescription());
        return;
    }
    if (state.equals(RepositoryState.MERGING_RESOLVED)) {
        isMergedResolved = true;
        mergeRepository = repository;
    } else if (state.equals(RepositoryState.CHERRY_PICKING_RESOLVED)) {
        isCherryPickResolved = true;
        mergeRepository = repository;
    }
    previousCommit = getHeadCommit(repository);
    final UserConfig config = repository.getConfig().get(UserConfig.KEY);
    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$

    if (isMergedResolved || isCherryPickResolved) {
        commitMessage = getMergeResolveMessage(mergeRepository);
    }

    if (isCherryPickResolved) {
        author = getCherryPickOriginalAuthor(mergeRepository);
    }
}

From source file:org.eclipse.egit.ui.internal.decorators.DecoratableResourceAdapter.java

License:Open Source License

@SuppressWarnings("fallthrough")
public DecoratableResourceAdapter(IResource resourceToWrap) throws IOException {
    trace = GitTraceLocation.DECORATION.isActive();
    resource = resourceToWrap;/*from   ww  w  . j ava  2  s.  c o  m*/
    long start = 0;
    if (trace) {
        GitTraceLocation.getTrace().trace(GitTraceLocation.DECORATION.getLocation(),
                "Decorate " + resource.getFullPath()); //$NON-NLS-1$
        start = System.currentTimeMillis();
    }
    try {
        mapping = RepositoryMapping.getMapping(resource);
        repository = mapping.getRepository();
        headId = repository.resolve(Constants.HEAD);

        store = Activator.getDefault().getPreferenceStore();
        String repoName = Activator.getDefault().getRepositoryUtil().getRepositoryName(repository);
        RepositoryState state = repository.getRepositoryState();
        if (state != RepositoryState.SAFE)
            repositoryName = repoName + '|' + state.getDescription();
        else
            repositoryName = repoName;

        branch = getShortBranch();

        TreeWalk treeWalk = createThreeWayTreeWalk();
        if (treeWalk == null)
            return;

        switch (resource.getType()) {
        case IResource.FILE:
            if (!treeWalk.next())
                return;
            extractResourceProperties(treeWalk);
            break;
        case IResource.PROJECT:
            tracked = true;
        case IResource.FOLDER:
            extractContainerProperties(treeWalk);
            break;
        }
    } finally {
        if (trace)
            GitTraceLocation.getTrace().trace(GitTraceLocation.DECORATION.getLocation(),
                    "Decoration took " + (System.currentTimeMillis() - start) //$NON-NLS-1$
                            + " ms"); //$NON-NLS-1$
    }
}

From source file:org.eclipse.egit.ui.internal.decorators.DecoratableResourceHelper.java

License:Open Source License

static String getRepositoryName(Repository repository) {
    String repoName = Activator.getDefault().getRepositoryUtil().getRepositoryName(repository);
    RepositoryState state = repository.getRepositoryState();
    if (state != RepositoryState.SAFE)
        return repoName + '|' + state.getDescription();
    else//from www  .  j a va  2 s  .  c o m
        return repoName;
}

From source file:org.eclipse.egit.ui.internal.GitLabelProvider.java

License:Open Source License

/**
 * @param repository/*from w w  w  . j a v a  2s.  c  om*/
 * @return a styled string for the repository
 * @throws IOException
 */
protected StyledString getStyledTextFor(Repository repository) throws IOException {
    File directory = repository.getDirectory();
    StyledString string = new StyledString();
    if (!repository.isBare())
        string.append(directory.getParentFile().getName());
    else
        string.append(directory.getName());

    String branch = Activator.getDefault().getRepositoryUtil().getShortBranch(repository);
    if (branch != null) {
        string.append(' ');
        string.append('[', StyledString.DECORATIONS_STYLER);
        string.append(branch, StyledString.DECORATIONS_STYLER);

        RepositoryState repositoryState = repository.getRepositoryState();
        if (repositoryState != RepositoryState.SAFE) {
            string.append(" - ", StyledString.DECORATIONS_STYLER); //$NON-NLS-1$
            string.append(repositoryState.getDescription(), StyledString.DECORATIONS_STYLER);
        }

        BranchTrackingStatus trackingStatus = BranchTrackingStatus.of(repository, branch);
        if (trackingStatus != null
                && (trackingStatus.getAheadCount() != 0 || trackingStatus.getBehindCount() != 0)) {
            String formattedTrackingStatus = formatBranchTrackingStatus(trackingStatus);
            string.append(' ');
            string.append(formattedTrackingStatus, StyledString.DECORATIONS_STYLER);
        }
        string.append(']', StyledString.DECORATIONS_STYLER);
    }

    string.append(" - ", StyledString.QUALIFIER_STYLER); //$NON-NLS-1$
    string.append(directory.getAbsolutePath(), StyledString.QUALIFIER_STYLER);

    return string;
}

From source file:org.eclipse.egit.ui.internal.GitLabels.java

License:Open Source License

/**
 * Computes detailed repository label that consists of repository name,
 * state, checked-out branch and it's status (returned by
 * {@linkplain #formatBranchTrackingStatus(BranchTrackingStatus)})
 *
 * @param repository/*from www.  java  2s  .  c om*/
 * @return a styled string for the repository
 * @throws IOException
 */
public static @NonNull StyledString getStyledLabel(@NonNull Repository repository) throws IOException {
    RepositoryUtil repositoryUtil = Activator.getDefault().getRepositoryUtil();

    StyledString string = getChangedPrefix(repository);

    string.append(repositoryUtil.getRepositoryName(repository));

    String branch = repositoryUtil.getShortBranch(repository);
    if (branch != null) {
        string.append(' ');
        string.append('[', StyledString.DECORATIONS_STYLER);
        string.append(branch, StyledString.DECORATIONS_STYLER);

        BranchTrackingStatus trackingStatus = BranchTrackingStatus.of(repository, branch);
        if (trackingStatus != null
                && (trackingStatus.getAheadCount() != 0 || trackingStatus.getBehindCount() != 0)) {
            String formattedTrackingStatus = GitLabels.formatBranchTrackingStatus(trackingStatus);
            string.append(' ');
            string.append(formattedTrackingStatus, StyledString.DECORATIONS_STYLER);
        }

        RepositoryState repositoryState = repository.getRepositoryState();
        if (repositoryState != RepositoryState.SAFE) {
            string.append(" - ", StyledString.DECORATIONS_STYLER); //$NON-NLS-1$
            string.append(repositoryState.getDescription(), StyledString.DECORATIONS_STYLER);
        }
        string.append(']', StyledString.DECORATIONS_STYLER);
    }

    return string;
}

From source file:org.eclipse.egit.ui.internal.rebase.RebaseInteractiveView.java

License:Open Source License

private static String getRepositoryName(Repository repository) {
    String repoName = Activator.getDefault().getRepositoryUtil().getRepositoryName(repository);
    RepositoryState state = repository.getRepositoryState();
    if (state != RepositoryState.SAFE)
        return repoName + '|' + state.getDescription();
    else/*ww w . j  ava  2s.c  o  m*/
        return repoName;
}