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

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

Introduction

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

Prototype

@NonNull
public File getWorkTree() throws NoWorkTreeException 

Source Link

Document

Get the root directory of the working tree, where files are checked out for viewing and editing.

Usage

From source file:org.efaps.cli.rest.ImportCICall.java

License:Apache License

/**
 * Gets the file information.// w w w  .java 2  s  .c  o m
 *
 * @param _file the _file
 * @return the file information
 */
protected String[] getFileInformation(final File _file) {
    final String[] ret = new String[2];

    try {
        final Repository repo = new FileRepository(evalGitDir(_file));

        final ObjectId lastCommitId = repo.resolve(Constants.HEAD);

        final PlotCommitList<PlotLane> plotCommitList = new PlotCommitList<PlotLane>();
        final PlotWalk revWalk = new PlotWalk(repo);

        final RevCommit root = revWalk.parseCommit(lastCommitId);
        revWalk.markStart(root);
        revWalk.setTreeFilter(AndTreeFilter.create(
                PathFilter.create(_file.getPath().replaceFirst(repo.getWorkTree().getPath() + "/", "")),
                TreeFilter.ANY_DIFF));
        plotCommitList.source(revWalk);
        plotCommitList.fillTo(2);
        final PlotCommit<PlotLane> commit = plotCommitList.get(0);
        if (commit != null) {
            final PersonIdent authorIdent = commit.getAuthorIdent();
            final Date authorDate = authorIdent.getWhen();
            final TimeZone authorTimeZone = authorIdent.getTimeZone();
            final DateTime dateTime = new DateTime(authorDate.getTime(),
                    DateTimeZone.forTimeZone(authorTimeZone));
            ret[1] = dateTime.toString();
            ret[0] = commit.getId().getName();
        } else {
            ret[1] = new DateTime().toString();
            ret[0] = "UNKNOWN";
        }
    } catch (final RevisionSyntaxException | IOException e) {
        e.printStackTrace();
    }
    return ret;
}

From source file:org.efaps.eclipse.rest.RestClient.java

License:Apache License

protected String[] getFileInformation(final File _file) {
    final String[] ret = new String[2];

    try {//from www .  j  ava  2 s  . com
        final Repository repo = new FileRepository(evalGitDir(_file));

        final ObjectId lastCommitId = repo.resolve(Constants.HEAD);

        final PlotCommitList<PlotLane> plotCommitList = new PlotCommitList<PlotLane>();
        final PlotWalk revWalk = new PlotWalk(repo);

        final RevCommit root = revWalk.parseCommit(lastCommitId);
        revWalk.markStart(root);
        revWalk.setTreeFilter(AndTreeFilter.create(
                PathFilter.create(_file.getPath().replaceFirst(repo.getWorkTree().getPath() + "/", "")),
                TreeFilter.ANY_DIFF));
        plotCommitList.source(revWalk);
        plotCommitList.fillTo(2);
        final PlotCommit<PlotLane> commit = plotCommitList.get(0);
        if (commit != null) {
            final PersonIdent authorIdent = commit.getAuthorIdent();
            final Date authorDate = authorIdent.getWhen();
            final TimeZone authorTimeZone = authorIdent.getTimeZone();
            final DateTime dateTime = new DateTime(authorDate.getTime(),
                    DateTimeZone.forTimeZone(authorTimeZone));
            ret[1] = dateTime.toString();
            ret[0] = commit.getId().getName();
        } else {
            ret[1] = new DateTime().toString();
            ret[0] = "UNKNOWN";
        }
    } catch (RevisionSyntaxException | IOException e) {
        e.printStackTrace();
    }
    return ret;
}

From source file:org.eluder.coveralls.maven.plugin.domain.GitRepository.java

License:Open Source License

public Git load() throws IOException {
    Repository repository = new RepositoryBuilder().findGitDir(this.sourceDirectory).build();
    try {// w w  w .j  a v  a2  s  .c  o  m
        Git.Head head = getHead(repository);
        String branch = getBranch(repository);
        List<Git.Remote> remotes = getRemotes(repository);
        return new Git(repository.getWorkTree(), head, branch, remotes);
    } finally {
        repository.close();
    }
}

From source file:org.flowerplatform.web.git.GitService.java

License:Open Source License

@RemoteInvocation
public ImportProjectPageDto getProjects(ServiceInvocationContext context, List<PathFragment> path) {
    try {//from ww  w. j  ava  2s  .  co  m
        List<String> directories = new ArrayList<String>();
        List<File> files = new ArrayList<File>();

        @SuppressWarnings("unchecked")
        Pair<File, String> node = (Pair<File, String>) GenericTreeStatefulService.getNodeByPathFor(path, null);
        Repository repo = GitPlugin.getInstance().getUtils().getRepository(node.a);

        GitPlugin.getInstance().getUtils().findProjectFiles(files, repo.getWorkTree(), null);

        List<ProjectDto> projects = new ArrayList<ProjectDto>();

        for (File projectSystemFile : files) {
            // project path
            IPath projPath = new Path(projectSystemFile.getParentFile().getCanonicalPath());
            String projectName = projPath.lastSegment();
            File repoFile = repo.getDirectory().getParentFile().getParentFile();
            String projectRelativeLocation = projPath.makeRelativeTo(new Path(repoFile.getAbsolutePath()))
                    .toString();
            ProjectDto dto = new ProjectDto();
            dto.setName(projectName + " (" + projectRelativeLocation + ")");
            dto.setLocation(projPath.toString());

            projects.add(dto);
        }
        ImportProjectPageDto result = new ImportProjectPageDto();
        result.setExistingProjects(projects);
        result.setSelectedFolders(directories);

        return result;
    } catch (Exception e) {
        logger.debug(GitPlugin.getInstance().getMessage("git.page.populate.error"), e);
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        GitPlugin.getInstance().getMessage("git.page.populate.error"),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
        return null;
    }
}

From source file:org.flowerplatform.web.git.operation.CheckoutOperation.java

License:Open Source License

public boolean execute() {
    ProgressMonitor monitor = ProgressMonitor
            .create(GitPlugin.getInstance().getMessage("git.checkout.monitor.title"), channel);

    try {//from   w w  w  . j a  v  a2 s  .c  o m
        monitor.beginTask(
                GitPlugin.getInstance().getMessage("git.checkout.monitor.message", new Object[] { name }), 4);
        monitor.setTaskName("Getting remote branch...");
        Git git = new Git(repository);
        Ref ref;
        if (node instanceof Ref) {
            ref = (Ref) node;
        } else {
            // get remote branch
            String dst = Constants.R_REMOTES + remote.getName();
            String remoteRefName = dst + "/" + upstreamBranch.getShortName();
            ref = repository.getRef(remoteRefName);
            if (ref == null) { // doesn't exist, fetch it
                RefSpec refSpec = new RefSpec();
                refSpec = refSpec.setForceUpdate(true);
                refSpec = refSpec.setSourceDestination(upstreamBranch.getName(), remoteRefName);

                git.fetch().setRemote(new URIish(remote.getUri()).toPrivateString()).setRefSpecs(refSpec)
                        .call();

                ref = repository.getRef(remoteRefName);
            }
        }
        monitor.worked(1);
        monitor.setTaskName("Creating local branch...");

        // create local branch
        git.branchCreate().setName(name).setStartPoint(ref.getName())
                .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM).call();

        if (!(node instanceof Ref)) {
            // save upstream configuration
            StoredConfig config = repository.getConfig();

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_MERGE,
                    upstreamBranch.getName());

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REMOTE,
                    remote.getName());

            if (rebase) {
                config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, name,
                        ConfigConstants.CONFIG_KEY_REBASE, true);
            } else {
                config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REBASE);
            }
            config.save();
        }
        monitor.worked(1);
        monitor.setTaskName("Creating working directory");

        // create working directory for local branch
        File mainRepoFile = repository.getDirectory().getParentFile();
        File wdirFile = new File(mainRepoFile.getParentFile(), GitUtils.WORKING_DIRECTORY_PREFIX + name);
        if (wdirFile.exists()) {
            GitPlugin.getInstance().getUtils().delete(wdirFile);
        }
        GitPlugin.getInstance().getUtils().run_git_workdir_cmd(mainRepoFile.getAbsolutePath(),
                wdirFile.getAbsolutePath());
        monitor.worked(1);
        monitor.setTaskName("Checkout branch");

        // checkout local branch
        Repository wdirRepo = GitPlugin.getInstance().getUtils().getRepository(wdirFile);
        git = new Git(wdirRepo);

        CheckoutCommand cc = git.checkout().setName(name).setForce(true);
        cc.call();

        // show checkout result
        if (cc.getResult().getStatus() == CheckoutResult.Status.CONFLICTS)
            channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                    GitPlugin.getInstance().getMessage("git.checkout.checkoutConflicts.title"),
                    GitPlugin.getInstance().getMessage("git.checkout.checkoutConflicts.message"),
                    cc.getResult().getConflictList().toString(),
                    DisplaySimpleMessageClientCommand.ICON_INFORMATION));

        else if (cc.getResult().getStatus() == CheckoutResult.Status.NONDELETED) {
            // double-check if the files are still there
            boolean show = false;
            List<String> pathList = cc.getResult().getUndeletedList();
            for (String path1 : pathList) {
                if (new File(wdirRepo.getWorkTree(), path1).exists()) {
                    show = true;
                    break;
                }
            }
            if (show) {
                channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                        GitPlugin.getInstance().getMessage("git.checkout.nonDeletedFiles.title"),
                        GitPlugin.getInstance().getMessage("git.checkout.nonDeletedFiles.message",
                                Repository.shortenRefName(name)),
                        cc.getResult().getUndeletedList().toString(),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
            }
        } else if (cc.getResult().getStatus() == CheckoutResult.Status.OK) {
            if (ObjectId.isId(wdirRepo.getFullBranch()))
                channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                        GitPlugin.getInstance().getMessage("git.checkout.detachedHead.title"),
                        GitPlugin.getInstance().getMessage("git.checkout.detachedHead.message"),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
        }
        monitor.worked(1);
        return true;
    } catch (Exception e) {
        channel.appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return false;
    } finally {
        monitor.done();
    }
}

From source file:org.jboss.tools.openshift.egit.internal.test.util.TestRepository.java

License:Open Source License

private String getWorkdirPrefix(Repository repository) {
    String workdirPrefix = repository.getWorkTree().getAbsolutePath();
    try {//from   w  w w.  ja  v a  2  s  . c  o m
        workdirPrefix = repository.getWorkTree().getCanonicalPath();
    } catch (IOException err) {
        // ignore;
    }
    return workdirPrefix;
}

From source file:org.jenkinsci.git.TreeCheckoutOperationTest.java

License:Open Source License

/**
 * Test checking out a tree from previous commit
 *
 * @throws Exception/*  w  w  w . j av  a 2  s. c om*/
 */
@Test
public void checkoutPreviousCommitTree() throws Exception {
    RevCommit commit = git.add("file.txt", "a");
    git.add("file.txt", "b");
    Repository repo = git.repo();
    File file = new File(repo.getWorkTree(), "file.txt");
    FileReader reader = new FileReader(file);
    assertEquals('b', (char) reader.read());
    reader.close();
    TreeCheckoutOperation op = new TreeCheckoutOperation(repo, commit);
    ObjectId tree = op.call();
    assertEquals(commit.getTree(), tree);
    reader = new FileReader(file);
    assertEquals('a', (char) reader.read());
    reader.close();
}

From source file:org.kuali.student.git.utils.ExternalGitUtils.java

License:Educational Community License

private static Process runGitCommand(Repository repo, boolean inGitMetaDirectory, List<String> commandArgs)
        throws IOException {

    File gitDirectory = null;/*w  w w . jav  a  2 s  .  co  m*/

    if (inGitMetaDirectory)
        gitDirectory = repo.getDirectory();
    else
        gitDirectory = repo.getWorkTree();

    // inherit the parent environment
    // locate in the working copy of the gir directory
    Process p = Runtime.getRuntime().exec(commandArgs.toArray(new String[] {}), null, gitDirectory);

    return p;
}

From source file:org.openflexo.hannah.IterativeFileGenerator.java

License:Open Source License

/**
 * <p>Ends the generation. It asks to resolve conflicts (if any). By 
 * default conflict are resolved using user modifications.</p>
 * @param callback callback to handle conflicts
 * @throws IOException//from ww  w . j  a  v  a  2 s. com
 */
public void end(ConflictHandler callback) throws IOException, GitAPIException {
    final Status status = git.status().call();

    // checks if needs commit.
    if (status.isClean() == false) {

        // checks for files to add
        boolean execute = false;
        final AddCommand add = git.add();
        for (String filename : status.getModified()) {
            execute = true;
            add.addFilepattern(filename);
        }

        for (String filename : status.getUntracked()) {
            execute = true;
            add.addFilepattern(filename);
        }
        if (execute)
            add.call();

        // checks for files to remove
        execute = false;
        final RmCommand rm = git.rm();
        for (String filename : status.getMissing()) {
            execute = true;
            rm.addFilepattern(filename);
        }
        if (execute)
            rm.call();

        git.commit().setMessage("Generation").call();
    }

    // checks out master branch
    git.checkout().setName(MASTER).call();

    // merges generation branch with master (resolving conflict with USER).
    final Repository repo = git.getRepository();
    final Ref generationHead = repo.getRef(GENERATION);
    final MergeStatus mergeStatus = git.merge().include(generationHead).call().getMergeStatus();

    // in case of conflicts, uses the resolution mode to choose the outcome
    if (mergeStatus == MergeStatus.CONFLICTING) {
        // maps to stores confliting files
        final Map<String, DirCacheEntry> baseEntry = new LinkedHashMap<String, DirCacheEntry>();
        final Map<String, DirCacheEntry> userEntry = new LinkedHashMap<String, DirCacheEntry>();
        final Map<String, DirCacheEntry> generationEntry = new LinkedHashMap<String, DirCacheEntry>();

        // for all conflicting entry collects base, user and generation entries. 
        final DirCache cache = repo.lockDirCache();
        for (int i = 0; i < cache.getEntryCount(); i++) {
            final DirCacheEntry entry = cache.getEntry(i);
            switch (entry.getStage()) {
            case DirCacheEntry.STAGE_1:
                baseEntry.put(entry.getPathString(), entry);
                break;
            case DirCacheEntry.STAGE_2:
                userEntry.put(entry.getPathString(), entry);
                break;
            case DirCacheEntry.STAGE_3:
                generationEntry.put(entry.getPathString(), entry);
                break;
            }
        }

        // creates list of conflicting files
        final List<ConflictingFile> conflictingFiles = new ArrayList<ConflictingFile>();
        final MergeAlgorithm mergeAlgorithm = new MergeAlgorithm();
        for (final String path : baseEntry.keySet()) {
            final RawText baseText = getRawText(baseEntry.get(path));
            final RawText userText = getRawText(userEntry.get(path));
            final RawText generationText = getRawText(generationEntry.get(path));

            final MergeResult<RawText> result = mergeAlgorithm.merge(RawTextComparator.DEFAULT, baseText,
                    userText, generationText);
            conflictingFiles.add(new ConflictingFile(path, result));

        }
        // unlocks cache.
        cache.unlock();

        // calls the callback
        callback.conflicts(conflictingFiles);

        // prepares the reset command
        final ResetCommand reset = git.reset();

        // applies callback selections
        for (final ConflictingFile conflictingFile : conflictingFiles) {
            final File file = new File(repo.getWorkTree(), conflictingFile.getPath());
            FileUtil.writeFile(file, conflictingFile.getContents(), "UTF-8");

            reset.addPath(conflictingFile.getPath());
        }

        // resets repository state to allows commit.
        reset.call();

        // commit resolutions
        git.commit().setMessage("User/Generation merge conflicts resolutions.").call();
    }

    // renames git repository to hannah
    gitFolder.renameTo(hannahFolder);
}

From source file:org.sonar.plugins.scm.git.JGitBlameCommand.java

License:Open Source License

@Override
public void blame(BlameInput input, BlameOutput output) {
    File basedir = input.fileSystem().baseDir();
    Repository repo = buildRepository(basedir);
    try {/*from w  w w  .ja  v  a 2 s  .  com*/
        Git git = Git.wrap(repo);
        File gitBaseDir = repo.getWorkTree();
        ExecutorService executorService = Executors
                .newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
        List<Future<Void>> tasks = submitTasks(input, output, git, gitBaseDir, executorService);
        waitForTaskToComplete(tasks);
    } finally {
        repo.close();
    }
}