Java 类org.eclipse.jgit.api.AddCommand 实例源码

项目:JGitFX    文件:AddMenuItem.java   
/**
 * Adds the files returned from {@link #filePatternGetter} and then calls {@link #updateFiles(List)}
 */
public final void addFiles() {
    try {
        AddCommand addCmd = git.getOrThrow().add();
        // insure add command will add newly staged files
        addCmd.setUpdate(false);

        // add files
        List<String> files = filePatternGetter.get();
        files.forEach(addCmd::addFilepattern);

        addCmd.call();

        updateFiles(files);
    } catch (GitAPIException e) {
        handleGitAPIException(e);
    }
}
项目:JGitFX    文件:CommitDialogBase.java   
/**
 * Adds the files that were selected and commits them. Note: the {@link AddCommand}
 * and {@link CommitCommand} are used in this method. {@link AddCommand#setWorkingTreeIterator(WorkingTreeIterator)}
 * can be configured fia {@link #setWorkingTreeIterator(WorkingTreeIterator)} before calling this method,
 * and the {@code CommitCommand} can be configured via {@link #configureCommitCommand(CommitCommand)}.
 * @return the result of {@link #createResult(DirCache, RevCommit, List)} or null if
 *         a {@link GitAPIException} is thrown.
 */
protected final R addAndCommitSelectedFiles() {
    List<String> selectedFiles = getDialogPane().getSelectedFiles();
    try {
        AddCommand add = getGitOrThrow().add();
        selectedFiles.forEach(add::addFilepattern);
        workingTreeIterator.ifPresent(add::setWorkingTreeIterator);
        DirCache cache = add.call();

        CommitCommand commit = getGitOrThrow().commit();
        configureCommitCommand(commit);
        RevCommit revCommit = commit.call();

        return createResult(cache, revCommit, selectedFiles);
    } catch (GitAPIException e) {
        handleGitAPIException(e);
        return null;
    }
}
项目:che    文件:JGitConnection.java   
@Override
public void add(AddParams params) throws GitException {
  AddCommand addCommand = getGit().add().setUpdate(params.isUpdate());

  List<String> filePatterns = params.getFilePattern();
  if (filePatterns.isEmpty()) {
    filePatterns = AddRequest.DEFAULT_PATTERN;
  }
  filePatterns.forEach(addCommand::addFilepattern);

  try {
    addCommand.call();

    addDeletedFilesToIndexIfNeeded(filePatterns);
  } catch (GitAPIException exception) {
    throw new GitException(exception.getMessage(), exception);
  }
}
项目:fitnesse-git-plugin    文件:GitFileVersionsController.java   
@Override
public VersionInfo makeVersion(FileVersion... fileVersions) throws IOException {
  persistence.makeVersion(fileVersions);
  Repository repository = getRepository(fileVersions[0].getFile());
  Git git = new Git(repository);
  try {
    AddCommand adder = git.add();
    for (FileVersion fileVersion : fileVersions) {
      adder.addFilepattern(getPath(fileVersion.getFile(), repository));
    }
    adder.call();
    commit(git, String.format("[FitNesse] Updated files: %s.", formatFileVersions(fileVersions)), fileVersions[0].getAuthor());
  } catch (GitAPIException e) {
    throw new IOException("Unable to commit changes", e);
  }
  return VersionInfo.makeVersionInfo(fileVersions[0].getAuthor(), fileVersions[0].getLastModificationTime());
}
项目:ghp-maven-plugin    文件:GitHubPages.java   
/**
 * Adds all of the files in the directory to the git repository, commits the changes, and pushes to the remote.
 *
 * @param commitMessage to use in commit
 * @throws MojoExecutionException if the files cannot be added, commited, or pushed
 */
public void update(String commitMessage) throws MojoExecutionException {
    log.info("Adding directory contents to git");
    AddCommand add = git.add();
    if (forEachPath(workingDir, add::addFilepattern)) {
        try {
            add.call();
            git.commit().setMessage(commitMessage).call();
            log.info("Pushing changes to remote branch \"" + branch + "\" at : \"" + uri + "\"");
            git.push().call();
        } catch (GitAPIException e) {
            throw new MojoExecutionException("Could not commit and push changes", e);
        }
    } else {
        log.warn("Nothing to add");
    }
}
项目:kie-wb-common    文件:MavenTestUtils.java   
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());
    }
    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;
}
项目:liveoak    文件:GitHelper.java   
static void addAllAndCommit(Git git, UserProfile user, String commitMsg) throws GitAPIException {
    AddCommand addCommand = git.add()
        .addFilepattern(".")
        .addFilepattern("application.json");

    CommitCommand commitCmd = git.commit();

    if (user != null && user.name() != null && user.email() != null) {
        commitCmd.setCommitter(user.name(), user.email());
    }
    if (commitMsg != null) {
        commitCmd.setMessage(commitMsg);
    }

    GitHandler.commit(() -> {
        addCommand.call();
        return commitCmd.call();
    });
}
项目:oxygen-git-plugin    文件:GitAccess.java   
/**
 * Adds multiple files to the staging area. Preparing the for commit
 * 
 * @param fileNames
 *          - the names of the files to be added
 */
public void addAll(List<FileStatus> files) {

    try {

      RmCommand removeCmd = null;
      AddCommand addCmd = null;

        for (FileStatus file : files) {
            if (file.getChangeType() == GitChangeType.MISSING) {
              if (removeCmd == null) {
                removeCmd = git.rm();
              }
         removeCmd.addFilepattern(file.getFileLocation());
            } else {
              if (addCmd == null) {
                addCmd = git.add();
              }
         addCmd.addFilepattern(file.getFileLocation());
            }
        }

        if (removeCmd != null) {
          removeCmd.call();
        }

        if (addCmd != null) {
          addCmd.call();
        }

        fireFileStateChanged(new ChangeEvent(GitCommand.STAGE, getPaths(files)));
    } catch (GitAPIException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e, e);
        }
    }
}
项目:jgitver    文件:Scenarios.java   
/**
 * Creates a commit in the repo, by modifying the given file.
 * The git commitID will be stored in the scenario in front of the given app identifier. 
 * @param fileName the filename to be touched, added and commited into the repo.
 * @param id the application identifier to use to store the git commitID in front of
 * @return the builder itself to continue building the scenario
 */
public ScenarioBuilder commit(String fileName, String id) {
    File content = new File(scenario.getRepositoryLocation(), fileName);
    try {
        AddCommand add = git.add().addFilepattern(fileName);
        Files.touch(content);
        add.call();
        RevCommit rc = git.commit().setMessage("content " + id).call();
        scenario.getCommits().put(id, rc.getId());
    } catch (Exception ex) {
        throw new IllegalStateException(String.format("error creating a commit with new file %s", content), ex);
    }
    return this;
}
项目:fabric8-forge    文件:RepositoryResource.java   
protected CommitInfo doCreateDirectory(Git git, String path) throws Exception {
    File file = getRelativeFile(path);
    if (file.exists()) {
        return null;
    }
    file.mkdirs();
    String filePattern = getFilePattern(path);
    AddCommand add = git.add().addFilepattern(filePattern).addFilepattern(".");
    add.call();

    CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(message);
    RevCommit revCommit = commitThenPush(git, commit);
    return createCommitInfo(revCommit);
}
项目:fabric8-forge    文件:RepositoryResource.java   
protected CommitInfo doWrite(Git git, String path, byte[] contents, PersonIdent personIdent, String commitMessage) throws Exception {
    File file = getRelativeFile(path);
    file.getParentFile().mkdirs();

    Files.writeToFile(file, contents);

    String filePattern = getFilePattern(path);
    AddCommand add = git.add().addFilepattern(filePattern).addFilepattern(".");
    add.call();

    CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(commitMessage);
    RevCommit revCommit = commitThenPush(git, commit);
    return createCommitInfo(revCommit);
}
项目:verigreen    文件:JGitOperator.java   
@Override
public void add(String itemToAdd) {

    AddCommand command = _git.add();
    command.addFilepattern(itemToAdd);
    try {
        command.call();
    } catch (Throwable e) {
        throw new RuntimeException(String.format("Failed to add  [%s]", itemToAdd), e);
    }

}
项目:raccovery    文件:AccumuloConfigurations.java   
public void dumpConfiguration(Configuration config, Entry e) throws Exception {
    Preconditions.checkNotNull(config, "Configuration must be supplied.");
    Preconditions.checkNotNull(e, "Entry must be supplied.");
    AddCommand add = git.add();
    CommitCommand commit = git.commit();
    try {
        //Dump Zookeeper
        String instanceId = config.getConnector().getInstance().getInstanceID();
        String zkPath = Constants.ZROOT + "/" + instanceId;
        File zkDump = new File(gitDir, ZK_DUMP_FILE);
        LOG.debug("Dump ZooKeeper configuration at {} to {}", zkPath, zkDump);
        FileOutputStream out = new FileOutputStream(zkDump);
        DumpZookeeper.run(out, zkPath);
        out.close();
        //Dump the configuration
        LOG.debug("Dumping Accumulo configuration to {}", gitDir);
        DumpConfigCommand command = new DumpConfigCommand();
        command.allConfiguration = true;
        command.directory = gitDir.getAbsolutePath();
        Instance instance = config.getConnector().getInstance();
        String principal = config.getUsername();
        PasswordToken token = new PasswordToken(config.getPassword().getBytes());
        Admin.printConfig(instance, principal, token, command);
        //Add, commit, and tag
        add.addFilepattern(".").call();
        commit.setMessage("Backup " + e.getUUID().toString()).call();
        git.tag().setName(e.getUUID().toString()).call();
        LOG.debug("Git tag {} created.", e.getUUID());
        //Should we remove all of the files from the existing git workspace?
    } catch (Exception ex) {
        LOG.error("Error saving configuration", ex);
        git.reset().setMode(ResetType.HARD).setRef("HEAD").call();
        throw ex;
    }
}
项目:ISAAC    文件:SyncServiceGIT.java   
/**
 * @see gov.va.isaac.interfaces.sync.ProfileSyncI#addFiles(java.io.File, java.util.Set)
 */
@Override
public void addFiles(String... files) throws IllegalArgumentException, IOException
{
    try
    {
        log.info("Add Files called {}", Arrays.toString(files));
        Git git = getGit();
        if (files.length == 0)
        {
            log.debug("No files to add");
        }
        else
        {
            AddCommand ac = git.add();
            for (String file : files)
            {
                ac.addFilepattern(file);
            }
            ac.call();
        }
        log.info("addFiles Complete.  Current status: " + statusToString(git.status().call()));
    }
    catch (GitAPIException e)
    {
        log.error("Unexpected", e);
        throw new IOException("Internal error", e);
    }
}
项目:easycukes    文件:GitHelper.java   
/**
 * Adds all the files of the specified directory in the local git repository
 * (git add .), then commits the changes (git commit .), and finally pushes
 * the changes on the remote repository (git push)
 *
 * @param directory the directory in which the local git repository is located
 * @param username  the username to be used while pushing
 * @param password  the password matching with the provided username to be used
 *                  for authentication
 * @param message   the commit message to be used
 * @throws GitAPIException if something's going wrong while interacting with Git
 * @throws IOException     if something's going wrong while manipulating the local
 *                         repository
 */
public static void commitAndPush(@NonNull File directory, String username,
                                 String password, String message) throws GitAPIException,
        IOException {
    try {
        final Git git = Git.open(directory);
        // run the add
        final AddCommand addCommand = git.add();
        for (final String filePath : directory.list())
            if (!".git".equals(filePath))
                addCommand.addFilepattern(filePath);
        addCommand.call();
        log.info("Added content of the directory" + directory
                + " in the Git repository located in "
                + directory.toString());
        // and then commit
        final PersonIdent author = new PersonIdent(username, "");
        git.commit().setCommitter(author).setMessage(message)
                .setAuthor(author).call();
        log.info("Commited the changes in the Git repository...");
        // and finally push
        final UsernamePasswordCredentialsProvider userCredential = new UsernamePasswordCredentialsProvider(
                username, password);
        git.push().setCredentialsProvider(userCredential).call();
        log.info("Pushed the changes in remote Git repository...");
    } catch (final GitAPIException e) {
        log.error(e.getMessage(), e);
        throw e;
    }
}
项目:fabric8poc    文件:ProfileRegistry.java   
DirCache addAll() {
    try {
        AddCommand addCmd = git.add().addFilepattern(".");
        return addCmd.call();
    } catch (GitAPIException ex) {
        throw new IllegalStateException("Cannot add files", ex);
    }
}
项目:ivy-pdi-git-steps    文件:AddGitCommand.java   
public Git call(final GitOperationsStep gitOperationsStep, Git git,
    CredentialsProvider cp, String gitRepoUrl, File gitRepoFolder)
    throws IllegalArgumentException, IOException,
    NoFilepatternException, GitAPIException {

  AddCommand ac = git.add();

  if (!Const.isEmpty(this.filepattern)) {
    ac = ac.addFilepattern(gitOperationsStep
        .environmentSubstitute(this.filepattern));
  }

  ac.setUpdate(update).call();
  return git;
}
项目:raccovery    文件:AccumuloConfigurations.java   
public void dumpConfiguration(Configuration config, Entry e) throws Exception {
    Preconditions.checkNotNull(config, "Configuration must be supplied.");
    Preconditions.checkNotNull(e, "Entry must be supplied.");
    AddCommand add = git.add();
    CommitCommand commit = git.commit();
    try {
        //Dump Zookeeper
        String instanceId = config.getConnector().getInstance().getInstanceID();
        String zkPath = Constants.ZROOT + "/" + instanceId;
        File zkDump = new File(gitDir, ZK_DUMP_FILE);
        LOG.debug("Dump ZooKeeper configuration at {} to {}", zkPath, zkDump);
        FileOutputStream out = new FileOutputStream(zkDump);
        DumpZookeeper.run(out, zkPath);
        out.close();
        //Dump the configuration
        LOG.debug("Dumping Accumulo configuration to {}", gitDir);
        DumpConfigCommand command = new DumpConfigCommand();
        command.allConfiguration = true;
        command.directory = gitDir.getAbsolutePath();
        Instance instance = config.getConnector().getInstance();
        String principal = config.getUsername();
        PasswordToken token = new PasswordToken(config.getPassword().getBytes());
        Admin.printConfig(instance, principal, token, command);
        //Add, commit, and tag
        add.addFilepattern(".").call();
        commit.setMessage("Backup " + e.getUUID().toString()).call();
        git.tag().setName(e.getUUID().toString()).call();
        LOG.debug("Git tag {} created.", e.getUUID());
        //Should we remove all of the files from the existing git workspace?
    } catch (Exception ex) {
        LOG.error("Error saving configuration", ex);
        git.reset().setMode(ResetType.HARD).setRef("HEAD").call();
        throw ex;
    }
}
项目:liveoak    文件:CommitsResource.java   
@Override
public void createMember(RequestContext ctx, ResourceState state, Responder responder) throws Exception {
    String commitMsg = state.getPropertyAsString("msg");
    Boolean includeUntracked = state.getPropertyAsBoolean("include-untracked");

    if (includeUntracked == null) {
        // Default to include all untracked files
        includeUntracked = Boolean.TRUE;
    }

    // Add changed files to staging ready for commit
    AddCommand addCmd = parent.git().add().addFilepattern(".");

    if (!includeUntracked) {
        // This will prevent new files from being added to the index, and therefore the commit
        addCmd.setUpdate(true);
    }

    // Commit staged changes
    RevCommit commit;
    CommitCommand commitCmd = parent.git().commit();

    if (ctx.securityContext() != null) {
        UserProfile user = ctx.securityContext().getUser();
        if (user != null && user.name() != null && user.email() != null) {
            commitCmd.setCommitter(user.name(), user.email());
        }
    }

    if (commitMsg != null) {
        commitCmd.setMessage(commitMsg);
    }

    commit = GitHandler.commit(() -> {
        addCmd.call();
        return commitCmd.call();
    });

    responder.resourceCreated(new GitCommitResource(this, commit));
}
项目:fabric8-forge    文件:ForgeTestSupport.java   
protected Build assertCodeChangeTriggersWorkingBuild(final String projectName, Build firstBuild) throws Exception {
    File cloneDir = new File(getBasedir(), "target/projects/" + projectName);

    String gitUrl = asserGetAppGitCloneURL(forgeClient, projectName);
    Git git = ForgeClientAsserts.assertGitCloneRepo(gitUrl, cloneDir);

    // lets make a dummy commit...
    File readme = new File(cloneDir, "ReadMe.md");
    boolean mustAdd = false;
    String text = "";
    if (readme.exists()) {
        text = IOHelpers.readFully(readme);
    } else {
        mustAdd = true;
    }
    text += "\nupdated at: " + new Date();
    Files.writeToFile(readme, text, Charset.defaultCharset());

    if (mustAdd) {
        AddCommand add = git.add().addFilepattern("*").addFilepattern(".");
        add.call();
    }


    LOG.info("Committing change to " + readme);

    CommitCommand commit = git.commit().setAll(true).setAuthor(forgeClient.getPersonIdent()).setMessage("dummy commit to trigger a rebuild");
    commit.call();
    PushCommand command = git.push();
    command.setCredentialsProvider(forgeClient.createCredentialsProvider());
    command.setRemote("origin").call();

    LOG.info("Git pushed change to " + readme);

    // now lets wait for the next build to start
    int nextBuildNumber = firstBuild.getNumber() + 1;


    Asserts.assertWaitFor(10 * 60 * 1000, new Block() {
        @Override
        public void invoke() throws Exception {
            JobWithDetails job = assertJob(projectName);
            Build lastBuild = job.getLastBuild();
            assertThat(lastBuild.getNumber()).describedAs("Waiting for latest build for job " + projectName + " to start").isGreaterThanOrEqualTo(nextBuildNumber);
        }
    });

    return ForgeClientAsserts.assertBuildCompletes(forgeClient, projectName);
}
项目:appformer    文件:GitImpl.java   
public AddCommand _add() {
    return git.add();
}
项目:JGitFX    文件:GitHelper.java   
/**
 * Add (stage) files to the index.
 * @param git the git repository
 * @param relativePaths the relative paths of the files to add
 * @param excludeNewFiles if true, any untracked files in {@code relativePaths} will not be added (they won't
 *                        become "tracked" at the end of the call).
 * @throws GitAPIException
 */
public static void addFiles(Git git, List<String> relativePaths, boolean excludeNewFiles) throws GitAPIException {
    AddCommand adder = git.add();
    adder.setUpdate(excludeNewFiles);
    relativePaths.forEach(adder::addFilepattern);
    adder.call();
}