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.forge.rest.main.GitCommandCompletePostProcessor.java

License:Apache License

protected void doAddCommitAndPushFiles(Git git, CredentialsProvider credentials, PersonIdent personIdent,
        String remote, String branch, String origin, String message) throws GitAPIException, IOException {
    git.add().addFilepattern(".").call();
    doCommitAndPush(git, message, credentials, personIdent, remote, branch, origin);
}

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

License:Apache License

/**
 * Recursively copies the given files from the given directory to the specified directory
 * adding them to the git repo along the way
 *///from  ww w.j  av  a2 s.c o  m
protected void recursiveCopyAndAdd(Git git, File from, File toDir, String path, boolean useToDirAsDestination)
        throws GitAPIException, IOException {
    assertValid();
    String name = from.getName();
    String pattern = path + (path.length() > 0 && !path.endsWith(File.separator) ? File.separator : "") + name;
    File toFile = new File(toDir, name);

    if (from.isDirectory()) {
        if (useToDirAsDestination) {
            toFile = toDir;
        }
        toFile.mkdirs();
        File[] files = from.listFiles();
        if (files != null) {
            for (File file : files) {
                recursiveCopyAndAdd(git, file, toFile, pattern, false);
            }
        }
    } else {
        Files.copy(from, toFile);
    }
    git.add().addFilepattern(fixFilePattern(pattern)).call();
}

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

License:Apache License

/**
 * Recursively copies the profiles in a single flat directory into the new
 * directory layout; changing "foo-bar" directory into "foo/bar.profile" along the way
 *///from   w w w.  j  av  a2  s .  co m
protected void recursiveAddLegacyProfileDirectoryFiles(Git git, File from, File toDir, String path)
        throws GitAPIException, IOException {
    assertValid();
    if (!from.isDirectory()) {
        throw new IllegalStateException(
                "Should only be invoked on the profiles directory but was given file " + from);
    }
    String name = from.getName();
    String pattern = path + (path.length() > 0 && !path.endsWith(File.separator) ? File.separator : "") + name;
    File[] profiles = from.listFiles();
    File toFile = new File(toDir, name);
    if (profiles != null) {
        for (File profileDir : profiles) {
            // TODO should we try and detect regular folders somehow using some naming convention?
            if (isProfileDirectory(profileDir)) {
                String profileId = profileDir.getName();
                String toProfileDirName = convertProfileIdToDirectory(profileId);
                File toProfileDir = new File(toFile, toProfileDirName);
                toProfileDir.mkdirs();
                recursiveCopyAndAdd(git, profileDir, toProfileDir, pattern, true);
            } else {
                recursiveCopyAndAdd(git, profileDir, toFile, pattern, false);
            }
        }
    }
    git.add().addFilepattern(fixFilePattern(pattern)).call();
}

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

License:Apache License

protected void doAddFiles(Git git, File... files) throws GitAPIException, IOException {
    assertValid();//from w  w  w  .j a va 2  s. co  m
    File rootDir = GitHelpers.getRootGitDirectory(git);
    for (File file : files) {
        String relativePath = getFilePattern(rootDir, file);
        git.add().addFilepattern(relativePath).call();
    }
}

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

License:Apache License

private void doCommit(Git git, GitContext context) {
    try {//from   www .j  av  a 2  s  .c om
        String message = context.getCommitMessage();
        IllegalStateAssertion.assertTrue(message.length() > 0, "Empty commit message");

        // git add --all
        git.add().addFilepattern(".").call();

        // git commit -m message
        git.commit().setMessage(message).call();

        if (--commitsWithoutGC < 0) {
            commitsWithoutGC = MAX_COMMITS_WITHOUT_GC;
            LOGGER.debug("Performing 'git gc' after {} commits", MAX_COMMITS_WITHOUT_GC);
            git.gc().call();
        }
    } catch (GitAPIException ex) {
        throw FabricException.launderThrowable(ex);
    }
}

From source file:io.fabric8.git.zkbridge.Bridge.java

License:Apache License

private static void syncVersionFromZkToGit(Git git, CuratorFramework curator, String zkNode) throws Exception {
    // Version metadata
    Properties versionProps = loadProps(curator, zkNode);
    versionProps.save(new File(getGitProfilesDirectory(git), METADATA));
    git.add().addFilepattern(METADATA).call();
    // Profiles/*ww w.ja  v  a2 s .c o m*/
    List<String> gitProfiles = list(getGitProfilesDirectory(git));
    gitProfiles.remove(".git");
    gitProfiles.remove(METADATA);
    gitProfiles.remove(CONTAINERS_PROPERTIES);
    List<String> zkProfiles = getChildren(curator, zkNode + "/profiles");
    for (String profile : zkProfiles) {
        File profileDir = new File(getGitProfilesDirectory(git), profile);
        profileDir.mkdirs();
        // Profile metadata
        Properties profileProps = loadProps(curator, zkNode + "/profiles/" + profile);
        profileProps.save(new File(getGitProfilesDirectory(git), profile + "/" + METADATA));
        git.add().addFilepattern(profile + "/" + METADATA).call();
        // Configs
        List<String> gitConfigs = list(profileDir);
        gitConfigs.remove(METADATA);
        List<String> zkConfigs = getChildren(curator, zkNode + "/profiles/" + profile);
        for (String file : zkConfigs) {
            byte[] data = curator.getData().forPath(zkNode + "/profiles/" + profile + "/" + file);
            Files.writeToFile(new File(getGitProfilesDirectory(git), profile + "/" + file), data);
            gitConfigs.remove(file);
            git.add().addFilepattern(profile + "/" + file).call();
        }
        for (String file : gitConfigs) {
            new File(profileDir, file).delete();
            git.rm().addFilepattern(profile + "/" + file).call();
        }
        gitProfiles.remove(profile);
    }
    for (String profile : gitProfiles) {
        delete(new File(getGitProfilesDirectory(git), profile));
        git.rm().addFilepattern(profile).call();
    }
    // Containers
    Properties containerProps = new Properties();
    for (String container : getChildren(curator, zkNode + "/containers")) {
        String str = getStringData(curator, zkNode + "/containers/" + container);
        if (str != null) {
            containerProps.setProperty(container, str);
        }
    }
    containerProps.save(new File(getGitProfilesDirectory(git), CONTAINERS_PROPERTIES));
    git.add().addFilepattern(CONTAINERS_PROPERTIES).call();
}

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

License:Apache License

/**
 * Create a profile in git and check that its bridged to the registry.
 *//*from w ww  .  jav  a  2s . c  om*/
protected void createAndTestProfileInGit(FabricService fabricService, CuratorFramework curator, Git git,
        String version, String profile) throws Exception {
    //Create the test profile in git
    System.out.println("Create test profile:" + profile + " in git.");
    GitUtils.checkoutBranch(git, "origin", version);
    String relativeProfileDir = "fabric/profiles/" + profile + ".profile";
    File testProfileDir = new File(git.getRepository().getWorkTree(), relativeProfileDir);
    testProfileDir.mkdirs();
    File testProfileConfig = new File(testProfileDir, "io.fabric8.agent.properties");
    testProfileConfig.createNewFile();
    Files.writeToFile(testProfileConfig, "", Charset.defaultCharset());
    git.add().addFilepattern(relativeProfileDir).call();
    git.commit().setAll(true).setMessage("Create " + profile).call();
    PullResult pullResult = git.pull().setCredentialsProvider(getCredentialsProvider()).setRebase(true).call();
    git.push().setCredentialsProvider(getCredentialsProvider()).setPushAll().setRemote("origin").call();
    GitUtils.waitForBranchUpdate(curator, version);
    for (int i = 0; i < 5; i++) {
        if (fabricService.getDataStore().hasProfile(version, profile)) {
            return;
        } else {
            Thread.sleep(1000);
        }
    }
    fail("Expected to find profile " + profile + " in version " + version);
}

From source file:io.fabric8.maven.HelmPushMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (!isRootReactorBuild()) {
        getLog().info("Not the root reactor build so not committing changes");
        return;//from  w w w  .  j  a  va  2 s  .  co m
    }

    File outputDir = getHelmRepoFolder();
    if (!Files.isDirectory(outputDir)) {
        throw new MojoExecutionException(
                "No helm repository exists for " + outputDir + ". Did you run `mvn fabric8:helm` yet?");
    }
    File gitFolder = new File(outputDir, ".git");
    if (!Files.isDirectory(gitFolder)) {
        throw new MojoExecutionException(
                "No helm git repository exists for " + gitFolder + ". Did you run `mvn fabric8:helm` yet?");
    }
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Git git = null;

    try {
        Repository repository = builder.setGitDir(gitFolder).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        git = new Git(repository);

        git.add().addFilepattern(".").call();
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to add files to the helm git repository: " + e, e);
    }
    CommitCommand commit = git.commit().setAll(true).setMessage(commitMessage);
    PersonIdent author = null;
    if (Strings.isNotBlank(userName) && Strings.isNotBlank(emailAddress)) {
        author = new PersonIdent(userName, emailAddress);
    }
    if (author != null) {
        commit = commit.setAuthor(author);
    }

    try {
        RevCommit answer = commit.call();
        getLog().info("Committed " + answer.getId() + " " + answer.getFullMessage());
    } catch (GitAPIException e) {
        throw new MojoExecutionException("Failed to commit changes to help repository: " + e, e);
    }

    if (pushChanges) {
        PushCommand push = git.push();
        try {
            push.setRemote(remoteRepoName).call();

            getLog().info("Pushed commits upstream to " + getHelmGitUrl());
        } catch (GitAPIException e) {
            throw new MojoExecutionException(
                    "Failed to push helm git changes to remote repository " + remoteRepoName + ": " + e, e);
        }
    }

}

From source file:io.fabric8.maven.MigrateMojo.java

License:Apache License

private void tryAddFilesToGit(String filePattern) {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    try {/*w  ww. jav  a 2s  . c o  m*/
        Repository repository = builder.readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        Git git = new Git(repository);
        git.add().addFilepattern(filePattern).call();
    } catch (Exception e) {
        getLog().warn("Failed to add generated files to the git repository: " + e, e);
    }
}

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

License:Apache License

/**
 * Lets download all the deployments and copy them into the {@link #webAppDir} or {@link #deployDir} in git
 *///from   www .  ja v a 2 s .c om
protected void copyDeploymentsIntoGit(Git git, File baseDir, Set<String> bundles, Set<Feature> features)
        throws Exception {
    List<String> webAppFilesToDelete = filesToDelete(baseDir, webAppDir);
    List<String> deployDirFilesToDelete = filesToDelete(baseDir, deployDir);

    LOG.debug("Deploying into container " + container.getId() + " features " + features + " and bundles "
            + bundles);
    Map<String, File> files = AgentUtils.downloadBundles(downloadManager, features, bundles,
            Collections.<String>emptySet());
    Set<Map.Entry<String, File>> entries = files.entrySet();
    for (Map.Entry<String, File> entry : entries) {
        String name = entry.getKey();
        File file = entry.getValue();
        String destPath;
        String fileName = file.getName();
        if (name.startsWith("war:") || name.contains("/war/") || fileName.toLowerCase().endsWith(".war")) {
            destPath = webAppDir;
            webAppFilesToDelete.remove(fileName);
        } else {
            destPath = deployDir;
            deployDirFilesToDelete.remove(fileName);
        }

        if (destPath != null) {
            File destDir = new File(baseDir, destPath);
            destDir.mkdirs();
            File destFile = new File(destDir, fileName);
            LOG.info("Copying file " + fileName + " to :  " + destFile.getCanonicalPath() + " for container "
                    + container.getId());
            Files.copy(file, destFile);
            git.add().addFilepattern(destPath + "/" + fileName).call();
        }

        // now lets delete all the old remaining files from the directory
        deleteFiles(git, baseDir, webAppDir, webAppFilesToDelete);
        deleteFiles(git, baseDir, deployDir, deployDirFilesToDelete);
    }
}