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

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

Introduction

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

Prototype

public CommitCommand commit() 

Source Link

Document

Return a command object to execute a Commit command

Usage

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

License:Apache License

public void updateDeployment(Git git, File baseDir, CredentialsProvider credentials) throws Exception {
    Set<String> bundles = new LinkedHashSet<String>();
    Set<Feature> features = new LinkedHashSet<Feature>();
    Profile overlayProfile = container.getOverlayProfile();
    Profile effectiveProfile = Profiles.getEffectiveProfile(fabricService, overlayProfile);
    bundles.addAll(effectiveProfile.getBundles());
    AgentUtils.addFeatures(features, fabricService, downloadManager, effectiveProfile);

    if (copyFilesIntoGit) {
        copyDeploymentsIntoGit(git, baseDir, bundles, features);
    } else {/*from w w w. j  av a2 s  . co  m*/
        addDeploymentsIntoPom(git, baseDir, effectiveProfile, bundles, features);
    }

    // now lets do a commit
    String message = "updating deployment";
    git.commit().setMessage(message).call();

    enableDeployDirectory(git, baseDir);

    String branch = GitHelpers.currentBranch(git);
    LOG.info("Pushing deployment changes to branch " + branch + " credentials " + credentials
            + " for container " + container.getId());
    try {
        Iterable<PushResult> results = git.push().setCredentialsProvider(credentials)
                .setRefSpecs(new RefSpec(branch)).setOutputStream(new LoggingOutputStream(LOG)).call();
        /*
                    for (PushResult result : results) {
        LOG.info(result.getMessages());
                    }
        */
        LOG.info("Pushed deployment changes to branch " + branch + " for container " + container.getId());
    } catch (GitAPIException e) {
        LOG.error("Failed to push deployment changes to branch " + branch + " for container "
                + container.getId() + ". Reason: " + e, e);
    }
}

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

License:Apache License

/**
 * Checks things like Tomcat to see if the deployDir needs to be added to the shared class loader
 *///  w w w  .j  av  a 2 s.  c  o  m
protected void enableDeployDirectory(Git git, File baseDir) throws GitAPIException {
    File catalinaProperties = new File(baseDir, OPENSHIFT_CONFIG_CATALINA_PROPERTIES);
    if (catalinaProperties.exists()) {
        // TODO make this configurable?
        String propertyName = "shared.loader";
        Properties properties = new Properties();
        String value = properties.getProperty(propertyName);
        if (Strings.isNotBlank(value)
                && (value.startsWith(deployDir + "/") || value.contains(":" + deployDir + "/"))) {
            LOG.info("Already has valid " + propertyName + " in " + catalinaProperties + " with value: "
                    + value);
        } else {
            String newValue = deployDir + "/*.jar";
            if (Strings.isNotBlank(value)) {
                newValue = newValue + ":" + value;
            }

            // now lets replace the line which starts with propertyName;
            LOG.info("Updating " + propertyName + " to " + newValue + " in " + catalinaProperties
                    + " to enable the use of the shared deploy directory: " + deployDir);
            try {
                int propertyNameLength = propertyName.length();
                List<String> lines = Files.readLines(catalinaProperties);
                for (int i = 0, size = lines.size(); i < size; i++) {
                    String line = lines.get(i);
                    if (line.startsWith(propertyName) && line.length() > propertyNameLength) {
                        char ch = line.charAt(propertyNameLength);
                        if (Character.isWhitespace(ch) || ch == '=') {
                            String newLine = propertyName + "=" + newValue;
                            lines.set(i, newLine);
                        }
                    }
                }
                Files.writeLines(catalinaProperties, lines);

                git.add().addFilepattern(OPENSHIFT_CONFIG_CATALINA_PROPERTIES).call();
                String message = "enabled the deploy directory '" + deployDir
                        + "' to be on the shared class loader";
                git.commit().setMessage(message).call();
                LOG.info("Committed changes to: " + catalinaProperties);

            } catch (IOException e) {
                LOG.warn("Failed to update " + catalinaProperties + " for container " + container.getId() + ". "
                        + e, 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   ww w. j ava  2  s .  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.fabric8.profiles.PluginTestHelpers.java

License:Apache License

public static Git initRepo(Path sourceDirectory) throws GitAPIException {
    Git sourceRepo = Git.init().setDirectory(sourceDirectory.toFile()).call();
    sourceRepo.add().addFilepattern(".").call();
    sourceRepo.commit().setMessage("Adding version 1.0").call();
    try {//from  w  w w  .j a v  a  2s . c om
        sourceRepo.branchRename().setNewName("1.0").call();
    } catch (RefAlreadyExistsException ignore) {
        // ignore
    }

    return sourceRepo;
}

From source file:io.fabric8.vertx.maven.plugin.it.ExtraManifestInfoIT.java

License:Apache License

@Test
public void testGITSCM() throws IOException, VerificationException, GitAPIException {
    File testDir = initProject(GIT_PROJECT_ROOT);
    assertThat(testDir).isDirectory();/*  www . j  a v  a2  s.  c o m*/

    initVerifier(testDir);

    prepareProject(testDir, verifier);

    File gitFolder = GitUtil.findGitFolder(testDir);

    assertThat(testDir).isNotNull();
    assertThat(testDir.getName()).endsWith("manifest-git-it");
    assertThat(gitFolder).isNull();

    Git git = prepareGitSCM(testDir, verifier);
    gitFolder = git.getRepository().getDirectory();
    assertThat(gitFolder.getParentFile().getName()).isEqualTo(testDir.getName());
    assertThat(git.status().call().getUntracked()).contains("pom.xml",
            "src/main/java/demo/SimpleVerticle.java");

    //Now add and commit the file
    DirCache index = git.add().addFilepattern(".").call();
    assertThat(index.getEntryCount()).isEqualTo(2);

    git.commit().setMessage("First Import").call();

    runPackage(verifier);
    assertManifest(testDir, "git");

}

From source file:io.hawt.git.GitFacadeSupport.java

License:Apache License

protected CommitInfo doCreateDirectory(Git git, File rootDir, String branch, String path,
        PersonIdent personIdent, String commitMessage) throws Exception {
    File file = getFile(rootDir, path);
    if (file.exists()) {
        return null;
    }//from   w  w  w  .j  ava2 s .  c o m
    file.mkdirs();
    String filePattern = getFilePattern(path);
    AddCommand add = git.add().addFilepattern(filePattern).addFilepattern(".");
    add.call();

    CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(commitMessage);
    RevCommit revCommit = commitThenPush(git, branch, commit);
    return createCommitInfo(revCommit);
}

From source file:io.hawt.git.GitFacadeSupport.java

License:Apache License

protected RevCommit doRename(Git git, File rootDir, String branch, String oldPath, String newPath,
        String commitMessage, PersonIdent personIdent) throws Exception {
    File file = getFile(rootDir, oldPath);
    File newFile = getFile(rootDir, newPath);
    if (file.exists()) {
        File parentFile = newFile.getParentFile();
        parentFile.mkdirs();/* ww w  .  j  a va2  s.c om*/
        if (!parentFile.exists()) {
            throw new IOException("Could not create directory " + parentFile + " when trying to move " + file
                    + " to " + newFile + ". Maybe a file permission issue?");
        }
        file.renameTo(newFile);
        String filePattern = getFilePattern(newPath);
        git.add().addFilepattern(filePattern).call();
        CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(commitMessage);
        return commitThenPush(git, branch, commit);
    } else {
        return null;
    }
}

From source file:io.hawt.git.GitFacadeSupport.java

License:Apache License

protected RevCommit doRemove(Git git, File rootDir, String branch, String path, String commitMessage,
        PersonIdent personIdent) throws Exception {
    File file = getFile(rootDir, path);
    if (file.exists()) {
        Files.recursiveDelete(file);

        String filePattern = getFilePattern(path);
        git.rm().addFilepattern(filePattern).call();
        CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(commitMessage);
        return commitThenPush(git, branch, commit);
    } else {/*from  w  ww  . j a v a  2  s  .co  m*/
        return null;
    }
}

From source file:io.hawt.git.GitFacadeSupport.java

License:Apache License

/**
 * Performs a write operation on the file
 *//*from ww  w. j ava2  s  .  c  o  m*/
protected <T> T doWriteFile(Git git, File rootDir, String branch, String pathOrEmpty, WriteCallback callback)
        throws Exception {
    checkoutBranch(git, branch);
    String path = Strings.isBlank(pathOrEmpty) ? "/" : pathOrEmpty;
    File file = getFile(rootDir, path);
    WriteContext context = new WriteContext(git, rootDir, file);
    T results = (T) callback.apply(context);
    if (context.isRequiresCommit()) {
        PersonIdent author = context.getAuthor();
        String message = context.getMessage();
        if (Strings.isBlank(message)) {
            message = "Updated " + Files.getRelativePath(rootDir, file);
        }
        CommitCommand command = git.commit().setAll(true).setMessage(message);
        if (author != null) {
            command = command.setAuthor(author);
        }
        RevCommit revCommit = commitThenPush(git, branch, command);
        createCommitInfo(revCommit);
    }
    return results;
}

From source file:io.hawt.git.GitFacadeSupport.java

License:Apache License

protected CommitInfo doWrite(Git git, File rootDir, String branch, String path, byte[] contents,
        PersonIdent personIdent, String commitMessage) throws Exception {
    File file = getFile(rootDir, path);
    file.getParentFile().mkdirs();//ww w .  j  a  va  2s. c  o m

    IOHelper.write(file, contents);

    String filePattern = getFilePattern(path);
    AddCommand add = git.add().addFilepattern(filePattern).addFilepattern(".");
    add.call();

    CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(commitMessage);
    RevCommit revCommit = commitThenPush(git, branch, commit);
    return createCommitInfo(revCommit);
}