View Javadoc
1   /*
2    * Copyright (C) 2016, Ned Twigg <ned.twigg@diffplug.com> and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.pgm;
12  
13  import java.io.IOException;
14  import java.text.MessageFormat;
15  import java.util.Set;
16  
17  import org.eclipse.jgit.api.Git;
18  import org.eclipse.jgit.api.errors.GitAPIException;
19  import org.eclipse.jgit.errors.NoWorkTreeException;
20  import org.eclipse.jgit.pgm.internal.CLIText;
21  import org.kohsuke.args4j.Option;
22  
23  @Command(common = true, usage = "usage_Clean")
24  class Clean extends TextBuiltin {
25  	@Option(name = "-d", usage = "usage_removeUntrackedDirectories")
26  	private boolean dirs = false;
27  
28  	@Option(name = "--force", aliases = {
29  			"-f" }, usage = "usage_forceClean")
30  	private boolean force = false;
31  
32  	@Option(name = "--dryRun", aliases = { "-n" })
33  	private boolean dryRun = false;
34  
35  	/** {@inheritDoc} */
36  	@Override
37  	protected void run() {
38  		try (Git git = new Git(db)) {
39  			boolean requireForce = git.getRepository().getConfig()
40  					.getBoolean("clean", "requireForce", true); //$NON-NLS-1$ //$NON-NLS-2$
41  			if (requireForce && !(force || dryRun)) {
42  				throw die(CLIText.fatalError(CLIText.get().cleanRequireForce));
43  			}
44  			// Note that CleanCommand's setForce(true) will delete
45  			// .git folders. In the cgit cli, this behavior
46  			// requires setting "-f" twice, not sure how to do
47  			// this with args4j, so this feature is unimplemented
48  			// for now.
49  			Set<String> removedFiles = git.clean().setCleanDirectories(dirs)
50  					.setDryRun(dryRun).call();
51  			for (String removedFile : removedFiles) {
52  				outw.println(MessageFormat.format(CLIText.get().removing,
53  						removedFile));
54  			}
55  		} catch (NoWorkTreeException | GitAPIException | IOException e) {
56  			throw die(e.getMessage(), e);
57  		}
58  	}
59  }