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

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

Introduction

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

Prototype

public AddCommand add() 

Source Link

Document

Return a command object to execute a Add command

Usage

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
 *//*from   ww  w .j a  va 2 s.  c  om*/
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);
    }/*w  w  w  .j  ava 2s .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.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 .ja  v a2 s  .  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();//from  www .  j  av a  2 s. co  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 .ja va2  s  .c  om*/
    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();/*from   w w  w.jav  a  2 s. c o  m*/
        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 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();//from w  w  w. j  a v  a2 s .  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);
}

From source file:io.jenkins.blueocean.blueocean_git_pipeline.GitCacheCloneReadSaveRequest.java

License:Open Source License

@Override
void save() throws IOException {
    invokeOnScm(new GitSCMFileSystem.FSFunction<Void>() {
        @Override// w  w w  .ja  v  a  2 s.c  om
        public Void invoke(Repository repository) throws IOException, InterruptedException {
            Git activeRepo = getActiveRepository(repository);
            Repository repo = activeRepo.getRepository();
            File repoDir = repo.getDirectory().getParentFile();
            log.fine("Repo cloned to: " + repoDir.getCanonicalPath());
            try {
                File f = new File(repoDir, filePath);
                if (!f.exists() || f.canWrite()) {
                    try (Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8")) {
                        w.write(new String(contents, "utf-8"));
                    }

                    try {
                        AddCommand add = activeRepo.add();
                        add.addFilepattern(filePath);
                        add.call();

                        CommitCommand commit = activeRepo.commit();
                        commit.setMessage(commitMessage);
                        commit.call();

                        // Push the changes
                        GitUtils.push(gitSource.getRemote(), repo, getCredential(),
                                LOCAL_REF_BASE + sourceBranch, REMOTE_REF_BASE + branch);
                    } catch (GitAPIException ex) {
                        throw new ServiceException.UnexpectedErrorException(ex.getMessage(), ex);
                    }

                    return null;
                }
                throw new ServiceException.UnexpectedErrorException("Unable to write " + filePath);
            } finally {
                FileUtils.deleteDirectory(repoDir);
            }
        }
    });
}

From source file:io.syndesis.git.GitWorkflow.java

License:Apache License

private void commitAndPush(Git git, String authorName, String authorEmail, String message,
        UsernamePasswordCredentialsProvider credentials) throws GitAPIException {

    // git add ./*from ww  w  .  j a  v a  2 s  .c  o m*/
    git.add().addFilepattern(".").call();
    if (LOG.isDebugEnabled()) {
        LOG.debug("git add all file");
    }

    // git commit
    RevCommit commit = git.commit().setAuthor(authorName, authorEmail).setMessage(message).call();
    LOG.info("git commit id {}", commit.getId());

    // git push -f, not merging but simply forcing the push (for now)
    Iterable<PushResult> pushResult = git.push().setCredentialsProvider(credentials).setForce(true).call();
    if (!pushResult.iterator().next().getMessages().equals("")) {
        LOG.warn("git push messages: {}", pushResult.iterator().next().getMessages());
    }
}

From source file:io.vertx.config.git.GitConfigStoreTest.java

License:Apache License

private GitConfigStoreTest add(Git git, File root, File file, String directory)
        throws IOException, GitAPIException {
    if (!file.isFile()) {
        throw new RuntimeException("File not found " + file.getAbsolutePath());
    }/*from w  w w  . j a v  a 2 s .c  o  m*/

    if (!"master".equalsIgnoreCase(git.getRepository().getBranch())) {
        git.checkout().setCreateBranch(true).setName("master").call();
    }

    if (!branch.equalsIgnoreCase(git.getRepository().getBranch())) {
        boolean create = true;
        for (Ref ref : git.branchList().call()) {
            if (ref.getName().equals("refs/heads/" + branch)) {
                create = false;
            }
        }
        git.checkout().setCreateBranch(create).setName(branch).call();
    }

    String relative;
    if (directory != null) {
        relative = directory + File.separator + file.getName();
    } else {
        relative = file.getName();
    }

    File output = new File(root, relative);
    if (output.exists()) {
        output.delete();
    }
    if (!output.getParentFile().isDirectory()) {
        output.getParentFile().mkdirs();
    }

    FileUtils.copyFile(file, output);

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

    git.commit().setAuthor("clement", "clement@apache.org").setCommitter("clement", "clement@apache.org")
            .setMessage("Add " + relative).call();

    return this;
}