View Javadoc
1   /*
2    * Copyright (C) 2012, Matthias Sohn <matthias.sohn@sap.com>
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  package org.eclipse.jgit.api;
44  
45  import java.io.IOException;
46  import java.text.MessageFormat;
47  import java.text.ParseException;
48  import java.util.Date;
49  import java.util.Properties;
50  
51  import org.eclipse.jgit.api.errors.GitAPIException;
52  import org.eclipse.jgit.api.errors.JGitInternalException;
53  import org.eclipse.jgit.internal.JGitText;
54  import org.eclipse.jgit.internal.storage.dfs.DfsGarbageCollector;
55  import org.eclipse.jgit.internal.storage.dfs.DfsRepository;
56  import org.eclipse.jgit.internal.storage.file.FileRepository;
57  import org.eclipse.jgit.internal.storage.file.GC;
58  import org.eclipse.jgit.internal.storage.file.GC.RepoStatistics;
59  import org.eclipse.jgit.lib.ConfigConstants;
60  import org.eclipse.jgit.lib.ProgressMonitor;
61  import org.eclipse.jgit.lib.Repository;
62  import org.eclipse.jgit.lib.StoredConfig;
63  import org.eclipse.jgit.storage.pack.PackConfig;
64  import org.eclipse.jgit.util.GitDateParser;
65  
66  /**
67   * A class used to execute a {@code gc} command. It has setters for all
68   * supported options and arguments of this command and a {@link #call()} method
69   * to finally execute the command. Each instance of this class should only be
70   * used for one invocation of the command (means: one call to {@link #call()})
71   *
72   * @since 2.2
73   * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-gc.html"
74   *      >Git documentation about gc</a>
75   */
76  public class GarbageCollectCommand extends GitCommand<Properties> {
77  	/**
78  	 * Default value of maximum delta chain depth during aggressive garbage
79  	 * collection: {@value}
80  	 *
81  	 * @since 3.6
82  	 */
83  	public static final int DEFAULT_GC_AGGRESSIVE_DEPTH = 250;
84  
85  	/**
86  	 * Default window size during packing during aggressive garbage collection:
87  	 * * {@value}
88  	 *
89  	 * @since 3.6
90  	 */
91  	public static final int DEFAULT_GC_AGGRESSIVE_WINDOW = 250;
92  
93  	private ProgressMonitor monitor;
94  
95  	private Date expire;
96  
97  	private PackConfig pconfig;
98  
99  	/**
100 	 * @param repo
101 	 */
102 	protected GarbageCollectCommand(Repository repo) {
103 		super(repo);
104 		pconfig = new PackConfig(repo);
105 	}
106 
107 	/**
108 	 * @param monitor
109 	 *            a progress monitor
110 	 * @return this instance
111 	 */
112 	public GarbageCollectCommand setProgressMonitor(ProgressMonitor monitor) {
113 		this.monitor = monitor;
114 		return this;
115 	}
116 
117 	/**
118 	 * During gc() or prune() each unreferenced, loose object which has been
119 	 * created or modified after <code>expire</code> will not be pruned. Only
120 	 * older objects may be pruned. If set to null then every object is a
121 	 * candidate for pruning. Use {@link GitDateParser} to parse time formats
122 	 * used by git gc.
123 	 *
124 	 * @param expire
125 	 *            minimal age of objects to be pruned.
126 	 * @return this instance
127 	 */
128 	public GarbageCollectCommand setExpire(Date expire) {
129 		this.expire = expire;
130 		return this;
131 	}
132 
133 	/**
134 	 * Whether to use aggressive mode or not. If set to true JGit behaves more
135 	 * similar to native git's "git gc --aggressive". If set to
136 	 * <code>true</code> compressed objects found in old packs are not reused
137 	 * but every object is compressed again. Configuration variables
138 	 * pack.window and pack.depth are set to 250 for this GC.
139 	 *
140 	 * @since 3.6
141 	 * @param aggressive
142 	 *            whether to turn on or off aggressive mode
143 	 * @return this instance
144 	 */
145 	public GarbageCollectCommand setAggressive(boolean aggressive) {
146 		if (aggressive) {
147 			StoredConfig repoConfig = repo.getConfig();
148 			pconfig.setDeltaSearchWindowSize(repoConfig.getInt(
149 					ConfigConstants.CONFIG_GC_SECTION,
150 					ConfigConstants.CONFIG_KEY_AGGRESSIVE_WINDOW,
151 					DEFAULT_GC_AGGRESSIVE_WINDOW));
152 			pconfig.setMaxDeltaDepth(repoConfig.getInt(
153 					ConfigConstants.CONFIG_GC_SECTION,
154 					ConfigConstants.CONFIG_KEY_AGGRESSIVE_DEPTH,
155 					DEFAULT_GC_AGGRESSIVE_DEPTH));
156 			pconfig.setReuseObjects(false);
157 		} else
158 			pconfig = new PackConfig(repo);
159 		return this;
160 	}
161 
162 	/**
163 	 * Whether to preserve old pack files instead of deleting them.
164 	 *
165 	 * @since 4.7
166 	 * @param preserveOldPacks
167 	 *            whether to preserve old pack files
168 	 * @return this instance
169 	 */
170 	public GarbageCollectCommand setPreserveOldPacks(boolean preserveOldPacks) {
171 		if (pconfig == null)
172 			pconfig = new PackConfig(repo);
173 
174 		pconfig.setPreserveOldPacks(preserveOldPacks);
175 		return this;
176 	}
177 
178 	/**
179 	 * Whether to prune preserved pack files in the preserved directory.
180 	 *
181 	 * @since 4.7
182 	 * @param prunePreserved
183 	 *            whether to prune preserved pack files
184 	 * @return this instance
185 	 */
186 	public GarbageCollectCommand setPrunePreserved(boolean prunePreserved) {
187 		if (pconfig == null)
188 			pconfig = new PackConfig(repo);
189 
190 		pconfig.setPrunePreserved(prunePreserved);
191 		return this;
192 	}
193 
194 	@Override
195 	public Properties call() throws GitAPIException {
196 		checkCallable();
197 
198 		try {
199 			if (repo instanceof FileRepository) {
200 				GC gc = new GC((FileRepository) repo);
201 				gc.setPackConfig(pconfig);
202 				gc.setProgressMonitor(monitor);
203 				if (this.expire != null)
204 					gc.setExpire(expire);
205 
206 				try {
207 					gc.gc();
208 					return toProperties(gc.getStatistics());
209 				} catch (ParseException e) {
210 					throw new JGitInternalException(JGitText.get().gcFailed, e);
211 				}
212 			} else if (repo instanceof DfsRepository) {
213 				DfsGarbageCollector gc =
214 					new DfsGarbageCollector((DfsRepository) repo);
215 				gc.setPackConfig(pconfig);
216 				gc.pack(monitor);
217 				return new Properties();
218 			} else {
219 				throw new UnsupportedOperationException(MessageFormat.format(
220 						JGitText.get().unsupportedGC,
221 						repo.getClass().toString()));
222 			}
223 		} catch (IOException e) {
224 			throw new JGitInternalException(JGitText.get().gcFailed, e);
225 		}
226 	}
227 
228 	/**
229 	 * Computes and returns the repository statistics.
230 	 *
231 	 * @return the repository statistics
232 	 * @throws GitAPIException
233 	 *             thrown if the repository statistics cannot be computed
234 	 * @since 3.0
235 	 */
236 	public Properties getStatistics() throws GitAPIException {
237 		try {
238 			if (repo instanceof FileRepository) {
239 				GC gc = new GC((FileRepository) repo);
240 				return toProperties(gc.getStatistics());
241 			} else {
242 				return new Properties();
243 			}
244 		} catch (IOException e) {
245 			throw new JGitInternalException(
246 					JGitText.get().couldNotGetRepoStatistics, e);
247 		}
248 	}
249 
250 	@SuppressWarnings("boxing")
251 	private static Properties toProperties(RepoStatistics stats) {
252 		Properties p = new Properties();
253 		p.put("numberOfLooseObjects", stats.numberOfLooseObjects); //$NON-NLS-1$
254 		p.put("numberOfLooseRefs", stats.numberOfLooseRefs); //$NON-NLS-1$
255 		p.put("numberOfPackedObjects", stats.numberOfPackedObjects); //$NON-NLS-1$
256 		p.put("numberOfPackedRefs", stats.numberOfPackedRefs); //$NON-NLS-1$
257 		p.put("numberOfPackFiles", stats.numberOfPackFiles); //$NON-NLS-1$
258 		p.put("sizeOfLooseObjects", stats.sizeOfLooseObjects); //$NON-NLS-1$
259 		p.put("sizeOfPackedObjects", stats.sizeOfPackedObjects); //$NON-NLS-1$
260 		return p;
261 	}
262 }