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:fr.duminy.tools.jgit.JGitToolbox.java

License:Open Source License

public String track(Parameters parameters) throws GitToolboxException {
    try {/*from  w ww. j av a 2  s .c om*/
        Git targetGit = Git.open(parameters.getGitDirectory());
        ProgressMonitor progressMonitor = new TextProgressMonitor();
        PullCommand pullCommand = targetGit.pull().setProgressMonitor(progressMonitor);
        PullResult result = pullCommand.call();
        System.out.println(result);
        if (!result.isSuccessful()) {
            throw new GitToolboxException("Failed to update tracking branch : " + result.toString());
        }

        MergeResult.MergeStatus mergeStatus = result.getMergeResult().getMergeStatus();
        if (!ALREADY_UP_TO_DATE.equals(mergeStatus) && !FAST_FORWARD.equals(mergeStatus)) {
            throw new GitToolboxException("Failed to update tracking branch : " + result.toString());
        }

        return targetGit.getRepository().getRef(Constants.HEAD).getName();
    } catch (Exception e) {
        throw new GitToolboxException("Error while updating tracking branch", e);
    }
}

From source file:getgitdata.JGitDiff.java

public static void main(String[] args) throws Exception {
    File gitWorkDir = new File("C:/Users/Masud/Documents/GitHub/tomcat");
    Git git = Git.open(gitWorkDir);

    String newHash = "278a36a";
    String oldHash = "1b46e37b92705159ddc22fd8a28ee1d2b7499072";

    //ObjectId headId = git.getRepository().resolve("HEAD^{tree}");
    // ObjectId headId = git.getRepository().resolve(newHash + "^{tree}");
    ObjectId headId = git.getRepository().resolve(newHash + "^{tree}");
    ObjectId oldId = git.getRepository().resolve(newHash + "^^{tree}");
    ObjectReader reader = git.getRepository().newObjectReader();

    CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
    oldTreeIter.reset(reader, oldId);/*from w ww  . java 2s . c  o m*/
    CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
    newTreeIter.reset(reader, headId);

    List<DiffEntry> diffs = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DiffFormatter df = new DiffFormatter(out);
    df.setRepository(git.getRepository());
    int count = 0;
    for (DiffEntry diff : diffs) {
        count++;
        System.out.println("DIff: " + diff.toString());
        df.format(diff);

        // diff.getOldId();
        String diffText = out.toString("UTF-8");
        System.out.println(diffText);
        out.reset();
    }
    System.out.println("Count: " + count);
}

From source file:GitBackend.GitAPI.java

License:Apache License

public Git openRepository(File path) {
    this.git = null;
    if (this.isDirectory(path)) {
        try {/*from  w  w  w.  j  a  v a  2  s .c o m*/
            this.git = Git.open(path);
            Logger.info("Open reposirory " + path.getAbsolutePath());
            this.repository = this.git.getRepository();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return git;

}

From source file:griffon.plugins.git.GitManager.java

License:Apache License

public Git git() throws IOException {
    if (null == git) {
        git = Git.open(new File(buildSettings.getBaseDir(), ".git"));
    }//from   ww w .j a v  a 2 s .  com
    return git;
}

From source file:io.fabric8.git.http.GitHttpServerRegistrationHandler.java

License:Apache License

private void registerServlet(Path dataPath, String realm, String role) throws Exception {
    synchronized (gitRemoteUrl) {
        basePath = dataPath.resolve(Paths.get("git", "servlet"));
        Path fabricRepoPath = basePath.resolve("fabric");
        String servletBase = basePath.toFile().getAbsolutePath();

        // Init and clone the local repo.
        File fabricRoot = fabricRepoPath.toFile();
        if (!fabricRoot.exists()) {
            File localRepo = gitDataStore.get().getGit().getRepository().getDirectory();
            git = Git.cloneRepository().setTimeout(10).setBare(true).setNoCheckout(true)
                    .setCloneAllBranches(true).setDirectory(fabricRoot).setURI(localRepo.toURI().toString())
                    .call();/*from w  ww .  j  ava  2s .co  m*/
        } else {
            git = Git.open(fabricRoot);
        }

        HttpContext base = httpService.get().createDefaultHttpContext();
        HttpContext secure = new GitSecureHttpContext(base, curator.get(), realm, role);

        Dictionary<String, Object> initParams = new Hashtable<String, Object>();
        initParams.put("base-path", servletBase);
        initParams.put("repository-root", servletBase);
        initParams.put("export-all", "true");
        httpService.get().registerServlet("/git", new FabricGitServlet(git, curator.get()), initParams, secure);
    }
}

From source file:io.fabric8.git.internal.FabricGitServiceImpl.java

License:Apache License

private Git openOrInit(File localRepo) throws IOException {
    try {/*from  w  ww  . j a  v a 2s .  com*/
        return Git.open(localRepo);
    } catch (RepositoryNotFoundException e) {
        try {
            return Git.init().setDirectory(localRepo).call();
        } catch (GitAPIException ex) {
            throw new IOException(ex);
        }
    }
}

From source file:io.fabric8.itests.basic.git.ExternalGitTest.java

License:Apache License

@Test
public void testCreateProfilesMixedWithVersion() throws Exception {
    String testZkProfilebase = "zkprofile";
    String testGitProfilebase = "gitprofile";
    System.out.println(executeCommand("fabric:create -n"));
    ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(bundleContext,
            FabricService.class);
    try {/*from  ww  w. j a v  a2  s .co m*/
        FabricService fabricService = fabricProxy.getService();
        CuratorFramework curator = fabricService.adapt(CuratorFramework.class);

        String gitRepoUrl = GitUtils.getMasterUrl(bundleContext, curator);
        assertNotNull(gitRepoUrl);
        GitUtils.waitForBranchUpdate(curator, "1.0");

        Git.cloneRepository().setURI(gitRepoUrl).setCloneAllBranches(true).setDirectory(testrepo)
                .setCredentialsProvider(getCredentialsProvider()).call();
        Git git = Git.open(testrepo);
        GitUtils.configureBranch(git, "origin", gitRepoUrl, "1.0");
        git.fetch().setCredentialsProvider(getCredentialsProvider());
        GitUtils.checkoutBranch(git, "origin", "1.0");

        //Check that the default profile exists
        assertTrue(new File(testrepo, "fabric/profiles/default.profile").exists());

        for (int v = 0; v < 2; v++) {
            //Create test profile
            for (int i = 1; i < 2; i++) {
                String gitProfile = testGitProfilebase + v + "p" + i;
                String zkProfile = testZkProfilebase + v + "p" + i;
                createAndTestProfileInGit(fabricService, curator, git, "1." + v, gitProfile);
                createAndTestProfileInDataStore(fabricService, curator, git, "1." + v, zkProfile);
            }
        }
    } finally {
        fabricProxy.close();
    }
}

From source file:io.fabric8.maven.profiles.ContainersInstallerMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    // initialize inherited fields
    super.execute();

    // get current repository branch version to compare against remotes
    try (final Git sourceRepo = Git.open(sourceDirectory)) {

        String currentVersion = sourceRepo.getRepository().getBranch();

        for (RevCommit revCommit : sourceRepo.log().setMaxCount(1).call()) {
            currentCommitId = revCommit.getId();
        }/*w ww . java 2s  .  co  m*/

        // add current version and commit id to config
        profilesProperties.setProperty(CURRENT_VERSION_PROPERTY, currentVersion);
        profilesProperties.setProperty(CURRENT_COMMIT_ID_PROPERTY, currentCommitId.name());

        // build processor list
        if (projectProcessors != null && !projectProcessors.isEmpty()) {

            processors = new ProjectProcessor[projectProcessors.size()];
            int i = 0;
            for (Processor processor : projectProcessors) {

                final String className = processor.getName();
                try {
                    ClassLoader classLoader = getProjectClassLoader();
                    final Class<?> aClass = classLoader.loadClass(className);
                    final Class<? extends ProjectProcessor> reifierClass = aClass
                            .asSubclass(ProjectProcessor.class);
                    final Constructor<? extends ProjectProcessor> constructor = reifierClass
                            .getConstructor(Properties.class);

                    Properties properties = new Properties(profilesProperties);
                    properties.putAll(processor.getProperties());
                    processors[i++] = constructor.newInstance(properties);
                } catch (ClassCastException e) {
                    throwMojoException("Class is not of type ProjectProcessor", className, e);
                } catch (ReflectiveOperationException e) {
                    throwMojoException("Error loading ProjectProcessor", className, e);
                }
            }
        } else {
            processors = new ProjectProcessor[] { new GitRemoteProcessor(profilesProperties) };
        }

        // list all containers, and update under targetDirectory
        final Path target = Paths.get(targetDirectory.getAbsolutePath());
        final List<Path> names = Files.list(configs.resolve("containers"))
                .filter(p -> p.getFileName().toString().endsWith(".cfg")).collect(Collectors.toList());

        // TODO handle container deletes

        // generate all current containers
        for (Path name : names) {
            manageContainer(target, name);
        }

    } catch (IOException e) {
        throwMojoException("Error reading Profiles Git repo", sourceDirectory, e);
    } catch (NoHeadException e) {
        throwMojoException("Error reading Profiles Git repo", sourceDirectory, e);
    } catch (GitAPIException e) {
        throwMojoException("Error reading Profiles Git repo", sourceDirectory, e);
    }
}

From source file:io.fabric8.profiles.containers.GitRemoteProcessor.java

License:Apache License

@Override
public void process(String name, Properties config, Path containerDir) throws IOException {
    // get or create remote repo URL
    String remoteUri = config.getProperty(GIT_REMOTE_URI_PROPERTY);
    if (remoteUri == null || remoteUri.isEmpty()) {
        remoteUri = getRemoteUri(config, name);
    }/*from   w  ww  .j av a2 s . c  o  m*/

    // try to clone remote repo in temp dir
    String remote = config.getProperty(GIT_REMOTE_NAME_PROPERTY, Constants.DEFAULT_REMOTE_NAME);
    Path tempDirectory = null;
    try {
        tempDirectory = Files.createTempDirectory(containerDir, "cloned-remote-");
    } catch (IOException e) {
        throwException("Error creating temp directory while cloning ", remoteUri, e);
    }

    final String userName = config.getProperty("gogsUsername");
    final String password = config.getProperty("gogsPassword");
    final UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(
            userName, password);

    Git clonedRepo = null;
    try {
        try {
            clonedRepo = Git.cloneRepository().setDirectory(tempDirectory.toFile()).setBranch(currentVersion)
                    .setRemote(remote).setURI(remoteUri).setCredentialsProvider(credentialsProvider).call();
        } catch (InvalidRemoteException e) {
            // TODO handle creating new remote repo in github, gogs, etc. using fabric8 devops connector
            if (e.getCause() instanceof NoRemoteRepositoryException) {
                final String address = "http://" + config.getProperty("gogsServiceHost", "gogs.vagrant.f8");

                GitRepoClient client = new GitRepoClient(address, userName, password);

                CreateRepositoryDTO request = new CreateRepositoryDTO();
                request.setName(name);
                request.setDescription("Fabric8 Profiles generated project for container " + name);
                RepositoryDTO repository = client.createRepository(request);

                // create new repo with Gogs clone URL
                clonedRepo = Git.init().setDirectory(tempDirectory.toFile()).call();
                final RemoteAddCommand remoteAddCommand = clonedRepo.remoteAdd();
                remoteAddCommand.setName(remote);
                try {
                    remoteAddCommand.setUri(new URIish(repository.getCloneUrl()));
                } catch (URISyntaxException e1) {
                    throwException("Error creating remote repo ", repository.getCloneUrl(), e1);
                }
                remoteAddCommand.call();

                // add currentVersion branch
                clonedRepo.add().addFilepattern(".").call();
                clonedRepo.commit().setMessage("Adding version " + currentVersion).call();
                try {
                    clonedRepo.branchRename().setNewName(currentVersion).call();
                } catch (RefAlreadyExistsException ignore) {
                    // ignore
                }

            } else {
                throwException("Error cloning ", remoteUri, e);
            }
        }

        // handle missing remote branch
        if (!clonedRepo.getRepository().getBranch().equals(currentVersion)) {
            clonedRepo.branchCreate().setName(currentVersion)
                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call();
        }

        // move .git dir to parent and drop old source altogether
        // TODO things like .gitignore, etc. need to be handled, perhaps through Profiles??
        Files.move(tempDirectory.resolve(".git"), containerDir.resolve(".git"));

    } catch (GitAPIException e) {
        throwException("Error cloning ", remoteUri, e);
    } catch (IOException e) {
        throwException("Error copying files from ", remoteUri, e);
    } finally {
        // close clonedRepo
        if (clonedRepo != null) {
            try {
                clonedRepo.close();
            } catch (Exception ignored) {
            }
        }
        // cleanup tempDirectory
        try {
            ProfilesHelpers.deleteDirectory(tempDirectory);
        } catch (IOException e) {
            // ignore
        }
    }

    try (Git containerRepo = Git.open(containerDir.toFile())) {

        // diff with remote
        List<DiffEntry> diffEntries = containerRepo.diff().call();
        if (!diffEntries.isEmpty()) {

            // add all changes
            containerRepo.add().addFilepattern(".").call();

            // with latest Profile repo commit ID in message
            // TODO provide other identity properties
            containerRepo.commit().setMessage("Container updated for commit " + currentCommitId).call();

            // push to remote
            containerRepo.push().setRemote(remote).setCredentialsProvider(credentialsProvider).call();
        } else {
            LOG.debug("No changes to container" + name);
        }

    } catch (GitAPIException e) {
        throwException("Error processing container Git repo ", containerDir, e);
    } catch (IOException e) {
        throwException("Error reading container Git repo ", containerDir, e);
    }
}

From source file:io.fabric8.tooling.archetype.builder.ArchetypeBuilder.java

License:Apache License

protected void generateArchetypeFromGitRepo(File outputDir, List<String> dirs, File cloneParentDir,
        String repoName, String repoURL, String tag) throws IOException {
    String archetypeFolderName = repoName + "-archetype";
    File projectDir = new File(outputDir, archetypeFolderName);
    File destDir = new File(projectDir, ARCHETYPE_RESOURCES_PATH);
    //File cloneDir = new File(projectDir, ARCHETYPE_RESOURCES_PATH);
    File cloneDir = new File(cloneParentDir, archetypeFolderName);
    cloneDir.mkdirs();/*from w w  w .  j  a va2 s .c om*/

    System.out.println("Cloning repo " + repoURL + " to " + cloneDir);
    cloneDir.getParentFile().mkdirs();
    if (cloneDir.exists()) {
        Files.recursiveDelete(cloneDir);
    }

    CloneCommand command = Git.cloneRepository().setCloneAllBranches(false).setURI(repoURL)
            .setDirectory(cloneDir);

    try {
        command.call();
    } catch (Throwable e) {
        LOG.error("Failed to command remote repo " + repoURL + " due: " + e.getMessage(), e);
        throw new IOException("Failed to command remote repo " + repoURL + " due: " + e.getMessage(), e);
    }

    // Try to checkout a specific tag.
    if (tag == null) {
        tag = System.getProperty("repo.tag", "").trim();
    }
    if (!tag.isEmpty()) {
        try {
            Git.open(cloneDir).checkout().setName(tag).call();
        } catch (Throwable e) {
            LOG.error("Failed checkout " + tag + " due: " + e.getMessage(), e);
            throw new IOException("Failed checkout " + tag + " due: " + e.getMessage(), e);
        }
    }

    File gitFolder = new File(cloneDir, ".git");
    Files.recursiveDelete(gitFolder);

    File pom = new File(cloneDir, "pom.xml");
    if (pom.exists()) {
        generateArchetype(cloneDir, pom, projectDir, false, dirs);
    } else {
        File from = cloneDir.getCanonicalFile();
        File to = destDir.getCanonicalFile();
        LOG.info("Copying git checkout from " + from + " to " + to);
        Files.copy(from, to);
    }

    String description = repoName.replace('-', ' ');

    dirs.add(repoName);
    File outputGitIgnoreFile = new File(projectDir, ".gitignore");
    if (!outputGitIgnoreFile.exists()) {
        ArchetypeUtils.writeGitIgnore(outputGitIgnoreFile);
    }
}