View Javadoc
1   /*
2    * Copyright (C) 2008-2009, Google Inc.
3    * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com>
4    * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
5    * and other copyright owners as documented in the project's IP log.
6    *
7    * This program and the accompanying materials are made available
8    * under the terms of the Eclipse Distribution License v1.0 which
9    * accompanies this distribution, is reproduced below, and is
10   * available at http://www.eclipse.org/org/documents/edl-v10.php
11   *
12   * All rights reserved.
13   *
14   * Redistribution and use in source and binary forms, with or
15   * without modification, are permitted provided that the following
16   * conditions are met:
17   *
18   * - Redistributions of source code must retain the above copyright
19   *   notice, this list of conditions and the following disclaimer.
20   *
21   * - Redistributions in binary form must reproduce the above
22   *   copyright notice, this list of conditions and the following
23   *   disclaimer in the documentation and/or other materials provided
24   *   with the distribution.
25   *
26   * - Neither the name of the Eclipse Foundation, Inc. nor the
27   *   names of its contributors may be used to endorse or promote
28   *   products derived from this software without specific prior
29   *   written permission.
30   *
31   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
32   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
33   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
36   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
37   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
39   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
40   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
41   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
42   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
43   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44   */
45  
46  package org.eclipse.jgit.revwalk;
47  
48  import static java.nio.charset.StandardCharsets.UTF_8;
49  
50  import java.io.IOException;
51  import java.nio.charset.Charset;
52  import java.nio.charset.IllegalCharsetNameException;
53  import java.nio.charset.UnsupportedCharsetException;
54  
55  import org.eclipse.jgit.errors.CorruptObjectException;
56  import org.eclipse.jgit.errors.IncorrectObjectTypeException;
57  import org.eclipse.jgit.errors.MissingObjectException;
58  import org.eclipse.jgit.lib.AnyObjectId;
59  import org.eclipse.jgit.lib.Constants;
60  import org.eclipse.jgit.lib.ObjectInserter;
61  import org.eclipse.jgit.lib.ObjectReader;
62  import org.eclipse.jgit.lib.PersonIdent;
63  import org.eclipse.jgit.util.MutableInteger;
64  import org.eclipse.jgit.util.RawParseUtils;
65  import org.eclipse.jgit.util.StringUtils;
66  
67  /** An annotated tag. */
68  public class RevTag extends RevObject {
69  	/**
70  	 * Parse an annotated tag from its canonical format.
71  	 *
72  	 * This method constructs a temporary revision pool, parses the tag as
73  	 * supplied, and returns it to the caller. Since the tag was built inside of
74  	 * a private revision pool its object pointer will be initialized, but will
75  	 * not have its headers loaded.
76  	 *
77  	 * Applications are discouraged from using this API. Callers usually need
78  	 * more than one object. Use {@link RevWalk#parseTag(AnyObjectId)} to obtain
79  	 * a RevTag from an existing repository.
80  	 *
81  	 * @param raw
82  	 *            the canonical formatted tag to be parsed.
83  	 * @return the parsed tag, in an isolated revision pool that is not
84  	 *         available to the caller.
85  	 * @throws CorruptObjectException
86  	 *             the tag contains a malformed header that cannot be handled.
87  	 */
88  	public static RevTag parse(byte[] raw) throws CorruptObjectException {
89  		return parse(new RevWalk((ObjectReader) null), raw);
90  	}
91  
92  	/**
93  	 * Parse an annotated tag from its canonical format.
94  	 * <p>
95  	 * This method inserts the tag directly into the caller supplied revision
96  	 * pool, making it appear as though the tag exists in the repository, even
97  	 * if it doesn't. The repository under the pool is not affected.
98  	 * <p>
99  	 * The body of the tag (message, tagger, signature) is always retained in
100 	 * the returned {@code RevTag}, even if the supplied {@code RevWalk} has
101 	 * been configured with {@code setRetainBody(false)}.
102 	 *
103 	 * @param rw
104 	 *            the revision pool to allocate the tag within. The tag's object
105 	 *            pointer will be obtained from this pool.
106 	 * @param raw
107 	 *            the canonical formatted tag to be parsed. This buffer will be
108 	 *            retained by the returned {@code RevTag} and must not be
109 	 *            modified by the caller.
110 	 * @return the parsed tag, in an isolated revision pool that is not
111 	 *         available to the caller.
112 	 * @throws CorruptObjectException
113 	 *             the tag contains a malformed header that cannot be handled.
114 	 */
115 	public static RevTag parse(RevWalk rw, byte[] raw)
116 			throws CorruptObjectException {
117 		try (ObjectInserter.Formatter fmt = new ObjectInserter.Formatter()) {
118 			RevTag r = rw.lookupTag(fmt.idFor(Constants.OBJ_TAG, raw));
119 			r.parseCanonical(rw, raw);
120 			r.buffer = raw;
121 			return r;
122 		}
123 	}
124 
125 	private RevObject object;
126 
127 	private byte[] buffer;
128 
129 	private String tagName;
130 
131 	/**
132 	 * Create a new tag reference.
133 	 *
134 	 * @param id
135 	 *            object name for the tag.
136 	 */
137 	protected RevTag(final AnyObjectId id) {
138 		super(id);
139 	}
140 
141 	@Override
142 	void parseHeaders(final RevWalk walk) throws MissingObjectException,
143 			IncorrectObjectTypeException, IOException {
144 		parseCanonical(walk, walk.getCachedBytes(this));
145 	}
146 
147 	@Override
148 	void parseBody(final RevWalk walk) throws MissingObjectException,
149 			IncorrectObjectTypeException, IOException {
150 		if (buffer == null) {
151 			buffer = walk.getCachedBytes(this);
152 			if ((flags & PARSED) == 0)
153 				parseCanonical(walk, buffer);
154 		}
155 	}
156 
157 	void parseCanonical(final RevWalk walk, final byte[] rawTag)
158 			throws CorruptObjectException {
159 		final MutableInteger pos = new MutableInteger();
160 		final int oType;
161 
162 		pos.value = 53; // "object $sha1\ntype "
163 		oType = Constants.decodeTypeString(this, rawTag, (byte) '\n', pos);
164 		walk.idBuffer.fromString(rawTag, 7);
165 		object = walk.lookupAny(walk.idBuffer, oType);
166 
167 		int p = pos.value += 4; // "tag "
168 		final int nameEnd = RawParseUtils.nextLF(rawTag, p) - 1;
169 		tagName = RawParseUtils.decode(UTF_8, rawTag, p, nameEnd);
170 
171 		if (walk.isRetainBody())
172 			buffer = rawTag;
173 		flags |= PARSED;
174 	}
175 
176 	@Override
177 	public final int getType() {
178 		return Constants.OBJ_TAG;
179 	}
180 
181 	/**
182 	 * Parse the tagger identity from the raw buffer.
183 	 * <p>
184 	 * This method parses and returns the content of the tagger line, after
185 	 * taking the tag's character set into account and decoding the tagger
186 	 * name and email address. This method is fairly expensive and produces a
187 	 * new PersonIdent instance on each invocation. Callers should invoke this
188 	 * method only if they are certain they will be outputting the result, and
189 	 * should cache the return value for as long as necessary to use all
190 	 * information from it.
191 	 *
192 	 * @return identity of the tagger (name, email) and the time the tag
193 	 *         was made by the tagger; null if no tagger line was found.
194 	 */
195 	public final PersonIdent getTaggerIdent() {
196 		final byte[] raw = buffer;
197 		final int nameB = RawParseUtils.tagger(raw, 0);
198 		if (nameB < 0)
199 			return null;
200 		return RawParseUtils.parsePersonIdent(raw, nameB);
201 	}
202 
203 	/**
204 	 * Parse the complete tag message and decode it to a string.
205 	 * <p>
206 	 * This method parses and returns the message portion of the tag buffer,
207 	 * after taking the tag's character set into account and decoding the buffer
208 	 * using that character set. This method is a fairly expensive operation and
209 	 * produces a new string on each invocation.
210 	 *
211 	 * @return decoded tag message as a string. Never null.
212 	 */
213 	public final String getFullMessage() {
214 		byte[] raw = buffer;
215 		int msgB = RawParseUtils.tagMessage(raw, 0);
216 		if (msgB < 0) {
217 			return ""; //$NON-NLS-1$
218 		}
219 		return RawParseUtils.decode(guessEncoding(), raw, msgB, raw.length);
220 	}
221 
222 	/**
223 	 * Parse the tag message and return the first "line" of it.
224 	 * <p>
225 	 * The first line is everything up to the first pair of LFs. This is the
226 	 * "oneline" format, suitable for output in a single line display.
227 	 * <p>
228 	 * This method parses and returns the message portion of the tag buffer,
229 	 * after taking the tag's character set into account and decoding the buffer
230 	 * using that character set. This method is a fairly expensive operation and
231 	 * produces a new string on each invocation.
232 	 *
233 	 * @return decoded tag message as a string. Never null. The returned string
234 	 *         does not contain any LFs, even if the first paragraph spanned
235 	 *         multiple lines. Embedded LFs are converted to spaces.
236 	 */
237 	public final String getShortMessage() {
238 		byte[] raw = buffer;
239 		int msgB = RawParseUtils.tagMessage(raw, 0);
240 		if (msgB < 0) {
241 			return ""; //$NON-NLS-1$
242 		}
243 
244 		int msgE = RawParseUtils.endOfParagraph(raw, msgB);
245 		String str = RawParseUtils.decode(guessEncoding(), raw, msgB, msgE);
246 		if (RevCommit.hasLF(raw, msgB, msgE)) {
247 			str = StringUtils.replaceLineBreaksWithSpace(str);
248 		}
249 		return str;
250 	}
251 
252 	private Charset guessEncoding() {
253 		try {
254 			return RawParseUtils.parseEncoding(buffer);
255 		} catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
256 			return UTF_8;
257 		}
258 	}
259 
260 	/**
261 	 * Get a reference to the object this tag was placed on.
262 	 * <p>
263 	 * Note that the returned object has only been looked up (see
264 	 * {@link RevWalk#lookupAny(AnyObjectId, int)}. To access the contents it
265 	 * needs to be parsed, see {@link RevWalk#parseHeaders(RevObject)} and
266 	 * {@link RevWalk#parseBody(RevObject)}.
267 	 * <p>
268 	 * As an alternative, use {@link RevWalk#peel(RevObject)} and pass this
269 	 * {@link RevTag} to peel it until the first non-tag object.
270 	 *
271 	 * @return object this tag refers to (only looked up, not parsed)
272 	 */
273 	public final RevObject getObject() {
274 		return object;
275 	}
276 
277 	/**
278 	 * Get the name of this tag, from the tag header.
279 	 *
280 	 * @return name of the tag, according to the tag header.
281 	 */
282 	public final String getTagName() {
283 		return tagName;
284 	}
285 
286 	/**
287 	 * Discard the message buffer to reduce memory usage.
288 	 * <p>
289 	 * After discarding the memory usage of the {@code RevTag} is reduced to
290 	 * only the {@link #getObject()} pointer and {@link #getTagName()}.
291 	 * Accessing other properties such as {@link #getTaggerIdent()} or either
292 	 * message function requires reloading the buffer by invoking
293 	 * {@link RevWalk#parseBody(RevObject)}.
294 	 *
295 	 * @since 4.0
296 	 */
297 	public final void disposeBody() {
298 		buffer = null;
299 	}
300 }