CleanCommand.java

  1. /*
  2.  * Copyright (C) 2011, Chris Aniszczyk <zx@redhat.com>
  3.  * Copyright (C) 2011, Abhishek Bhatnagar <abhatnag@redhat.com>
  4.  * and other copyright owners as documented in the project's IP log.
  5.  *
  6.  * This program and the accompanying materials are made available
  7.  * under the terms of the Eclipse Distribution License v1.0 which
  8.  * accompanies this distribution, is reproduced below, and is
  9.  * available at http://www.eclipse.org/org/documents/edl-v10.php
  10.  *
  11.  * All rights reserved.
  12.  *
  13.  * Redistribution and use in source and binary forms, with or
  14.  * without modification, are permitted provided that the following
  15.  * conditions are met:
  16.  *
  17.  * - Redistributions of source code must retain the above copyright
  18.  *   notice, this list of conditions and the following disclaimer.
  19.  *
  20.  * - Redistributions in binary form must reproduce the above
  21.  *   copyright notice, this list of conditions and the following
  22.  *   disclaimer in the documentation and/or other materials provided
  23.  *   with the distribution.
  24.  *
  25.  * - Neither the name of the Eclipse Foundation, Inc. nor the
  26.  *   names of its contributors may be used to endorse or promote
  27.  *   products derived from this software without specific prior
  28.  *   written permission.
  29.  *
  30.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31.  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32.  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33.  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34.  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35.  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36.  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37.  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38.  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39.  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40.  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41.  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42.  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43.  */
  44. package org.eclipse.jgit.api;

  45. import static org.eclipse.jgit.lib.Constants.DOT_GIT;

  46. import java.io.File;
  47. import java.io.IOException;
  48. import java.util.Collections;
  49. import java.util.Set;
  50. import java.util.TreeSet;

  51. import org.eclipse.jgit.api.errors.GitAPIException;
  52. import org.eclipse.jgit.api.errors.JGitInternalException;
  53. import org.eclipse.jgit.errors.NoWorkTreeException;
  54. import org.eclipse.jgit.events.WorkingTreeModifiedEvent;
  55. import org.eclipse.jgit.lib.Repository;
  56. import org.eclipse.jgit.util.FS;
  57. import org.eclipse.jgit.util.FileUtils;

  58. /**
  59.  * Remove untracked files from the working tree
  60.  *
  61.  * @see <a
  62.  *      href="http://www.kernel.org/pub/software/scm/git/docs/git-clean.html"
  63.  *      >Git documentation about Clean</a>
  64.  */
  65. public class CleanCommand extends GitCommand<Set<String>> {

  66.     private Set<String> paths = Collections.emptySet();

  67.     private boolean dryRun;

  68.     private boolean directories;

  69.     private boolean ignore = true;

  70.     private boolean force = false;

  71.     /**
  72.      * Constructor for CleanCommand
  73.      *
  74.      * @param repo
  75.      *            the {@link org.eclipse.jgit.lib.Repository}
  76.      */
  77.     protected CleanCommand(Repository repo) {
  78.         super(repo);
  79.     }

  80.     /**
  81.      * {@inheritDoc}
  82.      * <p>
  83.      * Executes the {@code clean} command with all the options and parameters
  84.      * collected by the setter methods of this class. Each instance of this
  85.      * class should only be used for one invocation of the command (means: one
  86.      * call to {@link #call()})
  87.      */
  88.     @Override
  89.     public Set<String> call() throws NoWorkTreeException, GitAPIException {
  90.         Set<String> files = new TreeSet<>();
  91.         try {
  92.             StatusCommand command = new StatusCommand(repo);
  93.             Status status = command.call();

  94.             Set<String> untrackedFiles = new TreeSet<>(status.getUntracked());
  95.             Set<String> untrackedDirs = new TreeSet<>(
  96.                     status.getUntrackedFolders());

  97.             FS fs = getRepository().getFS();
  98.             for (String p : status.getIgnoredNotInIndex()) {
  99.                 File f = new File(repo.getWorkTree(), p);
  100.                 if (fs.isFile(f) || fs.isSymLink(f)) {
  101.                     untrackedFiles.add(p);
  102.                 } else if (fs.isDirectory(f)) {
  103.                     untrackedDirs.add(p);
  104.                 }
  105.             }

  106.             Set<String> filtered = filterFolders(untrackedFiles, untrackedDirs);

  107.             Set<String> notIgnoredFiles = filterIgnorePaths(filtered,
  108.                     status.getIgnoredNotInIndex(), true);
  109.             Set<String> notIgnoredDirs = filterIgnorePaths(untrackedDirs,
  110.                     status.getIgnoredNotInIndex(), false);

  111.             for (String file : notIgnoredFiles)
  112.                 if (paths.isEmpty() || paths.contains(file)) {
  113.                     files = cleanPath(file, files);
  114.                 }

  115.             for (String dir : notIgnoredDirs)
  116.                 if (paths.isEmpty() || paths.contains(dir)) {
  117.                     files = cleanPath(dir, files);
  118.                 }
  119.         } catch (IOException e) {
  120.             throw new JGitInternalException(e.getMessage(), e);
  121.         } finally {
  122.             if (!dryRun && !files.isEmpty()) {
  123.                 repo.fireEvent(new WorkingTreeModifiedEvent(null, files));
  124.             }
  125.         }
  126.         return files;
  127.     }

  128.     /**
  129.      * When dryRun is false, deletes the specified path from disk. If dryRun
  130.      * is true, no paths are actually deleted. In both cases, the paths that
  131.      * would have been deleted are added to inFiles and returned.
  132.      *
  133.      * Paths that are directories are recursively deleted when
  134.      * {@link #directories} is true.
  135.      * Paths that are git repositories are recursively deleted when
  136.      * {@link #directories} and {@link #force} are both true.
  137.      *
  138.      * @param path
  139.      *          The path to be cleaned
  140.      * @param inFiles
  141.      *          A set of strings representing the files that have been cleaned
  142.      *          already, the path to be cleaned will be added to this set
  143.      *          before being returned.
  144.      *
  145.      * @return a set of strings with the cleaned path added to it
  146.      * @throws IOException
  147.      */
  148.     private Set<String> cleanPath(String path, Set<String> inFiles)
  149.             throws IOException {
  150.         File curFile = new File(repo.getWorkTree(), path);
  151.         if (curFile.isDirectory()) {
  152.             if (directories) {
  153.                 // Is this directory a git repository?
  154.                 if (new File(curFile, DOT_GIT).exists()) {
  155.                     if (force) {
  156.                         if (!dryRun) {
  157.                             FileUtils.delete(curFile, FileUtils.RECURSIVE
  158.                                     | FileUtils.SKIP_MISSING);
  159.                         }
  160.                         inFiles.add(path + "/"); //$NON-NLS-1$
  161.                     }
  162.                 } else {
  163.                     if (!dryRun) {
  164.                         FileUtils.delete(curFile,
  165.                                 FileUtils.RECURSIVE | FileUtils.SKIP_MISSING);
  166.                     }
  167.                     inFiles.add(path + "/"); //$NON-NLS-1$
  168.                 }
  169.             }
  170.         } else {
  171.             if (!dryRun) {
  172.                 FileUtils.delete(curFile, FileUtils.SKIP_MISSING);
  173.             }
  174.             inFiles.add(path);
  175.         }

  176.         return inFiles;
  177.     }

  178.     private Set<String> filterIgnorePaths(Set<String> inputPaths,
  179.             Set<String> ignoredNotInIndex, boolean exact) {
  180.         if (ignore) {
  181.             Set<String> filtered = new TreeSet<>(inputPaths);
  182.             for (String path : inputPaths)
  183.                 for (String ignored : ignoredNotInIndex)
  184.                     if ((exact && path.equals(ignored))
  185.                             || (!exact && path.startsWith(ignored))) {
  186.                         filtered.remove(path);
  187.                         break;
  188.                     }

  189.             return filtered;
  190.         }
  191.         return inputPaths;
  192.     }

  193.     private Set<String> filterFolders(Set<String> untracked,
  194.             Set<String> untrackedFolders) {
  195.         Set<String> filtered = new TreeSet<>(untracked);
  196.         for (String file : untracked)
  197.             for (String folder : untrackedFolders)
  198.                 if (file.startsWith(folder)) {
  199.                     filtered.remove(file);
  200.                     break;
  201.                 }


  202.         return filtered;
  203.     }

  204.     /**
  205.      * If paths are set, only these paths are affected by the cleaning.
  206.      *
  207.      * @param paths
  208.      *            the paths to set (with <code>/</code> as separator)
  209.      * @return {@code this}
  210.      */
  211.     public CleanCommand setPaths(Set<String> paths) {
  212.         this.paths = paths;
  213.         return this;
  214.     }

  215.     /**
  216.      * If dryRun is set, the paths in question will not actually be deleted.
  217.      *
  218.      * @param dryRun
  219.      *            whether to do a dry run or not
  220.      * @return {@code this}
  221.      */
  222.     public CleanCommand setDryRun(boolean dryRun) {
  223.         this.dryRun = dryRun;
  224.         return this;
  225.     }

  226.     /**
  227.      * If force is set, directories that are git repositories will also be
  228.      * deleted.
  229.      *
  230.      * @param force
  231.      *            whether or not to delete git repositories
  232.      * @return {@code this}
  233.      * @since 4.5
  234.      */
  235.     public CleanCommand setForce(boolean force) {
  236.         this.force = force;
  237.         return this;
  238.     }

  239.     /**
  240.      * If dirs is set, in addition to files, also clean directories.
  241.      *
  242.      * @param dirs
  243.      *            whether to clean directories too, or only files.
  244.      * @return {@code this}
  245.      */
  246.     public CleanCommand setCleanDirectories(boolean dirs) {
  247.         directories = dirs;
  248.         return this;
  249.     }

  250.     /**
  251.      * If ignore is set, don't report/clean files/directories that are ignored
  252.      * by a .gitignore. otherwise do handle them.
  253.      *
  254.      * @param ignore
  255.      *            whether to respect .gitignore or not.
  256.      * @return {@code this}
  257.      */
  258.     public CleanCommand setIgnore(boolean ignore) {
  259.         this.ignore = ignore;
  260.         return this;
  261.     }
  262. }