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

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

Introduction

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

Prototype

@Override
public void close() 

Source Link

Document

Free resources associated with this instance.

Usage

From source file:eu.atos.paas.git.Repository.java

License:Open Source License

public static Repository init(File path) throws GitAPIException, IOException {

    InitCommand cmd = Git.init();/*from  w  w  w  .j a  va2  s  .  c o m*/
    logger.debug("Start git init in {}", path.getPath());
    Git gitRepo = cmd.setDirectory(path).call();
    gitRepo.close();
    logger.debug("End git init in {}", path.getPath());
    return new Repository(path);
}

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);
    }/*  ww  w .j a v  a2s  .co  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.github.gitfx.util.GitFXGsonUtil.java

License:Apache License

public static void initializeGitRepository(String serverName, String projectName, String projectPath) {
    try {/*w ww.  j a  va 2s .  c  o  m*/
        File localPath = new File(projectPath);
        Git git;
        git = Git.init().setDirectory(localPath).call();
        git.close();
    } catch (GitAPIException e) {
        logger.debug("Error creating Git repository", e.getMessage());
    }
}

From source file:io.github.gitfx.util.GitFXGsonUtil.java

License:Apache License

public static boolean cloneGitRepository(String repoURL, String localPath) {
    try {//from   w  w w . j a  va  2 s. com
        Git result = Git.cloneRepository().setURI(repoURL).setDirectory(new File(localPath)).call();
        result.close();
        return true;
    } catch (GitAPIException e) {
        logger.debug("Error creating Git repository", e.getMessage());
        return false;
    }
}

From source file:io.hawkcd.agent.services.GitMaterialService.java

License:Apache License

@Override
public String fetchMaterial(FetchMaterialTask task) {
    String errorMessage = null;//from  w  w  w  . ja va 2s  .  c o  m
    String materialPath = Paths.get(AgentConfiguration.getInstallInfo().getAgentPipelinesDir(),
            task.getPipelineName(), task.getDestination()).toString();
    GitMaterial definition = (GitMaterial) task.getMaterialDefinition();
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(definition.getRepositoryUrl());
    clone.setBranch(definition.getBranch());
    clone.setDirectory(new File(materialPath));
    clone.setCloneSubmodules(true);
    UsernamePasswordCredentialsProvider credentials = this.handleCredentials(definition);
    clone.setCredentialsProvider(credentials);
    try {
        Git git = clone.call();
        git.close();
    } catch (GitAPIException e) {
        errorMessage = e.getMessage();
    }

    return errorMessage;
}

From source file:io.hawkcd.materials.materialservices.GitService.java

License:Apache License

@Override
public GitMaterial fetchLatestCommit(GitMaterial gitMaterial) {
    try {//  w ww  .  ja va2  s. c  om
        Git git = Git.open(new File(gitMaterial.getDestination() + File.separator + ".git"));
        CredentialsProvider credentials = this.handleCredentials(gitMaterial);
        git.fetch().setCredentialsProvider(credentials).setCheckFetchedObjects(true)
                .setRefSpecs(new RefSpec(
                        "refs/heads/" + gitMaterial.getBranch() + ":refs/heads/" + gitMaterial.getBranch()))
                .call();
        ObjectId objectId = git.getRepository().getRef(gitMaterial.getBranch()).getObjectId();
        RevWalk revWalk = new RevWalk(git.getRepository());
        RevCommit commit = revWalk.parseCommit(objectId);

        gitMaterial.setCommitId(commit.getId().getName());
        gitMaterial.setAuthorName(commit.getAuthorIdent().getName());
        gitMaterial.setAuthorEmail(commit.getAuthorIdent().getEmailAddress());
        gitMaterial.setComments(commit.getFullMessage());
        gitMaterial.setErrorMessage("");
        git.close();

        return gitMaterial;
    } catch (IOException | GitAPIException e) {
        gitMaterial.setErrorMessage(e.getMessage());
        return gitMaterial;
    }
}

From source file:io.verticle.apex.commons.oss.repository.GitRepositoryService.java

License:Apache License

private void cloneRepository() throws GitAPIException, IOException {
    logger.info("cloning repository from " + remoteRepositoryUri);
    if (!remoteRepositoryUri.startsWith("file:")) {
        this.deleteLocalRepoDirIfExists();

        Git git = this.cloneToLocalDir();
        if (git != null) {
            git.close();
        }/*from   www  . jav a 2s.  c o  m*/

        git = this.openGitRepository();
        if (git != null) {
            git.close();
        }
    }

}

From source file:nz.co.fortytwo.signalk.handler.GitHandler.java

License:Open Source License

protected String install(String path) throws Exception {
    //staticDir.mkdirs();
    Git result = null;
    try {/*from www .  j a va  2s  . c o m*/
        File installLogDir = new File(staticDir, "logs");
        installLogDir.mkdirs();
        //make log name
        String logFile = "output.log";
        File output = new File(installLogDir, logFile);
        File destDir = new File(staticDir, SLASH + path);
        destDir.mkdirs();
        String gitPath = github + path + ".git";
        logger.debug("Cloning from " + gitPath + " to " + destDir.getAbsolutePath());
        FileUtils.writeStringToFile(output,
                "Updating from " + gitPath + " to " + destDir.getAbsolutePath() + "\n", false);
        try {
            result = Git.cloneRepository().setURI(gitPath).setDirectory(destDir).call();
            result.fetch().setRemote(gitPath);
            logger.debug("Cloned " + gitPath + " repository: " + result.getRepository().getDirectory());
            FileUtils.writeStringToFile(output,
                    "DONE: Cloned " + gitPath + " repository: " + result.getRepository().getDirectory(), true);
        } catch (Exception e) {
            FileUtils.writeStringToFile(output, e.getMessage(), true);
            FileUtils.writeStringToFile(output, e.getStackTrace().toString(), true);
            logger.debug("Error updating " + gitPath + " repository: " + e.getMessage(), e);
        }
        /*try{
           //now run npm install
           runNpmInstall(output, destDir);
        }catch(Exception e){
           FileUtils.writeStringToFile(output, e.getMessage(),true);
           FileUtils.writeStringToFile(output, e.getStackTrace().toString(),true);
           logger.debug("Error updating "+gitPath+" repository: " + e.getMessage(),e);
        }*/
        return logFile;

    } finally {
        if (result != null)
            result.close();
    }

}

From source file:nz.co.fortytwo.signalk.handler.GitHandler.java

License:Open Source License

protected String upgrade(String path) throws Exception {
    //staticDir.mkdirs();
    Repository repository = null;//from ww w .ja  va2 s . c o m
    try {
        String logFile = "output.log";
        File installLogDir = new File(staticDir, "logs");
        installLogDir.mkdirs();
        //
        File destDir = new File(staticDir, SLASH + path);
        destDir.mkdirs();
        File output = new File(installLogDir, logFile);
        String gitPath = github + path + ".git";
        logger.debug("Updating from " + gitPath + " to " + destDir.getAbsolutePath());
        FileUtils.writeStringToFile(output,
                "Updating from " + gitPath + " to " + destDir.getAbsolutePath() + "\n", false);
        Git git = null;
        try {
            FileRepositoryBuilder builder = new FileRepositoryBuilder();
            repository = builder.setGitDir(new File(destDir, "/.git")).readEnvironment() // scan environment GIT_* variables
                    .findGitDir() // scan up the file system tree
                    .build();
            git = new Git(repository);
            PullResult result = git.pull().call();
            FileUtils.writeStringToFile(output, result.getMergeResult().toString(), true);
            logger.debug("DONE: Updated " + gitPath + " repository: " + result.getMergeResult().toString());

            //now run npm install
            //runNpmInstall(output, destDir);
        } catch (Exception e) {
            FileUtils.writeStringToFile(output, e.getMessage(), true);
            FileUtils.writeStringToFile(output, e.getStackTrace().toString(), true);
            logger.debug("Error updating " + gitPath + " repository: " + e.getMessage(), e);
        } finally {
            if (git != null)
                git.close();
            if (repository != null)
                repository.close();
        }
        return logFile;

    } finally {
        if (repository != null)
            repository.close();
    }

}

From source file:org.aysada.licensescollector.dependencies.impl.GitCodeBaseProvider.java

License:Open Source License

public File getLocalRepositoryRoot(String remoteUrl) {
    try {//w w  w . ja va2  s  . c o m
        File prjWs = getLocalWSFor(remoteUrl);
        if (prjWs.exists()) {
            Repository repo = Git.open(prjWs).getRepository();
            Git git = new Git(repo);
            git.fetch().call();
            git.close();
            LOGGER.info("Lcoal git repo for {} updated.", remoteUrl);
            return repo.getDirectory();
        } else {
            prjWs.mkdir();
            Git localRepo = Git.cloneRepository().setDirectory(prjWs).setURI(remoteUrl)
                    .setCloneAllBranches(false).call();
            File directory = localRepo.getRepository().getDirectory();
            localRepo.close();
            LOGGER.info("Cloned lcoal git repo for {}.", remoteUrl);
            return directory;
        }
    } catch (IOException | GitAPIException e) {
        LOGGER.error("Error working with git.", e);
    }
    return null;
}