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:com.microsoft.gittf.core.tasks.pendDiff.CheckinAnalysisChangeCollectionTest.java

License:Open Source License

private void add(String folder) throws NoFilepatternException, GitAPIException {
    Git git = new Git(repository);

    git.add().setUpdate(false).addFilepattern(folder).call();
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.egit.dialogs.GitBuildDefinitionDialog.java

License:Open Source License

@Override
protected SelectionListener getCreateButtonSelectionListener(final Shell shell) {
    return new SelectionAdapter() {
        @Override//from  w ww .j a  v  a 2  s  .c  o  m
        public void widgetSelected(final SelectionEvent e) {
            final CreateGitBuildConfigurationWizard wizard = new CreateGitBuildConfigurationWizard();
            updateAndVerifyBuildDefinition(true);

            wizard.init(buildDefinition);

            final WizardDialog dialog = new WizardDialog(getShell(), wizard);
            final int rc = dialog.open();

            if (rc == IDialogConstants.OK_ID) {
                localBuildProjectCreated = true;

                /*
                 * TFSBuild proj/resp files are created in a cloned
                 * repository, but they could be outside of projects
                 * imported into the Eclipse workspace.
                 */
                final List<IResource> resources = new ArrayList<IResource>();

                final LocationInfo buildProjectLocation = new LocationInfo(
                        new Path(getBuildProjectAbsolutePath()));
                if (buildProjectLocation.isPotentialSubProjectResource()) {
                    resources.add(buildProjectLocation.getSubProjectResource(false));
                }

                final LocationInfo buildResponceLocation = new LocationInfo(
                        new Path(getBuildResponseAbsolutePath()));
                if (buildResponceLocation.isPotentialSubProjectResource()) {
                    resources.add(buildResponceLocation.getSubProjectResource(false));
                }

                if (resources.size() > 0) {
                    final AddToIndexOperation op = new AddToIndexOperation(resources);
                    try {
                        op.execute(new NullProgressMonitor());
                    } catch (final CoreException ex) {
                        log.error("Error adding build files to index", ex); //$NON-NLS-1$
                    }

                } else {
                    final GitRepository repository = getBuildProjectRepository();
                    final Git git = new Git(repository.getLocalRepository());

                    final AddCommand addCommand = git.add();
                    addCommand.addFilepattern(getBuildProjectRelativePath());
                    addCommand.addFilepattern(getBuildResponseRelativePath());

                    try {
                        addCommand.call();
                    } catch (final Exception ex) {
                        log.error("Error adding build files to index", ex); //$NON-NLS-1$
                    }
                }

                checkForBuildFileExistence(true);
                validate();
            }
        }
    };
}

From source file:com.mortardata.project.EmbeddedMortarProject.java

License:Apache License

void setupGitMirror(Git gitMirror, CredentialsProvider cp, String committer)
        throws IOException, GitAPIException {

    // checkout master as base branch
    this.gitUtil.checkout(gitMirror, "master");

    // touch .gitkeep to ensure we have something in the repo
    File gitKeep = new File(gitMirror.getRepository().getWorkTree(), ".gitkeep");
    logger.debug("Touching " + gitKeep);
    Files.touch(gitKeep);//  w ww  . j  a v a2  s. c  o m

    // add it
    logger.debug("git add .");
    gitMirror.add().addFilepattern(".").call();

    // commit it
    logger.debug("git commit");
    gitMirror.commit().setCommitter(committer, committer).setMessage("mortar development initial commit")
            .call();

    // push it
    logger.info("Pushing initialization commit to mortar github mirror repo " + getGitMirrorURL());
    gitMirror.push().setRemote(getGitMirrorURL()).setCredentialsProvider(cp).setRefSpecs(new RefSpec("master"))
            .call();
}

From source file:com.mortardata.project.EmbeddedMortarProject.java

License:Apache License

String syncEmbeddedProjectWithMirror(Git gitMirror, CredentialsProvider cp, String targetBranch,
        String committer) throws GitAPIException, IOException {

    // checkout the target branch
    gitUtil.checkout(gitMirror, targetBranch);

    // clear out the mirror directory contents (except .git and .gitkeep)
    File localBackingGitRepoPath = gitMirror.getRepository().getWorkTree();
    for (File f : FileUtils.listFilesAndDirs(localBackingGitRepoPath,
            FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter(".gitkeep")),
            FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter(".git")))) {
        if (!f.equals(localBackingGitRepoPath)) {
            logger.debug("Deleting existing mirror file" + f.getAbsolutePath());
            FileUtils.deleteQuietly(f);/*from ww w.  ja  v a  2  s .c  o  m*/
        }
    }

    // copy everything from the embedded project
    List<File> manifestFiles = getFilesAndDirsInManifest();
    for (File fileToCopy : manifestFiles) {
        if (!fileToCopy.exists()) {
            logger.warn("Can't find file or directory " + fileToCopy.getCanonicalPath()
                    + " referenced in manifest file.  Ignoring.");
        } else if (fileToCopy.isDirectory()) {
            FileUtils.copyDirectoryToDirectory(fileToCopy, localBackingGitRepoPath);
        } else {
            FileUtils.copyFileToDirectory(fileToCopy, localBackingGitRepoPath);
        }
    }

    // add everything
    logger.debug("git add .");
    gitMirror.add().addFilepattern(".").call();

    // remove missing files (deletes)
    logger.debug("git add -u .");
    gitMirror.add().setUpdate(true).addFilepattern(".").call();

    // commit it
    logger.debug("git commit");
    RevCommit revCommit = gitMirror.commit().setCommitter(committer, committer)
            .setMessage("mortar development snapshot commit").call();
    return ObjectId.toString(revCommit);
}

From source file:com.osbitools.ws.shared.prj.utils.GitUtils.java

License:Open Source License

public static String commitFile(Git git, String fname, String comment, String user) throws WsSrvException {

    AddCommand add = git.add();
    try {//ww  w.  j  av a2s . c  o m
        add.addFilepattern(fname).call();
    } catch (GitAPIException e) {
        throw new WsSrvException(239, e);
    }

    CommitCommand commit = git.commit();
    try {
        RevCommit rev = commit.setMessage(comment).setCommitter(user, "").call();
        return rev.getName();
    } catch (GitAPIException e) {
        throw new WsSrvException(240, e);
    }
}

From source file:com.passgit.app.PassGit.java

License:Open Source License

public void gitAdd(PathModel pathModel) {
    Path relativePath = rootPath.relativize(pathModel.getPath());
    System.out.println(relativePath.toString());
    Git git = new Git(gitRepository);
    try {// www. ja  v a  2  s. c  o  m
        git.add().addFilepattern(relativePath.toString()).call();
    } catch (GitAPIException ex) {
        Logger.getLogger(PassGit.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

private void importToGITRepo(RepoDetail repodetail, ApplicationInfo appInfo, File appDir) throws Exception {
    if (debugEnabled) {
        S_LOGGER.debug("Entering Method  SCMManagerImpl.importToGITRepo()");
    }//from   w w  w. j  av a 2  s  .  co  m
    boolean gitExists = false;
    if (new File(appDir.getPath() + FORWARD_SLASH + DOT + GIT).exists()) {
        gitExists = true;
    }
    try {
        //For https and ssh
        additionalAuthentication(repodetail.getPassPhrase());

        CredentialsProvider cp = new UsernamePasswordCredentialsProvider(repodetail.getUserName(),
                repodetail.getPassword());

        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(appDir).readEnvironment().findGitDir().build();
        String dirPath = appDir.getPath();
        File gitignore = new File(dirPath + GITIGNORE_FILE);
        gitignore.createNewFile();
        if (gitignore.exists()) {
            String contents = FileUtils.readFileToString(gitignore);
            if (!contents.isEmpty() && !contents.contains(DO_NOT_CHECKIN_DIR)) {
                String source = NEWLINE + DO_NOT_CHECKIN_DIR + NEWLINE;
                OutputStream out = new FileOutputStream((dirPath + GITIGNORE_FILE), true);
                byte buf[] = source.getBytes();
                out.write(buf);
                out.close();
            } else if (contents.isEmpty()) {
                String source = NEWLINE + DO_NOT_CHECKIN_DIR + NEWLINE;
                OutputStream out = new FileOutputStream((dirPath + GITIGNORE_FILE), true);
                byte buf[] = source.getBytes();
                out.write(buf);
                out.close();
            }
        }

        Git git = new Git(repository);

        InitCommand initCommand = Git.init();
        initCommand.setDirectory(appDir);
        git = initCommand.call();

        AddCommand add = git.add();
        add.addFilepattern(".");
        add.call();

        CommitCommand commit = git.commit().setAll(true);
        commit.setMessage(repodetail.getCommitMessage()).call();
        StoredConfig config = git.getRepository().getConfig();

        config.setString(REMOTE, ORIGIN, URL, repodetail.getRepoUrl());
        config.setString(REMOTE, ORIGIN, FETCH, REFS_HEADS_REMOTE_ORIGIN);
        config.setString(BRANCH, MASTER, REMOTE, ORIGIN);
        config.setString(BRANCH, MASTER, MERGE, REF_HEAD_MASTER);
        config.save();

        try {
            PushCommand pc = git.push();
            pc.setCredentialsProvider(cp).setForce(true);
            pc.setPushAll().call();
        } catch (Exception e) {
            git.getRepository().close();
            PomProcessor appPomProcessor = new PomProcessor(new File(appDir, appInfo.getPhrescoPomFile()));
            appPomProcessor.removeProperty(Constants.POM_PROP_KEY_SRC_REPO_URL);
            appPomProcessor.save();
            throw e;
        }

        if (appInfo != null) {
            updateSCMConnection(appInfo, repodetail.getRepoUrl());
        }
        git.getRepository().close();
    } catch (Exception e) {
        Exception s = e;
        resetLocalCommit(appDir, gitExists, e);
        throw s;
    }
}

From source file:com.romanenco.gitt.git.GitHelper.java

License:Open Source License

/**
 * Current branch/tag name./*from w  w w . j ava2  s  . c  o m*/
 * 
 * @param path
 * @return
 */
public static String currentBranchName(String localPath) {
    try {
        Git git = Git.open(new File(localPath));

        String name = git.getRepository().getBranch();

        if (name.length() == 40) {
            //detached head processing
            Map<String, Ref> refs = git.add().getRepository().getAllRefs();
            Iterator<Entry<String, Ref>> iter = refs.entrySet().iterator();
            while (iter.hasNext()) {
                Entry<String, Ref> entry = iter.next();
                if (entry.getValue().getObjectId().getName().equals(name)) {
                    if (!entry.getKey().equals("HEAD")) { // so bad, will change later...
                        name = entry.getKey();
                        break;
                    }
                }
            }
        }
        return nameReFormat(name);
    } catch (IOException e) {
        GittApp.saveErrorTrace(e);
    }
    return null;
}

From source file:com.sebastian_daschner.asciiblog.business.source.control.GitExtractorTest.java

License:Apache License

private void changeAndRenameFile() throws IOException, GitAPIException {
    final Git git = Git.open(gitCloneDirectory);
    git.pull().setRemote("origin").setRemoteBranchName("master").call();

    try (FileWriter writer = new FileWriter(file2, true)) {
        writer.append("\nchanged");
    }/*  w  w w.  j  a v  a2  s .  co  m*/

    if (!file2.renameTo(file2.toPath().resolveSibling("file3.adoc").toFile()))
        throw new IOException("Could not rename file2 to file3");

    git.add().setUpdate(true).addFilepattern(".").call();
    git.add().addFilepattern(".").call();
    git.commit().setMessage("changed file2 and renamed to file3").call();
    git.push().setRemote("origin").add("master").call();
    git.close();
}

From source file:com.sebastian_daschner.asciiblog.business.source.control.GitExtractorTest.java

License:Apache License

private void addTestCommits() throws IOException, GitAPIException {
    final Git git = Git.open(gitCloneDirectory);

    try (FileWriter writer = new FileWriter(file1, true)) {
        writer.write("hello world");
    }//ww  w .j  a va2s  .c  o m
    git.add().addFilepattern(".").call();
    git.commit().setMessage("updated").call();

    try (FileWriter writer = new FileWriter(file1, true)) {
        writer.append("\nhello world");
    }
    git.add().addFilepattern(".").call();
    git.commit().setMessage("updated").call();

    try (FileWriter writer = new FileWriter(file2, true)) {
        writer.write("hi world");
    }
    git.add().addFilepattern(".").call();
    git.commit().setMessage("updated").call();
    git.push().setRemote("origin").add("master").call();

    git.close();
}