Example usage for org.eclipse.jgit.api RmCommand call

List of usage examples for org.eclipse.jgit.api RmCommand call

Introduction

In this page you can find the example usage for org.eclipse.jgit.api RmCommand call.

Prototype

@Override
public DirCache call() throws GitAPIException, NoFilepatternException 

Source Link

Document

Executes the Rm command.

Usage

From source file:com.chungkwong.jgitgui.StageTreeItem.java

License:Open Source License

@Override
public Node getContentPage() {
    Git git = (Git) getValue();// w  w  w.  java2  s  . c  o m
    GridPane page = new GridPane();
    ListView<String> list = new ListView<String>();
    GridPane.setHgrow(list, Priority.ALWAYS);
    GridPane.setVgrow(list, Priority.ALWAYS);
    list.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    try {
        DirCache cache = ((Git) getValue()).getRepository().readDirCache();
        for (int i = 0; i < cache.getEntryCount(); i++)
            list.getItems().add(cache.getEntry(i).getPathString());
    } catch (Exception ex) {
        Logger.getLogger(StageTreeItem.class.getName()).log(Level.SEVERE, null, ex);
        Util.informUser(ex);
    }
    Button remove = new Button(
            java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("REMOVE"));
    remove.setOnAction((e) -> {
        RmCommand command = git.rm().setCached(true);
        list.getSelectionModel().getSelectedItems().stream().forEach((path) -> {
            command.addFilepattern(path);
        });
        list.getItems().removeAll(list.getSelectionModel().getSelectedItems());
        try {
            command.call();
        } catch (Exception ex) {
            Logger.getLogger(StageTreeItem.class.getName()).log(Level.SEVERE, null, ex);
            Util.informUser(ex);
        }
    });
    Button blame = new Button(
            java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("BLAME"));
    blame.setOnAction((e) -> {
        Stage dialog = new Stage();
        dialog.setTitle(java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("BLAME"));
        StringBuilder buf = new StringBuilder();
        list.getSelectionModel().getSelectedItems().stream().forEach((path) -> {
            try {
                BlameResult command = git.blame().setFilePath(path).call();
                RawText contents = command.getResultContents();
                for (int i = 0; i < contents.size(); i++) {
                    buf.append(command.getSourcePath(i)).append(':');
                    buf.append(command.getSourceLine(i)).append(':');
                    buf.append(command.getSourceCommit(i)).append(':');
                    buf.append(command.getSourceAuthor(i)).append(':');
                    buf.append(contents.getString(i)).append('\n');
                }
            } catch (Exception ex) {
                Logger.getLogger(StageTreeItem.class.getName()).log(Level.SEVERE, null, ex);
                Util.informUser(ex);
            }
        });
        dialog.setScene(new Scene(new TextArea(buf.toString())));
        dialog.setMaximized(true);
        dialog.show();
    });
    page.addColumn(0, list, remove, blame);
    return page;
}

From source file:com.github.checkstyle.regression.internal.GitUtils.java

License:Open Source License

public static void addAllAndCommit(Repository repository, String message) throws GitAPIException {
    try (Git git = new Git(repository)) {
        // In JGit, the "add ." could not add the deleted files into staging area.
        // To obtain the same behavior as git CLI command "git add .", we have to
        // use RmCommand to handle deleted files.
        final Status status = git.status().call();
        if (!status.getMissing().isEmpty() || !status.getRemoved().isEmpty()) {
            final RmCommand rm = git.rm().setCached(true);
            Iterables.concat(status.getMissing(), status.getRemoved()).forEach(rm::addFilepattern);
            rm.call();
        }//  w w w. ja v a 2  s.  c o m
        git.add().addFilepattern(".").call();
        git.commit().setMessage(message).call();
    }
}

From source file:com.googlesource.gerrit.plugins.uploadvalidator.TestUtils.java

License:Apache License

public static void removeFiles(Git git, Set<File> files) throws GitAPIException {
    RmCommand rmc = git.rm();
    for (File f : files) {
        rmc.addFilepattern(generateFilePattern(f, git));
    }//from  www.j  a v a  2 s. c  o  m
    rmc.call();
}

From source file:com.meltmedia.cadmium.core.git.GitService.java

License:Apache License

/**
 * Checks in content from a source directory into the current git repository.
 * @param sourceDirectory The directory to pull content in from.
 * @param message The commit message to use.
 * @return The new SHA revision.//from  w w  w.  j  a  v a 2  s  .  co  m
 * @throws Exception
 */
public String checkinNewContent(String sourceDirectory, String message) throws Exception {
    RmCommand remove = git.rm();
    boolean hasFiles = false;
    for (String filename : new File(getBaseDirectory()).list()) {
        if (!filename.equals(".git")) {
            remove.addFilepattern(filename);
            hasFiles = true;
        }
    }
    if (hasFiles) {
        log.info("Removing old content.");
        remove.call();
    }
    log.info("Copying in new content.");
    FileSystemManager.copyAllContent(sourceDirectory, getBaseDirectory(), true);
    log.info("Adding new content.");
    AddCommand add = git.add();
    for (String filename : new File(getBaseDirectory()).list()) {
        if (!filename.equals(".git")) {
            add.addFilepattern(filename);
        }
    }
    add.call();
    log.info("Committing new content.");
    git.commit().setMessage(message).call();
    return getCurrentRevision();
}

From source file:com.rimerosolutions.ant.git.tasks.RmTask.java

License:Apache License

@Override
protected void doExecute() {
    try {/*from  www .j  a v  a 2  s.  c  om*/
        RmCommand rmCommand = git.rm();
        String prefix = getDirectory().getCanonicalPath();
        String[] allFiles = getPath().list();
        if (allFiles.length == 0) {
            return;
        }

        for (String file : allFiles) {
            String addedFile = translateFilePathUsingPrefix(file, prefix);
            rmCommand.addFilepattern(addedFile);
        }

        rmCommand.call();
    } catch (GitAPIException e) {
        throw new GitBuildException(e);
    } catch (Exception e) {
        throw new GitBuildException("Unexpected error.", e);
    }
}

From source file:eu.mihosoft.vrl.io.VersionedFile.java

License:Open Source License

/**
 * Commit file changes. IF flushing for commits is enabled changes will be
 * flushed./*from w  w w . java2  s  .co m*/
 *
 * @param message commit message
 * @return this file
 * @throws IOException
 * @throws IllegalStateException if this file is currently not open
 */
public VersionedFile commit(String message) throws IOException {

    // file has to be opened
    if (!isOpened()) {
        throw new IllegalStateException("File\"" + getFile().getPath() + "\" not opened!");
    }

    Git git = null;

    try {

        //             this should NEVER happen
        if (hasConflicts()) {
            throw new IllegalStateException("File \"" + getFile().getPath() + "\" has conflicts!");
        }

        // ensures that message is not null
        if (message == null || message.isEmpty()) {
            message = "no message";
        }

        System.out.print(">> commit version ");

        // open the git repository
        git = Git.open(tmpFolder);

        // retrieve the current git status
        Status status = git.status().call();

        // rm command to tell git to remove files
        RmCommand rm = git.rm();

        boolean needsRM = false;

        // checks whether rm is necessary and adds relevant paths
        for (String removedFile : status.getMissing()) {
            rm.addFilepattern(removedFile);
            needsRM = true;
        }

        // calls the rm command if necessary
        if (needsRM) {
            rm.call();
        }

        // adds all remaining files
        git.add().addFilepattern(".").call();

        // perform the commit
        git.commit().setMessage(message).setAuthor(System.getProperty("user.name"), "?").call();

        commits = null;

        // updates the current version number
        currentVersion = getNumberOfVersions() - 1;

        System.out.println(currentVersion + ": ");
        System.out.println(">>> commit-id (SHA-1): " + getVersions().get(currentVersion).getName());

        if (isFlushCommits()) {
            flush();
        }

        closeGit(git);

        return this;

    } catch (NoFilepatternException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    } catch (NoHeadException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    } catch (NoMessageException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    } catch (UnmergedPathException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    } catch (ConcurrentRefUpdateException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    } catch (JGitInternalException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    } catch (WrongRepositoryStateException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    } catch (IOException ex) {
        closeGit(git);
        throw new IOException("Git exception", ex);
    }
}

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

License:Apache License

/**
 * @see gov.va.isaac.interfaces.sync.ProfileSyncI#removeFiles(java.io.File, java.util.Set)
 *///  ww w. j a v a2  s.  com
@Override
public void removeFiles(String... files) throws IllegalArgumentException, IOException {
    try {
        log.info("Remove Files called {}", Arrays.toString(files));
        Git git = getGit();
        if (files.length == 0) {
            log.debug("No files to remove");
        } else {
            RmCommand rm = git.rm();
            for (String file : files) {
                rm.addFilepattern(file);
            }
            rm.call();
        }
        log.info("removeFiles Complete.  Current status: " + statusToString(git.status().call()));
    } catch (GitAPIException e) {
        log.error("Unexpected", e);
        throw new IOException("Internal error", e);
    }
}

From source file:net.polydawn.mdm.commands.MdmReleaseCommand.java

License:Open Source License

public MdmExitMessage call() throws IOException, MdmException, MdmExitMessage {
    MdmModuleRelease relModule = loadReleaseModule();
    Repository relRepo = relModule.getRepo();

    relModule.assertPresentsAsReleaseRepo();
    assertReleaseRepoDoesntAlreadyContain(relModule, version);
    assertReleaseRepoClean(relModule);//  ww w  .  j  a  v a2 s .c o  m

    List<String> inputFiles = selectInputFiles();

    // create a branch for the release commit.  depending on whether or not infix mode is enabled, this is either branching from the infix branch, or it's founding a new root of history.
    boolean infixMode = relRepo.getRef("refs/heads/mdm/infix") != null;
    if (infixMode)
        try {
            new Git(relRepo).checkout().setCreateBranch(true).setStartPoint("mdm/infix")
                    .setName("mdm/release/" + version).call();
        } catch (RefAlreadyExistsException e) {
            return new MdmExitMessage(":'(",
                    "the releases repo already has a release point labeled version " + version + " !");
        } catch (RefNotFoundException e) {
            throw new MdmException("aborted due to concurrent modification of repo");
        } catch (InvalidRefNameException e) {
            return new MdmExitMessage(":(", "you can't use version names that git rejects as branch names.");
        } catch (CheckoutConflictException e) {
            throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
        } catch (GitAPIException e) {
            throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
        }
    else {
        Plumbing.createOrphanBranch(relRepo, "mdm/release/" + version);
        try {
            new Git(relRepo).checkout().setName("mdm/release/" + version).call();
        } catch (GitAPIException e) {
            throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
        }
    }

    // enumerate and copy in artifact files.
    File inputBase = new File(inputPath).getCanonicalFile();
    if (inputBase.isFile())
        inputBase = inputBase.getParentFile();
    File relRepoFile = new File(relRepoPath).getCanonicalFile();
    for (String input : inputFiles) {
        File inputFull = new File(inputBase, input);
        File dest = new File(relRepoFile, input);
        if (inputFull.isDirectory())
            FileUtils.copyDirectory(inputFull, dest, new FileFilter() {
                public boolean accept(File file) {
                    return !(file.isDirectory() && file.listFiles().length == 0);
                }
            }, true, false);
        else
            FileUtils.copyFile(inputFull, dest, true, false);
    }

    // commit the changes
    try {
        new Git(relRepo).add().addFilepattern(".").call();
    } catch (NoFilepatternException e) {
        throw new MajorBug(e); // why would an api throw exceptions like this *checked*?
    } catch (GitAPIException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    }
    try {
        CommitCommand commit = new Git(relRepo).commit().setMessage("release version " + version);
        if (!infixMode) {
            commit.setAmend(true); // because our mechanism for creating an orphan branch starts us with an empty commit.
            PersonIdent convergenceIdent = new PersonIdent("mdm", "", new Date(0), TimeZone.getTimeZone("GMT"));
            commit.setAuthor(convergenceIdent);
            commit.setCommitter(convergenceIdent);
        }
        commit.call();

        // this tag will be removed in a future release, as it's no longer required for any structural purpose
        // (long long ago in a galaxy far away, this was used as an easy way for `mdm status` to report version names... but execing `git describe --tags` hasn't been the way we do this anymore for a long time now)
        new Git(relRepo).tag().setName("release/" + version).setAnnotated(false).call();
    } catch (NoHeadException e) {
        throw new MdmException("your repository is in an invalid state!", e);
    } catch (ConcurrentRefUpdateException e) {
        throw new MdmException("aborted due to concurrent modification of repo");
    } catch (NoMessageException e) {
        throw new MajorBug(e); // why would an api throw exceptions like this *checked*?
    } catch (UnmergedPathsException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    } catch (WrongRepositoryStateException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    } catch (GitAPIException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    }

    // generate an accumulation commit.  do this from the master branch, but don't submit it yet, because when we roll in the artifacts we want them in a subdirectory so that when master is checked out all the versions are splayed out in the working tree at once.
    try {
        new Git(relRepo).checkout().setName("master").call();
    } catch (RefAlreadyExistsException e) {
        throw new MajorBug(e); // not even valid unless we're creating a new branch, which we aren't.
    } catch (RefNotFoundException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    } catch (InvalidRefNameException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    } catch (CheckoutConflictException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    } catch (GitAPIException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    }
    try {
        new Git(relRepo).merge().include(relRepo.getRef("mdm/release/" + version))
                .setFastForward(FastForwardMode.NO_FF).setCommit(false).call();
    } catch (NoHeadException e) {
        throw new MdmException("your repository is in an invalid state!", e);
    } catch (ConcurrentRefUpdateException e) {
        throw new MdmException("aborted due to concurrent modification of repo");
    } catch (CheckoutConflictException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    } catch (InvalidMergeHeadsException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    } catch (WrongRepositoryStateException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    } catch (NoMessageException e) {
        throw new MajorBug(e); // why would an api throw exceptions like this *checked*?  also, we're not even making a commit here.
    } catch (GitAPIException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    }

    // move the artifact files into a version-named directory
    File artifactDestFile = new File(relRepoFile, version);
    if (!artifactDestFile.mkdir())
        return new MdmExitMessage(":'(", "couldn't make the directory named \"" + version
                + "\" to put the releases into because there was already something there.");

    for (String input : inputFiles)
        new File(relRepoFile, input).renameTo(new File(artifactDestFile, input));

    // now fire off the accumulation commit, and that commit now becomes head of the master branch.
    try {
        RmCommand rmc = new Git(relRepo).rm();
        for (String input : inputFiles)
            rmc.addFilepattern(input);
        rmc.call();
        new Git(relRepo).add().addFilepattern(version).call();
    } catch (NoFilepatternException e) {
        throw new MajorBug(e); // why would an api throw exceptions like this *checked*?
    } catch (GitAPIException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    }
    try {
        new Git(relRepo).commit().setMessage("merge release version " + version + " to master").call();
        new Git(relRepo).tag().setName("mdm/master/" + version).setAnnotated(false).call();
    } catch (NoHeadException e) {
        throw new MdmException("your repository is in an invalid state!", e);
    } catch (ConcurrentRefUpdateException e) {
        throw new MdmException("aborted due to concurrent modification of repo");
    } catch (NoMessageException e) {
        throw new MajorBug(e); // why would an api throw exceptions like this *checked*?
    } catch (UnmergedPathsException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    } catch (WrongRepositoryStateException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    } catch (GitAPIException e) {
        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
    }

    // commit the new hash of the releases-repo into the project main repo (if we are operating in a canonically placed releases submodule)
    if (isInRepoRoot() && relRepoPath.equals("releases") && Plumbing.isCommitedGitlink(repo, "releases")) {
        try {
            new Git(repo).commit().setOnly("releases").setMessage("release version " + version).call();
            new Git(repo).tag().setName("release/" + version).setAnnotated(false).call();
        } catch (NoHeadException e) {
            throw new MdmException("your repository is in an invalid state!", e);
        } catch (ConcurrentRefUpdateException e) {
            throw new MdmException("aborted due to concurrent modification of repo");
        } catch (NoMessageException e) {
            throw new MajorBug(e); // why would an api throw exceptions like this *checked*?
        } catch (UnmergedPathsException e) {
            throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
        } catch (WrongRepositoryStateException e) {
            throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
        } catch (GitAPIException e) {
            throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
        }
    }

    return new MdmExitMessage(":D", "release version " + version + " complete");
}

From source file:org.apache.stratos.cartridge.agent.artifact.deployment.synchronizer.git.impl.GitBasedArtifactRepository.java

License:Apache License

/**
 * Removes the set of artifacts from local repo
 *
 * @param gitRepoCtx RepositoryContext instance
 * @param artifacts  Set of artifact names to remove
 *//*from w  ww .  ja va 2s  .  co m*/
private void removeArtifacts(RepositoryContext gitRepoCtx, Set<String> artifacts) {

    if (artifacts.isEmpty())
        return;

    RmCommand rmCmd = gitRepoCtx.getGit().rm();
    Iterator<String> it = artifacts.iterator();
    while (it.hasNext()) {
        rmCmd.addFilepattern(it.next());
    }

    try {
        rmCmd.call();
        if (log.isDebugEnabled()) {
            log.debug("Removed artifacts for tenant : " + gitRepoCtx.getTenantId());
        }

    } catch (GitAPIException e) {
        log.error(
                "Removing artifact from the local repository at " + gitRepoCtx.getGitLocalRepoPath() + "failed",
                e);
        log.error(e);
    }
}

From source file:org.commonjava.aprox.subsys.git.GitManager.java

License:Apache License

public GitManager deleteAndCommitPaths(final ChangeSummary summary, final Collection<String> paths)
        throws GitSubsystemException {
    try {/*from w  w  w .  j a v  a  2s.c o  m*/
        RmCommand rm = git.rm();
        CommitCommand commit = git.commit();

        for (final String path : paths) {
            rm = rm.addFilepattern(path);
            commit = commit.setOnly(path);
        }

        logger.info("Deleting:\n  " + join(paths, "\n  ") + "\n\nSummary: " + summary);

        rm.call();

        commit.setMessage(buildMessage(summary, paths)).setAuthor(summary.getUser(), email).call();
    } catch (final NoFilepatternException e) {
        throw new GitSubsystemException("Cannot remove from git: " + e.getMessage(), e);
    } catch (final GitAPIException e) {
        throw new GitSubsystemException("Cannot remove from git: " + e.getMessage(), e);
    }

    return this;
}