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

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

Introduction

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

Prototype

public PushCommand push() 

Source Link

Document

Return a command object to execute a Push command

Usage

From source file:org.jclarity.GitReleaseRollback.java

License:Apache License

private void deleteTag() {
    try {/*from w  w  w.j a  va  2s  . co m*/
        FileRepositoryBuilder builder = new FileRepositoryBuilder();

        FileRepository db = builder.findGitDir(baseDir).readEnvironment().findGitDir().build();

        Git git = new Git(db);

        String scmTag = releaseProperties.getProperty("scm.tag");
        List<String> result = git.tagDelete().setTags(scmTag).call();
        for (String tag : result) {
            git.push().add(":" + tag).call();
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to read git repo data", e);
    } catch (GitAPIException e) {
        throw new RuntimeException("Failed to remove tag", e);
    }
}

From source file:org.kaazing.bower.dependency.maven.plugin.UploadBowerArtifactMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(username, password);
    File repoDir = new File(outputDir);
    Git repo = checkoutGitRepo(repoDir, gitBowerUrl, credentialsProvider);
    if (preserveFiles == null || preserveFiles.isEmpty()) {
        preserveFiles = new ArrayList<String>();
        preserveFiles.add("README.md");
        preserveFiles.add("bower.json");
        preserveFiles.add("package.json");
        preserveFiles.add(".git");

    }//from  w  w  w . j a v a  2s.  c  o m
    for (File file : repoDir.listFiles()) {
        if (!preserveFiles.contains(file.getName())) {
            file.delete();
            try {
                repo.rm().addFilepattern(file.getName()).call();
            } catch (GitAPIException e) {
                throw new MojoExecutionException("Failed to reset repo", e);
            }
        }
    }

    for (String include : includes) {
        File includedFile = new File(includeBaseDir, include);
        if (!includedFile.exists()) {
            throw new MojoExecutionException("Included file \"" + include
                    + "\" does not exist at includeBaseDir/{name}: " + includedFile.getAbsolutePath());
        }
        if (includedFile.isDirectory()) {
            throw new MojoExecutionException("Included files can not be directory: " + includedFile);
        }
        try {
            Files.copy(includedFile.toPath(), new File(outputDir, include).toPath());
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to copy included resource", e);
        }
        try {
            repo.add().addFilepattern(include).call();
        } catch (GitAPIException e) {
            throw new MojoExecutionException("Failed to add included file", e);
        }
    }

    if (directoryToInclude != null && !directoryToInclude.equals("")) {
        File includedDir = new File(directoryToInclude);
        if (!includedDir.exists() && includedDir.isDirectory()) {
            throw new MojoExecutionException(
                    "Included directory \"" + directoryToInclude + "\" does not exist");
        }
        for (File includedFile : includedDir.listFiles()) {
            String include = includedFile.getName();
            if (includedFile.isDirectory()) {
                throw new MojoExecutionException("Included files can not be directory: " + includedFile);
            }
            try {
                Files.copy(includedFile.toPath(), new File(outputDir, include).toPath());
            } catch (IOException e) {
                throw new MojoExecutionException("Failed to copy included resource", e);
            }
            try {
                repo.add().addFilepattern(include).call();
            } catch (GitAPIException e) {
                throw new MojoExecutionException("Failed to add included file", e);
            }
        }
    }

    try {
        repo.commit().setMessage("Added files for next release of " + version).call();
    } catch (GitAPIException e) {
        throw new MojoExecutionException("Failed to commit to repo with changes", e);
    }
    try {
        repo.tag().setName(version).setMessage("Releasing version: " + version).call();
    } catch (GitAPIException e) {
        throw new MojoExecutionException("Failed to tag release", e);
    }
    try {
        repo.push().setPushTags().setCredentialsProvider(credentialsProvider).call();
        repo.push().setPushAll().setCredentialsProvider(credentialsProvider).call();
    } catch (GitAPIException e) {
        throw new MojoExecutionException("Failed to push changes", e);
    }
}

From source file:org.komodo.rest.service.KomodoImportExportServiceTest.java

License:Open Source License

private void initGitRepository() throws Exception {
    String tmpDirPath = System.getProperty("java.io.tmpdir");
    File tmpDir = new File(tmpDirPath);

    long timestamp = System.currentTimeMillis();
    myGitDir = new File(tmpDir, "mygit-" + timestamp);
    assertTrue(myGitDir.mkdir());/*from   w  w w . j  a v a2 s.  co m*/

    myGit = Git.init().setDirectory(myGitDir).setBare(true).call();
    assertNotNull(myGit);

    // Need to initialise the master branch
    // as jgit does not automatically create on
    File seedDir = new File(tmpDir, "seedDir-" + timestamp);
    Git seedGit = Git.cloneRepository().setURI(myGitDir.getAbsolutePath()).setDirectory(seedDir).call();

    File tweetVdbFile = new File(seedDir,
            TestUtilities.TWEET_EXAMPLE_NAME + TestUtilities.TWEET_EXAMPLE_SUFFIX);
    assertTrue(tweetVdbFile.createNewFile());
    FileUtils.write(TestUtilities.tweetExample(), tweetVdbFile);
    assertTrue(tweetVdbFile.length() > 0);

    File usStatesZipFile = new File(tmpDir, TestUtilities.US_STATES_DATA_SERVICE_NAME + ZIP_SUFFIX);
    FileUtils.write(TestUtilities.usStatesDataserviceExample(), usStatesZipFile);
    try (FileInputStream fis = new FileInputStream(usStatesZipFile)) {
        File usStatesDir = new File(seedDir, TestUtilities.US_STATES_DATA_SERVICE_NAME);
        usStatesDir.mkdir();
        FileUtils.zipExtract(fis, usStatesDir);
        usStatesZipFile.delete();
    }

    seedGit.add().addFilepattern(DOT).call();
    seedGit.commit().setMessage("First Commit").call();
    seedGit.push().call();

    FileUtils.removeDirectoryAndChildren(seedDir);

    //
    // Local git repository
    //
    String dirName = System.currentTimeMillis() + HYPHEN;
    gitRepoDest = new File(FileUtils.tempDirectory(), dirName);
    gitRepoDest.mkdir();
}

From source file:org.komodo.storage.git.TestGitStorageConnector.java

License:Open Source License

@Before
public void setup() throws Exception {
    String tmpDirPath = System.getProperty("java.io.tmpdir");
    tmpDir = new File(tmpDirPath);

    timestamp = System.currentTimeMillis();
    myGitDir = new File(tmpDir, "mygit-" + timestamp);
    assertTrue(myGitDir.mkdir());//  w w w  . ja  va  2s.  c  o  m

    myGit = Git.init().setDirectory(myGitDir).setBare(true).call();
    assertNotNull(myGit);

    //
    // Create a clone to seed the repository with a file
    //
    File seedDir = new File(tmpDir, "seedDir-" + timestamp);
    Git seedGit = Git.cloneRepository().setURI(myGitDir.getAbsolutePath()).setDirectory(seedDir).call();

    // Adds a file into the seed repository
    File vdbFile = new File(seedDir, TEST_VDB_XML);
    assertTrue(vdbFile.createNewFile());
    FileUtils.write(TestUtilities.tweetExample(), vdbFile);
    assertTrue(vdbFile.length() > 0);

    File subDir = new File(seedDir, SUB_DIR);
    assertTrue(subDir.mkdir());

    File subDirVdbFile = new File(subDir, TEST_VDB_3_XML);
    assertTrue(subDirVdbFile.createNewFile());
    FileUtils.write(TestUtilities.tweetExample(), subDirVdbFile);
    assertTrue(subDirVdbFile.length() > 0);

    File usStatesZipFile = new File(tmpDir, TestUtilities.US_STATES_VDB_NAME + ZIP_SUFFIX);
    FileUtils.write(TestUtilities.usStatesDataserviceExample(), usStatesZipFile);
    try (FileInputStream fis = new FileInputStream(usStatesZipFile)) {
        File usStatesDir = new File(seedDir, TestUtilities.US_STATES_VDB_NAME);
        usStatesDir.mkdir();
        FileUtils.zipExtract(fis, usStatesDir);
        usStatesZipFile.delete();
    }

    seedGit.add().addFilepattern(DOT).call();
    seedGit.commit().setMessage("Adds Test Files").call();
    seedGit.push().call();

    FileUtils.removeDirectoryAndChildren(seedDir);
}

From source file:org.kuali.student.git.importer.ApplyManualBranchCleanup.java

License:Educational Community License

/**
 * @param args/*ww  w .  j  ava  2  s  .c  o  m*/
 */
public static void main(String[] args) {

    if (args.length < 4 || args.length > 7) {
        usage();
    }

    File inputFile = new File(args[0]);

    if (!inputFile.exists())
        usage();

    boolean bare = false;

    if (args[2].trim().equals("1")) {
        bare = true;
    }

    String remoteName = args[3].trim();

    String refPrefix = Constants.R_HEADS;

    if (args.length == 5)
        refPrefix = args[4].trim();

    String userName = null;
    String password = null;

    if (args.length == 6)
        userName = args[5].trim();

    if (args.length == 7)
        password = args[6].trim();

    try {

        Repository repo = GitRepositoryUtils.buildFileRepository(new File(args[1]).getAbsoluteFile(), false,
                bare);

        Git git = new Git(repo);

        RevWalk rw = new RevWalk(repo);

        ObjectInserter objectInserter = repo.newObjectInserter();

        BufferedReader fileReader = new BufferedReader(new FileReader(inputFile));

        String line = fileReader.readLine();

        int lineNumber = 1;

        BatchRefUpdate batch = repo.getRefDatabase().newBatchUpdate();

        List<RefSpec> branchesToDelete = new ArrayList<>();

        while (line != null) {

            if (line.startsWith("#") || line.length() == 0) {
                // skip over comments and blank lines
                line = fileReader.readLine();
                lineNumber++;

                continue;
            }

            String parts[] = line.trim().split(":");

            String branchName = parts[0];

            Ref branchRef = repo.getRef(refPrefix + "/" + branchName);

            if (branchRef == null) {
                log.warn("line: {}, No branch matching {} exists, skipping.", lineNumber, branchName);

                line = fileReader.readLine();
                lineNumber++;

                continue;
            }

            String tagName = null;

            if (parts.length > 1)
                tagName = parts[1];

            if (tagName != null) {

                if (tagName.equals("keep")) {
                    log.info("keeping existing branch for {}", branchName);

                    line = fileReader.readLine();
                    lineNumber++;

                    continue;
                }

                if (tagName.equals("tag")) {

                    /*
                     * Shortcut to say make the tag start with the same name as the branch.
                     */
                    tagName = branchName;
                }
                // create a tag

                RevCommit commit = rw.parseCommit(branchRef.getObjectId());

                ObjectId tag = GitRefUtils.insertTag(tagName, commit, objectInserter);

                batch.addCommand(new ReceiveCommand(null, tag, Constants.R_TAGS + tagName, Type.CREATE));

                log.info("converting branch {} into a tag {}", branchName, tagName);

            }

            if (remoteName.equals("local")) {
                batch.addCommand(
                        new ReceiveCommand(branchRef.getObjectId(), null, branchRef.getName(), Type.DELETE));
            } else {

                // if the branch is remote then remember its name so we can batch delete after we have the full list.
                branchesToDelete.add(new RefSpec(":" + Constants.R_HEADS + branchName));
            }

            line = fileReader.readLine();
            lineNumber++;

        }

        fileReader.close();

        // run the batch update
        batch.execute(rw, new TextProgressMonitor());

        if (!remoteName.equals("local")) {
            // push the tag to the remote right now

            log.info("pushing tags to {}", remoteName);

            PushCommand pushCommand = git.push().setRemote(remoteName).setPushTags()
                    .setProgressMonitor(new TextProgressMonitor());

            if (userName != null)
                pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, password));

            Iterable<PushResult> results = pushCommand.call();

            for (PushResult pushResult : results) {

                if (!pushResult.equals(Result.NEW)) {
                    log.warn("failed to push tag " + pushResult.getMessages());
                }
            }

            // delete the branches from the remote

            log.info("pushing branch deletes to remote: {}", remoteName);

            results = git.push().setRemote(remoteName).setRefSpecs(branchesToDelete)
                    .setProgressMonitor(new TextProgressMonitor()).call();
        }

        objectInserter.release();

        rw.release();

    } catch (Exception e) {

        log.error("unexpected Exception ", e);
    }
}

From source file:org.kuali.student.git.importer.ConvertBuildTagBranchesToGitTags.java

License:Educational Community License

/**
 * @param args//from   w w w  .java2  s.  c o m
 */
public static void main(String[] args) {

    if (args.length < 3 || args.length > 6) {
        System.err.println("USAGE: <git repository> <bare> <ref mode> [<ref prefix> <username> <password>]");
        System.err.println("\t<bare> : 0 (false) or 1 (true)");
        System.err.println("\t<ref mode> : local or name of remote");
        System.err.println("\t<ref prefix> : refs/heads (default) or say refs/remotes/origin (test clone)");
        System.exit(-1);
    }

    boolean bare = false;

    if (args[1].trim().equals("1")) {
        bare = true;
    }

    String remoteName = args[2].trim();

    String refPrefix = Constants.R_HEADS;

    if (args.length == 4)
        refPrefix = args[3].trim();

    String userName = null;
    String password = null;

    if (args.length == 5)
        userName = args[4].trim();

    if (args.length == 6)
        password = args[5].trim();

    try {

        Repository repo = GitRepositoryUtils.buildFileRepository(new File(args[0]).getAbsoluteFile(), false,
                bare);

        Git git = new Git(repo);

        ObjectInserter objectInserter = repo.newObjectInserter();

        Collection<Ref> repositoryHeads = repo.getRefDatabase().getRefs(refPrefix).values();

        RevWalk rw = new RevWalk(repo);

        Map<String, ObjectId> tagNameToTagId = new HashMap<>();

        Map<String, Ref> tagNameToRef = new HashMap<>();

        for (Ref ref : repositoryHeads) {

            String branchName = ref.getName().substring(refPrefix.length() + 1);

            if (branchName.contains("tag") && branchName.contains("builds")) {

                String branchParts[] = branchName.split("_");

                int buildsIndex = ArrayUtils.indexOf(branchParts, "builds");

                String moduleName = StringUtils.join(branchParts, "_", buildsIndex + 1, branchParts.length);

                RevCommit commit = rw.parseCommit(ref.getObjectId());

                ObjectId tag = GitRefUtils.insertTag(moduleName, commit, objectInserter);

                tagNameToTagId.put(moduleName, tag);

                tagNameToRef.put(moduleName, ref);

            }

        }

        BatchRefUpdate batch = repo.getRefDatabase().newBatchUpdate();

        List<RefSpec> branchesToDelete = new ArrayList<>();

        for (Entry<String, ObjectId> entry : tagNameToTagId.entrySet()) {

            String tagName = entry.getKey();

            // create the reference to the tag object
            batch.addCommand(
                    new ReceiveCommand(null, entry.getValue(), Constants.R_TAGS + tagName, Type.CREATE));

            // delete the original branch object

            Ref branch = tagNameToRef.get(entry.getKey());

            if (remoteName.equals("local")) {

                batch.addCommand(new ReceiveCommand(branch.getObjectId(), null, branch.getName(), Type.DELETE));

            } else {
                String adjustedBranchName = branch.getName().substring(refPrefix.length() + 1);

                branchesToDelete.add(new RefSpec(":" + Constants.R_HEADS + adjustedBranchName));
            }

        }

        // create the tags
        batch.execute(rw, new TextProgressMonitor());

        if (!remoteName.equals("local")) {
            // push the tag to the remote right now
            PushCommand pushCommand = git.push().setRemote(remoteName).setPushTags()
                    .setProgressMonitor(new TextProgressMonitor());

            if (userName != null)
                pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, password));

            Iterable<PushResult> results = pushCommand.call();

            for (PushResult pushResult : results) {

                if (!pushResult.equals(Result.NEW)) {
                    log.warn("failed to push tag " + pushResult.getMessages());
                }
            }

            // delete the branches from the remote
            results = git.push().setRemote(remoteName).setRefSpecs(branchesToDelete)
                    .setProgressMonitor(new TextProgressMonitor()).call();

            log.info("");

        }

        //         Result result = GitRefUtils.createTagReference(repo, moduleName, tag);
        //         
        //         if (!result.equals(Result.NEW)) {
        //            log.warn("failed to create tag {} for branch {}", moduleName, branchName);
        //            continue;
        //         }
        //         
        //         if (deleteMode) {
        //         result = GitRefUtils.deleteRef(repo, ref);
        //   
        //         if (!result.equals(Result.NEW)) {
        //            log.warn("failed to delete branch {}", branchName);
        //            continue;
        //         }

        objectInserter.release();

        rw.release();

    } catch (Exception e) {

        log.error("unexpected Exception ", e);
    }
}

From source file:org.ms123.common.git.GitServiceImpl.java

License:Open Source License

public void push(@PName("name") String name) throws RpcException {
    try {//from   w  w  w  .  j  a  va  2s  . co m
        String gitSpace = System.getProperty("git.repos");
        File dir = new File(gitSpace, name);
        if (!dir.exists()) {
            throw new RpcException(ERROR_FROM_METHOD, 100, "GitService.push:Repo(" + name + ") not exists");
        }
        Git git = Git.open(dir);
        PushCommand push = git.push();
        push.setRefSpecs(new RefSpec(REF_PREFIX + "master")).setRemote("origin");
        //ic.setPushAll(true);
        Iterable<PushResult> result = null;
        try {
            result = push.call();
        } catch (org.eclipse.jgit.api.errors.TransportException e) {
            if (e.getCause() instanceof org.eclipse.jgit.errors.NoRemoteRepositoryException) {
                info("Push:" + e.getCause().getMessage());
                return;
            } else {
                throw e;
            }
        }
        for (PushResult pushResult : result) {
            if (StringUtils.isNotBlank(pushResult.getMessages())) {
                debug(pushResult.getMessages());
            }
        }
        return;
    } catch (Exception e) {
        throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "GitService.push:", e);
    } finally {
    }
}

From source file:org.mule.module.git.GitConnector.java

License:Open Source License

/**
 * Update remote refs along with associated objects
 *
 * {@sample.xml ../../../doc/mule-module-git.xml.sample git:push}
 *
 * @param remote The remote (uri or name) used for the push operation.
 * @param force  Sets the force preference for push operation
 * @param overrideDirectory Name of the directory to use for git repository
 */// w w  w.j  ava  2s .c  om
@Processor
public void push(@Optional @Default("origin") String remote, @Optional @Default("false") boolean force,
        @Optional String overrideDirectory) {
    try {
        Git git = new Git(getGitRepo(overrideDirectory));
        PushCommand push = git.push();
        push.setRemote(remote);
        push.setForce(force);

        push.call();
    } catch (Exception e) {
        throw new RuntimeException("Unable to push to " + remote, e);
    }

}

From source file:org.obiba.git.command.AbstractGitWriteCommand.java

License:Open Source License

protected Iterable<PushResult> commitAndPush(Git git) throws GitAPIException {
    String name = getAuthorName();
    String email = getAuthorEmail();
    log.debug("Commit: {} <{}> - {}", name, email, getCommitMessage());
    git.commit() //
            .setAuthor(name, email) //
            .setCommitter(name, email) //
            .setMessage(getCommitMessage()) //
            .call();/* w w  w . jav  a 2 s .  c om*/
    return git.push().setPushAll().setRemote("origin").call();
}

From source file:org.obiba.opal.core.cfg.OpalViewPersistenceStrategy.java

License:Open Source License

private void doCommitPush(Git git, String message) throws GitAPIException {
    git.commit().setAuthor(getAuthorName(), "opal@obiba.org").setCommitter("opal", "opal@obiba.org")
            .setMessage(message).call();
    git.push().setPushAll().setRemote("origin").call();
}