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

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

Introduction

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

Prototype

public static Git wrap(Repository repo) 

Source Link

Document

Wrap repository

Usage

From source file:org.gitistics.test.RepositoryWokerImpl.java

License:Open Source License

public RepositoryWokerImpl modify(String file, String newContent) throws Exception {
    File f = new File(dir, file);
    FileUtils.writeStringToFile(f, newContent);
    Git.wrap(repository).add().addFilepattern(file).call();
    return this;
}

From source file:org.gitistics.test.RepositoryWokerImpl.java

License:Open Source License

public RepositoryWokerImpl remove(String file) throws Exception {
    File f = new File(dir, file);
    if (f.exists()) {
        f.delete();/*  ww w.j a  va 2 s .c om*/
    }
    Git.wrap(repository).add().setUpdate(true).addFilepattern(".").call();
    return this;
}

From source file:org.gradle.vcs.fixtures.GitFileRepository.java

License:Apache License

/**
 * Updates any submodules in this repository to the latest in the submodule origin repository
 *///www . ja v  a  2s .co m
public RevCommit updateSubmodulesToLatest() throws GitAPIException {
    List<String> submodulePaths = Lists.newArrayList();
    try {
        SubmoduleWalk walker = SubmoduleWalk.forIndex(git.getRepository());
        try {
            while (walker.next()) {
                Repository submodule = walker.getRepository();
                try {
                    submodulePaths.add(walker.getPath());
                    Git.wrap(submodule).pull().call();
                } finally {
                    submodule.close();
                }
            }
        } finally {
            walker.close();
        }
        return commit("update submodules", submodulePaths.toArray(new String[submodulePaths.size()]));
    } catch (IOException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}

From source file:org.gradle.vcs.git.internal.GitVersionControlSystem.java

License:Apache License

private static void updateSubModules(Git git) throws IOException, GitAPIException {
    SubmoduleWalk walker = SubmoduleWalk.forIndex(git.getRepository());
    try {//  w w w .j  av  a 2s.  c  o m
        while (walker.next()) {
            Repository submodule = walker.getRepository();
            try {
                Git submoduleGit = Git.wrap(submodule);
                submoduleGit.fetch().call();
                git.submoduleUpdate().addPath(walker.getPath()).call();
                submoduleGit.reset().setMode(ResetCommand.ResetType.HARD).call();
                updateSubModules(submoduleGit);
            } finally {
                submodule.close();
            }
        }
    } finally {
        walker.close();
    }
}

From source file:org.jabylon.team.git.GitTeamProvider.java

License:Open Source License

@Override
public Collection<PropertyFileDiff> update(ProjectVersion project, IProgressMonitor monitor)
        throws TeamProviderException {

    SubMonitor subMon = SubMonitor.convert(monitor, 100);
    List<PropertyFileDiff> updatedFiles = new ArrayList<PropertyFileDiff>();
    try {/*  ww w.  j av a  2s  .  com*/
        Repository repository = createRepository(project);
        Git git = Git.wrap(repository);
        FetchCommand fetchCommand = git.fetch();
        URI uri = project.getParent().getRepositoryURI();
        if (uri != null)
            fetchCommand.setRemote(stripUserInfo(uri).toString());
        String refspecString = "refs/heads/{0}:refs/remotes/origin/{0}";
        refspecString = MessageFormat.format(refspecString, project.getName());
        RefSpec spec = new RefSpec(refspecString);
        fetchCommand.setRefSpecs(spec);
        subMon.subTask("Fetching from remote");
        if (!"https".equals(uri.scheme()) && !"http".equals(uri.scheme()))
            fetchCommand.setTransportConfigCallback(createTransportConfigCallback(project.getParent()));
        fetchCommand.setCredentialsProvider(createCredentialsProvider(project.getParent()));
        fetchCommand.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(80)));
        fetchCommand.call();
        ObjectId remoteHead = repository.resolve("refs/remotes/origin/" + project.getName() + "^{tree}");

        DiffCommand diff = git.diff();
        subMon.subTask("Caculating Diff");
        diff.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(20)));
        diff.setOldTree(new FileTreeIterator(repository));
        CanonicalTreeParser p = new CanonicalTreeParser();
        ObjectReader reader = repository.newObjectReader();
        try {
            p.reset(reader, remoteHead);
        } finally {
            reader.release();
        }
        diff.setNewTree(p);
        checkCanceled(subMon);
        List<DiffEntry> diffs = diff.call();
        for (DiffEntry diffEntry : diffs) {
            checkCanceled(subMon);
            updatedFiles.add(convertDiffEntry(diffEntry));
            LOGGER.trace(diffEntry.toString());
        }
        if (!updatedFiles.isEmpty()) {
            checkCanceled(subMon);
            //no more cancel after this point
            ObjectId lastCommitID = repository
                    .resolve("refs/remotes/origin/" + project.getName() + "^{commit}");
            LOGGER.info("Merging remote commit {} to {}/{}",
                    new Object[] { lastCommitID, project.getName(), project.getParent().getName() });
            //TODO: use rebase here?
            if (isRebase(project)) {
                RebaseCommand rebase = git.rebase();
                rebase.setUpstream("refs/remotes/origin/" + project.getName());
                RebaseResult result = rebase.call();
                if (result.getStatus().isSuccessful()) {
                    LOGGER.info("Rebase finished: {}", result.getStatus());
                } else {
                    LOGGER.error("Rebase of {} failed. Attempting abort", project.relativePath());
                    rebase = git.rebase();
                    rebase.setOperation(Operation.ABORT);
                    result = rebase.call();
                    LOGGER.error("Abort finished with {}", result.getStatus());
                }
            } else {
                MergeCommand merge = git.merge();
                merge.include(lastCommitID);
                MergeResult mergeResult = merge.call();

                LOGGER.info("Merge finished: {}", mergeResult.getMergeStatus());
            }
        } else
            LOGGER.info("Update finished successfully. Nothing to merge, already up to date");
    } catch (JGitInternalException e) {
        throw new TeamProviderException(e);
    } catch (InvalidRemoteException e) {
        throw new TeamProviderException(e);
    } catch (GitAPIException e) {
        throw new TeamProviderException(e);
    } catch (AmbiguousObjectException e) {
        throw new TeamProviderException(e);
    } catch (IOException e) {
        throw new TeamProviderException(e);
    } finally {
        monitor.done();
    }
    return updatedFiles;
}

From source file:org.jboss.as.server.controller.git.GitRepository.java

License:Apache License

public GitRepository(GitRepositoryConfiguration gitConfig)
        throws IllegalArgumentException, IOException, ConfigXMLParseException, GeneralSecurityException {
    this.basePath = gitConfig.getBasePath();
    this.branch = gitConfig.getBranch();
    this.ignored = gitConfig.getIgnored();
    this.defaultRemoteRepository = gitConfig.getRepository();
    File baseDir = basePath.toFile();
    File gitDir = new File(baseDir, DOT_GIT);
    if (gitConfig.getAuthenticationConfig() != null) {
        CredentialsProvider/* www  .  j  a  va2 s .  co m*/
                .setDefault(new ElytronClientCredentialsProvider(gitConfig.getAuthenticationConfig()));
    }
    if (gitDir.exists()) {
        try {
            repository = new FileRepositoryBuilder().setWorkTree(baseDir).setGitDir(gitDir).setup().build();
        } catch (IOException ex) {
            throw ServerLogger.ROOT_LOGGER.failedToPullRepository(ex, gitConfig.getRepository());
        }
        try (Git git = Git.wrap(repository)) {
            git.clean();
            if (!isLocalGitRepository(gitConfig.getRepository())) {
                String remote = getRemoteName(gitConfig.getRepository());
                checkoutToSelectedBranch(git);
                PullResult result = git.pull().setRemote(remote).setRemoteBranchName(branch)
                        .setStrategy(MergeStrategy.RESOLVE).call();
                if (!result.isSuccessful()) {
                    throw ServerLogger.ROOT_LOGGER.failedToPullRepository(null, gitConfig.getRepository());
                }
            } else {
                if (!this.branch.equals(repository.getBranch())) {
                    CheckoutCommand checkout = git.checkout().setName(branch);
                    checkout.call();
                    if (checkout.getResult().getStatus() == CheckoutResult.Status.ERROR) {
                        throw ServerLogger.ROOT_LOGGER.failedToPullRepository(null, gitConfig.getRepository());
                    }
                }
            }
        } catch (GitAPIException ex) {
            throw ServerLogger.ROOT_LOGGER.failedToPullRepository(ex, gitConfig.getRepository());
        }
    } else {
        if (isLocalGitRepository(gitConfig.getRepository())) {
            try (Git git = Git.init().setDirectory(baseDir).call()) {
                final AddCommand addCommand = git.add();
                addCommand.addFilepattern("data/content/");
                Path configurationDir = basePath.resolve("configuration");
                try (Stream<Path> files = Files.list(configurationDir)) {
                    files.filter(configFile -> !"logging.properties".equals(configFile.getFileName().toString())
                            && Files.isRegularFile(configFile))
                            .forEach(configFile -> addCommand.addFilepattern(getPattern(configFile)));
                }
                addCommand.call();
                createGitIgnore(git, basePath);
                git.commit().setMessage(ServerLogger.ROOT_LOGGER.repositoryInitialized()).call();
            } catch (GitAPIException | IOException ex) {
                throw ServerLogger.ROOT_LOGGER.failedToInitRepository(ex, gitConfig.getRepository());
            }
        } else {
            clearExistingFiles(basePath, gitConfig.getRepository());
            try (Git git = Git.init().setDirectory(baseDir).call()) {
                String remoteName = UUID.randomUUID().toString();
                StoredConfig config = git.getRepository().getConfig();
                config.setString("remote", remoteName, "url", gitConfig.getRepository());
                config.setString("remote", remoteName, "fetch",
                        "+" + R_HEADS + "*:" + R_REMOTES + remoteName + "/*");
                config.save();
                git.clean();
                git.pull().setRemote(remoteName).setRemoteBranchName(branch).setStrategy(MergeStrategy.RESOLVE)
                        .call();
                checkoutToSelectedBranch(git);
                if (createGitIgnore(git, basePath)) {
                    git.commit().setMessage(ServerLogger.ROOT_LOGGER.addingIgnored()).call();
                }
            } catch (GitAPIException ex) {
                throw ServerLogger.ROOT_LOGGER.failedToInitRepository(ex, gitConfig.getRepository());
            }
        }
        repository = new FileRepositoryBuilder().setWorkTree(baseDir).setGitDir(gitDir).setup().build();
    }
    ServerLogger.ROOT_LOGGER.usingGit();
}

From source file:org.jboss.as.server.controller.git.GitRepository.java

License:Apache License

public Git getGit() {
    return Git.wrap(repository);
}

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

License:Open Source License

public RevCommit call() throws IOException {
    FetchCommand fetch = Git.wrap(gitRepo).fetch();
    fetch.setRemote(repo.getUri());/*from www. ja v a2  s .  co m*/
    fetch.setRefSpecs(new RefSpec(repo.getBranch()));
    if (monitor != null)
        fetch.setProgressMonitor(monitor);
    try {
        fetch.call();
        return CommitUtils.getRef(gitRepo, Constants.FETCH_HEAD);
    } catch (GitException e) {
        throw new IOException(e);
    } catch (JGitInternalException e) {
        throw new IOException(e);
    } catch (InvalidRemoteException e) {
        throw new IOException(e);
    }
}

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

License:Open Source License

public ObjectId call() throws IOException {
    LsRemoteCommand ls = Git.wrap(gitRepo).lsRemote();
    ls.setRemote(repo.getUri());/*from w  ww .  j  a v  a  2  s  .co m*/
    String branch = repo.getBranch();
    Collection<Ref> refs;
    try {
        refs = ls.call();
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException(e);
    }
    for (Ref ref : refs)
        if (branch.equals(ref.getName()))
            return ref.getObjectId();
    return null;
}

From source file:org.kabir.github.merges.model.GitRepositoryManager.java

License:Open Source License

public String viewCheckout(String name) {
    if (this.gitRepositoryDetails == null || this.gitRepositoryDetails.getName() == null
            || !this.gitRepositoryDetails.getName().equals(name)) {
        this.gitRepositoryDetails = GitRepositoryDetails.load(userConfig, name);
    }//www.  j  a  va  2s  .c o  m
    if (this.gitRepositoryDetails.getPassword() == null) {
        return "password";
    }
    if (!initGitHubHelperAndAuthenticate()) {
        facesContext.addMessage(null, new FacesMessage("Wrong password"));
        return "password";
    }

    File checkoutDir = Util
            .getExistingDirectory(new File(userConfig.getCheckoutsDirectory(), name).getAbsolutePath());
    Git git = null;
    BranchManager branchManager = null;
    try {
        Repository repository = new FileRepositoryBuilder().setWorkTree(checkoutDir).readEnvironment().build();
        git = Git.wrap(repository);
        branchManager = new BranchManager(git, gitRepositoryDetails.getMainBranch(),
                gitRepositoryDetails.getTestingBranch());
    } catch (Exception e) {
        facesContext.addMessage(null, new FacesMessage("Error loading the repository " + e.getMessage()));
        return "error";
    }

    branchStatus = new BranchStatus(branchManager);
    return "view";
}