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

License:Open Source License

private CommitCherryPickResult tryResolveConflict(ILockedRepository repo, String branchName, String path,
        PageVersion pageVersion, String targetBranch, Set<CommitCherryPickConflictResolve> conflictResolves,
        User user, Locale locale) throws IOException, GitAPIException {

    File workingDir = RepositoryUtil.getWorkingDir(repo.r());
    File pagesDir = new File(workingDir, DocumentrConstants.PAGES_DIR_NAME);
    File workingFile = Util.toFile(pagesDir, path + DocumentrConstants.PAGE_SUFFIX);

    String resolveText = getCherryPickConflictResolveText(conflictResolves, targetBranch,
            pageVersion.getCommitName());
    CommitCherryPickResult result;/*  ww w.j  a  v a 2s  .  c  o m*/
    if (resolveText != null) {
        if (!CONFLICT_MARKERS_RE.matcher("\n" + resolveText).matches()) { //$NON-NLS-1$
            FileUtils.writeStringToFile(workingFile, resolveText, 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 + DocumentrConstants.PAGE_SUFFIX) //$NON-NLS-1$
                    .call();
            result = new CommitCherryPickResult(pageVersion, CommitCherryPickResult.Status.OK);
        } else {
            result = new CommitCherryPickResult(pageVersion, resolveText);
        }
    } else {
        String text = FileUtils.readFileToString(workingFile, Charsets.UTF_8);
        text = StringUtils.replace(text, "<<<<<<< OURS", //$NON-NLS-1$
                "<<<<<<< " + messageSource.getMessage("targetBranchX", new Object[] { targetBranch }, locale)); //$NON-NLS-1$ //$NON-NLS-2$
        text = StringUtils.replace(text, ">>>>>>> THEIRS", //$NON-NLS-1$
                ">>>>>>> " + messageSource.getMessage("sourceBranchX", new Object[] { branchName }, locale)); //$NON-NLS-1$ //$NON-NLS-2$
        result = new CommitCherryPickResult(pageVersion, text);
    }
    return result;
}

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

License:Open Source License

private MergeConflict savePageInternal(String projectName, String branchName, String path, String suffix,
        Page page, String baseCommit, String rootDir, User user, ILockedRepository repo, boolean push)
        throws IOException, GitAPIException {

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

    String headCommit = CommitUtils.getHead(repo.r()).getName();
    if ((baseCommit != null) && headCommit.equals(baseCommit)) {
        baseCommit = null;//w w  w  .  j a v  a2s . c  o  m
    }

    String editBranchName = "_edit_" + String.valueOf((long) (Math.random() * Long.MAX_VALUE)); //$NON-NLS-1$
    if (baseCommit != null) {
        git.branchCreate().setName(editBranchName).setStartPoint(baseCommit).call();

        git.checkout().setName(editBranchName).call();
    }

    Map<String, Object> metaMap = new HashMap<String, Object>();
    metaMap.put(TITLE, page.getTitle());
    metaMap.put(CONTENT_TYPE, page.getContentType());
    if (!page.getTags().isEmpty()) {
        metaMap.put(TAGS, page.getTags());
    }
    metaMap.put(VIEW_RESTRICTION_ROLE, page.getViewRestrictionRole());
    Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
    String json = gson.toJson(metaMap);
    File workingDir = RepositoryUtil.getWorkingDir(repo.r());
    File pagesDir = new File(workingDir, rootDir);
    File workingFile = Util.toFile(pagesDir, path + DocumentrConstants.META_SUFFIX);
    FileUtils.write(workingFile, json, Charsets.UTF_8);

    PageData pageData = page.getData();
    if (pageData != null) {
        workingFile = Util.toFile(pagesDir, path + suffix);
        FileUtils.writeByteArrayToFile(workingFile, pageData.getData());
    }

    AddCommand addCommand = git.add().addFilepattern(rootDir + "/" + path + DocumentrConstants.META_SUFFIX); //$NON-NLS-1$
    if (pageData != null) {
        addCommand.addFilepattern(rootDir + "/" + path + suffix); //$NON-NLS-1$
    }
    addCommand.call();

    PersonIdent ident = new PersonIdent(user.getLoginName(), user.getEmail());
    git.commit().setAuthor(ident).setCommitter(ident).setMessage(rootDir + "/" + path + suffix).call(); //$NON-NLS-1$

    MergeConflict conflict = null;

    if (baseCommit != null) {
        git.rebase().setUpstream(branchName).call();

        if (repo.r().getRepositoryState() != RepositoryState.SAFE) {
            String text = FileUtils.readFileToString(workingFile, Charsets.UTF_8);
            conflict = new MergeConflict(text, headCommit);

            git.rebase().setOperation(RebaseCommand.Operation.ABORT).call();
        }

        git.checkout().setName(branchName).call();

        if (conflict == null) {
            git.merge().include(repo.r().resolve(editBranchName)).call();
        }

        git.branchDelete().setBranchNames(editBranchName).setForce(true).call();
    }

    if (push && (conflict == null)) {
        git.push().call();
    }

    page.setParentPagePath(getParentPagePath(path, repo.r()));

    if (conflict == null) {
        PageUtil.updateProjectEditTime(projectName);
    }

    return conflict;
}

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

License:Open Source License

@Override
public void relocatePage(final String projectName, final String branchName, final String path,
        String newParentPagePath, User user) throws IOException {

    Assert.hasLength(projectName);/*from w w  w . j a v  a2  s.  c om*/
    Assert.hasLength(branchName);
    Assert.hasLength(path);
    Assert.hasLength(newParentPagePath);
    Assert.notNull(user);
    // check if pages exist by trying to load them
    getPage(projectName, branchName, path, false);
    getPage(projectName, branchName, newParentPagePath, false);

    ILockedRepository repo = null;
    List<String> oldPagePaths;
    List<String> deletedPagePaths;
    List<String> newPagePaths;
    List<PagePathChangedEvent> pagePathChangedEvents;
    try {
        repo = globalRepositoryManager.getProjectBranchRepository(projectName, branchName);
        String pageName = path.contains("/") ? StringUtils.substringAfterLast(path, "/") : path; //$NON-NLS-1$ //$NON-NLS-2$
        final String newPagePath = newParentPagePath + "/" + pageName; //$NON-NLS-1$

        File workingDir = RepositoryUtil.getWorkingDir(repo.r());

        File oldSubPagesDir = Util.toFile(new File(workingDir, DocumentrConstants.PAGES_DIR_NAME), path);
        oldPagePaths = listPagePaths(oldSubPagesDir, true);
        oldPagePaths = Lists.newArrayList(Lists.transform(oldPagePaths, new Function<String, String>() {
            @Override
            public String apply(String p) {
                return path + "/" + p; //$NON-NLS-1$
            }
        }));
        oldPagePaths.add(path);

        File deletedPagesSubDir = Util.toFile(new File(workingDir, DocumentrConstants.PAGES_DIR_NAME),
                newPagePath);
        deletedPagePaths = listPagePaths(deletedPagesSubDir, true);
        deletedPagePaths = Lists.newArrayList(Lists.transform(deletedPagePaths, new Function<String, String>() {
            @Override
            public String apply(String p) {
                return newPagePath + "/" + p; //$NON-NLS-1$
            }
        }));
        deletedPagePaths.add(newPagePath);

        Git git = Git.wrap(repo.r());
        AddCommand addCommand = git.add();

        for (String dirName : Sets.newHashSet(DocumentrConstants.PAGES_DIR_NAME,
                DocumentrConstants.ATTACHMENTS_DIR_NAME)) {
            File dir = new File(workingDir, dirName);

            File newSubPagesDir = Util.toFile(dir, newPagePath);
            if (newSubPagesDir.exists()) {
                git.rm().addFilepattern(dirName + "/" + newPagePath).call(); //$NON-NLS-1$
            }
            File newPageFile = Util.toFile(dir, newPagePath + DocumentrConstants.PAGE_SUFFIX);
            if (newPageFile.exists()) {
                git.rm().addFilepattern(dirName + "/" + newPagePath + DocumentrConstants.PAGE_SUFFIX).call(); //$NON-NLS-1$
            }
            File newMetaFile = Util.toFile(dir, newPagePath + DocumentrConstants.META_SUFFIX);
            if (newMetaFile.exists()) {
                git.rm().addFilepattern(dirName + "/" + newPagePath + DocumentrConstants.META_SUFFIX).call(); //$NON-NLS-1$
            }

            File newParentPageDir = Util.toFile(dir, newParentPagePath);
            File subPagesDir = Util.toFile(dir, path);
            if (subPagesDir.exists()) {
                FileUtils.copyDirectoryToDirectory(subPagesDir, newParentPageDir);
                git.rm().addFilepattern(dirName + "/" + path).call(); //$NON-NLS-1$
                addCommand.addFilepattern(dirName + "/" + newParentPagePath + "/" + pageName); //$NON-NLS-1$ //$NON-NLS-2$
            }
            File pageFile = Util.toFile(dir, path + DocumentrConstants.PAGE_SUFFIX);
            if (pageFile.exists()) {
                FileUtils.copyFileToDirectory(pageFile, newParentPageDir);
                git.rm().addFilepattern(dirName + "/" + path + DocumentrConstants.PAGE_SUFFIX).call(); //$NON-NLS-1$
                addCommand.addFilepattern(
                        dirName + "/" + newParentPagePath + "/" + pageName + DocumentrConstants.PAGE_SUFFIX); //$NON-NLS-1$ //$NON-NLS-2$
            }
            File metaFile = Util.toFile(dir, path + DocumentrConstants.META_SUFFIX);
            if (metaFile.exists()) {
                FileUtils.copyFileToDirectory(metaFile, newParentPageDir);
                git.rm().addFilepattern(dirName + "/" + path + DocumentrConstants.META_SUFFIX).call(); //$NON-NLS-1$
                addCommand.addFilepattern(
                        dirName + "/" + newParentPagePath + "/" + pageName + DocumentrConstants.META_SUFFIX); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }

        addCommand.call();
        PersonIdent ident = new PersonIdent(user.getLoginName(), user.getEmail());
        git.commit().setAuthor(ident).setCommitter(ident)
                .setMessage("move " + path + " to " + newParentPagePath + "/" + pageName) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                .call();
        git.push().call();

        newPagePaths = Lists.transform(oldPagePaths, new Function<String, String>() {
            @Override
            public String apply(String p) {
                return newPagePath + StringUtils.removeStart(p, path);
            }
        });

        pagePathChangedEvents = Lists.transform(oldPagePaths, new Function<String, PagePathChangedEvent>() {
            @Override
            public PagePathChangedEvent apply(String oldPath) {
                String newPath = newPagePath + StringUtils.removeStart(oldPath, path);
                return new PagePathChangedEvent(projectName, branchName, oldPath, newPath);
            }
        });

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

    Set<String> allDeletedPagePaths = Sets.newHashSet(oldPagePaths);
    allDeletedPagePaths.addAll(deletedPagePaths);
    eventBus.post(new PagesDeletedEvent(projectName, branchName, allDeletedPagePaths));

    for (String newPath : newPagePaths) {
        eventBus.post(new PageChangedEvent(projectName, branchName, newPath));
    }

    for (PagePathChangedEvent event : pagePathChangedEvents) {
        eventBus.post(event);
    }
}

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);//w  w  w .ja v a2  s .co  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.subscription.SubscriptionStore.java

License:Open Source License

public void subscribe(String projectName, String branchName, String path, User user) throws IOException {
    ILockedRepository repo = null;/*from w  ww .j a  v  a  2s  . c  o  m*/
    try {
        repo = getOrCreateRepository(user);
        String loginName = user.getLoginName();
        String json = BlobUtils.getHeadContent(repo.r(), loginName + SUBSCRIPTIONS_SUFFIX);
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
        Set<Page> pages = Sets.newHashSet();
        if (StringUtils.isNotBlank(json)) {
            List<Page> pagesList = gson.fromJson(json, new TypeToken<List<Page>>() {
            }.getType());
            pages = Sets.newHashSet(pagesList);
        }

        Page page = new Page(projectName, branchName, path);
        if (pages.add(page)) {
            json = gson.toJson(pages);
            File workingDir = RepositoryUtil.getWorkingDir(repo.r());
            File file = new File(workingDir, loginName + SUBSCRIPTIONS_SUFFIX);
            FileUtils.writeStringToFile(file, json, Charsets.UTF_8);

            Git git = Git.wrap(repo.r());
            git.add().addFilepattern(loginName + SUBSCRIPTIONS_SUFFIX).call();
            PersonIdent ident = new PersonIdent(loginName, user.getEmail());
            git.commit().setAuthor(ident).setCommitter(ident).setMessage(loginName + SUBSCRIPTIONS_SUFFIX)
                    .call();
        }
    } catch (GitAPIException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(repo);
    }
}

From source file:de.blizzy.documentr.subscription.SubscriptionStore.java

License:Open Source License

public void unsubscribe(String projectName, String branchName, String path, User user) throws IOException {
    ILockedRepository repo = null;//from w  w w  .  j av a  2 s.  c o m
    try {
        repo = getOrCreateRepository(user);
        String json = BlobUtils.getHeadContent(repo.r(), user.getLoginName() + SUBSCRIPTIONS_SUFFIX);
        if (StringUtils.isNotBlank(json)) {
            Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
            List<Page> pagesList = gson.fromJson(json, new TypeToken<List<Page>>() {
            }.getType());
            Set<Page> pages = Sets.newHashSet(pagesList);
            Page page = new Page(projectName, branchName, path);
            if (pages.remove(page)) {
                Git git = Git.wrap(repo.r());
                if (!pages.isEmpty()) {
                    json = gson.toJson(pages);
                    File workingDir = RepositoryUtil.getWorkingDir(repo.r());
                    File file = new File(workingDir, user.getLoginName() + SUBSCRIPTIONS_SUFFIX);
                    FileUtils.writeStringToFile(file, json, Charsets.UTF_8);
                    git.add().addFilepattern(user.getLoginName() + SUBSCRIPTIONS_SUFFIX).call();
                } else {
                    git.rm().addFilepattern(user.getLoginName() + SUBSCRIPTIONS_SUFFIX).call();
                }

                PersonIdent ident = new PersonIdent(user.getLoginName(), user.getEmail());
                git.commit().setAuthor(ident).setCommitter(ident)
                        .setMessage(user.getLoginName() + SUBSCRIPTIONS_SUFFIX).call();
            }
        }
    } catch (GitAPIException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(repo);
    }
}

From source file:de.blizzy.documentr.system.SystemSettingsStore.java

License:Open Source License

private void storeSettings(Map<String, String> settings, User currentUser) throws IOException {
    log.info("storing system settings"); //$NON-NLS-1$

    ILockedRepository repo = null;/*  w w w. j a va2  s  .  c o  m*/
    try {
        repo = getOrCreateRepository(currentUser);
        File workingDir = RepositoryUtil.getWorkingDir(repo.r());
        File file = new File(workingDir, SETTINGS_FILE_NAME);
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
        String json = gson.toJson(settings);
        FileUtils.writeStringToFile(file, json, Charsets.UTF_8);
        Git git = Git.wrap(repo.r());
        git.add().addFilepattern(SETTINGS_FILE_NAME).call();
        PersonIdent ident = new PersonIdent(currentUser.getLoginName(), currentUser.getEmail());
        git.commit().setAuthor(ident).setCommitter(ident).setMessage(SETTINGS_FILE_NAME).call();
    } catch (GitAPIException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(repo);
    }
}

From source file:de.fkoeberle.autocommit.git.GitRepositoryAdapter.java

License:Open Source License

private void stageForCommit(Git git, FilesToAdd filesToAdd) {
    WorkingTreeIterator workingTreeIterator = IteratorService.createInitialIterator(repository);
    try {/* www .j av a  2  s  .  c o m*/
        AddCommand addCommand = git.add();
        addCommand.addFilepattern(".");
        addCommand.setWorkingTreeIterator(workingTreeIterator);
        addCommand.setUpdate(filesToAdd == FilesToAdd.REMOVED_OR_MODIFIED);
        addCommand.call();
    } catch (NoFilepatternException e) {
        throw new RuntimeException(e);
    }
}

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();//  w  w  w.  ja  v a 2  s .  com
    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:de.ks.blogging.grav.pages.GravPages.java

License:Apache License

public void addCommit(String msg) throws RuntimeException {
    Git git = getGit();
    if (git != null) {
        try {//  w w w .  j av a2  s  .com
            Status status = git.status().call();

            Set<String> modified = status.getModified();
            Set<String> untracked = status.getUntracked();

            AddCommand add = git.add();
            modified.forEach(s -> add.addFilepattern(s));
            untracked.forEach(s -> add.addFilepattern(s));
            add.call();

            CommitCommand commit = git.commit();
            if (msg == null || msg.isEmpty()) {
                commit.setAmend(true);
            } else {
                commit.setMessage(msg);
            }
            RevCommit rev = commit.call();
            log.info("Commited change {} with new rev {}", msg, rev);
        } catch (Exception e) {
            log.error("Could not add and commit ", e);
            throw new RuntimeException(e);
        }
    }
}