Added a clean command.

Change-Id: I05d5392789b5b64e6ee44f678556cf25dc30d7ba
Signed-off-by: Ned Twigg <ned.twigg@diffplug.com>
diff --git a/org.eclipse.jgit.pgm.test/tst/org/eclipse/jgit/pgm/CleanTest.java b/org.eclipse.jgit.pgm.test/tst/org/eclipse/jgit/pgm/CleanTest.java
new file mode 100644
index 0000000..bbac296
--- /dev/null
+++ b/org.eclipse.jgit.pgm.test/tst/org/eclipse/jgit/pgm/CleanTest.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright (C) 2016, Ned Twigg <ned.twigg@diffplug.com>
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ *   copyright notice, this list of conditions and the following
+ *   disclaimer in the documentation and/or other materials provided
+ *   with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ *   names of its contributors may be used to endorse or promote
+ *   products derived from this software without specific prior
+ *   written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+package org.eclipse.jgit.pgm;
+
+import org.eclipse.jgit.api.Git;
+import org.eclipse.jgit.lib.CLIRepositoryTestCase;
+import org.junit.Test;
+import static org.eclipse.jgit.junit.JGitTestUtil.check;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+
+public class CleanTest extends CLIRepositoryTestCase {
+	@Test
+	public void testCleanRequiresForce() throws Exception {
+		try (Git git = new Git(db)) {
+			assertArrayOfLinesEquals(
+					new String[] { "Removing a", "Removing b" },
+					execute("git clean"));
+		} catch (Die e) {
+			// TODO: should be "fatal: clean.requireForce defaults to true and
+			// neither -i, -n, nor -f given; refusing to clean" but we don't
+			// support -i yet. Fix this when/if we add support for -i.
+			assertEquals(
+					"fatal: clean.requireForce defaults to true and neither -n nor -f given; refusing to clean",
+					e.getMessage());
+		}
+	}
+
+	@Test
+	public void testCleanRequiresForceConfig() throws Exception {
+		try (Git git = new Git(db)) {
+			git.getRepository().getConfig().setBoolean("clean", null,
+					"requireForce", false);
+			assertArrayOfLinesEquals(
+					new String[] { "" },
+					execute("git clean"));
+		}
+	}
+
+	@Test
+	public void testCleanLeaveDirs() throws Exception {
+		try (Git git = new Git(db)) {
+			git.commit().setMessage("initial commit").call();
+
+			writeTrashFile("dir/file", "someData");
+			writeTrashFile("a", "someData");
+			writeTrashFile("b", "someData");
+
+			// all these files should be there
+			assertTrue(check(db, "a"));
+			assertTrue(check(db, "b"));
+			assertTrue(check(db, "dir/file"));
+
+			// dry run should make no change
+			assertArrayOfLinesEquals(
+					new String[] { "Removing a", "Removing b" },
+					execute("git clean -n"));
+			assertTrue(check(db, "a"));
+			assertTrue(check(db, "b"));
+			assertTrue(check(db, "dir/file"));
+
+			// force should make a change
+			assertArrayOfLinesEquals(
+					new String[] { "Removing a", "Removing b" },
+					execute("git clean -f"));
+			assertFalse(check(db, "a"));
+			assertFalse(check(db, "b"));
+			assertTrue(check(db, "dir/file"));
+		}
+	}
+
+	@Test
+	public void testCleanDeleteDirs() throws Exception {
+		try (Git git = new Git(db)) {
+			git.commit().setMessage("initial commit").call();
+
+			writeTrashFile("dir/file", "someData");
+			writeTrashFile("a", "someData");
+			writeTrashFile("b", "someData");
+
+			// all these files should be there
+			assertTrue(check(db, "a"));
+			assertTrue(check(db, "b"));
+			assertTrue(check(db, "dir/file"));
+
+			assertArrayOfLinesEquals(
+					new String[] { "Removing a", "Removing b",
+							"Removing dir/" },
+					execute("git clean -d -f"));
+			assertFalse(check(db, "a"));
+			assertFalse(check(db, "b"));
+			assertFalse(check(db, "dir/file"));
+		}
+	}
+}
diff --git a/org.eclipse.jgit.pgm/META-INF/services/org.eclipse.jgit.pgm.TextBuiltin b/org.eclipse.jgit.pgm/META-INF/services/org.eclipse.jgit.pgm.TextBuiltin
index c159f7d..5495be6 100644
--- a/org.eclipse.jgit.pgm/META-INF/services/org.eclipse.jgit.pgm.TextBuiltin
+++ b/org.eclipse.jgit.pgm/META-INF/services/org.eclipse.jgit.pgm.TextBuiltin
@@ -4,6 +4,7 @@
 org.eclipse.jgit.pgm.Blame
 org.eclipse.jgit.pgm.Branch
 org.eclipse.jgit.pgm.Checkout
+org.eclipse.jgit.pgm.Clean
 org.eclipse.jgit.pgm.Clone
 org.eclipse.jgit.pgm.Commit
 org.eclipse.jgit.pgm.Config
diff --git a/org.eclipse.jgit.pgm/resources/org/eclipse/jgit/pgm/internal/CLIText.properties b/org.eclipse.jgit.pgm/resources/org/eclipse/jgit/pgm/internal/CLIText.properties
index abe04b8..6990559 100644
--- a/org.eclipse.jgit.pgm/resources/org/eclipse/jgit/pgm/internal/CLIText.properties
+++ b/org.eclipse.jgit.pgm/resources/org/eclipse/jgit/pgm/internal/CLIText.properties
@@ -46,6 +46,7 @@
 changesToBeCommitted=Changes to be committed:
 checkoutConflict=error: Your local changes to the following files would be overwritten by checkout:
 checkoutConflictPathLine=\t{0}
+cleanRequireForce=clean.requireForce defaults to true and neither -n nor -f given; refusing to clean
 clonedEmptyRepository=warning: You appear to have cloned an empty repository.
 cloningInto=Cloning into ''{0}''...
 commitLabel=commit
@@ -177,6 +178,7 @@
 remoteMessage=remote: {0}
 remoteRefObjectChangedIsNotExpectedOne=remote ref object changed - is not expected one {0}
 remoteSideDoesNotSupportDeletingRefs=remote side does not support deleting refs
+removing=Removing {0}
 repaint=Repaint
 s3InvalidBucket=Invalid S3 bucket ''{0}''
 serviceNotSupported=Service ''{0}'' not supported
@@ -212,6 +214,7 @@
 usage_Aggressive=This option will cause gc to more aggressively optimize the repository at the expense of taking much more time
 usage_bareClone=Make a bare Git repository. That is, instead of creating [DIRECTORY] and placing the administrative files in [DIRECTORY]/.git, make the [DIRECTORY] itself the $GIT_DIR.
 usage_Blame=Show what revision and author last modified each line
+usage_Clean=Remove untracked files from the working tree
 usage_CommandLineClientForamazonsS3Service=Command line client for Amazon's S3 service
 usage_CommitAll=commit all modified and deleted files
 usage_CommitAuthor=Override the author name used in the commit. You can use the standard A U Thor <author@example.com> format.
@@ -323,6 +326,7 @@
 usage_fixAThinPackToBeComplete=fix a thin pack to be complete
 usage_forEachRefOutput=for-each-ref output
 usage_forceCheckout=when switching branches, proceed even if the index or the working tree differs from HEAD
+usage_forceClean=required to delete files or directories
 usage_forceCreateBranchEvenExists=force create branch even exists
 usage_forceReplacingAnExistingTag=force replacing an existing tag
 usage_getAndSetOptions=Get and set repository or global options
@@ -362,6 +366,7 @@
 usage_quiet=don't show progress messages
 usage_recordChangesToRepository=Record changes to the repository
 usage_recurseIntoSubtrees=recurse into subtrees
+usage_removeUntrackedDirectories=remove untracked directories
 usage_renameLimit=limit size of rename matrix
 usage_reset=Reset current HEAD to the specified state
 usage_resetReference=Reset to given reference name
diff --git a/org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Clean.java b/org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Clean.java
new file mode 100644
index 0000000..fa94d2c
--- /dev/null
+++ b/org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/Clean.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2016, Ned Twigg <ned.twigg@diffplug.com>
+ * and other copyright owners as documented in the project's IP log.
+ *
+ * This program and the accompanying materials are made available
+ * under the terms of the Eclipse Distribution License v1.0 which
+ * accompanies this distribution, is reproduced below, and is
+ * available at http://www.eclipse.org/org/documents/edl-v10.php
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ *
+ * - Redistributions in binary form must reproduce the above
+ *   copyright notice, this list of conditions and the following
+ *   disclaimer in the documentation and/or other materials provided
+ *   with the distribution.
+ *
+ * - Neither the name of the Eclipse Foundation, Inc. nor the
+ *   names of its contributors may be used to endorse or promote
+ *   products derived from this software without specific prior
+ *   written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
+ * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.eclipse.jgit.pgm;
+
+import java.text.MessageFormat;
+import java.util.Set;
+
+import org.eclipse.jgit.api.Git;
+import org.eclipse.jgit.pgm.internal.CLIText;
+import org.kohsuke.args4j.Option;
+
+@Command(common = true, usage = "usage_clean")
+class Clean extends TextBuiltin {
+	@Option(name = "-d", usage = "usage_removeUntrackedDirectories")
+	private boolean dirs = false;
+
+	@Option(name = "--force", aliases = {
+			"-f" }, usage = "usage_forceClean")
+	private boolean force = false;
+
+	@Option(name = "--dryRun", aliases = { "-n" })
+	private boolean dryRun = false;
+
+	@Override
+	protected void run() throws Exception {
+		try (Git git = new Git(db)) {
+			boolean requireForce = git.getRepository().getConfig()
+					.getBoolean("clean", "requireForce", true); //$NON-NLS-1$ //$NON-NLS-2$
+			if (requireForce && !(force || dryRun)) {
+				throw die(CLIText.fatalError(CLIText.get().cleanRequireForce));
+			}
+			// Note that CleanCommand's setForce(true) will delete
+			// .git folders. In the cgit cli, this behavior
+			// requires setting "-f" twice, not sure how to do
+			// this with args4j, so this feature is unimplemented
+			// for now.
+			Set<String> removedFiles = git.clean().setCleanDirectories(dirs)
+					.setDryRun(dryRun).call();
+			for (String removedFile : removedFiles) {
+				outw.println(MessageFormat.format(CLIText.get().removing,
+						removedFile));
+			}
+		}
+	}
+}
diff --git a/org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/internal/CLIText.java b/org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/internal/CLIText.java
index e99fe00..4148cf6 100644
--- a/org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/internal/CLIText.java
+++ b/org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/internal/CLIText.java
@@ -125,6 +125,7 @@ public static String fatalError(String message) {
 	/***/ public String changesToBeCommitted;
 	/***/ public String checkoutConflict;
 	/***/ public String checkoutConflictPathLine;
+	/***/ public String cleanRequireForce;
 	/***/ public String clonedEmptyRepository;
 	/***/ public String cloningInto;
 	/***/ public String commitLabel;
@@ -246,6 +247,7 @@ public static String fatalError(String message) {
 	/***/ public String remoteMessage;
 	/***/ public String remoteRefObjectChangedIsNotExpectedOne;
 	/***/ public String remoteSideDoesNotSupportDeletingRefs;
+	/***/ public String removing;
 	/***/ public String repaint;
 	/***/ public String s3InvalidBucket;
 	/***/ public String serviceNotSupported;