aboutsummaryrefslogtreecommitdiff
path: root/jimfs/src/main/java/com/google/common/jimfs/GlobToRegex.java
blob: c3e463b8795484d52319a326a024615bb5719030 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/*
 * Copyright 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.jimfs;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.regex.PatternSyntaxException;

/**
 * Translates globs to regex patterns.
 *
 * @author Colin Decker
 */
final class GlobToRegex {

  /**
   * Converts the given glob to a regular expression pattern. The given separators determine what
   * characters the resulting expression breaks on for glob expressions such as * which should not
   * cross directory boundaries.
   *
   * <p>Basic conversions (assuming / as only separator):
   *
   * <pre>{@code
   * ?        = [^/]
   * *        = [^/]*
   * **       = .*
   * [a-z]    = [[^/]&&[a-z]]
   * [!a-z]   = [[^/]&&[^a-z]]
   * {a,b,c}  = (a|b|c)
   * }</pre>
   */
  public static String toRegex(String glob, String separators) {
    return new GlobToRegex(glob, separators).convert();
  }

  private static final InternalCharMatcher REGEX_RESERVED =
      InternalCharMatcher.anyOf("^$.?+*\\[]{}()");

  private final String glob;
  private final String separators;
  private final InternalCharMatcher separatorMatcher;

  private final StringBuilder builder = new StringBuilder();
  private final Deque<State> states = new ArrayDeque<>();
  private int index;

  private GlobToRegex(String glob, String separators) {
    this.glob = checkNotNull(glob);
    this.separators = separators;
    this.separatorMatcher = InternalCharMatcher.anyOf(separators);
  }

  /**
   * Converts the glob to a regex one character at a time. A state stack (states) is maintained,
   * with the state at the top of the stack being the current state at any given time. The current
   * state is always used to process the next character. When a state processes a character, it may
   * pop the current state or push a new state as the current state. The resulting regex is written
   * to {@code builder}.
   */
  private String convert() {
    pushState(NORMAL);
    for (index = 0; index < glob.length(); index++) {
      currentState().process(this, glob.charAt(index));
    }
    currentState().finish(this);
    return builder.toString();
  }

  /** Enters the given state. The current state becomes the previous state. */
  private void pushState(State state) {
    states.push(state);
  }

  /** Returns to the previous state. */
  private void popState() {
    states.pop();
  }

  /** Returns the current state. */
  private State currentState() {
    return states.peek();
  }

  /** Throws a {@link PatternSyntaxException}. */
  private PatternSyntaxException syntaxError(String desc) {
    throw new PatternSyntaxException(desc, glob, index);
  }

  /** Appends the given character as-is to the regex. */
  private void appendExact(char c) {
    builder.append(c);
  }

  /** Appends the regex form of the given normal character or separator from the glob. */
  private void append(char c) {
    if (separatorMatcher.matches(c)) {
      appendSeparator();
    } else {
      appendNormal(c);
    }
  }

  /** Appends the regex form of the given normal character from the glob. */
  private void appendNormal(char c) {
    if (REGEX_RESERVED.matches(c)) {
      builder.append('\\');
    }
    builder.append(c);
  }

  /** Appends the regex form matching the separators for the path type. */
  private void appendSeparator() {
    if (separators.length() == 1) {
      appendNormal(separators.charAt(0));
    } else {
      builder.append('[');
      for (int i = 0; i < separators.length(); i++) {
        appendInBracket(separators.charAt(i));
      }
      builder.append("]");
    }
  }

  /** Appends the regex form that matches anything except the separators for the path type. */
  private void appendNonSeparator() {
    builder.append("[^");
    for (int i = 0; i < separators.length(); i++) {
      appendInBracket(separators.charAt(i));
    }
    builder.append(']');
  }

  /** Appends the regex form of the glob ? character. */
  private void appendQuestionMark() {
    appendNonSeparator();
  }

  /** Appends the regex form of the glob * character. */
  private void appendStar() {
    appendNonSeparator();
    builder.append('*');
  }

  /** Appends the regex form of the glob ** pattern. */
  private void appendStarStar() {
    builder.append(".*");
  }

  /** Appends the regex form of the start of a glob [] section. */
  private void appendBracketStart() {
    builder.append('[');
    appendNonSeparator();
    builder.append("&&[");
  }

  /** Appends the regex form of the end of a glob [] section. */
  private void appendBracketEnd() {
    builder.append("]]");
  }

  /** Appends the regex form of the given character within a glob [] section. */
  private void appendInBracket(char c) {
    // escape \ in regex character class
    if (c == '\\') {
      builder.append('\\');
    }

    builder.append(c);
  }

  /** Appends the regex form of the start of a glob {} section. */
  private void appendCurlyBraceStart() {
    builder.append('(');
  }

  /** Appends the regex form of the separator (,) within a glob {} section. */
  private void appendSubpatternSeparator() {
    builder.append('|');
  }

  /** Appends the regex form of the end of a glob {} section. */
  private void appendCurlyBraceEnd() {
    builder.append(')');
  }

  /** Converter state. */
  private abstract static class State {
    /**
     * Process the next character with the current state, transitioning the converter to a new state
     * if necessary.
     */
    abstract void process(GlobToRegex converter, char c);

    /** Called after all characters have been read. */
    void finish(GlobToRegex converter) {}
  }

  /** Normal state. */
  private static final State NORMAL =
      new State() {
        @Override
        void process(GlobToRegex converter, char c) {
          switch (c) {
            case '?':
              converter.appendQuestionMark();
              return;
            case '[':
              converter.appendBracketStart();
              converter.pushState(BRACKET_FIRST_CHAR);
              return;
            case '{':
              converter.appendCurlyBraceStart();
              converter.pushState(CURLY_BRACE);
              return;
            case '*':
              converter.pushState(STAR);
              return;
            case '\\':
              converter.pushState(ESCAPE);
              return;
            default:
              converter.append(c);
          }
        }

        @Override
        public String toString() {
          return "NORMAL";
        }
      };

  /** State following the reading of a single \. */
  private static final State ESCAPE =
      new State() {
        @Override
        void process(GlobToRegex converter, char c) {
          converter.append(c);
          converter.popState();
        }

        @Override
        void finish(GlobToRegex converter) {
          throw converter.syntaxError("Hanging escape (\\) at end of pattern");
        }

        @Override
        public String toString() {
          return "ESCAPE";
        }
      };

  /** State following the reading of a single *. */
  private static final State STAR =
      new State() {
        @Override
        void process(GlobToRegex converter, char c) {
          if (c == '*') {
            converter.appendStarStar();
            converter.popState();
          } else {
            converter.appendStar();
            converter.popState();
            converter.currentState().process(converter, c);
          }
        }

        @Override
        void finish(GlobToRegex converter) {
          converter.appendStar();
        }

        @Override
        public String toString() {
          return "STAR";
        }
      };

  /** State immediately following the reading of a [. */
  private static final State BRACKET_FIRST_CHAR =
      new State() {
        @Override
        void process(GlobToRegex converter, char c) {
          if (c == ']') {
            // A glob like "[]]" or "[]q]" is apparently fine in Unix (when used with ls for
            // example) but doesn't work for the default java.nio.file implementations. In the cases
            // of "[]]" it produces:
            // java.util.regex.PatternSyntaxException: Unclosed character class near index 13
            // ^[[^/]&&[]]\]$
            //              ^
            // The error here is slightly different, but trying to make this work would require some
            // kind of lookahead and break the simplicity of char-by-char conversion here. Also, if
            // someone wants to include a ']' inside a character class, they should escape it.
            throw converter.syntaxError("Empty []");
          }
          if (c == '!') {
            converter.appendExact('^');
          } else if (c == '-') {
            converter.appendExact(c);
          } else {
            converter.appendInBracket(c);
          }
          converter.popState();
          converter.pushState(BRACKET);
        }

        @Override
        void finish(GlobToRegex converter) {
          throw converter.syntaxError("Unclosed [");
        }

        @Override
        public String toString() {
          return "BRACKET_FIRST_CHAR";
        }
      };

  /** State inside [brackets], but not at the first character inside the brackets. */
  private static final State BRACKET =
      new State() {
        @Override
        void process(GlobToRegex converter, char c) {
          if (c == ']') {
            converter.appendBracketEnd();
            converter.popState();
          } else {
            converter.appendInBracket(c);
          }
        }

        @Override
        void finish(GlobToRegex converter) {
          throw converter.syntaxError("Unclosed [");
        }

        @Override
        public String toString() {
          return "BRACKET";
        }
      };

  /** State inside {curly braces}. */
  private static final State CURLY_BRACE =
      new State() {
        @Override
        void process(GlobToRegex converter, char c) {
          switch (c) {
            case '?':
              converter.appendQuestionMark();
              break;
            case '[':
              converter.appendBracketStart();
              converter.pushState(BRACKET_FIRST_CHAR);
              break;
            case '{':
              throw converter.syntaxError("{ not allowed in subpattern group");
            case '*':
              converter.pushState(STAR);
              break;
            case '\\':
              converter.pushState(ESCAPE);
              break;
            case '}':
              converter.appendCurlyBraceEnd();
              converter.popState();
              break;
            case ',':
              converter.appendSubpatternSeparator();
              break;
            default:
              converter.append(c);
          }
        }

        @Override
        void finish(GlobToRegex converter) {
          throw converter.syntaxError("Unclosed {");
        }

        @Override
        public String toString() {
          return "CURLY_BRACE";
        }
      };
}