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

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

Introduction

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

Prototype

public Git(Repository repo) 

Source Link

Document

Construct a new org.eclipse.jgit.api.Git object which can interact with the specified git repository.

Usage

From source file:io.fabric8.openshift.agent.CartridgeGitRepository.java

License:Apache License

/**
 * Clones or pulls the remote repository and returns the directory with the checkout
 *//*from  w  w w .  ja va 2  s  .  c  o  m*/
public void cloneOrPull(final String repo, final CredentialsProvider credentials) throws Exception {
    if (!localRepo.exists() && !localRepo.mkdirs()) {
        throw new IOException("Failed to create local repository");
    }
    File gitDir = new File(localRepo, ".git");
    if (!gitDir.exists()) {
        LOG.info("Cloning remote repo " + repo);
        CloneCommand command = Git.cloneRepository().setCredentialsProvider(credentials).setURI(repo)
                .setDirectory(localRepo).setRemote(remoteName);
        git = command.call();
    } else {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(gitDir).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        git = new Git(repository);

        // update the remote repo just in case
        StoredConfig config = repository.getConfig();
        config.setString("remote", remoteName, "url", repo);
        config.setString("remote", remoteName, "fetch", "+refs/heads/*:refs/remotes/" + remoteName + "/*");

        String branch = "master";
        config.setString("branch", branch, "remote", remoteName);
        config.setString("branch", branch, "merge", "refs/heads/" + branch);

        try {
            config.save();
        } catch (IOException e) {
            LOG.error("Failed to save the git configuration to " + localRepo + " with remote repo: " + repo
                    + ". " + e, e);
        }

        // now pull
        LOG.info("Pulling from remote repo " + repo);
        git.pull().setCredentialsProvider(credentials).setRebase(true).call();
    }
}

From source file:io.fabric8.vertx.maven.plugin.util.GitUtil.java

License:Apache License

/**
 * Retrieve the git commitId hash/*from  ww  w.j a v a2 s  . co  m*/
 *
 * @param repository - the Git repository from where the latest commit will be retrieved
 * @return String of Git commit hash
 * @throws GitAPIException - any Git exception that might occur while getting commitId
 */
public static String getGitCommitId(Repository repository) throws GitAPIException {
    try {
        if (repository != null) {
            Iterable<RevCommit> logs = new Git(repository).log().call();
            for (RevCommit rev : logs) {
                return rev.getName();
            }
        }
    } finally {

    }
    return null;
}

From source file:io.github.thefishlive.updater.Updater.java

License:Open Source License

public void run() {
    System.out.println("-------------------------");
    System.out.println(gitDir.getAbsolutePath());
    File updateFile = new File(basedir, "UPDATE");
    Git git = null;//from   w  ww .j a va  2 s  . co  m

    try {
        if (!gitDir.exists()) {
            git = Git.cloneRepository().setDirectory(basedir).setURI(GitUpdater.remote)
                    .setProgressMonitor(buildProgressMonitor()).call();

            System.out.println("Repository cloned");
        } else {
            updateFile.createNewFile();

            FileRepositoryBuilder builder = new FileRepositoryBuilder();
            Repository repo = builder.setGitDir(gitDir).readEnvironment() // scan environment GIT_* variables
                    .findGitDir() // scan up the file system tree
                    .build();

            git = new Git(repo);

            PullResult result = git.pull().setProgressMonitor(buildProgressMonitor()).call();

            if (!result.isSuccessful() || result.getMergeResult().getMergeStatus().equals(MergeStatus.MERGED)) {
                System.out.println("Update Failed");
                FileUtils.deleteDirectory(basedir);
                basedir.mkdir();
                System.out.println("Re-cloning repository");

                git = Git.cloneRepository().setDirectory(basedir).setURI(GitUpdater.remote)
                        .setProgressMonitor(buildProgressMonitor()).call();

                System.out.println("Repository cloned");
            }

            System.out.println("State: " + result.getMergeResult().getMergeStatus());
        }

        File configdir = new File("config");

        if (configdir.exists()) {
            FileUtils.copyDirectory(configdir, new File(basedir, "config"));
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        git.getRepository().close();
    }

    updateFile.delete();
    System.out.println("-------------------------");
}

From source file:jbenchmarker.trace.git.GitExtraction.java

License:Open Source License

public GitExtraction(Repository repo, CouchDbRepositorySupport<Commit> dbc, CouchDbRepositorySupport<Patch> dbp,
        DiffAlgorithm diffAlgorithm, String path, boolean detectMovesAndUpdates, int updateThresold,
        int moveThresold) {
    this.repository = repo;
    this.reader = repo.newObjectReader();
    this.source = ContentSource.create(reader);
    this.pairSource = new ContentSource.Pair(source, source);
    this.diffAlgorithm = diffAlgorithm;
    this.patchCrud = dbp;
    this.commitCrud = dbc;
    this.git = new Git(repo);
    this.path = path;
    this.detectMoveAndUpdate = detectMovesAndUpdates;
    this.updateThresold = updateThresold;
    this.moveThresold = moveThresold;
}

From source file:jbenchmarker.trace.git.GitWalker.java

License:Open Source License

public GitWalker(String... args) throws IOException {

    try {/*from  w  ww .  j  av  a 2  s  . c  o m*/
        this.parser = new CmdLineParser(this);

        parser.parseArgument(args);

        if (help) {
            help(0);
        }
    } catch (CmdLineException ex) {
        System.err.println("Error in argument " + ex);
        help(-1);
    }

    Logger.getLogger("").setLevel(levels[logLevel.ordinal()]);

    builder = new FileRepositoryBuilder();
    repository = builder.setGitDir(new File(gitDir + "/.git")).readEnvironment().findGitDir().build();
    this.reader = repository.newObjectReader();
    this.git = new Git(repository);
    this.source = ContentSource.create(reader);
    this.diffAlgorithm = DiffAlgorithm.getAlgorithm(DiffAlgorithm.SupportedAlgorithm.MYERS);
    this.fromCommit = repository.resolve(fromCommitStr);

}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.GitGcProcess.java

License:Apache License

public static void main(String... args) throws Exception {
    GitServerUtil.configureExternalProcessLogger(false);
    try {/*  w w w.  j ava 2  s  . co  m*/
        String gitDir = args[0];
        System.out.println("run gc in " + gitDir);
        Repository r = new RepositoryBuilder().setBare().setGitDir(new File(gitDir)).build();
        Git git = new Git(r);
        GarbageCollectCommand gc = git.gc();
        gc.setProgressMonitor(new TextProgressMonitor(new PrintWriter(System.out)));
        gc.call();
    } catch (Throwable t) {
        if (isImportant(t)) {
            t.printStackTrace(System.err);
        } else {
            System.err.println(t.getMessage());
        }
        System.exit(1);
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.GitLabelingSupport.java

License:Apache License

@NotNull
public String label(@NotNull String label, @NotNull String version, @NotNull VcsRoot root,
        @NotNull CheckoutRules checkoutRules) throws VcsException {
    OperationContext context = myVcs.createContext(root, "labeling");
    GitVcsRoot gitRoot = context.getGitRoot();
    RevisionsInfo revisionsInfo = new RevisionsInfo();
    if (myConfig.useTagPackHeuristics()) {
        LOG.debug("Update repository before labeling " + gitRoot.debugInfo());
        RepositoryStateData currentState = myVcs.getCurrentState(gitRoot);
        if (!myConfig.analyzeTagsInPackHeuristics())
            currentState = excludeTags(currentState);
        try {/*from w w w. j  a v  a2 s  .c om*/
            myVcs.getCollectChangesPolicy().ensureRepositoryStateLoadedFor(context, context.getRepository(),
                    false, currentState);
        } catch (Exception e) {
            LOG.debug("Error while updating repository " + gitRoot.debugInfo(), e);
        }
        revisionsInfo = new RevisionsInfo(currentState);
    }
    ReadWriteLock rmLock = myRepositoryManager.getRmLock(gitRoot.getRepositoryDir());
    rmLock.readLock().lock();
    try {
        long start = System.currentTimeMillis();
        Repository r = context.getRepository();
        String commitSHA = GitUtils.versionRevision(version);
        RevCommit commit = myCommitLoader.loadCommit(context, gitRoot, commitSHA);
        Git git = new Git(r);
        Ref tagRef = git.tag().setTagger(gitRoot.getTagger(r)).setName(label).setObjectId(commit).call();
        if (tagRef.getObjectId() == null || resolve(r, tagRef) == null) {
            LOG.warn("Tag's " + tagRef.getName() + " objectId "
                    + (tagRef.getObjectId() != null ? tagRef.getObjectId().name() + " " : "")
                    + "cannot be resolved");
        } else if (LOG.isDebugEnabled()) {
            LOG.debug("Tag created  " + label + "=" + version + " for " + gitRoot.debugInfo() + " in "
                    + (System.currentTimeMillis() - start) + "ms");
        }
        return push(label, version, gitRoot, r, tagRef, revisionsInfo);
    } catch (Exception e) {
        throw context.wrapException(e);
    } finally {
        rmLock.readLock().unlock();
        context.close();
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.AgentVcsSupportTest.java

License:Apache License

@TestFor(issues = "TW-20165")
public void push_with_local_mirrors_should_go_to_original_repository() throws Exception {
    AgentRunningBuild build = createRunningBuild(true);
    myVcsSupport.updateSources(myRoot, CheckoutRules.DEFAULT,
            GitUtils.makeVersion("465ad9f630e451b9f2b782ffb09804c6a98c4bb9", 1289483394000L), myCheckoutDir,
            build, false);//w w w  . j a va 2 s.co m

    final File fileToChange = new File(myCheckoutDir, "file");
    FileUtil.writeToFile(fileToChange, "text".getBytes());

    Repository r = new RepositoryBuilder().setWorkTree(myCheckoutDir).build();
    Git git = new Git(r);
    git.add().addFilepattern("file").call();
    RevCommit commitDuringTheBuild = git.commit().setMessage("Commit during the build").call();
    new PushCommand().run(getGitPath(), myCheckoutDir.getAbsolutePath());//push using native git, seems like jgit doesn't respect url.insteadOf settings

    Repository remote = new RepositoryBuilder().setGitDir(myMainRepo).build();
    assertTrue("Push didn't go to the remote repository", remote.hasObject(commitDuringTheBuild));
}

From source file:licenseUtil.Utils.java

License:Apache License

public static void updateRepository(String gitDir) {
    try {// w ww .  j  a  v a2s.c  o  m
        // Open an existing repository
        Repository existingRepo = new FileRepositoryBuilder().setGitDir(new File(gitDir + "/.git")).build();
        Git git = new Git(existingRepo);

        git.pull().call();
    } catch (GitAPIException e) {
        logger.warn("Could not update local repository: \"" + gitDir + "\" with git pull.");
    } catch (IOException e) {
        logger.warn("Could not open local git repository directory: \"" + gitDir + "\"");
    }

}

From source file:licenseUtil.Utils.java

License:Apache License

public static void commitAndPushRepository(String gitDir, String message) {
    try {/* w  ww . ja  v a  2s.co m*/
        // Open an existing repository
        Repository existingRepo = new FileRepositoryBuilder().setGitDir(new File(gitDir + "/.git")).build();
        Git git = new Git(existingRepo);

        logger.info("commit & push to repo (" + gitDir + "): " + message);
        git.commit().setMessage(message).call();
        git.push().call();
    } catch (GitAPIException e) {
        logger.warn("Could not commit and push local repository: \"" + gitDir + "\" with message: \"" + message
                + "\" because of " + e.getMessage());
    } catch (IOException e) {
        logger.warn("Could not open local git repository directory: \"" + gitDir + "\"");
    }

}