View Javadoc
1   /*
2    * Copyright (C) 2010, Red Hat Inc.
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.attributes;
44  
45  import static org.eclipse.jgit.ignore.internal.IMatcher.NO_MATCH;
46  
47  import java.util.ArrayList;
48  import java.util.Collections;
49  import java.util.List;
50  
51  import org.eclipse.jgit.attributes.Attribute.State;
52  import org.eclipse.jgit.errors.InvalidPatternException;
53  import org.eclipse.jgit.ignore.FastIgnoreRule;
54  import org.eclipse.jgit.ignore.internal.IMatcher;
55  import org.eclipse.jgit.ignore.internal.PathMatcher;
56  
57  /**
58   * A single attributes rule corresponding to one line in a .gitattributes file.
59   *
60   * Inspiration from: {@link FastIgnoreRule}
61   *
62   * @since 3.7
63   */
64  public class AttributesRule {
65  
66  	/**
67  	 * regular expression for splitting attributes - space, tab and \r (the C
68  	 * implementation oddly enough allows \r between attributes)
69  	 * */
70  	private static final String ATTRIBUTES_SPLIT_REGEX = "[ \t\r]"; //$NON-NLS-1$
71  
72  	private static List<Attribute> parseAttributes(String attributesLine) {
73  		// the C implementation oddly enough allows \r between attributes too.
74  		ArrayList<Attribute> result = new ArrayList<Attribute>();
75  		for (String attribute : attributesLine.split(ATTRIBUTES_SPLIT_REGEX)) {
76  			attribute = attribute.trim();
77  			if (attribute.length() == 0)
78  				continue;
79  
80  			if (attribute.startsWith("-")) {//$NON-NLS-1$
81  				if (attribute.length() > 1)
82  					result.add(new Attribute(attribute.substring(1),
83  							State.UNSET));
84  				continue;
85  			}
86  
87  			final int equalsIndex = attribute.indexOf("="); //$NON-NLS-1$
88  			if (equalsIndex == -1)
89  				result.add(new Attribute(attribute, State.SET));
90  			else {
91  				String attributeKey = attribute.substring(0, equalsIndex);
92  				if (attributeKey.length() > 0) {
93  					String attributeValue = attribute
94  							.substring(equalsIndex + 1);
95  					result.add(new Attribute(attributeKey, attributeValue));
96  				}
97  			}
98  		}
99  		return result;
100 	}
101 
102 	private final String pattern;
103 	private final List<Attribute> attributes;
104 
105 	private boolean nameOnly;
106 	private boolean dirOnly;
107 
108 	private IMatcher matcher;
109 
110 	/**
111 	 * Create a new attribute rule with the given pattern. Assumes that the
112 	 * pattern is already trimmed.
113 	 *
114 	 * @param pattern
115 	 *            Base pattern for the attributes rule. This pattern will be
116 	 *            parsed to generate rule parameters. It can not be
117 	 *            <code>null</code>.
118 	 * @param attributes
119 	 *            the rule attributes. This string will be parsed to read the
120 	 *            attributes.
121 	 */
122 	public AttributesRule(String pattern, String attributes) {
123 		this.attributes = parseAttributes(attributes);
124 		nameOnly = false;
125 		dirOnly = false;
126 
127 		if (pattern.endsWith("/")) { //$NON-NLS-1$
128 			pattern = pattern.substring(0, pattern.length() - 1);
129 			dirOnly = true;
130 		}
131 
132 		boolean hasSlash = pattern.contains("/"); //$NON-NLS-1$
133 
134 		if (!hasSlash)
135 			nameOnly = true;
136 		else if (!pattern.startsWith("/")) { //$NON-NLS-1$
137 			// Contains "/" but does not start with one
138 			// Adding / to the start should not interfere with matching
139 			pattern = "/" + pattern; //$NON-NLS-1$
140 		}
141 
142 		try {
143 			matcher = PathMatcher.createPathMatcher(pattern,
144 					Character.valueOf(FastIgnoreRule.PATH_SEPARATOR), dirOnly);
145 		} catch (InvalidPatternException e) {
146 			matcher = NO_MATCH;
147 		}
148 
149 		this.pattern = pattern;
150 	}
151 
152 	/**
153 	 * @return True if the pattern should match directories only
154 	 */
155 	public boolean dirOnly() {
156 		return dirOnly;
157 	}
158 
159 	/**
160 	 * Returns the attributes.
161 	 *
162 	 * @return an unmodifiable list of attributes (never returns
163 	 *         <code>null</code>)
164 	 */
165 	public List<Attribute> getAttributes() {
166 		return Collections.unmodifiableList(attributes);
167 	}
168 
169 	/**
170 	 * @return <code>true</code> if the pattern is just a file name and not a
171 	 *         path
172 	 */
173 	public boolean isNameOnly() {
174 		return nameOnly;
175 	}
176 
177 	/**
178 	 * @return The blob pattern to be used as a matcher (never returns
179 	 *         <code>null</code>)
180 	 */
181 	public String getPattern() {
182 		return pattern;
183 	}
184 
185 	/**
186 	 * Returns <code>true</code> if a match was made.
187 	 *
188 	 * @param relativeTarget
189 	 *            Name pattern of the file, relative to the base directory of
190 	 *            this rule
191 	 * @param isDirectory
192 	 *            Whether the target file is a directory or not
193 	 * @return True if a match was made.
194 	 */
195 	public boolean isMatch(String relativeTarget, boolean isDirectory) {
196 		if (relativeTarget == null)
197 			return false;
198 		if (relativeTarget.length() == 0)
199 			return false;
200 		boolean match = matcher.matches(relativeTarget, isDirectory);
201 		return match;
202 	}
203 }