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:de.blizzy.documentr.page.PageStore.java

License:Open Source License

@Override
public void deleteAttachment(String projectName, String branchName, String pagePath, String name, User user)
        throws IOException {

    Assert.hasLength(projectName);// ww w .  j av  a  2  s .co m
    Assert.hasLength(branchName);
    Assert.hasLength(pagePath);
    Assert.hasLength(name);
    Assert.notNull(user);

    ILockedRepository repo = null;
    try {
        repo = globalRepositoryManager.getProjectBranchRepository(projectName, branchName);
        File workingDir = RepositoryUtil.getWorkingDir(repo.r());

        Git git = Git.wrap(repo.r());

        File attachmentsDir = new File(workingDir, DocumentrConstants.ATTACHMENTS_DIR_NAME);
        boolean deleted = false;
        File file = Util.toFile(attachmentsDir, pagePath + "/" + name + DocumentrConstants.PAGE_SUFFIX); //$NON-NLS-1$
        if (file.isFile()) {
            FileUtils.forceDelete(file);
            git.rm().addFilepattern(DocumentrConstants.ATTACHMENTS_DIR_NAME + "/" + //$NON-NLS-1$
                    pagePath + "/" + name + DocumentrConstants.PAGE_SUFFIX) //$NON-NLS-1$
                    .call();
            deleted = true;
        }
        file = Util.toFile(attachmentsDir, pagePath + "/" + name + DocumentrConstants.META_SUFFIX); //$NON-NLS-1$
        if (file.isFile()) {
            FileUtils.forceDelete(file);
            git.rm().addFilepattern(DocumentrConstants.ATTACHMENTS_DIR_NAME + "/" + //$NON-NLS-1$
                    pagePath + "/" + name + DocumentrConstants.META_SUFFIX) //$NON-NLS-1$
                    .call();
            deleted = true;
        }

        if (deleted) {
            PersonIdent ident = new PersonIdent(user.getLoginName(), user.getEmail());
            git.commit().setAuthor(ident).setCommitter(ident).setMessage("delete " + pagePath + "/" + name) //$NON-NLS-1$ //$NON-NLS-2$
                    .call();
            git.push().call();

            PageUtil.updateProjectEditTime(projectName);
        }
    } catch (GitAPIException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(repo);
    }
}

From source file:de.blizzy.documentr.page.PageStore.java

License:Open Source License

@Override
public void restorePageVersion(String projectName, String branchName, String path, String version, User user)
        throws IOException {

    Assert.hasLength(projectName);/* www.ja  v a  2s.c  o  m*/
    Assert.hasLength(branchName);
    Assert.hasLength(path);
    Assert.hasLength(version);

    ILockedRepository repo = null;
    try {
        repo = globalRepositoryManager.getProjectBranchRepository(projectName, branchName);
        String text = BlobUtils.getContent(repo.r(), version,
                DocumentrConstants.PAGES_DIR_NAME + "/" + path + DocumentrConstants.PAGE_SUFFIX); //$NON-NLS-1$
        File workingDir = RepositoryUtil.getWorkingDir(repo.r());
        File pagesDir = new File(workingDir, DocumentrConstants.PAGES_DIR_NAME);
        File file = Util.toFile(pagesDir, path + DocumentrConstants.PAGE_SUFFIX);
        FileUtils.writeStringToFile(file, text, Charsets.UTF_8.name());

        Git git = Git.wrap(repo.r());
        git.add()
                .addFilepattern(DocumentrConstants.PAGES_DIR_NAME + "/" + path + DocumentrConstants.PAGE_SUFFIX) //$NON-NLS-1$
                .call();
        PersonIdent ident = new PersonIdent(user.getLoginName(), user.getEmail());
        git.commit().setAuthor(ident).setCommitter(ident)
                .setMessage(DocumentrConstants.PAGES_DIR_NAME + "/" + path) //$NON-NLS-1$
                .call();
        git.push().call();
    } catch (GitAPIException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(repo);
    }

    eventBus.post(new PageChangedEvent(projectName, branchName, path));
}

From source file:de.blizzy.documentr.repository.ProjectRepositoryManager.java

License:Open Source License

ILockedRepository createCentralRepository(boolean bare, User user) throws IOException, GitAPIException {
    if (centralRepoDir.isDirectory()) {
        throw new IllegalStateException("repository already exists: " + centralRepoDir.getAbsolutePath()); //$NON-NLS-1$
    }/*from  ww w.j a  v a 2  s  . com*/

    ILock lock = lockManager.lockAll();
    try {
        Repository repo = null;
        File gitDir = new File(centralRepoDir, ".git"); //$NON-NLS-1$
        try {
            RepositoryBuilder builder = new RepositoryBuilder().setGitDir(gitDir);
            if (bare) {
                builder.setBare();
            }
            repo = builder.build();
            repo.create();
        } finally {
            RepositoryUtil.closeQuietly(repo);
        }

        File tempGitDir = new File(new File(reposDir, CENTRAL_REPO_NAME + "_temp"), ".git"); //$NON-NLS-1$ //$NON-NLS-2$
        Repository tempRepo = null;
        try {
            tempRepo = Git.cloneRepository().setURI(gitDir.toURI().toString()).setDirectory(tempGitDir).call()
                    .getRepository();
            Git git = Git.wrap(tempRepo);
            PersonIdent ident = new PersonIdent(user.getLoginName(), user.getEmail());
            git.commit().setAuthor(ident).setCommitter(ident).setMessage("init").call(); //$NON-NLS-1$
            git.push().call();
        } finally {
            RepositoryUtil.closeQuietly(tempRepo);
        }
        FileUtils.forceDelete(tempGitDir.getParentFile());
    } finally {
        lockManager.unlock(lock);
    }

    return getCentralRepository(bare);
}

From source file:de.fraunhofer.ipa.CobPipelineProperty.java

License:Open Source License

@JavaScriptMethod
public JSONObject doGeneratePipeline() throws Exception {
    JSONObject response = new JSONObject();
    String message = "";

    // wait until config.xml is updated
    File configFile = new File(Jenkins.getInstance().getRootDir(), "users/" + user.getId() + "/config.xml");
    Date mod = new Date();
    Long start = mod.getTime();/*from w  ww  .  j a v  a  2  s. c om*/
    Date now;
    do {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        if (configFile.exists()) {
            try {
                mod = new Date(configFile.lastModified());
            } catch (Exception ex) {
            }
        }

        now = new Date();
        if (now.getTime() - start > 30000) {
            throw new Exception("Timeout");
        }
    } while (start.equals(mod.getTime()) || now.getTime() - mod.getTime() > 15000);

    try {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("user_name", user.getId());
        data.put("server_name", getMasterName());
        data.put("email", this.email);
        data.put("committer_email_enabled", this.committerEmailEnabled);
        Map<String, Object> repos = new HashMap<String, Object>();
        for (RootRepository rootRepo : this.rootRepos) {
            Map<String, Object> repo = new HashMap<String, Object>();
            repo.put("type", rootRepo.type);
            repo.put("url", rootRepo.url);
            repo.put("version", rootRepo.branch);
            repo.put("poll", rootRepo.poll);
            repo.put("ros_distro", rootRepo.getRosDistro());
            repo.put("prio_ubuntu_distro", rootRepo.getPrioUbuntuDistro());
            repo.put("prio_arch", rootRepo.getPrioArch());
            repo.put("regular_matrix", rootRepo.getMatrixDistroArch());
            repo.put("jobs", rootRepo.getJobs());
            repo.put("robots", rootRepo.robot);

            Map<String, Object> deps = new HashMap<String, Object>();
            for (Repository repoDep : rootRepo.getRepoDeps()) {
                Map<String, Object> dep = new HashMap<String, Object>();
                if (repoDep.fork.equals("") || repoDep.fork.equals(null)) {
                    response.put("message", Messages.Pipeline_GenerationNoFork(rootRepo.fullName));
                    response.put("status",
                            "<font color=\"red\">" + Messages.Pipeline_GenerationFailure() + "</font>");
                    return response;
                }
                if (repoDep.name.equals("") || repoDep.name.equals(null)) {
                    response.put("message", Messages.Pipeline_GenerationNoDepName(rootRepo.fullName));
                    response.put("status",
                            "<font color=\"red\">" + Messages.Pipeline_GenerationFailure() + "</font>");
                    return response;
                }
                if (repoDep.branch.equals("") || repoDep.branch.equals(null)) {
                    response.put("message", Messages.Pipeline_GenerationNoBranch(rootRepo.fullName));
                    response.put("status",
                            "<font color=\"red\">" + Messages.Pipeline_GenerationFailure() + "</font>");
                    return response;
                }
                dep.put("type", repoDep.type);
                dep.put("url", repoDep.url);
                dep.put("version", repoDep.branch);
                dep.put("poll", repoDep.poll);
                dep.put("test", repoDep.test);
                deps.put(repoDep.name, dep);
            }
            repo.put("dependencies", deps);

            repos.put(rootRepo.fullName, repo);
        }
        data.put("repositories", repos);
        Yaml yaml = new Yaml();
        yaml.dump(data, getPipelineConfigFile());
        LOGGER.log(Level.INFO, "Created " + getPipelineConfigFilePath().getAbsolutePath()); //TODO

    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Failed to save " + getPipelineConfigFilePath().getAbsolutePath(), e); //TODO
    }

    // clone/pull configuration repository
    File configRepoFolder = new File(Jenkins.getInstance()
            .getDescriptorByType(CobPipelineProperty.DescriptorImpl.class).getConfigFolder(), "jenkins_config");
    String configRepoURL = "git@github.com:" + Jenkins.getInstance()
            .getDescriptorByType(CobPipelineProperty.DescriptorImpl.class).getPipelineReposOwner()
            + "/jenkins_config.git";
    Git git = new Git(new FileRepository(configRepoFolder + "/.git"));

    // check if configuration repository exists
    if (!configRepoFolder.isDirectory()) {
        try {
            Git.cloneRepository().setURI(configRepoURL).setDirectory(configRepoFolder).call();
            LOGGER.log(Level.INFO, "Successfully cloned configuration repository from " + configRepoURL); //TODO
        } catch (Exception ex) {
            LOGGER.log(Level.WARNING, "Failed to clone configuration repository", ex); //TODO
        }
    } else {
        try {
            git.pull().call();
            LOGGER.log(Level.INFO, "Successfully pulled configuration repository from " + configRepoURL); //TODO
        } catch (Exception ex) {
            LOGGER.log(Level.WARNING, "Failed to pull configuration repository", ex); //TODO
        }
    }

    // copy pipeline-config.yaml into repository
    File configRepoFile = new File(configRepoFolder, getMasterName() + "/" + user.getId() + "/");
    if (!configRepoFile.isDirectory())
        configRepoFile.mkdirs();
    String[] cpCommand = { "cp", "-f", getPipelineConfigFilePath().getAbsolutePath(),
            configRepoFile.getAbsolutePath() };

    Runtime rt = Runtime.getRuntime();
    Process proc;
    BufferedReader readIn, readErr;
    String s, feedback;
    proc = rt.exec(cpCommand);
    readIn = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    readErr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
    feedback = "";
    while ((s = readErr.readLine()) != null)
        feedback += s + "\n";
    if (feedback.length() != 0) {
        LOGGER.log(Level.WARNING, "Failed to copy " + getPipelineConfigFilePath().getAbsolutePath()
                + " to config repository: " + configRepoFile.getAbsolutePath()); //TODO
        LOGGER.log(Level.WARNING, feedback); //TODO
    } else {
        LOGGER.log(Level.INFO, "Successfully copied " + getPipelineConfigFilePath().getAbsolutePath()
                + " to config repository: " + configRepoFile.getAbsolutePath()); //TODO
    }

    // add
    try {
        git.add().addFilepattern(getMasterName() + "/" + user.getId() + "/pipeline_config.yaml").call();
        LOGGER.log(Level.INFO, "Successfully added file to configuration repository"); //TODO
    } catch (Exception e) {
        LOGGER.log(Level.WARNING,
                "Failed to add " + getMasterName() + "/" + user.getId() + "/pipeline_config.yaml", e); //TODO
    }

    // commit
    try {
        git.commit().setMessage("Updated pipeline configuration for " + user.getId()).call();
    } catch (Exception e) {
        LOGGER.log(Level.WARNING,
                "Failed to commit change in " + getMasterName() + "/" + user.getId() + "/pipeline_config.yaml",
                e); //TODO
    }

    // push
    try {
        git.push().call();
        LOGGER.log(Level.INFO, "Successfully pushed configuration repository"); //TODO
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Failed to push configuration repository", e); //TODO
    }

    // trigger Python job generation script
    String[] generationCall = {
            new File(Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class)
                    .getConfigFolder(), "jenkins_setup/scripts/generate_buildpipeline.py").toString(),
            "-m", Jenkins.getInstance().getRootUrl(), "-l",
            Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class)
                    .getJenkinsLogin(),
            "-p",
            Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class)
                    .getJenkinsPassword(),
            "-c",
            Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class)
                    .getConfigFolder(),
            "-o",
            Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class)
                    .getPipelineReposOwner(),
            "-t", Jenkins.getInstance().getDescriptorByType(CobPipelineProperty.DescriptorImpl.class)
                    .getTarballLocation(),
            "-u", user.getId() };

    proc = rt.exec(generationCall);
    readIn = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    readErr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
    feedback = "";
    while ((s = readErr.readLine()) != null)
        feedback += s + "\n";
    if (feedback.length() != 0) {
        LOGGER.log(Level.WARNING, "Failed to generate pipeline: "); //TODO
        LOGGER.log(Level.WARNING, feedback);
        response.put("message", feedback.replace("\n", "<br/>"));
        response.put("status", "<font color=\"red\">" + Messages.Pipeline_GenerationFailure() + "</font>");
        return response;
    } else {
        feedback = "";
        while ((s = readIn.readLine()) != null)
            feedback += s + "\n";
        if (feedback.length() != 0) {
            LOGGER.log(Level.INFO, feedback);
            LOGGER.log(Level.INFO, "Successfully generated pipeline"); //TODO
            message += feedback;
        }
    }
    response.put("message", message.replace("\n", "<br/>"));
    response.put("status", "<font color=\"green\">" + Messages.Pipeline_GenerationSuccess() + "</font>");
    return response;
}

From source file:es.logongas.openshift.ant.impl.OpenShiftUtil.java

License:Apache License

public void gitPushApplication(String serverUrl, String userName, String password, String domainName,
        String applicationName, String privateKeyFile, String path) throws GitAPIException, IOException {

    SshSessionFactory.setInstance(new CustomConfigSessionFactory(privateKeyFile));

    Git git = Git.open(new File(path));

    PushCommand push = git.push();
    push.setProgressMonitor(new TextProgressMonitor());
    LOGGER.info("Finalizado push");
    LOGGER.info("Mostrando resultados");
    Iterable<PushResult> pushResults = push.call();
    for (PushResult pushResult : pushResults) {
        LOGGER.info(pushResult.getMessages());
    }//ww w.  j ava  2 s . c  o  m

}

From source file:facade.GitFacade.java

public static String pushRepo(Repository repository, String username, String password) throws GitAPIException {
    Git git = new Git(repository);
    CredentialsProvider provider = new UsernamePasswordCredentialsProvider(username, password);
    PushCommand pushCommand = git.push();
    pushCommand.setCredentialsProvider(provider).setForce(true).setPushAll();

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

    if (!result.iterator().next().getMessages().isEmpty())
        return result.iterator().next().getMessages();
    else/* w w w . jav a2s .  c o m*/
        return "OK";

}

From source file:fi.otavanopisto.changelogger.Changelogger.java

private static void prependLine(String line, String message) throws IOException, GitAPIException {
    FileRepositoryBuilder frBuilder = new FileRepositoryBuilder();
    Repository repository = frBuilder.setGitDir(new File("./.git")).readEnvironment().build();
    Git git = new Git(repository);

    git.reset().setMode(ResetCommand.ResetType.HARD).call();
    git.clean().call();//from ww  w .j av  a  2s  . c  om
    git.fetch().call();
    git.pull().call();

    File file = new File(CHANGELOG_FILE);
    List<String> lines = FileUtils.readLines(file, Charsets.UTF_8);
    lines.add(0, line);
    FileUtils.writeLines(file, lines);

    git.commit().setMessage(message).setAuthor("Changelogger", "changelogger@otavanopisto.fi").call();

    git.push().call();
}

From source file:fr.treeptik.cloudunit.utils.GitUtils.java

License:Open Source License

/**
 * this method is associate with listGitTagsOfApplication() method
 * which list all tags with index, this is this index which must pass as parammeter of this method
 *
 * @param application//from  ww  w. j  a v a 2 s .  com
 * @param indexChosen
 * @param dockerManagerAddress
 * @param containerGitAddress
 * @return
 * @throws InvalidRemoteException
 * @throws TransportException
 * @throws GitAPIException
 * @throws IOException
 */
public static List<String> resetOnChosenGitTag(Application application, int indexChosen,
        String dockerManagerAddress, String containerGitAddress)
        throws InvalidRemoteException, TransportException, GitAPIException, IOException {
    User user = application.getUser();
    String sshPort = application.getServers().get(0).getSshPort();
    String password = user.getPassword();
    String userNameGit = user.getLogin();
    String dockerManagerIP = dockerManagerAddress.substring(0, dockerManagerAddress.length() - 5);
    String remoteRepository = "ssh://" + userNameGit + "@" + dockerManagerIP + ":" + sshPort
            + containerGitAddress;
    File gitworkDir = Files.createTempDirectory("clone").toFile();
    CloneCommand clone = Git.cloneRepository();
    clone.setDirectory(gitworkDir);

    CredentialsProvider credentialsProvider = configCredentialsForGit(userNameGit, password);
    clone.setCredentialsProvider(credentialsProvider);
    clone.setURI(remoteRepository);
    Git git = clone.call();

    ListTagCommand listTagCommand = git.tagList();
    List<Ref> listRefs = listTagCommand.call();

    Ref ref = listRefs.get(indexChosen);

    ResetCommand resetCommand = git.reset();
    resetCommand.setMode(ResetType.HARD);
    resetCommand.setRef(ref.getName());
    resetCommand.call();

    PushCommand pushCommand = git.push();
    pushCommand.setCredentialsProvider(credentialsProvider);
    pushCommand.setForce(true);

    List<PushResult> listPushResults = (List<PushResult>) pushCommand.call();
    List<String> listPushResultsMessages = new ArrayList<>();
    for (PushResult pushResult : listPushResults) {
        listPushResultsMessages.add(pushResult.getMessages());
    }
    FilesUtils.deleteDirectory(gitworkDir);
    return listPushResultsMessages;
}

From source file:fr.xebia.workshop.git.GithubRepositoriesCreator.java

License:Apache License

private void processGitRepositoryHandler(Git git, GithubCreateRepositoryRequest createRequest) {
    try {// w w w.  ja va2  s . co m
        RevCommit revCommit = git.log().call().iterator().next();

        //call delegate
        createRequest.getGitRepositoryHandler().updateGitRepository(git, createRequest);
        logger.info("Local repository is pushing on remote {}", createRequest.getGithubRepositoryUrl());
        git.push().setCredentialsProvider(createRequest.getCredentialsProvider())
                .setRemote(createRequest.getGithubRepositoryUrl()).call();
        git.reset().setRef(revCommit.getName()).setMode(ResetCommand.ResetType.HARD).call();
    } catch (IOException e) {
        throw new RuntimeException("cannot perform git operation", e);
    } catch (GitAPIException e) {
        throw new RuntimeException("cannot perform git operation", e);
    }
}

From source file:gov.va.isaac.sync.git.SyncServiceGIT.java

License:Apache License

/**
 * @throws AuthenticationException //from w  w  w .j a v a  2  s .  c o m
 * @see gov.va.isaac.interfaces.sync.ProfileSyncI#linkAndFetchFromRemote(java.io.File, java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public void linkAndFetchFromRemote(String remoteAddress, String username, String password)
        throws IllegalArgumentException, IOException, AuthenticationException {
    log.info("linkAndFetchFromRemote called - folder: {}, remoteAddress: {}, username: {}", localFolder,
            remoteAddress, username);
    try {
        File gitFolder = new File(localFolder, ".git");
        Repository r = new FileRepository(gitFolder);

        if (!gitFolder.isDirectory()) {
            log.debug("Root folder does not contain a .git subfolder.  Creating new git repository.");
            r.create();
        }

        relinkRemote(remoteAddress, username, password);

        Git git = new Git(r);

        CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username,
                (password == null ? new char[] {} : password.toCharArray()));

        log.debug("Fetching");
        FetchResult fr = git.fetch().setCheckFetchedObjects(true).setCredentialsProvider(cp).call();
        log.debug("Fetch messages: {}", fr.getMessages());

        boolean remoteHasMaster = false;
        Collection<Ref> refs = git.lsRemote().setCredentialsProvider(cp).call();
        for (Ref ref : refs) {
            if ("refs/heads/master".equals(ref.getName())) {
                remoteHasMaster = true;
                log.debug("Remote already has 'heads/master'");
                break;
            }
        }

        if (remoteHasMaster) {
            //we need to fetch and (maybe) merge - get onto origin/master.

            log.debug("Fetching from remote");
            String fetchResult = git.fetch().setCredentialsProvider(cp).call().getMessages();
            log.debug("Fetch Result: {}", fetchResult);

            log.debug("Resetting to origin/master");
            git.reset().setMode(ResetType.MIXED).setRef("origin/master").call();

            //Get the files from master that we didn't have in our working folder
            log.debug("Checking out missing files from origin/master");
            for (String missing : git.status().call().getMissing()) {
                log.debug("Checkout {}", missing);
                git.checkout().addPath(missing).call();
            }

            for (String newFile : makeInitialFilesAsNecessary(localFolder)) {
                log.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding " + newFile).setAuthor(username, "42").call();

                for (PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                    log.debug("Push Message: {}", pr.getMessages());
                }
            }
        } else {
            //just push
            //make sure we have something to push
            for (String newFile : makeInitialFilesAsNecessary(localFolder)) {
                log.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding readme file").setAuthor(username, "42").call();
            }

            log.debug("Pushing repository");
            for (PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                log.debug("Push Result: {}", pr.getMessages());
            }
        }

        log.info("linkAndFetchFromRemote Complete.  Current status: " + statusToString(git.status().call()));
    } catch (TransportException te) {
        if (te.getMessage().contains("Auth fail")) {
            log.info("Auth fail", te);
            throw new AuthenticationException("Auth fail");
        } else {
            log.error("Unexpected", te);
            throw new IOException("Internal error", te);
        }
    } catch (GitAPIException e) {
        log.error("Unexpected", e);
        throw new IOException("Internal error", e);
    }
}