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.curioswitch.gradle.plugins.ci.CurioGenericCiPluginTest.java

License:Open Source License

private static void addTwoEmptyCommits(Path projectDir) {
    try (Git git = Git.open(projectDir.toFile())) {
        git.commit().setAllowEmpty(true).setMessage("Empty commit 1")
                .setAuthor("Unit Test", "test@curioswitch.org").call();
        git.commit().setAllowEmpty(true).setMessage("Empty commit 2")
                .setAuthor("Unit Test", "test@curioswitch.org").call();
    } catch (Exception e) {
        throw new IllegalStateException("Error manipulating git repo.", e);
    }/*w ww .j  a  va2s.  com*/
}

From source file:org.curioswitch.gradle.release.ReleasePlugin.java

License:Open Source License

private static String determineVersion(Project project) {
    String revisionId;/*from w w w  . j a  v  a2 s.  co m*/
    if (project.hasProperty("curiostack.revisionId")) {
        revisionId = (String) project.property("curiostack.revisionId");
    } else if (System.getenv().containsKey("REVISION_ID")) {
        revisionId = System.getenv("REVISION_ID");
    } else if (!Strings.isNullOrEmpty(System.getenv().get("TAG_NAME"))) {
        revisionId = System.getenv("TAG_NAME");
    } else if (!Strings.isNullOrEmpty(System.getenv().get("BRANCH_NAME"))) {
        revisionId = System.getenv("BRANCH_NAME");
    } else {
        try (Git git = Git.open(project.getRootDir())) {
            revisionId = git.getRepository().resolve(Constants.HEAD).getName().substring(0, 12);
        } catch (IOException e) {
            revisionId = "unknown";
        }
    }

    checkNotNull(revisionId);

    boolean isRelease = "true".equals(project.findProperty("curiostack.release"));

    if (isRelease) {
        return revisionId;
    } else {
        return "0.0.0-" + TIMESTAMP_FORMATTER.format(LocalDateTime.now(ZoneOffset.UTC)) + "-" + revisionId;
    }
}

From source file:org.debian.dependency.sources.JGitSource.java

License:Apache License

private void openRepo(final File location, final String origin) throws IOException, GitAPIException {
    try {//  w  ww.j av a2s . co  m
        git = Git.open(location);

        if (git.getRepository().isBare()) {
            throw new IllegalArgumentException("Cannot work with bare git repos, convert to a non-bare repo");
        } else if (git.getRepository().getRef(Constants.HEAD).getObjectId() == null) {
            throw new IllegalArgumentException(
                    "Repository must have " + Constants.HEAD + " setup and pointing to a valid commit");
        }
    } catch (RepositoryNotFoundException e) {
        getLogger().debug("No existing git repository found, creating from " + location);
        git = Git.init().setDirectory(location).setBare(false).call();

        git.add().addFilepattern(".").call();

        // we don't want to track other SCM metadata files
        RmCommand removeAction = git.rm();
        for (String pattern : FileUtils.getDefaultExcludes()) {
            if (pattern.startsWith(".git")) {
                continue;
            }
            removeAction.addFilepattern(pattern);
        }
        removeAction.call();

        git.commit().setMessage(COMMIT_MESSAGE_PREFIX + " Import upstream from " + origin).call();
    }
}

From source file:org.debian.dependency.sources.TestJGitSource.java

License:Apache License

/**
 * We should be able to create a git repo over top of other version control systems, public void testInitOtherVcs() throws
 * Exception { }/*from  w ww.j  a v  a 2 s  .c o m*/
 *
 * /** When cleaning the source, we must take into account all types of dirty file states.
 */
@Test
public void testClean() throws Exception {
    Git git = Git.open(directory);

    File.createTempFile("unchanged", "file", directory);

    File subChanged = new File(new File(directory, "directory"), "changed");
    subChanged.getParentFile().mkdirs();
    subChanged.createNewFile();
    File changed = File.createTempFile("changed", "file", directory);

    git.add().addFilepattern(".").call();
    git.commit().setMessage("Prepare for test").call();

    source.initialize(directory, ORIGIN);

    Files.write("some data", subChanged, Charset.defaultCharset());
    Files.write("more data", changed, Charset.defaultCharset());
    File.createTempFile("new", "file", directory);

    File untrackedDir = new File(directory, "untracked");
    untrackedDir.mkdirs();
    File.createTempFile("another", "file", untrackedDir);

    source.clean();

    Status status = git.status().call();
    assertThat(status.getUntracked(), hasSize(0));
    assertThat(status.getUntrackedFolders(), hasSize(0));
    assertThat(status.getIgnoredNotInIndex(), hasSize(0));
    assertTrue("No changes", status.isClean());
}

From source file:org.dstadler.jgit.api.JGitPrintContent.java

License:BSD License

public static void main(String[] args) throws Exception {
    File gitWorkDir = new File("C:\\Users\\kishore\\git\\JavaRepos\\.git");
    Git git = Git.open(gitWorkDir);
    Repository repo = git.getRepository();

    ObjectId lastCommitId = repo.resolve(Constants.HEAD);

    RevWalk revWalk = new RevWalk(repo);
    RevCommit commit = revWalk.parseCommit(lastCommitId);

    RevTree tree = commit.getTree();/*from  ww  w. jav a2s .com*/

    TreeWalk treeWalk = new TreeWalk(repo);
    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);
    treeWalk.setFilter(PathFilter.ALL);
    if (!treeWalk.next()) {
        System.out.println("Nothing found!");
        return;
    }

    ObjectId objectId = treeWalk.getObjectId(0);
    System.err.println(treeWalk.getPathString());
    System.err.println(objectId.getName());

    ObjectLoader loader = repo.open(objectId);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    loader.copyTo(out);
    System.out.println("file1.txt:\n" + out.toString());
}

From source file:org.eclipse.emf.compare.git.pgm.internal.app.LogicalDiffApplication.java

License:Open Source License

/**
 * {@inheritDoc}./*from  w  w w . j  av a2  s .  c om*/
 */
@Override
protected Integer performGitCommand() {
    try {
        IWorkspace ws = ResourcesPlugin.getWorkspace();

        // Call JGit diff to get the files involved
        OutputStream out = new ByteArrayOutputStream();
        DiffCommand diffCommand = Git.open(repo.getDirectory()).diff().setOutputStream(out);
        if (commit != null) {
            diffCommand = diffCommand.setOldTree(getTreeIterator(repo, commit));
        }
        if (commitWith != null) {
            diffCommand = diffCommand.setNewTree(getTreeIterator(repo, commitWith));
        }
        if (pathFilter != null) {
            diffCommand = diffCommand.setPathFilter(pathFilter);
        }
        Set<IFile> files = new HashSet<IFile>();
        List<DiffEntry> entries = diffCommand.call();

        for (DiffEntry diffEntry : entries) {
            String path = diffEntry.getOldPath();
            if (path != null) {
                IFile file = ws.getRoot().getFile(new Path(path));
                if (file != null) {
                    files.add(file);
                }
            }
        }

        if (files.isEmpty()) {
            System.out.println("No difference to display.");
            return Returns.COMPLETE.code();
        }

        for (IFile file : files) {
            RemoteResourceMappingContext mergeContext = createSubscriberForComparison(repo, commit, commitWith,
                    file);
            if (!isEMFCompareCompliantFile(mergeContext, file)) {
                diffCommand.setPathFilter(PathFilter.create(file.getProjectRelativePath().toString()));
                diffCommand.call();
                System.out.println(out.toString());
            } else {
                final ResourceMapping[] emfMappings = getResourceMappings(mergeContext, file);
                for (ResourceMapping mapping : emfMappings) {
                    if (mapping instanceof EMFResourceMapping) {
                        /*
                         * These two won't be used by the builder in our case since we retrieve the
                         * already created syncModel from the resource mapping.
                         */
                        final IModelMinimizer minimizer = new IdenticalResourceMinimizer();
                        final NullProgressMonitor nullProgressMonitor = new NullProgressMonitor();

                        mapping.getTraversals(mergeContext, nullProgressMonitor);
                        final SynchronizationModel syncModel = ((EMFResourceMapping) mapping).getLatestModel();
                        minimizer.minimize(syncModel, nullProgressMonitor);
                        final IComparisonScope scope = ComparisonScopeBuilder.create(syncModel,
                                nullProgressMonitor);

                        final Comparison comparison = EMFCompare.builder().build().compare(scope,
                                BasicMonitor.toMonitor(nullProgressMonitor));

                        Resource resource = new XMIResourceImpl();
                        Copier copier = new Copier(false);
                        EObject comparisonCopy = copier.copy(comparison);
                        copier.copyReferences();
                        resource.getContents().add(comparisonCopy);

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        resource.save(baos, null);
                        System.out.println(baos.toString("UTF-8"));//$NON-NLS-1$
                    }
                }
            }
        }
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    }

    return Returns.COMPLETE.code();
}

From source file:org.eclipse.oomph.setup.git.impl.GitCloneTaskImpl.java

License:Open Source License

public boolean isNeeded(final SetupTaskContext context) throws Exception {
    if (StringUtil.isEmpty(getRemoteURI())) {
        return false;
    }// w  w w  . j  a va  2s  .c  o m

    // If the EGit UI is available, this will contain the list of repositories that have been added to the repositories view.
    Set<String> repositories = null;

    // Force start egit to make the clone appears in the repositories view and so projects are connected by the egit team provider.
    try {
        Class<?> egitUIActivatorClass = CommonPlugin.loadClass("org.eclipse.egit.ui",
                "org.eclipse.egit.ui.Activator");
        Object egitUIActivator = ReflectUtil.invokeMethod("getDefault", egitUIActivatorClass);
        repositoryUtil = ReflectUtil.invokeMethod("getRepositoryUtil", egitUIActivator);

        @SuppressWarnings("unchecked")
        List<String> configuredRepositories = (List<String>) ReflectUtil
                .invokeMethod("getConfiguredRepositories", repositoryUtil);
        repositories = new HashSet<String>(configuredRepositories);
    } catch (Throwable ex) {
        // Ignore.
    }

    String location = getLocation();

    workDir = new File(location);
    if (!workDir.isDirectory()) {
        return true;
    }

    workDirExisted = true;

    boolean needsToBeAdded = repositories != null
            && !repositories.contains(new File(workDir, ".git").toString());
    if (workDir.list().length > 1) {
        // Even though cloning isn't needed, return true if the repository needs to be added to the repositories view.
        bypassCloning = true;
        return needsToBeAdded;
    }

    context.log("Opening Git clone " + workDir);

    try {
        Git git = Git.open(workDir);
        if (!hasWorkTree(git) || !hasReflog(git)) {
            FileUtil.rename(workDir);
            workDirExisted = false;
            return true;
        }

        Repository repository = git.getRepository();
        String checkoutBranch = getCheckoutBranch();
        String remoteName = getRemoteName();
        String remoteURI = getRemoteURI();
        String pushURI = getPushURI();
        configureRepository(context, repository, checkoutBranch, remoteName, remoteURI, pushURI,
                getConfigSections());

        hasCheckout = repository.getAllRefs().containsKey("refs/heads/" + checkoutBranch);
        if (!hasCheckout) {
            cachedGit = git;
            cachedRepository = repository;
            return true;
        }

        // Even though cloning isn't needed, return true if the repository needs to be added to the repositories view.
        bypassCloning = true;
        return needsToBeAdded;
    } catch (Throwable ex) {
        if (!workDirExisted) {
            FileUtil.delete(workDir, new NullProgressMonitor() {
                @Override
                public boolean isCanceled() {
                    return context.isCanceled();
                }
            });
        }

        throw new Exception(ex);
    }
}

From source file:org.eclipse.recommenders.snipmatch.GitSnippetRepository.java

License:Open Source License

private void configureGit() throws IOException {
    Git git = Git.open(gitFile);
    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", getRepositoryLocation());
    config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    config.setString("remote", "origin", "pushUrl", pushUrl);
    // prevents trust anchor errors when pulling from eclipse.org
    config.setBoolean("http", null, "sslVerify", false);
    config.save();/*  w ww .  j  a  v  a2 s.  c o m*/
}

From source file:org.eclipse.recommenders.snipmatch.GitSnippetRepository.java

License:Open Source License

private void configureGitBranch(String remoteBranch) throws IOException {
    Git git = Git.open(gitFile);
    StoredConfig config = git.getRepository().getConfig();
    String pushBranch = "HEAD:" + pushBranchPrefix + "/" + remoteBranch;
    config.setString("remote", "origin", "push", pushBranch);

    config.setString("branch", remoteBranch, "remote", "origin");
    String branch = "refs/heads/" + remoteBranch;
    config.setString("branch", remoteBranch, "merge", branch);
    config.save();//from ww w.ja v  a2s .c  o m
}

From source file:org.fusesource.fabric.git.internal.FabricGitServiceImpl.java

License:Apache License

private Git openOrInit(File repo) throws IOException {
    try {//from   w  w w.  j  a v  a2s . com
        return Git.open(repo);
    } catch (RepositoryNotFoundException e) {
        try {
            Git git = Git.init().setDirectory(repo).call();
            git.commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
            return git;
        } catch (GitAPIException ex) {
            throw new IOException(ex);
        }
    }
}