View Javadoc
1   /*
2    * Copyright (C) 2008, Google Inc. 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.patch;
12  
13  import static java.nio.charset.StandardCharsets.UTF_8;
14  
15  import java.util.Locale;
16  
17  import org.eclipse.jgit.util.RawParseUtils;
18  
19  /**
20   * An error in a patch script
21   */
22  public class FormatError {
23  	/** Classification of an error. */
24  	public enum Severity {
25  		/** The error is unexpected, but can be worked around. */
26  		WARNING,
27  
28  		/** The error indicates the script is severely flawed. */
29  		ERROR;
30  	}
31  
32  	private final byte[] buf;
33  
34  	private final int offset;
35  
36  	private final Severity severity;
37  
38  	private final String message;
39  
40  	FormatError(final byte[] buffer, final int ptr, final Severity sev,
41  			final String msg) {
42  		buf = buffer;
43  		offset = ptr;
44  		severity = sev;
45  		message = msg;
46  	}
47  
48  	/**
49  	 * Get the severity of the error.
50  	 *
51  	 * @return the severity of the error.
52  	 */
53  	public Severity getSeverity() {
54  		return severity;
55  	}
56  
57  	/**
58  	 * Get a message describing the error.
59  	 *
60  	 * @return a message describing the error.
61  	 */
62  	public String getMessage() {
63  		return message;
64  	}
65  
66  	/**
67  	 * Get the byte buffer holding the patch script.
68  	 *
69  	 * @return the byte buffer holding the patch script.
70  	 */
71  	public byte[] getBuffer() {
72  		return buf;
73  	}
74  
75  	/**
76  	 * Get byte offset within {@link #getBuffer()} where the error is.
77  	 *
78  	 * @return byte offset within {@link #getBuffer()} where the error is.
79  	 */
80  	public int getOffset() {
81  		return offset;
82  	}
83  
84  	/**
85  	 * Get line of the patch script the error appears on.
86  	 *
87  	 * @return line of the patch script the error appears on.
88  	 */
89  	public String getLineText() {
90  		final int eol = RawParseUtils.nextLF(buf, offset);
91  		return RawParseUtils.decode(UTF_8, buf, offset, eol);
92  	}
93  
94  	/** {@inheritDoc} */
95  	@Override
96  	public String toString() {
97  		final StringBuilder r = new StringBuilder();
98  		r.append(getSeverity().name().toLowerCase(Locale.ROOT));
99  		r.append(": at offset "); //$NON-NLS-1$
100 		r.append(getOffset());
101 		r.append(": "); //$NON-NLS-1$
102 		r.append(getMessage());
103 		r.append("\n"); //$NON-NLS-1$
104 		r.append("  in "); //$NON-NLS-1$
105 		r.append(getLineText());
106 		return r.toString();
107 	}
108 }