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:net.polydawn.mdm.Plumbing.java

License:Open Source License

public static boolean fetch(Repository repo, MdmModuleDependency module) throws ConfigInvalidException,
        MdmRepositoryIOException, MdmRepositoryStateException, MdmException, IOException {
    switch (module.getStatus().getType()) {
    case MISSING:
        throw new MajorBug();
    case UNINITIALIZED:
        if (module.getRepo() == null)
            try {
                RepositoryBuilder builder = new RepositoryBuilder();
                builder.setWorkTree(new File(repo.getWorkTree() + "/" + module.getPath()));
                builder.setGitDir(new File(repo.getDirectory() + "/modules/" + module.getPath()));
                module.repo = builder.build();

                // we actually *might* not have to make the repo from zero.
                // this getRepo gets its effective data from SubmoduleWalk.getSubmoduleRepository...
                // which does its job by looking in the working tree of the parent repo.
                // meaning if it finds nothing, it certainly won't find any gitdir indirections.
                // so, even if this is null, we might well have a gitdir cached that we still have to go find.
                final FileBasedConfig cfg = (FileBasedConfig) module.repo.getConfig();
                if (!cfg.getFile().exists()) { // though seemly messy, this is the same question the jgit create() function asks, and it's not exposed to us, so.
                    module.repo.create(false);
                } else {
                    // do something crazy, because... i think the user's expectation after blowing away their submodule working tree is likely wanting a clean state of index and such here
                    try {
                        new Git(module.getRepo()).reset().setMode(ResetType.HARD).call();
                    } catch (CheckoutConflictException e) {
                        /* Can a hard reset even have a conflict? */
                        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
                    } catch (GitAPIException e) {
                        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
                    }/*ww w.  j a  v a2 s .com*/
                }

                // set up a working tree which points to the gitdir in the parent repo:

                // handling paths in java, god forbid relative paths, is such an unbelievable backwater.  someday please make a whole library that actually disambiguates pathnames from filedescriptors properly
                int ups = StringUtils.countMatches(module.getPath(), "/");
                // look up the path between the `repo` and its possible git dir location.  if the gitdir is relocated, we have adjust our own relocations to compensate.
                String parentGitPointerStr = ".git/";
                String parentWorktreePointerStr = "../";
                // load it ourselves because we explicitly want the unresolved path, not what jgit would give us back from `repo.getDirectory().toString()`.
                File parentGitPointer = new File(repo.getWorkTree(), ".git");
                if (parentGitPointer.isFile()) {
                    // this shouldn't have to be recursive fortunately (that recursion is done implicitly by the chaining of each guy at each stage).
                    // this does however feel fairly fragile.  it's considerable that perhaps we should try to heuristically determine when paths are just to crazy to deal with.  but, on the off chance that check was overzealous, it would be very irritating, so let's not.
                    // frankly, if you're doing deeply nested submodules, or other advanced gitdir relocations, at some point you're taking it upon yourself to deal with the inevitably complex outcomes and edge case limitations.
                    parentGitPointerStr = IOForge.readFileAsString(parentGitPointer);
                    if (!"gitdir:".equals(parentGitPointerStr.substring(0, 7)))
                        throw new ConfigInvalidException(
                                "cannot understand location of parent project git directory");
                    parentGitPointerStr = parentGitPointerStr.substring(7).trim() + "/";
                    parentWorktreePointerStr = repo.getConfig().getString("core", null, "worktree") + "/";
                }
                // jgit does not appear to create the .git file correctly here :/
                // nor even consider it to be jgit's job to create the worktree yet, apparently, so do that
                module.repo.getWorkTree().mkdirs();
                // need modules/[module]/config to contain 'core.worktree' = appropriate
                String submoduleWorkTreeRelativeToGitDir = StringUtils.repeat("../", ups + 2)
                        + parentWorktreePointerStr + module.getPath();
                StoredConfig cnf = module.repo.getConfig();
                cnf.setString("core", null, "worktree", submoduleWorkTreeRelativeToGitDir);
                cnf.save();
                // need [module]/.git to contain 'gitdir: appropriate' (which appears to not be normal gitconfig)
                String submoduleGitDirRelativeToWorkTree = StringUtils.repeat("../", ups + 1)
                        + parentGitPointerStr + "modules/" + module.getPath();
                IOForge.saveFile("gitdir: " + submoduleGitDirRelativeToWorkTree + "\n",
                        new File(module.repo.getWorkTree(), ".git"));
            } catch (IOException e) {
                throw new MdmRepositoryIOException("create a new submodule", true, module.getHandle(), e);
            }

        try {
            if (initLocalConfig(repo, module))
                repo.getConfig().save();
        } catch (IOException e) {
            throw new MdmRepositoryIOException("save changes", true, "the local git configuration file", e);
        }
        try {
            setMdmRemote(module);
            module.getRepo().getConfig().save();
        } catch (IOException e) {
            throw new MdmRepositoryIOException("save changes", true,
                    "the git configuration file for submodule " + module.getHandle(), e);
        }
    case INITIALIZED:
        if (module.getVersionName() == null || module.getVersionName().equals(module.getVersionActual()))
            return false;
    case REV_CHECKED_OUT:
        try {
            if (initModuleConfig(repo, module))
                module.getRepo().getConfig().save();
        } catch (IOException e) {
            throw new MdmRepositoryIOException("save changes", true,
                    "the git configuration file for submodule " + module.getHandle(), e);
        }

        final String versionBranchName = "refs/heads/mdm/release/" + module.getVersionName();
        final String versionTagName = "refs/tags/release/" + module.getVersionName();

        /* Fetch only the branch labelled with the version requested. */
        if (module.getRepo().getRef(versionBranchName) == null)
            try {
                RefSpec releaseBranchRef = new RefSpec().setForceUpdate(true).setSource(versionBranchName)
                        .setDestination(versionBranchName);
                RefSpec releaseTagRef = new RefSpec().setForceUpdate(true).setSource(versionTagName)
                        .setDestination(versionTagName);
                new Git(module.getRepo()).fetch().setRemote("origin")
                        .setRefSpecs(releaseBranchRef, releaseTagRef).setTagOpt(TagOpt.NO_TAGS).call();
            } catch (InvalidRemoteException e) {
                throw new MdmRepositoryStateException(
                        "find a valid remote origin in the config for the submodule", module.getHandle(), e);
            } catch (TransportException e) {
                URIish remote = null;
                try { //XXX: if we went through all the work to resolve the remote like the fetch command does, we could just as well do it and hand the resolved uri to fetch for better consistency.
                    remote = new RemoteConfig(module.getRepo().getConfig(), "origin").getURIs().get(0);
                } catch (URISyntaxException e1) {
                }
                throw new MdmRepositoryIOException("fetch from a remote", false, remote.toASCIIString(), e)
                        .setAdditionalMessage("check your connectivity and try again?");
            } catch (GitAPIException e) {
                throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
            }

        /* Drop the files into the working tree. */
        try {
            new Git(module.getRepo()).checkout().setName(versionBranchName).setForce(true).call();
        } catch (RefAlreadyExistsException e) {
            /* I'm not creating a new branch, so this exception wouldn't even make sense. */
            throw new MajorBug(e);
        } catch (RefNotFoundException e) {
            /* I just got this branch, so we shouldn't have a problem here. */
            throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
        } catch (InvalidRefNameException e) {
            /* I just got this branch, so we shouldn't have a problem here. */
            throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
        } catch (CheckoutConflictException e) {
            // this one is just a perfectly reasonable message with a list of files in conflict; we'll take it.
            throw new MdmRepositoryStateException(module.getHandle(), e); // this currently gets translated to a :'( exception and it's probably more like a :(
        } catch (GitAPIException e) {
            throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
        }
        return true;
    default:
        throw new MajorBug();
    }
}

From source file:org.apache.oozie.action.hadoop.GitServer.java

License:Apache License

/**
 * A method to:/* w  ww. j ava2  s .  c o  m*/
 * <ul>
 *     <li>remove all files on disk for all repositories</li>
 *     <li>clear the repositories listed for the {@link GitServer}</li>
 * </ul>
 */
private void cleanUpRepos() {
    for (final Repository repository : repositories.values()) {
        final File workTree = repository.getWorkTree();
        try {
            FileUtils.deleteDirectory(workTree.getParentFile());
        } catch (final IOException e) {
            LOG.warn("Could not delete parent directory of working tree: ", e);
        }
    }
    repositories.clear();
}

From source file:org.commonwl.view.researchobject.ROBundleServiceTest.java

License:Apache License

@Before
public void setUp() throws Exception {
    Repository mockRepo = Mockito.mock(Repository.class);
    when(mockRepo.getWorkTree()).thenReturn(new File("src/test/resources/cwl/"));

    Git gitRepo = Mockito.mock(Git.class);
    when(gitRepo.getRepository()).thenReturn(mockRepo);

    // Get mock Git service
    GitService mockGitService = Mockito.mock(GitService.class);
    when(mockGitService.getRepository(anyObject(), anyBoolean())).thenReturn(gitRepo);

    Set<HashableAgent> authors = new HashSet<>();
    authors.add(new HashableAgent("Mark Robinson", null, new URI("mailto:mark@example.com")));
    when(mockGitService.getAuthors(anyObject(), anyObject())).thenReturn(authors);

    // Mock Graphviz service
    GraphVizService mockGraphvizService = Mockito.mock(GraphVizService.class);
    when(mockGraphvizService.getGraph(anyString(), anyString(), anyString()))
            .thenReturn(new File("src/test/resources/graphviz/testVis.png"))
            .thenReturn(new File("src/test/resources/graphviz/testVis.svg"));

    // Mock CWLTool
    CWLTool mockCwlTool = Mockito.mock(CWLTool.class);
    when(mockCwlTool.getPackedVersion(anyString())).thenReturn("cwlVersion: v1.0");

    // Mock RDF Service
    ResultSet emptyResult = Mockito.mock(ResultSet.class);
    when(emptyResult.hasNext()).thenReturn(false);
    RDFService mockRdfService = Mockito.mock(RDFService.class);
    when(mockRdfService.getAuthors(anyString(), anyString())).thenReturn(emptyResult);
    when(mockRdfService.graphExists(anyString())).thenReturn(true);
    when(mockRdfService.getModel(anyObject(), anyObject()))
            .thenReturn("@prefix cwl: <https://w3id.org/cwl/cwl#> .".getBytes());

    // Create new RO bundle
    roBundleService = new ROBundleService(roBundleFolder.getRoot().toPath(), "CWL Viewer",
            "https://view.commonwl.org", 5242880, mockGraphvizService, mockGitService, mockRdfService,
            Mockito.mock(GitSemaphore.class), mockCwlTool);
    roBundleServiceZeroSizeLimit = new ROBundleService(roBundleFolder.getRoot().toPath(), "CWL Viewer",
            "https://view.commonwl.org", 0, mockGraphvizService, mockGitService, mockRdfService,
            Mockito.mock(GitSemaphore.class), mockCwlTool);

    GitDetails lobSTRdraft3Details = new GitDetails("https://github.com/common-workflow-language/workflows.git",
            "933bf2a1a1cce32d88f88f136275535da9df0954", "workflows/lobSTR/lobSTR-workflow.cwl");
    lobSTRdraft3 = Mockito.mock(Workflow.class);
    when(lobSTRdraft3.getID()).thenReturn("testID");
    when(lobSTRdraft3.getRetrievedFrom()).thenReturn(lobSTRdraft3Details);
    when(lobSTRdraft3.getLastCommit()).thenReturn("933bf2a1a1cce32d88f88f136275535da9df0954");
    final String permalink = "https://w3id.org/cwl/view/git/"
            + "933bf2a1a1cce32d88f88f136275535da9df0954/workflows/lobSTR/lobSTR-workflow.cwl";
    when(lobSTRdraft3.getIdentifier()).thenReturn(permalink);
    when(lobSTRdraft3.getPermalink()).thenReturn(permalink);
    when(lobSTRdraft3.getPermalink(any())).thenAnswer(new Answer<String>() {
        @Override//from   ww w  . ja va 2  s.c  om
        public String answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            return permalink + "?format=" + args[0];
        }
    });
}

From source file:org.commonwl.view.workflow.WorkflowServiceTest.java

License:Apache License

/**
 * Getting a list of workflow overviews from a directory
 *///from   www.  jav a2  s .c  om
@Test
public void getWorkflowsFromDirectory() throws Exception {

    // Mock CWL service which returns simple overview once simulating 1 workflow found
    CWLService mockCWLService = Mockito.mock(CWLService.class);
    when(mockCWLService.getWorkflowOverview(anyObject()))
            .thenReturn(new WorkflowOverview("workflow.cwl", "label", "doc"))
            .thenReturn(new WorkflowOverview("workflow2.cwl", "label2", "doc2")).thenReturn(null);

    Repository mockRepo = Mockito.mock(Repository.class);
    when(mockRepo.getWorkTree()).thenReturn(new File("src/test/resources/cwl/hello"));

    Git mockGitRepo = Mockito.mock(Git.class);
    when(mockGitRepo.getRepository()).thenReturn(mockRepo);

    GitService mockGitService = Mockito.mock(GitService.class);
    when(mockGitService.getRepository(anyObject(), anyBoolean())).thenReturn(mockGitRepo);

    // Create service under test
    WorkflowService testWorkflowService = new WorkflowService(mockGitService, mockCWLService,
            Mockito.mock(WorkflowRepository.class), Mockito.mock(QueuedWorkflowRepository.class),
            Mockito.mock(ROBundleFactory.class), Mockito.mock(GraphVizService.class),
            Mockito.mock(CWLToolRunner.class), Mockito.mock(GitSemaphore.class), 1);

    // Get a list of workflows from the directory
    List<WorkflowOverview> list = testWorkflowService
            .getWorkflowsFromDirectory(new GitDetails(null, null, "/"));

    // 1 workflow should be found
    assertTrue(list.size() == 2);
    assertEquals("workflow.cwl", list.get(0).getFileName());
    assertEquals("label", list.get(0).getLabel());
    assertEquals("doc", list.get(0).getDoc());

    assertEquals("workflow2.cwl", list.get(1).getFileName());
    assertEquals("label2", list.get(1).getLabel());
    assertEquals("doc2", list.get(1).getDoc());

}

From source file:org.commonwl.view.workflow.WorkflowServiceTest.java

License:Apache License

/**
 * Getting a workflow when cache has expired
 * And a new workflow needs to be created
 */// w ww.  ja va  2s  . c  om
@Test
public void getWorkflowCacheHasExpired() throws Exception {

    GitDetails githubInfo = new GitDetails("https://github.com/common-workflow-language/workflows.git",
            "master", "dna.cwl");

    Workflow oldWorkflow = new Workflow("old", "This is the expired workflow", new HashMap<>(), new HashMap<>(),
            new HashMap<>());
    oldWorkflow.setId("theworkflowid");
    oldWorkflow.setRetrievedOn(new Date());
    oldWorkflow.setRetrievedFrom(githubInfo);
    oldWorkflow.setLastCommit("d46ce365f1a10c4c4d6b0caed51c6f64b84c2f63");
    oldWorkflow.setRoBundlePath(roBundleFolder.newFile("robundle.zip").getAbsolutePath());

    Workflow updatedWorkflow = new Workflow("new", "This is the updated workflow", new HashMap<>(),
            new HashMap<>(), new HashMap<>());
    updatedWorkflow.setId("newworkflowid");

    WorkflowRepository mockWorkflowRepo = Mockito.mock(WorkflowRepository.class);
    when(mockWorkflowRepo.findByRetrievedFrom(anyObject())).thenReturn(oldWorkflow);

    CWLService mockCWLService = Mockito.mock(CWLService.class);
    when(mockCWLService.parseWorkflowNative(anyObject(), anyObject())).thenReturn(updatedWorkflow);

    Repository mockRepo = Mockito.mock(Repository.class);
    when(mockRepo.getWorkTree()).thenReturn(new File("src/test/resources/cwl/make_to_cwl"));

    Git mockGitRepo = Mockito.mock(Git.class);
    when(mockGitRepo.getRepository()).thenReturn(mockRepo);

    GitService mockGitService = Mockito.mock(GitService.class);
    when(mockGitService.getRepository(anyObject(), anyBoolean())).thenReturn(mockGitRepo);
    when(mockGitService.getCurrentCommitID(anyObject())).thenReturn("newCommitId");

    // Create service under test with negative cache time (always create new workflow)
    WorkflowService testWorkflowService = new WorkflowService(mockGitService, mockCWLService, mockWorkflowRepo,
            Mockito.mock(QueuedWorkflowRepository.class), Mockito.mock(ROBundleFactory.class),
            Mockito.mock(GraphVizService.class), Mockito.mock(CWLToolRunner.class),
            Mockito.mock(GitSemaphore.class), -1);

    // Will use check cache algorithm, find expired,
    // check git and find commit IDs do not match,
    // and thus create a new workflow + matching RO bundle
    Workflow workflow = testWorkflowService.getWorkflow(githubInfo);

    // Check the old workflow was deleted
    // TODO: check new workflow was queued
    assertEquals(workflow, null);

}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public void lockItem(String site, String path) {
    Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX);

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        try (TreeWalk tw = new TreeWalk(repo)) {
            RevTree tree = helper.getTreeForLastCommit(repo);
            tw.addTree(tree); // tree 0
            tw.setRecursive(false);/*w w  w .ja va  2 s .  c  o m*/
            tw.setFilter(PathFilter.create(path));

            if (!tw.next()) {
                return;
            }

            File repoRoot = repo.getWorkTree();
            Paths.get(repoRoot.getPath(), tw.getPathString());
            File file = new File(tw.getPathString());
            LockFile lock = new LockFile(file);
            lock.lock();

            tw.close();

        } catch (IOException e) {
            logger.error("Error while locking file for site: " + site + " path: " + path, e);
        }
    }
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public void unLockItem(String site, String path) {
    Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX);

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        try (TreeWalk tw = new TreeWalk(repo)) {
            RevTree tree = helper.getTreeForLastCommit(repo);
            tw.addTree(tree); // tree 0
            tw.setRecursive(false);/*from  ww  w  .  j  a va 2  s.  c  o  m*/
            tw.setFilter(PathFilter.create(path));

            if (!tw.next()) {
                return;
            }

            File repoRoot = repo.getWorkTree();
            Paths.get(repoRoot.getPath(), tw.getPathString());
            File file = new File(tw.getPathString());
            LockFile lock = new LockFile(file);
            lock.unlock();

            tw.close();

        } catch (IOException e) {
            logger.error("Error while unlocking file for site: " + site + " path: " + path, e);
        }
    }
}

From source file:org.eclipse.egit.core.AdaptableFileTreeIterator.java

License:Open Source License

/**
 * Create a new iterator to traverse the work tree of the given repository
 * <p>//from w  ww.  j  ava2 s . co m
 * The iterator will automatically adapt to a {@link ContainerTreeIterator}
 * when encountering directories what can be mapped into the given workspace
 * root.
 *
 * @param repository
 *            the repository this iterator should traverse the working tree
 *            of
 * @param workspaceRoot
 *            the workspace root to check resource mapping against.
 */
public AdaptableFileTreeIterator(final Repository repository, final IWorkspaceRoot workspaceRoot) {
    super(repository.getWorkTree(), FS.DETECTED, repository.getConfig().get(WorkingTreeOptions.KEY));
    root = workspaceRoot;
}

From source file:org.eclipse.egit.core.internal.CompareCoreUtils.java

License:Open Source License

/**
 * Determine the encoding used by Eclipse for the resource which belongs to
 * repoPath in the eclipse workspace or null if no resource is found
 *
 * @param db//from   w ww  . java2s .  co  m
 *            the repository
 * @param repoPath
 *            the path in the git repository
 * @return the encoding used in eclipse for the resource or null if
 *
 */
public static String getResourceEncoding(Repository db, String repoPath) {
    if (db.isBare())
        return null;
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = workspace.getRoot();
    IPath absolutePath = new Path(db.getWorkTree().getAbsolutePath()).append(repoPath);
    IResource resource = root.getFileForLocation(absolutePath);
    if (resource == null)
        return null;

    return getResourceEncoding(resource);
}

From source file:org.eclipse.egit.core.internal.FileChecker.java

License:Open Source License

/**
 * The method checks a collection of files. Problems are reported for a
 * file if no resource exists for the file or if the related resource is
 * located in a project not shared with Git.
 *
 * @param repository// w  w w. j  a  va2s. c  o  m
 * @param files
 * @return a {@link CheckResult} containing result of the check
 */
public static CheckResult checkFiles(Repository repository, Collection<String> files) {
    CheckResult result = new CheckResult();
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    String workTreePath = repository.getWorkTree().getAbsolutePath();
    for (String filePath : files) {
        IFile[] filesForLocation = root.findFilesForLocationURI(new File(workTreePath, filePath).toURI());
        if (filesForLocation.length == 0) {
            result.addEntry(filePath, new CheckResultEntry(false, false));
            continue;
        }
        boolean mappedResourceFound = false;
        for (IFile file : filesForLocation) {
            if (RepositoryMapping.getMapping(file) != null) {
                mappedResourceFound = true;
                break;
            }
        }
        if (!mappedResourceFound)
            result.addEntry(filePath, new CheckResultEntry(true, false));
    }
    return result;
}