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

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

Introduction

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

Prototype


public File getDirectory() 

Source Link

Document

Get local metadata directory

Usage

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

License:Open Source License

@Override
public String createFolder(String site, String path, String name) {
    // SJ: Git doesn't care about empty folders, so we will create the folders and put a 0 byte file in them
    String commitId = null;//from  w  ww  .j  a  va2  s .c om
    boolean result;

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        Path emptyFilePath = Paths.get(path, name, EMPTY_FILE);
        Repository repo = helper.getRepository(site,
                StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : GitRepositories.SANDBOX);

        try {
            // Create basic file
            File file = new File(repo.getDirectory().getParent(), emptyFilePath.toString());

            // Create parent folders
            File folder = file.getParentFile();
            if (folder != null) {
                if (!folder.exists()) {
                    folder.mkdirs();
                }
            }

            // Create the file
            if (!file.createNewFile()) {
                logger.error("error writing file: site: " + site + " path: " + emptyFilePath);
                result = false;
            } else {
                // Add the file to git
                try (Git git = new Git(repo)) {
                    git.add().addFilepattern(helper.getGitPath(emptyFilePath.toString())).call();

                    git.close();
                    result = true;
                } catch (GitAPIException e) {
                    logger.error("error adding file to git: site: " + site + " path: " + emptyFilePath, e);
                    result = false;
                }
            }
        } catch (IOException e) {
            logger.error("error writing file: site: " + site + " path: " + emptyFilePath, e);
            result = false;
        }

        if (result) {
            commitId = helper.commitFile(repo, site, emptyFilePath.toString(),
                    "Created folder site: " + site + " " + "path: " + path, helper.getCurrentUserIdent());
        }
    }

    return commitId;
}

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

License:Open Source License

@Override
public String moveContent(String site, String fromPath, String toPath, String newName) {
    String commitId = null;/*from ww w.  j  a  v a 2 s  .c o m*/

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        Repository repo = helper.getRepository(site,
                StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : GitRepositories.SANDBOX);

        String gitFromPath = helper.getGitPath(fromPath);
        String gitToPath = helper.getGitPath(toPath + newName);

        try (Git git = new Git(repo)) {
            // Check if destination is a file, then this is a rename operation
            // Perform rename and exit
            Path sourcePath = Paths.get(repo.getDirectory().getParent(), fromPath);
            File sourceFile = sourcePath.toFile();
            Path targetPath = Paths.get(repo.getDirectory().getParent(), toPath);
            File targetFile = targetPath.toFile();
            if (targetFile.isFile()) {
                if (sourceFile.isFile()) {
                    sourceFile.renameTo(targetFile);
                } else {
                    // This is not a valid operation
                    logger.error("Invalid move operation: Trying to rename a directory to a file for site: "
                            + site + " fromPath: " + fromPath + " toPath: " + toPath + " newName: " + newName);
                }
            } else if (sourceFile.isDirectory()) {
                // Check if we're moving a single file or whole subtree
                FileUtils.moveToDirectory(sourceFile, targetFile, true);
            }

            // The operation is done on disk, now it's time to commit
            git.add().addFilepattern(gitToPath).call();
            RevCommit commit = git.commit().setOnly(gitFromPath).setOnly(gitToPath)
                    .setAuthor(helper.getCurrentUserIdent()).setCommitter(helper.getCurrentUserIdent())
                    .setMessage("Moving " + fromPath + " to " + toPath + newName).call();
            commitId = commit.getName();

            git.close();
        } catch (IOException | GitAPIException e) {
            logger.error("Error while moving content for site: " + site + " fromPath: " + fromPath + " toPath: "
                    + toPath + " newName: " + newName);
        }
    }

    return commitId;
}

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

License:Open Source License

@Override
public String copyContent(String site, String fromPath, String toPath) {
    String commitId = null;// w  ww  .  j  a v  a 2  s .  co m

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        Repository repo = helper.getRepository(site,
                StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : GitRepositories.SANDBOX);

        String gitFromPath = helper.getGitPath(fromPath);
        String gitToPath = helper.getGitPath(toPath);

        try (Git git = new Git(repo)) {
            Path sourcePath = Paths.get(repo.getDirectory().getParent(), fromPath);
            File sourceFile = sourcePath.toFile();
            Path targetPath = Paths.get(repo.getDirectory().getParent(), toPath);
            File targetFile = targetPath.toFile();

            // Check if we're copying a single file or whole subtree
            FileUtils.copyDirectory(sourceFile, targetFile);

            // The operation is done on disk, now it's time to commit
            git.add().addFilepattern(gitToPath).call();
            RevCommit commit = git.commit().setOnly(gitFromPath).setOnly(gitToPath)
                    .setAuthor(helper.getCurrentUserIdent()).setCommitter(helper.getCurrentUserIdent())
                    .setMessage("Copying " + fromPath + " to " + toPath).call();
            commitId = commit.getName();

            git.close();
        } catch (IOException | GitAPIException e) {
            logger.error("Error while copying content for site: " + site + " fromPath: " + fromPath + " toPath:"
                    + " " + toPath + " newName: ");
        }
    }

    return commitId;
}

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

License:Open Source License

public boolean writeFile(Repository repo, String site, String path, InputStream content) {
    boolean result;

    try {//from  ww  w  .  ja  va2 s  .  c om
        // Create basic file
        File file = new File(repo.getDirectory().getParent(), path);

        // Create parent folders
        File folder = file.getParentFile();
        if (folder != null) {
            if (!folder.exists()) {
                folder.mkdirs();
            }
        }

        // Create the file if it doesn't exist already
        if (!file.createNewFile()) {
            logger.error("error creating file: site: " + site + " path: " + path);
            result = false;
        } else {
            // Write the bits
            FileChannel outChannel = new FileOutputStream(file.getPath()).getChannel();
            logger.debug("created the file output channel");
            ReadableByteChannel inChannel = Channels.newChannel(content);
            logger.debug("created the file input channel");
            long amount = 1024 * 1024; // 1MB at a time
            long count;
            long offset = 0;
            while ((count = outChannel.transferFrom(inChannel, offset, amount)) > 0) {
                logger.debug("writing the bits: offset = " + offset + " count: " + count);
                offset += count;
            }

            // Add the file to git
            try (Git git = new Git(repo)) {
                git.add().addFilepattern(getGitPath(path)).call();

                git.close();
                result = true;
            } catch (GitAPIException e) {
                logger.error("error adding file to git: site: " + site + " path: " + path, e);
                result = false;
            }
        }
    } catch (IOException e) {
        logger.error("error writing file: site: " + site + " path: " + path, e);
        result = false;
    }

    return result;
}

From source file:org.eclipse.che.git.impl.jgit.JGitConfigImpl.java

License:Open Source License

JGitConfigImpl(Repository repository) throws GitException {
    super(repository.getDirectory());
    this.repository = repository;
}

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

License:Open Source License

/**
 * Rename and move a project in the workspace containing a Git repository.
 * <p>/* w ww  . j a v a  2  s  .  c om*/
 * The repository will be moved with the project.
 * Note that there is no way to rename a project in the workspace without
 * moving it. See https://bugs.eclipse.org/358828 for a discussion.
 *
 * @throws Exception
 */
@Test
public void testMoveAndRenameProjectContainingGitRepo() throws Exception {
    ResourcesPlugin.getWorkspace().getRoot().getProject("Project-1").delete(true, null);
    ResourcesPlugin.getWorkspace().getRoot().getProject("P2").delete(true, null);

    TestProject project = initRepoInsideProjectInsideWorkspace();
    testUtils.addFileToProject(project.getProject(), "file.txt", "some text");
    AddToIndexOperation addToIndexOperation = new AddToIndexOperation(
            new IResource[] { project.getProject().getFile("file.txt") });
    addToIndexOperation.execute(null);
    IProjectDescription description = project.getProject().getDescription();
    description.setName("P2");
    registerWorkspaceRelativeTestDir("P2");
    project.getProject().move(description, IResource.FORCE | IResource.SHALLOW, null);
    IProject project2 = ResourcesPlugin.getWorkspace().getRoot().getProject("P2");
    assertNotNull(RepositoryMapping.getMapping(project2.getProject()));
    Repository movedRepo = RepositoryMapping.getMapping(project2).getRepository();
    assertEquals("P2", movedRepo.getDirectory().getParentFile().getName());
    DirCache dc = movedRepo.readDirCache();
    assertEquals(1, dc.getEntryCount());
    assertEquals("file.txt", dc.getEntry(0).getPathString());

    assertFalse(ResourcesPlugin.getWorkspace().getRoot().getProject("Project-1").exists());
}

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

License:Open Source License

/**
 * Rename a project outside the workspace containing a Git repository.
 * <p>//from   www.  jav  a 2  s . com
 * Note the similarity of the code with {@link #testMoveAndRenameProjectContainingGitRepo()}
 *
 * @throws Exception
 */
@Test
public void testRenameProjectOutsideWorkspaceContainingGitRepo() throws Exception {
    ResourcesPlugin.getWorkspace().getRoot().getProject("Project-1").delete(true, null);
    ResourcesPlugin.getWorkspace().getRoot().getProject("P2").delete(true, null);
    TestProject project = initRepoInsideProjectOutsideWorkspace();
    testUtils.addFileToProject(project.getProject(), "file.txt", "some text");
    AddToIndexOperation addToIndexOperation = new AddToIndexOperation(
            new IResource[] { project.getProject().getFile("file.txt") });
    addToIndexOperation.execute(null);
    IProjectDescription description = project.getProject().getDescription();
    description.setName("P2");
    project.getProject().move(description, IResource.FORCE | IResource.SHALLOW, null);
    IProject project2 = ResourcesPlugin.getWorkspace().getRoot().getProject("P2");
    assertNotNull(RepositoryMapping.getMapping(project2.getProject()));
    Repository movedRepo = RepositoryMapping.getMapping(project2).getRepository();
    assertEquals("Project-1", movedRepo.getDirectory().getParentFile().getName());
    DirCache dc = movedRepo.readDirCache();
    assertEquals(1, dc.getEntryCount());
    assertEquals("file.txt", dc.getEntry(0).getPathString());

    assertFalse(ResourcesPlugin.getWorkspace().getRoot().getProject("Project-1").exists());
}

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

License:Open Source License

/**
 * Move a project outside the workspace containing a Git repository, but do not rename it.
 * <p>/* w ww  .j  a va 2s.  c o m*/
 * Note the similarity of the code with {@link #testMoveAndRenameProjectContainingGitRepo()}
 *
 * @throws Exception
 */
@Test
public void testMoveButDoNotRenameProjectOutsideWorkspaceContainingGitRepo() throws Exception {
    ResourcesPlugin.getWorkspace().getRoot().getProject("Project-1").delete(true, null);
    ResourcesPlugin.getWorkspace().getRoot().getProject("P2").delete(true, null);
    TestProject project = initRepoInsideProjectOutsideWorkspace();
    testUtils.addFileToProject(project.getProject(), "file.txt", "some text");
    AddToIndexOperation addToIndexOperation = new AddToIndexOperation(
            new IResource[] { project.getProject().getFile("file.txt") });
    addToIndexOperation.execute(null);
    IProjectDescription description = project.getProject().getDescription();
    description.setLocationURI(
            URIUtil.toURI(new Path(new File(project.getWorkspaceSupplement(), "P2").getAbsolutePath())));
    project.getProject().move(description, IResource.FORCE | IResource.SHALLOW, null);
    IProject project2 = ResourcesPlugin.getWorkspace().getRoot().getProject("Project-1"); // same name
    assertNotNull(RepositoryMapping.getMapping(project2.getProject()));
    Repository movedRepo = RepositoryMapping.getMapping(project2).getRepository();
    assertEquals("P2", movedRepo.getDirectory().getParentFile().getName());
    DirCache dc = movedRepo.readDirCache();
    assertEquals(1, dc.getEntryCount());
    assertEquals("file.txt", dc.getEntry(0).getPathString());

    assertFalse(ResourcesPlugin.getWorkspace().getRoot().getProject("P2").exists());
}

From source file:org.eclipse.egit.core.internal.gerrit.GerritUtil.java

License:Open Source License

/**
 * If the repository is not bare and looks like it might be a Gerrit
 * repository, try to configure it such that EGit's Gerrit support is
 * enabled.//ww w.  ja  v  a 2 s .c o  m
 *
 * @param repository
 *            to try to configure
 */
public static void tryToAutoConfigureForGerrit(@NonNull Repository repository) {
    if (repository.isBare()) {
        return;
    }
    StoredConfig config = repository.getConfig();
    boolean isGerrit = false;
    boolean changed = false;
    try {
        for (RemoteConfig remote : RemoteConfig.getAllRemoteConfigs(config)) {
            if (isGerritPush(remote)) {
                isGerrit = true;
                if (configureFetchNotes(remote)) {
                    changed = true;
                    remote.update(config);
                }
            }
        }
    } catch (URISyntaxException ignored) {
        // Ignore it here -- we're just trying to set up Gerrit support.
    }
    if (isGerrit) {
        if (config.getString(ConfigConstants.CONFIG_GERRIT_SECTION, null,
                ConfigConstants.CONFIG_KEY_CREATECHANGEID) != null) {
            // Already configured.
        } else {
            setCreateChangeId(config);
            changed = true;
        }
        if (changed) {
            try {
                config.save();
            } catch (IOException e) {
                Activator.logError(
                        MessageFormat.format(CoreText.GerritUtil_ConfigSaveError, repository.getDirectory()),
                        e);
            }
        }
    }
}

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

License:Open Source License

/**
 * Provides a singleton instance of {@link RebaseInteractivePlan} for a
 * given {@link Repository}/*  w w  w .j a  v a 2  s.c  om*/
 * <p>
 * If a {@link RebaseInteractivePlan} for the given {@link Repository} has
 * already been created and has not been disposed yet, this instance is
 * returned, otherwise a newly created instance is returned.
 *
 * @param repo
 * @return the {@link RebaseInteractivePlan} for the given
 *         {@link Repository}
 */
public static RebaseInteractivePlan getPlan(Repository repo) {
    RebaseInteractivePlan plan = planRegistry.get(repo.getDirectory());
    if (plan == null) {
        plan = new RebaseInteractivePlan(repo);
        planRegistry.put(repo.getDirectory(), plan);
    }
    return plan;
}