Example usage for org.eclipse.jgit.api Git open

List of usage examples for org.eclipse.jgit.api Git open

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git open.

Prototype

public static Git open(File dir) throws IOException 

Source Link

Document

Open repository

Usage

From source file:org.archicontribs.modelrepository.grafico.GraficoUtils.java

License:Open Source License

/**
 * Get the file contents of a file in the working tree
 * @param localGitFolder/*from   w w w. ja v  a 2s  . c o m*/
 * @param path
 * @return
 * @throws IOException
 */
public static String getWorkingTreeFileContents(File localGitFolder, String path) throws IOException {
    String str = ""; //$NON-NLS-1$

    try (Git git = Git.open(localGitFolder)) {
        try (BufferedReader in = new BufferedReader(new FileReader(new File(localGitFolder, path)))) {
            String line;
            while ((line = in.readLine()) != null) {
                str += line + "\n"; //$NON-NLS-1$
            }
        }
    }

    return str;
}

From source file:org.archicontribs.modelrepository.grafico.MergeConflictHandler.java

License:Open Source License

public void mergeAndCommit() throws IOException, GitAPIException {
    try (Git git = Git.open(fLocalGitFolder)) {
        if (fOurs != null && !fOurs.isEmpty()) {
            checkout(git, Stage.OURS, fOurs);
        }//from w  ww .  j a v  a  2s .com
        if (fTheirs != null && !fTheirs.isEmpty()) {
            checkout(git, Stage.THEIRS, fTheirs);
        }

        // Add to index all files
        AddCommand addCommand = git.add();
        addCommand.addFilepattern("."); //$NON-NLS-1$
        addCommand.setUpdate(false);
        addCommand.call();

        // Commit
        CommitCommand commitCommand = git.commit();
        String userName = ModelRepositoryPlugin.INSTANCE.getPreferenceStore()
                .getString(IPreferenceConstants.PREFS_COMMIT_USER_NAME);
        String userEmail = ModelRepositoryPlugin.INSTANCE.getPreferenceStore()
                .getString(IPreferenceConstants.PREFS_COMMIT_USER_EMAIL);
        commitCommand.setAuthor(userName, userEmail);
        commitCommand.call();
    }
}

From source file:org.archicontribs.modelrepository.grafico.MergeConflictHandler.java

License:Open Source License

private void resetToState(String ref) throws IOException, GitAPIException {
    // Reset HARD  which will lose all changes
    try (Git git = Git.open(fLocalGitFolder)) {
        ResetCommand resetCommand = git.reset();
        resetCommand.setRef(ref);// w ww  . j  av  a 2  s .c om
        resetCommand.setMode(ResetType.HARD);
        resetCommand.call();
    }
}

From source file:org.aysada.licensescollector.dependencies.impl.GitCodeBaseProvider.java

License:Open Source License

public File getLocalRepositoryRoot(String remoteUrl) {
    try {/*from   w  w w . j  a  va 2s.  c  o m*/
        File prjWs = getLocalWSFor(remoteUrl);
        if (prjWs.exists()) {
            Repository repo = Git.open(prjWs).getRepository();
            Git git = new Git(repo);
            git.fetch().call();
            git.close();
            LOGGER.info("Lcoal git repo for {} updated.", remoteUrl);
            return repo.getDirectory();
        } else {
            prjWs.mkdir();
            Git localRepo = Git.cloneRepository().setDirectory(prjWs).setURI(remoteUrl)
                    .setCloneAllBranches(false).call();
            File directory = localRepo.getRepository().getDirectory();
            localRepo.close();
            LOGGER.info("Cloned lcoal git repo for {}.", remoteUrl);
            return directory;
        }
    } catch (IOException | GitAPIException e) {
        LOGGER.error("Error working with git.", e);
    }
    return null;
}

From source file:org.commonwl.view.git.GitService.java

License:Apache License

/**
 * Gets a repository, cloning into a local directory or
 * @param gitDetails The details of the Git repository
 * @param reuseDir Whether the cached repository can be used
 * @return The git object for the repository
 *//*from   w w w .  j a  v a 2  s  .c o  m*/
public Git getRepository(GitDetails gitDetails, boolean reuseDir) throws GitAPIException, IOException {
    Git repo;
    if (reuseDir) {
        // Base dir from configuration, name from hash of repository URL
        String baseName = DigestUtils.sha1Hex(GitDetails.normaliseUrl(gitDetails.getRepoUrl()));

        // Check if folder already exists
        Path repoDir = gitStorage.resolve(baseName);
        if (Files.isReadable(repoDir) && Files.isDirectory(repoDir)) {
            repo = Git.open(repoDir.toFile());
            repo.fetch().call();
        } else {
            // Create a folder and clone repository into it
            Files.createDirectory(repoDir);
            repo = cloneRepo(gitDetails.getRepoUrl(), repoDir.toFile());
        }
    } else {
        // Another thread is already using the existing folder
        // Must create another temporary one
        repo = cloneRepo(gitDetails.getRepoUrl(), createTempDir());
    }

    // Checkout the specific branch or commit ID
    if (repo != null) {
        // Create a new local branch if it does not exist and not a commit ID
        String branchOrCommitId = gitDetails.getBranch();
        final boolean isId = ObjectId.isId(branchOrCommitId);
        if (!isId) {
            branchOrCommitId = "refs/remotes/origin/" + branchOrCommitId;
        }
        try {
            repo.checkout().setName(branchOrCommitId).call();
        } catch (Exception ex) {
            // Maybe it was a tag
            if (!isId && ex instanceof RefNotFoundException) {
                final String tag = gitDetails.getBranch();
                try {
                    repo.checkout().setName(tag).call();
                } catch (Exception ex2) {
                    // Throw the first exception, to keep the same behavior as before.
                    throw ex;
                }
            } else {
                throw ex;
            }
        }
    }

    return repo;
}

From source file:org.craftercms.commons.git.impl.GitRepositoryFactoryImpl.java

License:Open Source License

@Override
public GitRepository open(File dir) throws GitException {
    try {//from   w  ww. j  av  a  2s  . c  o  m
        Git git = Git.open(dir);

        logger.debug("Git repository opened at {}", git.getRepository().getDirectory());

        return new GitRepositoryImpl(git);
    } catch (IOException e) {
        throw new GitException("Error opening Git repository at " + dir, e);
    }
}

From source file:org.craftercms.deployer.utils.GitUtils.java

License:Open Source License

public static Git openRepository(File localRepositoryFolder) throws IOException {
    return Git.open(localRepositoryFolder);
}

From source file:org.curioswitch.gradle.plugins.ci.CurioGenericCiPlugin.java

License:Open Source License

private static Set<Project> computeAffectedProjects(Project project) {
    final Set<String> affectedRelativeFilePaths;
    try (Git git = Git.open(project.getRootDir())) {
        // TODO(choko): Validate the remote of the branch, which matters if there are forks.
        String branch = git.getRepository().getBranch();

        if (branch.equals("master")) {
            affectedRelativeFilePaths = computeAffectedFilesForMaster(git, project);
        } else {//from  ww w . j  a  v a 2 s.c om
            affectedRelativeFilePaths = computeAffectedFilesForBranch(git, branch, project);
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }

    Set<Path> affectedPaths = affectedRelativeFilePaths.stream()
            .map(p -> Paths.get(project.getRootDir().getAbsolutePath(), p)).collect(Collectors.toSet());

    Map<Path, Project> projectsByPath = Collections.unmodifiableMap(project.getAllprojects().stream().collect(
            Collectors.toMap(p -> Paths.get(p.getProjectDir().getAbsolutePath()), Function.identity())));

    project.getLogger().info("CI found affected paths {}", affectedPaths);
    project.getLogger().info("CI found affected projects {}", projectsByPath);

    return affectedPaths.stream().map(f -> getProjectForFile(f, projectsByPath)).collect(Collectors.toSet());
}

From source file:org.curioswitch.gradle.plugins.ci.CurioGenericCiPluginTest.java

License:Open Source License

private static void addDiffs(Path projectDir, String... paths) {
    for (String path : paths) {
        var filePath = projectDir.resolve(path);
        try {//from  w  ww.  j  a  v  a 2s  .c om
            Files.writeString(filePath, Files.readString(filePath).replace("|DIFF-ME|", "-DIFFED-"));
        } catch (IOException e) {
            throw new UncheckedIOException("Could not add diff to file.", e);
        }
    }

    try (Git git = Git.open(projectDir.toFile())) {
        git.commit().setAll(true).setMessage("Automated commit in test")
                .setAuthor("Unit Test", "test@curioswitch.org").call();
    } catch (Exception e) {
        throw new IllegalStateException("Error manipulating git repo.", e);
    }
}

From source file:org.curioswitch.gradle.plugins.ci.CurioGenericCiPluginTest.java

License:Open Source License

private static void changeBranch(Path projectDir, String branch) {
    try (Git git = Git.open(projectDir.toFile())) {
        git.checkout().setName(branch).call();
    } catch (Exception e) {
        throw new IllegalStateException("Error manipulating git repo.", e);
    }//  www .  j  a v  a  2s .  co  m
}