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

项目:fabric8-forge    文件:RepositoryResource.java   
protected CommitInfo doRename(Git git, String oldPath, String newPath) throws Exception {
    File file = getRelativeFile(oldPath);
    File newFile = getRelativeFile(newPath);
    if (file.exists()) {
        File parentFile = newFile.getParentFile();
        parentFile.mkdirs();
        if (!parentFile.exists()) {
            throw new IOException("Could not create directory " + parentFile + " when trying to move " + file + " to " + newFile + ". Maybe a file permission issue?");
        }
        file.renameTo(newFile);
        String filePattern = getFilePattern(newPath);
        git.add().addFilepattern(filePattern).call();
        CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(message);
        return createCommitInfo(commitThenPush(git, commit));
    } else {
        return null;
    }
}
项目:fabric8-forge    文件:RepositoryResource.java   
protected CommitInfo doRemove(Git git, List<String> paths) throws Exception {
    if (paths != null && paths.size() > 0) {
        int count = 0;
        for (String path : paths) {
            File file = getRelativeFile(path);
            if (file.exists()) {
                count++;
                Files.recursiveDelete(file);
                String filePattern = getFilePattern(path);
                git.rm().addFilepattern(filePattern).call();
            }
        }
        if (count > 0) {
            CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(message);
            return createCommitInfo(commitThenPush(git, commit));
        }
    }
    return null;
}
项目:WebIDE-Backend    文件:GitManagerTest.java   
private RevCommit writeFileAndCommitWithAuthor(Git git, String authorName, String email, String fileName, String commitMessage,
                                               String... lines) throws IOException, GitAPIException {
    StringBuilder sb = new StringBuilder();
    for (String line : lines) {
        sb.append(line);
        sb.append('\n');
    }
    writeTrashFile(fileName, sb.toString());
    git.add().addFilepattern(fileName).call();

    CommitCommand commitCommand = git.commit().setMessage(commitMessage);

    if (authorName != null && email != null) {
        return commitCommand.setAuthor(authorName, email).call();
    } else {
        return commitCommand.call();
    }
}
项目: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;
    }
}
项目:fabric8-devops    文件:GitHelpers.java   
public static RevCommit doCommitAndPush(Git git, String message, UserDetails userDetails, PersonIdent author, String branch, String origin, boolean pushOnCommit) throws GitAPIException {
    CommitCommand commit = git.commit().setAll(true).setMessage(message);
    if (author != null) {
        commit = commit.setAuthor(author);
    }

    RevCommit answer = commit.call();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Committed " + answer.getId() + " " + answer.getFullMessage());
    }

    if (pushOnCommit) {
        PushCommand push = git.push();
        configureCommand(push, userDetails);
        Iterable<PushResult> results = push.setRemote(origin).call();
        for (PushResult result : results) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Pushed " + result.getMessages() + " " + result.getURI() + " branch: " + branch + " updates: " + toString(result.getRemoteUpdates()));
            }
        }
    }
    return answer;
}
项目:verigreen    文件:JGitOperator.java   
@Override
public String commit(String author, String email, String message) {

    RevCommit revCommit = null;
    CommitCommand command = _git.commit();
    command.setCommitter(author, email);
    command.setMessage(message);
    command.setAll(true);
    try {
        revCommit = command.call();
    } catch (Throwable e) {
        throw new RuntimeException("Failed to commit", e);
    }

    return revCommit.getId().getName();
}
项目:raccovery    文件:AccumuloConfigurations.java   
public AccumuloConfigurations(Configuration config) throws Exception {
    Preconditions.checkNotNull(config, "Configuration must be supplied");
    gitDir = new File(config.getDataDir()+"/git");
    LOG.debug("Creating Git repository at {}", gitDir);
    if (!gitDir.exists()) {
        if (!gitDir.mkdir()) {
            throw new IOException("Error creating directory: "+gitDir.getAbsolutePath());
        }
        InitCommand initCommand = Git.init();
        initCommand.setBare(false);
        initCommand.setDirectory(gitDir);
        git = initCommand.call();
        CommitCommand commit = git.commit();
        commit.setMessage("Initial commit").call();
        repo = git.getRepository();
    } else {
        git = Git.open(gitDir);
        repo = git.getRepository();         
    }
    LOG.info("Accumulo configuration store initialized");
}
项目:raccovery    文件:AccumuloConfigurations.java   
public AccumuloConfigurations(Configuration config) throws Exception {
    Preconditions.checkNotNull(config, "Configuration must be supplied");
    gitDir = new File(config.getDataDir()+"/git");
    LOG.debug("Creating Git repository at {}", gitDir);
    if (!gitDir.exists()) {
        if (!gitDir.mkdir()) {
            throw new IOException("Error creating directory: "+gitDir.getAbsolutePath());
        }
        InitCommand initCommand = Git.init();
        initCommand.setBare(false);
        initCommand.setDirectory(gitDir);
        git = initCommand.call();
        CommitCommand commit = git.commit();
        commit.setMessage("Initial commit").call();
        repo = git.getRepository();
    } else {
        git = Git.open(gitDir);
        repo = git.getRepository();         
    }
    LOG.info("Accumulo configuration store initialized");
}
项目: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();
    });
}
项目:gitplex-mit    文件:AbstractGitTest.java   
protected void commit(String comment) {
    CommitCommand ci = git.commit();
    ci.setMessage(comment);
    ci.setAuthor(user);
    ci.setCommitter(user);
    try {
        ci.call();
    } catch (GitAPIException e) {
        throw new RuntimeException(e);
    }
}
项目: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 doRemove(Git git, String path) throws Exception {
    File file = getRelativeFile(path);
    if (file.exists()) {
        Files.recursiveDelete(file);
        String filePattern = getFilePattern(path);
        git.rm().addFilepattern(filePattern).call();
        CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(message);
        return createCommitInfo(commitThenPush(git, commit));
    } else {
        return null;
    }
}
项目: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);
}
项目:fabric8-forge    文件:RepositoryResource.java   
protected RevCommit commitThenPush(Git git, CommitCommand commit) throws Exception {
    RevCommit answer = commit.call();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Committed " + answer.getId() + " " + answer.getFullMessage());
    }
    if (isPushOnCommit()) {
        Iterable<PushResult> results = doPush(git);
        for (PushResult result : results) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Pushed " + result.getMessages() + " " + result.getURI() + " branch: " + branch + " updates: " + toString(result.getRemoteUpdates()));
            }
        }
    }
    return answer;
}
项目: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;
    }
}
项目:fabric8poc    文件:ProfileRegistry.java   
RevCommit commit(String message) {
    try {
        CommitCommand commitCmd = git.commit().setAll(true).setMessage(message).setCommitter(getDefaultCommiter());
        return commitCmd.call();
    } catch (GitAPIException ex) {
        throw new IllegalStateException("Cannot commit: " + message, ex);
    }
}
项目:ivy-pdi-git-steps    文件:CommitGitCommand.java   
public Git call(final GitOperationsStep gitOperationsStep, Git git,
    CredentialsProvider cp, String gitRepoUrl, File gitRepoFolder)
    throws IllegalArgumentException, IOException, NoHeadException,
    NoMessageException, UnmergedPathsException,
    ConcurrentRefUpdateException, WrongRepositoryStateException,
    GitAPIException {
  CommitCommand cc = git
      .commit()
      .setAuthor(
          gitOperationsStep
              .environmentSubstitute(this.authorName == null ? ""
                  : this.authorName),
          gitOperationsStep
              .environmentSubstitute(this.authorEmail == null ? ""
                  : this.authorEmail))
      .setCommitter(
          gitOperationsStep
              .environmentSubstitute(this.committerName == null ? ""
                  : this.committerName),
          gitOperationsStep
              .environmentSubstitute(this.committerEmail == null ? ""
                  : this.committerName));

  if (!Const.isEmpty(this.commitMessage)) {
    cc = cc.setMessage(gitOperationsStep
        .environmentSubstitute(this.commitMessage));
  }
  cc.setAll(all).setInsertChangeId(insertChangeId).setAmend(amend).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));
}
项目:git-client-plugin    文件:JGitAPIImpl.java   
/** {@inheritDoc} */
public void commit(String message) throws GitException {
    try (Repository repo = getRepository()) {
        CommitCommand cmd = git(repo).commit().setMessage(message);
        if (author!=null)
            cmd.setAuthor(author);
        if (committer!=null)
            cmd.setCommitter(new PersonIdent(committer,new Date()));
        cmd.call();
    } catch (GitAPIException e) {
        throw new GitException(e);
    }
}
项目:mideaas    文件:GitRepository.java   
/**
 * Commit all.
 *
 * @param msg the msg
 * @throws GitAPIException the git api exception
 */
public void commitAll(String msg) throws GitAPIException {
    CommitCommand command = git.commit().setMessage(msg).setAll(true);
    RevCommit result = command.call();
    String message=result.getFullMessage();
    if (message.length()>0){
        Notification.show("Commit ok, message: " + message);            
    }else{
        Notification.show("Commit ok, no commit message :( ?");
    }   
}
项目:SGit    文件:CommitChangesTask.java   
public static void commit(Repo repo, boolean stageAll, boolean isAmend,
        String msg, String authorName, String authorEmail) throws Exception, NoHeadException, NoMessageException,
        UnmergedPathsException, ConcurrentRefUpdateException,
        WrongRepositoryStateException, GitAPIException, StopTaskException {
    Context context = SGitApplication.getContext();
    StoredConfig config = repo.getGit().getRepository().getConfig();
    String committerEmail = config.getString("user", null, "email");
    String committerName = config.getString("user", null, "name");

    if (committerName == null || committerName.equals("")) {
        committerName = Profile.getUsername(context);
    }
    if (committerEmail == null || committerEmail.equals("")) {
        committerEmail = Profile.getEmail(context);
    }
    if (committerName.isEmpty() || committerEmail.isEmpty()) {
        throw new Exception("Please set your name and email");
    }
    if (msg.isEmpty()) {
        throw new Exception("Please include a commit message");
    }
    CommitCommand cc = repo.getGit().commit()
            .setCommitter(committerName, committerEmail).setAll(stageAll)
            .setAmend(isAmend).setMessage(msg);
    if (authorName != null && authorEmail != null) {
        cc.setAuthor(authorName, authorEmail);
    }
    cc.call();
    repo.updateLatestCommitInfo();
}
项目: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 CommitCommand _commit() {
    return git.commit();
}
项目:Android-Password-Store    文件:GitAsyncTask.java   
@Override
protected String doInBackground(GitCommand... commands) {
    Integer nbChanges = null;
    for (GitCommand command : commands) {
        Log.d("doInBackground", "Executing the command <" + command.toString() + ">");
        try {
            if (command instanceof StatusCommand) {
                // in case we have changes, we want to keep track of it
                org.eclipse.jgit.api.Status status = ((StatusCommand) command).call();
                nbChanges = status.getChanged().size() + status.getMissing().size();
            } else if (command instanceof CommitCommand) {
                // the previous status will eventually be used to avoid a commit
                if (nbChanges == null || nbChanges > 0)
                    command.call();
            }else if (command instanceof PushCommand) {
                for (final PushResult result : ((PushCommand) command).call()) {
                    // Code imported (modified) from Gerrit PushOp, license Apache v2
                    for (final RemoteRefUpdate rru : result.getRemoteUpdates()) {
                        switch (rru.getStatus()) {
                            case REJECTED_NONFASTFORWARD:
                                return activity.getString(R.string.git_push_nff_error);
                            case REJECTED_NODELETE:
                            case REJECTED_REMOTE_CHANGED:
                            case NON_EXISTING:
                            case NOT_ATTEMPTED:
                                return activity.getString(R.string.git_push_generic_error) + rru.getStatus().name();
                            case REJECTED_OTHER_REASON:
                                if ("non-fast-forward".equals(rru.getMessage())) {
                                    return activity.getString(R.string.git_push_other_error);
                                } else {
                                    return activity.getString(R.string.git_push_generic_error) + rru.getMessage();
                                }
                            default:
                                break;
                        }
                    }
                }
            } else {
                command.call();
            }

        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage() + "\nCaused by:\n" + e.getCause();
        }
    }
    return "";
}
项目:pretested-integration-plugin    文件:UniqueBranchGenerator.java   
/**
 * Requires a bare repository. We clone to a random workspace
 *
 * @throws Exception
 * @return The generator currently being worked on
 */
public UniqueBranchGenerator build() throws Exception {

    Git git;

    File workDirTarget = new File(repo.getDirectory().getAbsolutePath() + "/../../" + UUID.randomUUID().toString());
    System.out.println(workDirTarget.getAbsolutePath());

    Git.cloneRepository()
            .setURI("file://" + repo.getDirectory().getAbsolutePath())
            .setBare(false)
            .setNoCheckout(false)
            .setCloneAllBranches(true)
            .setDirectory(workDirTarget).call().close();

    File gitMetaDir = new File(workDirTarget.getAbsolutePath() + System.getProperty("file.separator") + ".git");
    System.out.println("Setting .git metadata to work in directory: " + gitMetaDir.getAbsolutePath());

    git = Git.open(gitMetaDir);

    CreateBranchCommand createBranchCommand = git.branchCreate();
    createBranchCommand.setName(branchName);
    createBranchCommand.call();
    git.checkout().setName(branchName).call();

    File repoRoot = git.getRepository().getWorkTree();
    UUID rand = UUID.randomUUID();
    File randomFile = new File(repoRoot, rand.toString() + ".log");
    randomFile.createNewFile();
    git.add().addFilepattern(".").call();

    int cnt = 0;
    for (String msg : commitMessages) {
        FileUtils.writeStringToFile(randomFile, rand.toString() + "-" + cnt + "\n", true);
        CommitCommand commitCommand = git.commit();
        commitCommand.setMessage(msg);
        commitCommand.setAuthor(AUTHOR_NAME, AUTHOR_EMAIL);
        commitCommand.call();
        cnt++;
    }

    git.push().setPushAll().call();
    git.checkout().setName("master");
    git.close();

    FileUtils.deleteDirectory(workDirTarget);
    return this;
}
项目:pretested-integration-plugin    文件:TestUtilsFactory.java   
/**
 * Creates a bare git repository with initial commit and a 'readme.md' file
 * containing one line. Author and email is set on commit.
 *
 * @param repoFolderName
 * @return
 * @throws IOException
 * @throws GitAPIException
 */
public static Repository createRepoWithoutBranches(String repoFolderName) throws IOException, GitAPIException {
    //'git init --bare test.git' :
    //Initialized empty Git repository in /home/bue/gitlab-repos/pretested-integration-plugin/test.git/
    //'ls -al test.git/' :
    //total 40
    //drwxrwxr-x  7 doe usr 4096 dec 11 00:23 .
    //drwxrwxr-x 12 doe usr 4096 dec 11 00:23 ..
    //drwxrwxr-x  2 doe usr 4096 dec 11 00:23 branches
    //-rw-rw-r--  1 doe usr   66 dec 11 00:23 config
    //-rw-rw-r--  1 doe usr   73 dec 11 00:23 description
    //-rw-rw-r--  1 doe usr   23 dec 11 00:23 HEAD
    //drwxrwxr-x  2 doe usr 4096 dec 11 00:23 hooks
    //drwxrwxr-x  2 doe usr 4096 dec 11 00:23 info
    //drwxrwxr-x  4 doe usr 4096 dec 11 00:23 objects
    //drwxrwxr-x  4 doe usr 4096 dec 11 00:23 refs
    File repo = new File(WORKDIR,repoFolderName + ".git"); // bare repo should have suffix .git, and contain what normally in .git

    File workDirForRepo = new File(WORKDIR, repoFolderName);

    System.out.format(workDirForRepo.getAbsolutePath());

    if (repo.exists()) {
        System.out.format("EXIST:" + repo.getAbsolutePath());
        try {
            TestUtilsFactory.destroyDirectory(repo);
        } catch (InterruptedException e) {
            throw new IOException(e);
        }
    }

    Repository repository = new FileRepository(repo);
    repository.create(true);

    Git.cloneRepository().setURI("file:///" + repo.getAbsolutePath()).setDirectory(workDirForRepo)
            .setBare(false)
            .setCloneAllBranches(true)
            .setNoCheckout(false)
            .call().close();

    Git git = Git.open(workDirForRepo);

    File readme = new File(workDirForRepo, "readme.md");
    if (!readme.exists()) {
        FileUtils.writeStringToFile(readme, "#My first repository");
    }

    git.add().addFilepattern(".");
    CommitCommand commit = git.commit();
    commit.setMessage(TestUtilsFactory.createCommitMessageForRepo(repoFolderName, repository.getBranch(), "Initial commit"));
    commit.setAuthor(AUTHOR_NAME, AUTHOR_EMAIL);
    commit.call();

    git.push().setPushAll().setRemote("origin").call();

    git.close();

    FileUtils.deleteDirectory(workDirForRepo);

    return repository;
}
项目:pretested-integration-plugin    文件:TestUtilsFactory.java   
public static Repository createValidRepository(String repoFolderName) throws IOException, GitAPIException {
    File repo = new File(WORKDIR,repoFolderName + ".git"); // bare repo should have suffix .git, and contain what normally in .git

    if (repo.exists()) {
        System.out.format("EXIST:" + repo.getAbsolutePath());
        try {
            TestUtilsFactory.destroyDirectory(repo);
        } catch (InterruptedException e) {
            throw new IOException(e);
        }
    }

    File workDirForRepo = new File(WORKDIR, repoFolderName);
    Repository repository = new FileRepository(repo);
    repository.create(true);

    Git.cloneRepository().setURI("file:///" + repo.getAbsolutePath()).setDirectory(workDirForRepo)
            .setBare(false)
            .setCloneAllBranches(true)
            .setNoCheckout(false)
            .call().close();

    Git git = Git.open(workDirForRepo);

    String FEATURE_BRANCH_NAME = "ready/feature_1";

    File readme = new File(workDirForRepo + "/readme");
    if (!readme.exists()) {
        FileUtils.writeStringToFile(readme, "sample text\n");
    }

    git.add().addFilepattern(readme.getName()).call();
    git.commit().setMessage(TestUtilsFactory.createCommitMessageForRepo(repoFolderName, git.getRepository().getBranch(), "commit message 1")).call();

    FileUtils.writeStringToFile(readme, "changed sample text\n");

    git.add().addFilepattern(readme.getName()).call();
    git.commit().setMessage(TestUtilsFactory.createCommitMessageForRepo(repoFolderName, git.getRepository().getBranch(), "commit message 2")).call();

    CreateBranchCommand createBranchCommand = git.branchCreate();
    createBranchCommand.setName(FEATURE_BRANCH_NAME);
    createBranchCommand.call();

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

    FileUtils.writeStringToFile(readme, "FEATURE_1 branch commit 1\n", true);

    git.add().addFilepattern(readme.getName()).call();
    CommitCommand commitCommand = git.commit();
    commitCommand.setMessage(TestUtilsFactory.createCommitMessageForRepo(repoFolderName, git.getRepository().getBranch(), "feature 1 commit 1"));
    commitCommand.setAuthor(AUTHOR_NAME, AUTHOR_EMAIL);
    commitCommand.call();

    FileUtils.writeStringToFile(readme, "FEATURE_1 branch commit 2\n", true);

    git.add().addFilepattern(readme.getName()).call();
    commitCommand = git.commit();
    commitCommand.setMessage(TestUtilsFactory.createCommitMessageForRepo(repoFolderName, git.getRepository().getBranch(), "feature 1 commit 2"));
    commitCommand.setAuthor(AUTHOR_NAME, AUTHOR_EMAIL);
    commitCommand.call();

    git.push().setPushAll().call();

    git.checkout().setName("master").call();

    FileUtils.deleteDirectory(workDirForRepo);
    return repository;
}
项目:pretested-integration-plugin    文件:TestUtilsFactory.java   
public static Repository createRepositoryWithMergeConflict(String repoFolderName) throws IOException, GitAPIException {
    String FEATURE_BRANCH_NAME = "ready/feature_1";

    File repo = new File(WORKDIR,repoFolderName + ".git"); // bare repo should have suffix .git, and contain what normally in .git
    File workDirForRepo = new File(WORKDIR, repoFolderName);
    Repository repository = new FileRepository(repo);
    repository.create(true);

    Git.cloneRepository().setURI("file:///" + repo.getAbsolutePath()).setDirectory(workDirForRepo)
            .setBare(false)
            .setCloneAllBranches(true)
            .setNoCheckout(false)
            .call().close();

    Git git = Git.open(workDirForRepo);

    File readme = new File(workDirForRepo + "/readme");
    if (!readme.exists()) {
        FileUtils.writeStringToFile(readme, "sample text\n");
    }

    git.add().addFilepattern(readme.getName()).call();
    git.commit().setMessage("commit message 1").call();

    FileUtils.writeStringToFile(readme, "changed sample text\n");

    git.add().addFilepattern(readme.getName()).call();
    git.commit().setMessage("commit message 2").call();

    CreateBranchCommand createBranchCommand = git.branchCreate();
    createBranchCommand.setName(FEATURE_BRANCH_NAME);
    createBranchCommand.call();

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

    FileUtils.writeStringToFile(readme, "FEATURE_1 branch commit 1\n");

    git.add().addFilepattern(readme.getName()).call();
    CommitCommand commitCommand = git.commit();
    commitCommand.setMessage("feature 1 commit 1");
    commitCommand.setAuthor(AUTHOR_NAME, AUTHOR_EMAIL);
    commitCommand.call();

    FileUtils.writeStringToFile(readme, "FEATURE_1 branch commit 2\n");

    git.add().addFilepattern(readme.getName()).call();
    commitCommand = git.commit();
    commitCommand.setMessage("feature 1 commit 2");
    commitCommand.setAuthor(AUTHOR_NAME, AUTHOR_EMAIL);
    commitCommand.call();

    git.checkout().setName("master").call();

    FileUtils.writeStringToFile(readme, "Merge conflict branch commit 2\n");

    git.add().addFilepattern(readme.getName()).call();
    commitCommand = git.commit();
    commitCommand.setMessage("merge conflict message 1");
    commitCommand.setAuthor(AUTHOR_NAME, AUTHOR_EMAIL);
    commitCommand.call();

    git.push().setPushAll().call();

    FileUtils.deleteDirectory(workDirForRepo);

    return repository;
}
项目:ant-git-tasks    文件:CommitTask.java   
@Override
protected void doExecute() throws BuildException {
        try {
                setFailOnError(true);
                CommitCommand cmd = git.commit();

                if (!GitTaskUtils.isNullOrBlankString(message)) {
                        cmd.setMessage(brandedMessage ? GitTaskUtils.BRANDING_MESSAGE + " " + message : message);
                }
                else {
                        cmd.setMessage(GitTaskUtils.BRANDING_MESSAGE);
                }

                String prefix = getDirectory().getCanonicalPath();
                String[] allFiles = getPath().list();

                if (!GitTaskUtils.isNullOrBlankString(only)) {
                        cmd.setOnly(only);
                }
                else if (allFiles.length > 0) {
                        for (String file : allFiles) {
                                String modifiedFile = translateFilePathUsingPrefix(file, prefix);
                                log("Will commit " + modifiedFile);
                                cmd.setOnly(modifiedFile);
                        }
                }
                else {
                        cmd.setAll(true);
                }

                GitSettings gitSettings = lookupSettings();

                if (gitSettings == null) {
                        throw new MissingRequiredGitSettingsException();
                }

                cmd.setAmend(amend).setAuthor(gitSettings.getIdentity()).setCommitter(gitSettings.getIdentity());

                if (reflogComment != null) {
                        cmd.setReflogComment(reflogComment);
                }

                RevCommit revCommit = cmd.call();

                if (revCommitIdProperty != null) {
                        String revisionId = ObjectId.toString(revCommit.getId());
                        getProject().setProperty(revCommitIdProperty, revisionId);
                }

                log(revCommit.getFullMessage());
        } catch (IOException ioe) {
                throw new GitBuildException(MESSAGE_COMMIT_FAILED, ioe);
        } catch (GitAPIException ex) {
                throw new GitBuildException(MESSAGE_COMMIT_FAILED, ex);
        }
}
项目:JGitFX    文件:CommitDialogBase.java   
/**
 * Method used to configure the {@link CommitCommand} before {@link CommitCommand#call()} is called.
 * Default configuration:
 * <pre>
 *     {@code
 *      P pane = getDialogPane();
 *      commitCmd
 *               .setAllowEmpty(false)  // insures newly tracked files are actually committed
 *               .setAmend(pane.isAmendCommit())
 *               .setMessage(pane.getCommitMessage())
 *               .setAuthor(pane.getAuthor());
 *     }
 * </pre>
 * @param commitCmd the commit command to configure
 */
protected void configureCommitCommand(CommitCommand commitCmd) {
    P pane = getDialogPane();
    commitCmd
            .setAllowEmpty(false)
            .setAmend(pane.isAmendCommit())
            .setMessage(pane.getCommitMessage())
            .setAuthor(pane.getAuthor());
}