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 	@Override
163 	public Properties call() throws GitAPIException {
164 		checkCallable();
165 
166 		try {
167 			if (repo instanceof FileRepository) {
168 				GC gc = new GC((FileRepository) repo);
169 				gc.setPackConfig(pconfig);
170 				gc.setProgressMonitor(monitor);
171 				if (this.expire != null)
172 					gc.setExpire(expire);
173 
174 				try {
175 					gc.gc();
176 					return toProperties(gc.getStatistics());
177 				} catch (ParseException e) {
178 					throw new JGitInternalException(JGitText.get().gcFailed, e);
179 				}
180 			} else if (repo instanceof DfsRepository) {
181 				DfsGarbageCollector gc =
182 					new DfsGarbageCollector((DfsRepository) repo);
183 				gc.setPackConfig(pconfig);
184 				gc.pack(monitor);
185 				return new Properties();
186 			} else {
187 				throw new UnsupportedOperationException(MessageFormat.format(
188 						JGitText.get().unsupportedGC,
189 						repo.getClass().toString()));
190 			}
191 		} catch (IOException e) {
192 			throw new JGitInternalException(JGitText.get().gcFailed, e);
193 		}
194 	}
195 
196 	/**
197 	 * Computes and returns the repository statistics.
198 	 *
199 	 * @return the repository statistics
200 	 * @throws GitAPIException
201 	 *             thrown if the repository statistics cannot be computed
202 	 * @since 3.0
203 	 */
204 	public Properties getStatistics() throws GitAPIException {
205 		try {
206 			if (repo instanceof FileRepository) {
207 				GC gc = new GC((FileRepository) repo);
208 				return toProperties(gc.getStatistics());
209 			} else {
210 				return new Properties();
211 			}
212 		} catch (IOException e) {
213 			throw new JGitInternalException(
214 					JGitText.get().couldNotGetRepoStatistics, e);
215 		}
216 	}
217 
218 	@SuppressWarnings("boxing")
219 	private static Properties toProperties(RepoStatistics stats) {
220 		Properties p = new Properties();
221 		p.put("numberOfLooseObjects", stats.numberOfLooseObjects); //$NON-NLS-1$
222 		p.put("numberOfLooseRefs", stats.numberOfLooseRefs); //$NON-NLS-1$
223 		p.put("numberOfPackedObjects", stats.numberOfPackedObjects); //$NON-NLS-1$
224 		p.put("numberOfPackedRefs", stats.numberOfPackedRefs); //$NON-NLS-1$
225 		p.put("numberOfPackFiles", stats.numberOfPackFiles); //$NON-NLS-1$
226 		p.put("sizeOfLooseObjects", stats.sizeOfLooseObjects); //$NON-NLS-1$
227 		p.put("sizeOfPackedObjects", stats.sizeOfPackedObjects); //$NON-NLS-1$
228 		return p;
229 	}
230 }