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.jdamico.jgitbkp.tests.JGitTester.java

License:Open Source License

@Test
public void test() throws IOException, GitAPIException {

    String user = "";
    String passwd = "";
    String hostPath = "/git";
    String backupRoot = "/tmp/test";
    String gitRoot = "/mnt";
    String bundlePath = "/tmp";
    boolean keepOld = false;

    List<org.jdamico.jgitbkp.entities.RepoImpl> repos = new ArrayList<org.jdamico.jgitbkp.entities.RepoImpl>();

    File fGitRoot = new File(gitRoot);
    String[] fRepos = fGitRoot.list();
    for (String itemRepo : fRepos) {
        File fItemRepo = new File(gitRoot + "/" + itemRepo);
        if (fItemRepo.isDirectory() && itemRepo.contains(".git") && !itemRepo.equals(".git")) {
            repos.add(new org.jdamico.jgitbkp.entities.RepoImpl(itemRepo, null, backupRoot + "/" + itemRepo));
        }/* ww w  .  j a v  a 2  s .c om*/
    }

    for (int i = 0; i < repos.size(); i++) {

        File f = new File(repos.get(i).getClonedPath());

        if (f.mkdir()) {

            Git.cloneRepository().setCloneAllBranches(true)
                    .setURI("http://" + hostPath + "/" + repos.get(i).getName())
                    .setCredentialsProvider(new UsernamePasswordCredentialsProvider(user, passwd))
                    .setDirectory(new File(repos.get(i).getClonedPath()))
                    .setProgressMonitor(new TextProgressMonitor()).call();

        }

        File gitWorkDir = new File(repos.get(i).getClonedPath());
        Git git = Git.open(gitWorkDir);
        git.pull();
        Repository localRepoGit = git.getRepository();
        BundleWriter bundleWriter = new BundleWriter(localRepoGit);
        ProgressMonitor pMonitor = new TextProgressMonitor();
        OutputStream oStream = new FileOutputStream(bundlePath + "/" + repos.get(i).getName() + ".bundle");

        Map<String, Ref> allRefs = localRepoGit.getAllRefs();
        Collection<Ref> values = allRefs.values();
        Iterator<Ref> iter = values.iterator();
        while (iter.hasNext()) {
            Ref element = iter.next();
            try {

                bundleWriter.include(element);
                System.out.println("Added: " + element.getName());
            } catch (Exception e) {
                // TODO: handle exception
            }

        }

        bundleWriter.writeBundle(pMonitor, oStream);

    }

}

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

License:Open Source License

/**
 * Add files to test repository/*from ww w.j a v a  2 s .  c o m*/
 * 
 * @param repo
 * @param paths
 * @param contents
 * @param message
 * @return commit
 * @throws Exception
 */
public RevCommit add(File repo, List<String> paths, List<String> contents, String message) throws Exception {
    Git git = Git.open(repo);
    for (int i = 0; i < paths.size(); i++) {
        String path = paths.get(i);
        String content = contents.get(i);
        File file = new File(repo.getParentFile(), path);
        if (!file.getParentFile().exists())
            assertTrue(file.getParentFile().mkdirs());
        if (!file.exists())
            assertTrue(file.createNewFile());
        PrintWriter writer = new PrintWriter(file);
        if (content == null)
            content = "";
        try {
            writer.print(content);
        } finally {
            writer.close();
        }
        git.add().addFilepattern(path).call();
    }
    RevCommit commit = git.commit().setMessage(message).setAuthor(author).setCommitter(committer).call();
    assertNotNull(commit);
    return commit;
}

From source file:org.jenkinsci.plugins.pretestedintegration.integration.scm.git.MatrixProjectCompatabilityTestIT.java

/**
 * Git Plugin//from   w w w.  java  2  s .c om
 *
 * Test that show that a ready/feature_1 branch get integrated into master
 * using a Matrix job type.
 *
 * Pretested integration:
 *  - 'Integration branch' : master (default)
 *  - 'Repository name' : origin (default) 
 *  - 'Strategy' : Squash Commit
 *
 * GitSCM:
 *  - 'Name' : (empty)
 *
 * Workflow
 *  - Create a repository containing a 'ready' branch.
 *  - The build is triggered. 
 *
 * Results
 *  - We expect that the plugin triggers, and that the commits on ready branch
 *    is merged into our integration branch master and build result becomes SUCCESS.
 *
 * @throws Exception
 */
@Test
public void oneBuildBasicSmokeTest() throws Exception {
    repository = TestUtilsFactory.createValidRepository("test-repo");

    File workDir = new File("test-repo");

    Git.cloneRepository().setURI("file:///" + repository.getDirectory().getAbsolutePath()).setDirectory(workDir)
            .setBare(false).setCloneAllBranches(true).setNoCheckout(false).call().close();

    Git git = Git.open(workDir);

    System.out.println("Opening git repository in: " + workDir.getAbsolutePath());

    String readmeFromIntegration = FileUtils.readFileToString(new File("test-repo/readme"));

    git.checkout().setName(FEATURE_BRANCH_NAME).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
            .setCreateBranch(true).call();
    final int COMMIT_COUNT_ON_FEATURE_BEFORE_EXECUTION = TestUtilsFactory.countCommits(git);
    git.checkout().setName("master").setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();

    GitProjectBuilder builder = new GitProjectBuilder()
            .setGitRepos(Collections.singletonList(new UserRemoteConfig(
                    "file://" + repository.getDirectory().getAbsolutePath(), null, null, null)))
            .setUseSlaves(true).setRule(jenkinsRule).setStrategy(GitProjectBuilder.STRATEGY_TYPE.ACCUMULATED);
    builder.setJobType(MatrixProject.class);

    MatrixProject project = (MatrixProject) builder.generateJenkinsJob();
    TestUtilsFactory.triggerProject(project);

    jenkinsRule.waitUntilNoActivityUpTo(60000);

    assertEquals("2 runs for this particular matrix build", 2, project.getLastBuild().getRuns().size());

    String readmeFileContents = FileUtils.readFileToString(new File("test-repo/readme"));
    assertEquals(readmeFromIntegration, readmeFileContents);

    git.pull().call();

    final int COMMIT_COUNT_ON_MASTER_AFTER_EXECUTION = TestUtilsFactory.countCommits(git);

    git.close();

    //We assert that 2 commits from branch gets merged + 1 combined merge commit since we do --no-ff
    assertEquals(COMMIT_COUNT_ON_FEATURE_BEFORE_EXECUTION + 3, COMMIT_COUNT_ON_MASTER_AFTER_EXECUTION);
}

From source file:org.jenkinsci.plugins.pretestedintegration.integration.scm.git.MatrixProjectCompatibilityTestIT.java

/**
 * Git Plugin/*w w w. j a  v  a  2s  .  co  m*/
 *
 * Test that show that a ready/feature_1 branch get integrated into master
 * using a Matrix job type.
 *
 * Pretested integration:
 *  - 'Integration branch' : master (default)
 *  - 'Repository name' : origin (default)
 *  - 'Strategy' : Squash Commit
 *
 * GitSCM:
 *  - 'Name' : (empty)
 *
 * Workflow
 *  - Create a repository containing a 'ready' branch.
 *  - The build is triggered.
 *
 * Results
 *  - We expect that the plugin triggers, and that the commits on ready branch
 *    is merged into our integration branch master and build result becomes SUCCESS.
 *
 * @throws Exception
 */

@Test
public void oneBuildBasicSmokeTest() throws Exception {
    repository = TestUtilsFactory.createValidRepository("test-repo");
    File workDir = new File(TestUtilsFactory.WORKDIR, "test-repo");
    Git.cloneRepository().setURI("file:///" + repository.getDirectory().getAbsolutePath()).setDirectory(workDir)
            .setBare(false).setCloneAllBranches(true).setNoCheckout(false).call().close();

    Git git = Git.open(workDir);

    System.out.println("Opening git repository in: " + workDir.getAbsolutePath());

    String readmeFromIntegration = FileUtils.readFileToString(new File(workDir, "readme"));

    git.checkout().setName(FEATURE_BRANCH_NAME).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
            .setCreateBranch(true).call();
    final int COMMIT_COUNT_ON_FEATURE_BEFORE_EXECUTION = TestUtilsFactory.countCommits(git);
    git.checkout().setName("master").setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();

    MatrixProjectBuilder builder = new MatrixProjectBuilder()
            .setGitRepos(Collections.singletonList(new UserRemoteConfig(
                    "file://" + repository.getDirectory().getAbsolutePath(), null, null, null)))
            .setUseSlaves(true).setRule(jenkinsRule).setStrategy(TestUtilsFactory.STRATEGY_TYPE.ACCUMULATED);
    builder.setJobType(MatrixProject.class);

    MatrixProject project = (MatrixProject) builder.generateJenkinsJob();
    TestUtilsFactory.triggerProject(project);

    jenkinsRule.waitUntilNoActivityUpTo(60000);

    String readmeFileContents = FileUtils.readFileToString(new File(workDir, "readme"));
    assertEquals(readmeFromIntegration, readmeFileContents);
    git.pull().call();

    assertEquals("3 runs for this particular matrix build", 3, project.getLastBuild().getRuns().size());

    final int COMMIT_COUNT_ON_MASTER_AFTER_EXECUTION = TestUtilsFactory.countCommits(git);
    git.close();
    //We assert that 2 commits from branch gets merged + 1 combined merge commit since we do --no-ff
    assertEquals(COMMIT_COUNT_ON_FEATURE_BEFORE_EXECUTION + 3, COMMIT_COUNT_ON_MASTER_AFTER_EXECUTION);
}

From source file:org.jplus.jenkins.plugin.git.GITRepositoryUtils.java

public GITRepositoryUtils(String repositoryPath) throws IOException {
    this.repositoryPath = repositoryPath;
    git = Git.open(new File(repositoryPath));
    this.repo = git.getRepository();
}

From source file:org.kantega.reststop.maven.CreatePluginMojo.java

License:Apache License

private void addNewFilesToGit(File pluginsDir, File pluginPomFile, File pluginClassFile) throws IOException {
    File gitDir = new File(new File(pluginsDir.getParent()), ".git");
    if (gitDir.exists()) {
        File workDir = new File(gitDir.getParent());
        Git git = null;/* www .jav  a  2s  . com*/

        try {
            git = Git.open(workDir);
            git.add().addFilepattern(getRelativeTo(pluginPomFile, workDir)).call();
            git.add().addFilepattern(getRelativeTo(pluginClassFile, workDir)).call();
        } catch (GitAPIException e) {
            // ignore
        } finally {
            if (git != null) {
                git.close();
            }

        }
    }
}

From source file:org.kercoin.magrit.core.user.UserIdentityServiceImpl.java

License:Open Source License

private void open() throws IOException {
    if (this.datasource == null) {
        this.datasource = Git.open(configuration.getPublickeyRepositoryDir()).getRepository();
    }//www .  j av a2s . c o  m
}

From source file:org.kercoin.magrit.core.utils.GitUtilsTest.java

License:Open Source License

@Before
public void setUp() throws Exception {
    gitUtils = new GitUtils();
    clone = Git.open(new File("target/tmp/repos/clone")).getRepository();
}

From source file:org.kercoin.magrit.sshd.auth.GitPublickeyAuthenticator.java

License:Open Source License

private void open() throws IOException {
    if (this.datasource == null) {
        this.datasource = Git.open(context.configuration().getPublickeyRepositoryDir()).getRepository();
    }/*from w w w .jav  a2 s. co m*/
}

From source file:org.kie.eclipse.server.KieRepositoryHandler.java

License:Open Source License

@Override
public Object load() {
    if (repository == null) {
        try {//from w ww. j  a va 2s  .  com
            final File repoRoot = new File(PreferencesUtils.getRepoRoot(this));
            final Set<File> gitDirs = new HashSet<File>();
            GitUtils.findGitDirsRecursive(repoRoot, gitDirs, false);
            for (File dir : gitDirs) {
                if (getName().equals(dir.getParentFile().getName())) {
                    Git git = Git.open(dir);
                    Repository repository = git.getRepository();
                    StoredConfig storedConfig = repository.getConfig();
                    Set<String> remotes = storedConfig.getSubsections("remote");
                    for (String remoteName : remotes) {
                        try {
                            String url = storedConfig.getString("remote", remoteName, "url");
                            URI uri = new URI(url);
                            int port = uri.getPort();
                            String host = uri.getHost();
                            String scheme = uri.getScheme();
                            String path[] = uri.getPath().split("/");
                            String repoName = path[path.length - 1];
                            if (name.equals(repoName) && host.equals(getServer().getHost())
                                    && port == getDelegate().getGitPort() && "ssh".equals(scheme)) {
                                this.repository = repository;
                                break;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            if (git != null) {
                                git.close();
                                git = null;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return repository;
}