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:org.fusesource.fabric.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  .ja  v a 2s .c o  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 ? "/" : "") + 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(pattern).call();
}

From source file:org.fusesource.fabric.itests.basic.git.FabricGitTestSupport.java

License:Apache License

/**
 * Create a profile in git and check that its bridged to the registry.
 *
 * @param git     The git object of the test repository.
 * @param version The version of the profile.
 * @param profile The profile name.//from w w w .j  a v  a 2s. c  om
 * @throws Exception
 */
public void createAndTestProfileInGit(Git git, String version, String profile) throws Exception {
    //Create the test profile in git
    System.err.println("Create test profile:" + profile + " in git.");
    GitUtils.checkoutBranch(git, "origin", version);
    File testProfileDir = new File(git.getRepository().getWorkTree(), profile);
    testProfileDir.mkdirs();
    File testProfileConfig = new File(testProfileDir, "org.fusesource.fabric.agent.properties");
    testProfileConfig.createNewFile();
    Files.writeToFile(testProfileConfig, "", Charset.defaultCharset());
    git.add().addFilepattern(profile).call();
    git.commit().setMessage("Create " + profile).call();
    PullResult pullResult = git.pull().setCredentialsProvider(getCredentialsProvider()).setRebase(true).call();
    git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call();
    GitUtils.waitForBranchUpdate(getCurator(), version);
    //Check that it has been bridged in zookeeper
    Thread.sleep(5000);
    assertNotNull(getCurator().checkExists().forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath(version, profile)));
}

From source file:org.fusesource.fabric.itests.basic.git.GitBridgeTest.java

License:Apache License

public void testWithProfiles() throws Exception {
    String testProfileNameBase = "mytestprofile-";
    System.err.println(executeCommand("fabric:create -n"));
    Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult()
            .build();//  w w w .  j  av  a 2 s.  c  o m
    String gitRepoUrl = GitUtils.getMasterUrl(getCurator());

    GitUtils.waitForBranchUpdate(getCurator(), "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, "default").exists());

    //Create test profile
    for (int i = 1; i <= 3; i++) {
        String testProfileName = testProfileNameBase + i;
        System.err.println("Create test profile:" + testProfileName + " in zookeeper");
        getFabricService().getVersion("1.0").createProfile(testProfileName);
        GitUtils.waitForBranchUpdate(getCurator(), "1.0");
        git.pull().setRebase(true).setCredentialsProvider(getCredentialsProvider()).call();
        //Check that a newly created profile exists
        assertTrue(new File(testrepo, testProfileName).exists());
        //Delete test profile
        System.err.println("Delete test profile:" + testProfileName + " in git.");
        git.rm().addFilepattern(testProfileName).call();
        git.commit().setMessage("Delete " + testProfileName).call();
        git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call();
        GitUtils.waitForBranchUpdate(getCurator(), "1.0");
        Thread.sleep(5000);
        assertFalse(new File(testrepo, testProfileName).exists());
        assertNull(getCurator().checkExists()
                .forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath("1.0", testProfileName)));

        //Create the test profile in git
        System.err.println("Create test profile:" + testProfileName + " in git.");
        File testProfileDir = new File(testrepo, testProfileName);
        testProfileDir.mkdirs();
        File testProfileConfig = new File(testProfileDir, "org.fusesource.fabric.agent.properties");
        testProfileConfig.createNewFile();
        Files.writeToFile(testProfileConfig, "", Charset.defaultCharset());
        git.add().addFilepattern(testProfileName).call();
        RevCommit commit = git.commit().setMessage("Create " + testProfileName).call();
        FileTreeIterator fileTreeItr = new FileTreeIterator(git.getRepository());
        IndexDiff indexDiff = new IndexDiff(git.getRepository(), commit.getId(), fileTreeItr);
        System.out.println(indexDiff.getChanged());
        System.out.println(indexDiff.getAdded());
        git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call();
        GitUtils.waitForBranchUpdate(getCurator(), "1.0");
        //Check that it has been bridged in zookeeper
        Thread.sleep(15000);
        assertNotNull(getCurator().checkExists()
                .forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath("1.0", testProfileName)));
    }
}

From source file:org.gitective.tests.GitTestCase.java

License:Open Source License

/**
 * Add file to test repository/*from  w w w  .j av a2  s.c o m*/
 *
 * @param repo
 * @param path
 * @param content
 * @param message
 * @return commit
 * @throws Exception
 */
protected RevCommit add(File repo, String path, String content, String message) throws Exception {
    File file = new File(repo.getParentFile(), path);
    if (!file.getParentFile().exists())
        assertTrue(file.getParentFile().mkdirs());
    if (!file.exists())
        assertTrue(file.createNewFile());
    PrintWriter writer = new PrintWriter(file);
    if (content == null)
        content = "";
    try {
        writer.print(content);
    } finally {
        writer.close();
    }
    Git git = Git.open(repo);
    git.add().addFilepattern(path).call();
    RevCommit commit = git.commit().setOnly(path).setMessage(message).setAuthor(author).setCommitter(committer)
            .call();
    assertNotNull(commit);
    return commit;
}

From source file:org.gitective.tests.GitTestCase.java

License:Open Source License

/**
 * Move file in test repository//from w  w w  . ja v  a2s .c om
 *
 * @param repo
 * @param from
 * @param to
 * @param message
 * @return commit
 * @throws Exception
 */
protected RevCommit mv(File repo, String from, String to, String message) throws Exception {
    File file = new File(repo.getParentFile(), from);
    file.renameTo(new File(repo.getParentFile(), to));
    Git git = Git.open(repo);
    git.rm().addFilepattern(from);
    git.add().addFilepattern(to).call();
    RevCommit commit = git.commit().setAll(true).setMessage(message).setAuthor(author).setCommitter(committer)
            .call();
    assertNotNull(commit);
    return commit;
}

From source file:org.gitective.tests.GitTestCase.java

License:Open Source License

/**
 * Add files to test repository//  w w  w.j a v a2 s.  c o  m
 *
 * @param repo
 * @param paths
 * @param contents
 * @param message
 * @return commit
 * @throws Exception
 */
protected RevCommit add(File repo, List<String> paths, List<String> contents, String message) throws Exception {
    Git git = Git.open(repo);
    for (int i = 0; i < paths.size(); i++) {
        String path = paths.get(i);
        String content = contents.get(i);
        File file = new File(repo.getParentFile(), path);
        if (!file.getParentFile().exists())
            assertTrue(file.getParentFile().mkdirs());
        if (!file.exists())
            assertTrue(file.createNewFile());
        PrintWriter writer = new PrintWriter(file);
        if (content == null)
            content = "";
        try {
            writer.print(content);
        } finally {
            writer.close();
        }
        git.add().addFilepattern(path).call();
    }
    RevCommit commit = git.commit().setMessage(message).setAuthor(author).setCommitter(committer).call();
    assertNotNull(commit);
    return commit;
}

From source file:org.guvnor.ala.build.maven.executor.MavenTestUtils.java

License:Apache License

public static String createGitRepoWithPom(final File path, final InputStream pom, final File... files)
        throws Exception {
    File repo = new File(path, "repo");
    if (repo.exists() == false) {
        Files.createDirectory(repo.toPath());
    }//from w  w  w  .j a va 2 s .  c  o m
    Git git = Git.init().setDirectory(repo).call();
    String gitUrl = "file://" + repo.getAbsolutePath();

    FileUtils.copyInputStreamToFile(pom, new File(repo, "pom.xml"));
    AddCommand add = git.add();
    add.addFilepattern("pom.xml");
    for (File f : files) {
        add.addFilepattern(f.getName());
    }
    add.call();
    CommitCommand commit = git.commit();
    commit.setMessage("initial commit").call();
    return gitUrl;
}

From source file:org.ihtsdo.ttk.services.sync.Example.java

License:Apache License

/**
 * Method description/*from   ww  w  .ja v a  2  s  .  c o m*/
 *
 *
 * @param args
 */
public static void main(String[] args) {
    try {

        // jGit provides the ability to manage the git repositories from 
        // your code in a very easy manner. For example, to create the new 
        // repository, you just have to indicate the target directory:
        File targetDir = new File("target/newRepository.git");
        Repository repo = new FileRepository(targetDir);
        repo.create(true);

        //Cloning the existing git repository is also very easy and nice:
        Git.cloneRepository().setURI(targetDir.toURI().toString()).setDirectory(new File("target/working-copy"))
                .setBranch("master").setBare(false).setRemote("origin").setNoCheckout(false).call();

        // And here is the way how you can add the changes, 
        // commit and push them to the origin:
        Git git = new Git(new FileRepository(new File("target/working-copy")));
        git.add().addFilepattern(".").call();
        git.commit().setMessage("some comment").call();
        git.push().setPushAll().setRemote("origin").call();

        // http://jzelenkov.com/post/35653947951/diving-into-jgit

        // http://download.eclipse.org/jgit/docs/jgit-2.0.0.201206130900-r/apidocs/org/eclipse/jgit/api/package-summary.html

        // http://blogs.atlassian.com/2013/04/git-flow-comes-to-java/
    } catch (IOException ex) {
        Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
    } catch (GitAPIException ex) {
        Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.jabylon.team.git.GitTeamProvider.java

License:Open Source License

private List<String> addNewFiles(Git git, IProgressMonitor monitor) throws IOException, GitAPIException {
    monitor.beginTask("Creating Diff", 100);
    DiffCommand diffCommand = git.diff();

    AddCommand addCommand = git.add();
    List<String> changedFiles = new ArrayList<String>();
    List<String> newFiles = new ArrayList<String>();

    List<DiffEntry> result = diffCommand.call();
    //TODO: delete won't work
    for (DiffEntry diffEntry : result) {
        checkCanceled(monitor);/*from   w w w .  ja va2s  .  co  m*/
        if (diffEntry.getChangeType() == ChangeType.ADD) {
            addCommand.addFilepattern(diffEntry.getNewPath());
            newFiles.add(diffEntry.getNewPath());
            monitor.subTask(diffEntry.getNewPath());
        } else if (diffEntry.getChangeType() == ChangeType.MODIFY) {
            monitor.subTask(diffEntry.getOldPath());
            changedFiles.add(diffEntry.getOldPath());
        }
        monitor.worked(0);
    }
    if (!newFiles.isEmpty())
        addCommand.call();

    changedFiles.addAll(newFiles);
    monitor.done();
    return changedFiles;
}

From source file:org.jboss.as.server.controller.git.GitRepository.java

License:Apache License

private boolean createGitIgnore(Git git, Path root) throws IOException, GitAPIException {
    Path gitIgnore = root.resolve(DOT_GIT_IGNORE);
    if (Files.notExists(gitIgnore)) {
        Files.write(gitIgnore, ignored);
        git.add().addFilepattern(DOT_GIT_IGNORE).call();
        return true;
    }/*  w w  w . jav a  2s.  co m*/
    return false;
}