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:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java

License:Open Source License

/**
 * loads the comments for the given {@link ModelReview} from the given
 * repository. The current reviewer should be set for the given model to
 * avoid duplicated user objects representing the same user. The resource
 * set used to load the comments tries to load resources containing
 * referenced EObjects from the given list of model resource sets before
 * creating the resource directly, in order to avoid duplicated model
 * elements. This is necessary as {@link CommentLink}s may refer to objects
 * contained in other resource sets./*w w  w  .ja va 2  s . c o  m*/
 * 
 * @param repository
 *            the repository to load the comments from.
 * @param modelReview
 *            the {@link ModelReview} to load the comments for.
 * @param modelResourceSets
 *            a list of resource sets to resolve referenced model elements
 *            if they cannot be found in the comments model.
 * @throws RepositoryIOException
 */
private void loadComments(Repository repository, final ModelReview modelReview,
        List<ResourceSet> modelResourceSets) throws RepositoryIOException {

    String commentRefName = getCommentRefName(modelReview);
    String repoPath = repository.getWorkTree().getPath();
    Ref commentRef;

    try {

        commentRef = repository.exactRef(commentRefName);
        String commitHash = commentRef.getObjectId().name();

        /* prepare the resource set and the resource for the comments */
        org.eclipse.emf.common.util.URI commentsUri = org.eclipse.emf.common.util.URI.createURI(
                GitURIParser.GIT_COMMIT_SCHEME + "://" + repoPath + "/" + commitHash + "/" + COMMENTS_FILE_URI);
        ResourceSet resourceSet = createGitAwareResourceSet(commitHash, repoPath, modelResourceSets);
        Resource commentsResource = resourceSet.createResource(commentsUri);

        /* load the comments from the repository */
        commentsResource.load(null);
        final EList<EObject> content = commentsResource.getContents();

        /* add the loaded comments to the given model review */

        TransactionalEditingDomain editingDomain = findTransactionalEditingDomainFor(commentsResource);

        Command addCommentsCommand = new RecordingCommand(editingDomain) {

            @Override
            protected void doExecute() {

                User reviewer = modelReview.getCurrentReviewer();

                for (EObject object : content) {

                    if (object instanceof Comment) {

                        Comment comment = (Comment) object;
                        comment.resolvePatchSet(modelReview);
                        User author = comment.getAuthor();

                        if (isSameUser(reviewer, author)) {
                            // avoid duplicated users
                            comment.setAuthor(reviewer);
                        }

                        modelReview.getComments().add(comment);
                    }
                }
            }

        };

        editingDomain.getCommandStack().execute(addCommentsCommand);

    } catch (IOException e) {
        throw new RepositoryIOException(MessageFormat.format(
                "An IO error occured during loading the comments for the review with id #{0}",
                modelReview.getId()), e);
    }
}

From source file:com.atlassian.labs.speakeasy.manager.AbstractOsgiPluginTypeHandler.java

public String getPluginFile(final String pluginKey, final String fileName) throws IOException {
    return gitRepositoryManager.operateOnRepository(pluginKey, new ReadOnlyOperation<Repository, String>() {
        public String operateOn(Repository repo) throws Exception {
            File dir = repo.getWorkTree();
            File file = new File(dir, fileName);
            if (file.exists()) {
                return FileUtils.readFileToString(file);
            }/*from  w  ww.  j a va  2 s.co  m*/
            throw new FileNotFoundException(fileName);
        }
    });

}

From source file:com.atlassian.labs.speakeasy.manager.AbstractOsgiPluginTypeHandler.java

public List<String> getPluginFileNames(String pluginKey) {
    return gitRepositoryManager.operateOnRepository(pluginKey,
            new ReadOnlyOperation<Repository, List<String>>() {
                public List<String> operateOn(Repository repo) throws Exception {
                    final File dir = repo.getWorkTree();
                    return RepositoryDirectoryUtil.getEntries(dir);
                }/*from ww  w . j  ava2s . c  o m*/
            });
}

From source file:com.atlassian.labs.speakeasy.manager.AbstractOsgiPluginTypeHandler.java

public File getPluginAsProject(String pluginKey, final Map<String, Object> context) {
    return gitRepositoryManager.operateOnRepository(pluginKey, new ReadOnlyOperation<Repository, File>() {
        public File operateOn(Repository repo) throws Exception {
            FileOutputStream fout = null;
            ZipOutputStream zout = null;
            File file = null;//www  .j a  v  a 2s. co  m
            try {
                file = File.createTempFile("speakeasy-plugin-project", ".zip");
                fout = new FileOutputStream(file);
                zout = new ZipOutputStream(fout);
                zout.putNextEntry(new ZipEntry("src/"));
                zout.putNextEntry(new ZipEntry("src/main/"));
                zout.putNextEntry(new ZipEntry("src/main/resources/"));

                List<String> paths = RepositoryDirectoryUtil.getEntries(repo.getWorkTree());
                for (String path : paths) {

                    String actualPath = "src/main/resources/" + path;
                    ZipEntry entry = new ZipEntry(actualPath);
                    zout.putNextEntry(entry);
                    if (!path.endsWith("/")) {
                        byte[] data = FileUtils.readFileToByteArray(new File(repo.getWorkTree(), path));
                        zout.write(data, 0, data.length);
                    }
                }

                zout.putNextEntry(new ZipEntry("pom.xml"));
                String pomContents = renderPom(context);
                IOUtils.copy(new StringReader(pomContents), zout);
            } catch (IOException e) {
                throw new RuntimeException("Unable to create plugin project", e);
            } finally {
                IOUtils.closeQuietly(zout);
                IOUtils.closeQuietly(fout);
            }
            return file;
        }
    });
}

From source file:com.atlassian.labs.speakeasy.manager.AbstractOsgiPluginTypeHandler.java

public File createFork(String pluginKey, final String forkPluginKey, String user, final String description)
        throws IOException {
    return gitRepositoryManager.operateOnRepository(pluginKey, new ReadOnlyOperation<Repository, File>() {
        public File operateOn(Repository repo) throws Exception {
            ZipOutputStream zout = null;
            File tmpFile = null;/*  w  w w.ja  v a2 s .c om*/
            try {
                tmpFile = createTempFile(forkPluginKey);
                zout = new ZipOutputStream(new FileOutputStream(tmpFile));
                final File repoDir = repo.getWorkTree();
                List<String> bundlePaths = RepositoryDirectoryUtil.getEntries(repoDir);
                bundlePaths.remove(getDescriptorPath());
                for (String path : bundlePaths) {
                    ZipEntry entry = new ZipEntry(path);
                    zout.putNextEntry(entry);
                    if (!path.endsWith("/")) {
                        byte[] data = FileUtils.readFileToByteArray(new File(repoDir, path));
                        zout.write(data, 0, data.length);
                    }
                }

                zout.putNextEntry(new ZipEntry(getDescriptorPath()));
                forkDescriptor(
                        new ByteArrayInputStream(
                                FileUtils.readFileToByteArray(new File(repoDir, getDescriptorPath()))),
                        zout, forkPluginKey, description);

                zout.close();
            } finally {
                IOUtils.closeQuietly(zout);
            }
            return tmpFile;
        }
    });
}

From source file:com.atlassian.labs.speakeasy.manager.AbstractOsgiPluginTypeHandler.java

public File rebuildPlugin(final String pluginKey, final String fileName, final String contents)
        throws IOException {
    return gitRepositoryManager.operateOnRepository(pluginKey, new ReadOnlyOperation<Repository, File>() {
        public File operateOn(Repository repo) throws Exception {
            ZipOutputStream zout = null;
            File tmpFile = null;//from w  w  w  . j  a va2  s.co m
            try {
                tmpFile = createTempFile(pluginKey);
                zout = new ZipOutputStream(new FileOutputStream(tmpFile));
                final File repoDir = repo.getWorkTree();
                for (String path : RepositoryDirectoryUtil.getEntries(repoDir)) {
                    if (!path.equals(fileName) && !path.contains("-min.")) {
                        ZipEntry entry = new ZipEntry(path);
                        zout.putNextEntry(entry);
                        if (!path.endsWith("/")) {
                            byte[] data = FileUtils.readFileToByteArray(new File(repoDir, path));
                            zout.write(data, 0, data.length);
                        }
                    }
                }
                ZipEntry entry = new ZipEntry(fileName);
                byte[] data = contents.getBytes();
                entry.setSize(data.length);
                zout.putNextEntry(entry);
                zout.write(data);
                zout.close();
            } finally {
                IOUtils.closeQuietly(zout);
            }
            return tmpFile;
        }
    });
}

From source file:com.diffplug.gradle.spotless.GitAttributesLineEndingPolicy.java

License:Apache License

public static GitAttributesLineEndingPolicy create(File rootFolder) {
    return Errors.rethrow().get(() -> {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        builder.findGitDir(rootFolder);/*from ww  w.j  a v a  2  s . c  o  m*/
        if (builder.getGitDir() != null) {
            // we found a repository, so we can grab all the values we need from it
            Repository repo = builder.build();
            AttributesNodeProvider nodeProvider = repo.createAttributesNodeProvider();
            Function<AttributesNode, List<AttributesRule>> getRules = node -> node == null
                    ? Collections.emptyList()
                    : node.getRules();
            return new GitAttributesLineEndingPolicy(repo.getConfig(),
                    getRules.apply(nodeProvider.getInfoAttributesNode()), repo.getWorkTree(),
                    getRules.apply(nodeProvider.getGlobalAttributesNode()));
        } else {
            // there's no repo, so it takes some work to grab the system-wide values
            Config systemConfig = SystemReader.getInstance().openSystemConfig(null, FS.DETECTED);
            Config userConfig = SystemReader.getInstance().openUserConfig(systemConfig, FS.DETECTED);
            if (userConfig == null) {
                userConfig = new Config();
            }

            List<AttributesRule> globalRules = Collections.emptyList();
            // copy-pasted from org.eclipse.jgit.lib.CoreConfig
            String globalAttributesPath = userConfig.getString(ConfigConstants.CONFIG_CORE_SECTION, null,
                    ConfigConstants.CONFIG_KEY_ATTRIBUTESFILE);
            // copy-pasted from org.eclipse.jgit.internal.storage.file.GlobalAttributesNode
            if (globalAttributesPath != null) {
                FS fs = FS.detect();
                File attributesFile;
                if (globalAttributesPath.startsWith("~/")) { //$NON-NLS-1$
                    attributesFile = fs.resolve(fs.userHome(), globalAttributesPath.substring(2));
                } else {
                    attributesFile = fs.resolve(null, globalAttributesPath);
                }
                globalRules = parseRules(attributesFile);
            }
            return new GitAttributesLineEndingPolicy(userConfig,
                    // no git info file
                    Collections.emptyList(), null, globalRules);
        }
    });
}

From source file:com.google.appraise.eclipse.ui.AppraiseUiPlugin.java

License:Open Source License

/**
 * Helper method to open the given file in the workspace editor.
 *///  w  w  w .  j a va 2  s .com
public static void openFileInEditor(String filePath, TaskRepository taskRepository) {
    Repository repository = AppraisePluginUtils.getGitRepoForRepository(taskRepository);
    IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    String fullPath = new Path(repository.getWorkTree().getAbsolutePath()).append(filePath).toOSString();
    File file = new File(fullPath);
    if (!file.exists()) {
        AppraiseUiPlugin.logError("File to open not found: " + fullPath);
        return;
    }
    IWorkbenchPage page = window.getActivePage();
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IFile fileResource = root.getFileForLocation(new Path(file.getAbsolutePath()));
    if (fileResource != null) {
        try {
            IDE.openEditor(page, fileResource, OpenStrategy.activateOnOpen());
        } catch (PartInitException e) {
            AppraiseUiPlugin.logError("Failed to open editor for " + filePath, e);
        }
    } else {
        IFileStore store = EFS.getLocalFileSystem().getStore(new Path(file.getAbsolutePath()));
        try {
            IDE.openEditor(page, new FileStoreEditorInput(store), EditorsUI.DEFAULT_TEXT_EDITOR_ID);
        } catch (PartInitException e) {
            AppraiseUiPlugin.logError("Failed to open editor for " + filePath, e);
        }
    }
}

From source file:com.google.gerrit.server.git.ReadOnlyRepository.java

License:Apache License

private static BaseRepositoryBuilder<?, ?> builder(Repository r) {
    checkNotNull(r);/*from   ww w  .j a  v  a  2s.co  m*/
    BaseRepositoryBuilder<?, ?> builder = new BaseRepositoryBuilder<>().setFS(r.getFS())
            .setGitDir(r.getDirectory());

    if (!r.isBare()) {
        builder.setWorkTree(r.getWorkTree()).setIndexFile(r.getIndexFile());
    }
    return builder;
}

From source file:com.googlesource.gerrit.plugins.gitiles.FilteredRepository.java

License:Apache License

private static RepositoryBuilder toBuilder(Repository repo) {
    RepositoryBuilder b = new RepositoryBuilder().setGitDir(repo.getDirectory()).setFS(repo.getFS());
    if (!repo.isBare()) {
        b.setWorkTree(repo.getWorkTree()).setIndexFile(repo.getIndexFile());
    }/*  w  w w .  j  ava  2s  . c  o  m*/
    return b;
}