@herb-tools/linter 0.8.6 → 0.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { getNodesBeforePosition, getNodesAfterPosition, filterNodes, ERBContentNode, isERBOutputNode, Visitor, isToken, isParseResult, getStaticAttributeName, hasDynamicAttributeName as hasDynamicAttributeName$1, getCombinedAttributeName, hasStaticContent, getStaticContentFromNodes, Location, hasERBOutput, isEffectivelyStatic, getValidatableStaticContent, isERBNode, isWhitespaceNode, isCommentNode, isLiteralNode, isHTMLTextNode, Position, filterERBContentNodes, isNode, LiteralNode, didyoumean, filterLiteralNodes, Token, getTagName as getTagName$1, isHTMLElementNode, HTMLCloseTagNode, isHTMLOpenTagNode, WhitespaceNode, filterWhitespaceNodes, HTMLOpenTagNode, isERBCommentNode } from '@herb-tools/core';
2
+ import picomatch from 'picomatch';
2
3
 
3
4
  class PrintContext {
4
5
  output = "";
@@ -669,2061 +670,6 @@ class ERBToRubyStringPrinter extends IdentityPrinter {
669
670
  }
670
671
  }
671
672
 
672
- const balanced = (a, b, str) => {
673
- const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
674
- const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
675
- const r = ma !== null && mb != null && range(ma, mb, str);
676
- return (r && {
677
- start: r[0],
678
- end: r[1],
679
- pre: str.slice(0, r[0]),
680
- body: str.slice(r[0] + ma.length, r[1]),
681
- post: str.slice(r[1] + mb.length),
682
- });
683
- };
684
- const maybeMatch = (reg, str) => {
685
- const m = str.match(reg);
686
- return m ? m[0] : null;
687
- };
688
- const range = (a, b, str) => {
689
- let begs, beg, left, right = undefined, result;
690
- let ai = str.indexOf(a);
691
- let bi = str.indexOf(b, ai + 1);
692
- let i = ai;
693
- if (ai >= 0 && bi > 0) {
694
- if (a === b) {
695
- return [ai, bi];
696
- }
697
- begs = [];
698
- left = str.length;
699
- while (i >= 0 && !result) {
700
- if (i === ai) {
701
- begs.push(i);
702
- ai = str.indexOf(a, i + 1);
703
- }
704
- else if (begs.length === 1) {
705
- const r = begs.pop();
706
- if (r !== undefined)
707
- result = [r, bi];
708
- }
709
- else {
710
- beg = begs.pop();
711
- if (beg !== undefined && beg < left) {
712
- left = beg;
713
- right = bi;
714
- }
715
- bi = str.indexOf(b, i + 1);
716
- }
717
- i = ai < bi && ai >= 0 ? ai : bi;
718
- }
719
- if (begs.length && right !== undefined) {
720
- result = [left, right];
721
- }
722
- }
723
- return result;
724
- };
725
-
726
- const escSlash = '\0SLASH' + Math.random() + '\0';
727
- const escOpen = '\0OPEN' + Math.random() + '\0';
728
- const escClose = '\0CLOSE' + Math.random() + '\0';
729
- const escComma = '\0COMMA' + Math.random() + '\0';
730
- const escPeriod = '\0PERIOD' + Math.random() + '\0';
731
- const escSlashPattern = new RegExp(escSlash, 'g');
732
- const escOpenPattern = new RegExp(escOpen, 'g');
733
- const escClosePattern = new RegExp(escClose, 'g');
734
- const escCommaPattern = new RegExp(escComma, 'g');
735
- const escPeriodPattern = new RegExp(escPeriod, 'g');
736
- const slashPattern = /\\\\/g;
737
- const openPattern = /\\{/g;
738
- const closePattern = /\\}/g;
739
- const commaPattern = /\\,/g;
740
- const periodPattern = /\\./g;
741
- function numeric(str) {
742
- return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
743
- }
744
- function escapeBraces(str) {
745
- return str
746
- .replace(slashPattern, escSlash)
747
- .replace(openPattern, escOpen)
748
- .replace(closePattern, escClose)
749
- .replace(commaPattern, escComma)
750
- .replace(periodPattern, escPeriod);
751
- }
752
- function unescapeBraces(str) {
753
- return str
754
- .replace(escSlashPattern, '\\')
755
- .replace(escOpenPattern, '{')
756
- .replace(escClosePattern, '}')
757
- .replace(escCommaPattern, ',')
758
- .replace(escPeriodPattern, '.');
759
- }
760
- /**
761
- * Basically just str.split(","), but handling cases
762
- * where we have nested braced sections, which should be
763
- * treated as individual members, like {a,{b,c},d}
764
- */
765
- function parseCommaParts(str) {
766
- if (!str) {
767
- return [''];
768
- }
769
- const parts = [];
770
- const m = balanced('{', '}', str);
771
- if (!m) {
772
- return str.split(',');
773
- }
774
- const { pre, body, post } = m;
775
- const p = pre.split(',');
776
- p[p.length - 1] += '{' + body + '}';
777
- const postParts = parseCommaParts(post);
778
- if (post.length) {
779
- p[p.length - 1] += postParts.shift();
780
- p.push.apply(p, postParts);
781
- }
782
- parts.push.apply(parts, p);
783
- return parts;
784
- }
785
- function expand(str) {
786
- if (!str) {
787
- return [];
788
- }
789
- // I don't know why Bash 4.3 does this, but it does.
790
- // Anything starting with {} will have the first two bytes preserved
791
- // but *only* at the top level, so {},a}b will not expand to anything,
792
- // but a{},b}c will be expanded to [a}c,abc].
793
- // One could argue that this is a bug in Bash, but since the goal of
794
- // this module is to match Bash's rules, we escape a leading {}
795
- if (str.slice(0, 2) === '{}') {
796
- str = '\\{\\}' + str.slice(2);
797
- }
798
- return expand_(escapeBraces(str), true).map(unescapeBraces);
799
- }
800
- function embrace(str) {
801
- return '{' + str + '}';
802
- }
803
- function isPadded(el) {
804
- return /^-?0\d/.test(el);
805
- }
806
- function lte(i, y) {
807
- return i <= y;
808
- }
809
- function gte(i, y) {
810
- return i >= y;
811
- }
812
- function expand_(str, isTop) {
813
- /** @type {string[]} */
814
- const expansions = [];
815
- const m = balanced('{', '}', str);
816
- if (!m)
817
- return [str];
818
- // no need to expand pre, since it is guaranteed to be free of brace-sets
819
- const pre = m.pre;
820
- const post = m.post.length ? expand_(m.post, false) : [''];
821
- if (/\$$/.test(m.pre)) {
822
- for (let k = 0; k < post.length; k++) {
823
- const expansion = pre + '{' + m.body + '}' + post[k];
824
- expansions.push(expansion);
825
- }
826
- }
827
- else {
828
- const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
829
- const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
830
- const isSequence = isNumericSequence || isAlphaSequence;
831
- const isOptions = m.body.indexOf(',') >= 0;
832
- if (!isSequence && !isOptions) {
833
- // {a},b}
834
- if (m.post.match(/,(?!,).*\}/)) {
835
- str = m.pre + '{' + m.body + escClose + m.post;
836
- return expand_(str);
837
- }
838
- return [str];
839
- }
840
- let n;
841
- if (isSequence) {
842
- n = m.body.split(/\.\./);
843
- }
844
- else {
845
- n = parseCommaParts(m.body);
846
- if (n.length === 1 && n[0] !== undefined) {
847
- // x{{a,b}}y ==> x{a}y x{b}y
848
- n = expand_(n[0], false).map(embrace);
849
- //XXX is this necessary? Can't seem to hit it in tests.
850
- /* c8 ignore start */
851
- if (n.length === 1) {
852
- return post.map(p => m.pre + n[0] + p);
853
- }
854
- /* c8 ignore stop */
855
- }
856
- }
857
- // at this point, n is the parts, and we know it's not a comma set
858
- // with a single entry.
859
- let N;
860
- if (isSequence && n[0] !== undefined && n[1] !== undefined) {
861
- const x = numeric(n[0]);
862
- const y = numeric(n[1]);
863
- const width = Math.max(n[0].length, n[1].length);
864
- let incr = n.length === 3 && n[2] !== undefined ? Math.abs(numeric(n[2])) : 1;
865
- let test = lte;
866
- const reverse = y < x;
867
- if (reverse) {
868
- incr *= -1;
869
- test = gte;
870
- }
871
- const pad = n.some(isPadded);
872
- N = [];
873
- for (let i = x; test(i, y); i += incr) {
874
- let c;
875
- if (isAlphaSequence) {
876
- c = String.fromCharCode(i);
877
- if (c === '\\') {
878
- c = '';
879
- }
880
- }
881
- else {
882
- c = String(i);
883
- if (pad) {
884
- const need = width - c.length;
885
- if (need > 0) {
886
- const z = new Array(need + 1).join('0');
887
- if (i < 0) {
888
- c = '-' + z + c.slice(1);
889
- }
890
- else {
891
- c = z + c;
892
- }
893
- }
894
- }
895
- }
896
- N.push(c);
897
- }
898
- }
899
- else {
900
- N = [];
901
- for (let j = 0; j < n.length; j++) {
902
- N.push.apply(N, expand_(n[j], false));
903
- }
904
- }
905
- for (let j = 0; j < N.length; j++) {
906
- for (let k = 0; k < post.length; k++) {
907
- const expansion = pre + N[j] + post[k];
908
- if (!isTop || isSequence || expansion) {
909
- expansions.push(expansion);
910
- }
911
- }
912
- }
913
- }
914
- return expansions;
915
- }
916
-
917
- const MAX_PATTERN_LENGTH = 1024 * 64;
918
- const assertValidPattern = (pattern) => {
919
- if (typeof pattern !== 'string') {
920
- throw new TypeError('invalid pattern');
921
- }
922
- if (pattern.length > MAX_PATTERN_LENGTH) {
923
- throw new TypeError('pattern is too long');
924
- }
925
- };
926
-
927
- // translate the various posix character classes into unicode properties
928
- // this works across all unicode locales
929
- // { <posix class>: [<translation>, /u flag required, negated]
930
- const posixClasses = {
931
- '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
932
- '[:alpha:]': ['\\p{L}\\p{Nl}', true],
933
- '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
934
- '[:blank:]': ['\\p{Zs}\\t', true],
935
- '[:cntrl:]': ['\\p{Cc}', true],
936
- '[:digit:]': ['\\p{Nd}', true],
937
- '[:graph:]': ['\\p{Z}\\p{C}', true, true],
938
- '[:lower:]': ['\\p{Ll}', true],
939
- '[:print:]': ['\\p{C}', true],
940
- '[:punct:]': ['\\p{P}', true],
941
- '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
942
- '[:upper:]': ['\\p{Lu}', true],
943
- '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
944
- '[:xdigit:]': ['A-Fa-f0-9', false],
945
- };
946
- // only need to escape a few things inside of brace expressions
947
- // escapes: [ \ ] -
948
- const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
949
- // escape all regexp magic characters
950
- const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
951
- // everything has already been escaped, we just have to join
952
- const rangesToString = (ranges) => ranges.join('');
953
- // takes a glob string at a posix brace expression, and returns
954
- // an equivalent regular expression source, and boolean indicating
955
- // whether the /u flag needs to be applied, and the number of chars
956
- // consumed to parse the character class.
957
- // This also removes out of order ranges, and returns ($.) if the
958
- // entire class just no good.
959
- const parseClass = (glob, position) => {
960
- const pos = position;
961
- /* c8 ignore start */
962
- if (glob.charAt(pos) !== '[') {
963
- throw new Error('not in a brace expression');
964
- }
965
- /* c8 ignore stop */
966
- const ranges = [];
967
- const negs = [];
968
- let i = pos + 1;
969
- let sawStart = false;
970
- let uflag = false;
971
- let escaping = false;
972
- let negate = false;
973
- let endPos = pos;
974
- let rangeStart = '';
975
- WHILE: while (i < glob.length) {
976
- const c = glob.charAt(i);
977
- if ((c === '!' || c === '^') && i === pos + 1) {
978
- negate = true;
979
- i++;
980
- continue;
981
- }
982
- if (c === ']' && sawStart && !escaping) {
983
- endPos = i + 1;
984
- break;
985
- }
986
- sawStart = true;
987
- if (c === '\\') {
988
- if (!escaping) {
989
- escaping = true;
990
- i++;
991
- continue;
992
- }
993
- // escaped \ char, fall through and treat like normal char
994
- }
995
- if (c === '[' && !escaping) {
996
- // either a posix class, a collation equivalent, or just a [
997
- for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
998
- if (glob.startsWith(cls, i)) {
999
- // invalid, [a-[] is fine, but not [a-[:alpha]]
1000
- if (rangeStart) {
1001
- return ['$.', false, glob.length - pos, true];
1002
- }
1003
- i += cls.length;
1004
- if (neg)
1005
- negs.push(unip);
1006
- else
1007
- ranges.push(unip);
1008
- uflag = uflag || u;
1009
- continue WHILE;
1010
- }
1011
- }
1012
- }
1013
- // now it's just a normal character, effectively
1014
- escaping = false;
1015
- if (rangeStart) {
1016
- // throw this range away if it's not valid, but others
1017
- // can still match.
1018
- if (c > rangeStart) {
1019
- ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
1020
- }
1021
- else if (c === rangeStart) {
1022
- ranges.push(braceEscape(c));
1023
- }
1024
- rangeStart = '';
1025
- i++;
1026
- continue;
1027
- }
1028
- // now might be the start of a range.
1029
- // can be either c-d or c-] or c<more...>] or c] at this point
1030
- if (glob.startsWith('-]', i + 1)) {
1031
- ranges.push(braceEscape(c + '-'));
1032
- i += 2;
1033
- continue;
1034
- }
1035
- if (glob.startsWith('-', i + 1)) {
1036
- rangeStart = c;
1037
- i += 2;
1038
- continue;
1039
- }
1040
- // not the start of a range, just a single character
1041
- ranges.push(braceEscape(c));
1042
- i++;
1043
- }
1044
- if (endPos < i) {
1045
- // didn't see the end of the class, not a valid class,
1046
- // but might still be valid as a literal match.
1047
- return ['', false, 0, false];
1048
- }
1049
- // if we got no ranges and no negates, then we have a range that
1050
- // cannot possibly match anything, and that poisons the whole glob
1051
- if (!ranges.length && !negs.length) {
1052
- return ['$.', false, glob.length - pos, true];
1053
- }
1054
- // if we got one positive range, and it's a single character, then that's
1055
- // not actually a magic pattern, it's just that one literal character.
1056
- // we should not treat that as "magic", we should just return the literal
1057
- // character. [_] is a perfectly valid way to escape glob magic chars.
1058
- if (negs.length === 0 &&
1059
- ranges.length === 1 &&
1060
- /^\\?.$/.test(ranges[0]) &&
1061
- !negate) {
1062
- const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
1063
- return [regexpEscape(r), false, endPos - pos, false];
1064
- }
1065
- const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
1066
- const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
1067
- const comb = ranges.length && negs.length
1068
- ? '(' + sranges + '|' + snegs + ')'
1069
- : ranges.length
1070
- ? sranges
1071
- : snegs;
1072
- return [comb, uflag, endPos - pos, true];
1073
- };
1074
-
1075
- /**
1076
- * Un-escape a string that has been escaped with {@link escape}.
1077
- *
1078
- * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
1079
- * square-bracket escapes are removed, but not backslash escapes.
1080
- *
1081
- * For example, it will turn the string `'[*]'` into `*`, but it will not
1082
- * turn `'\\*'` into `'*'`, because `\` is a path separator in
1083
- * `windowsPathsNoEscape` mode.
1084
- *
1085
- * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
1086
- * backslash escapes are removed.
1087
- *
1088
- * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
1089
- * or unescaped.
1090
- *
1091
- * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
1092
- * unescaped.
1093
- */
1094
- const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
1095
- if (magicalBraces) {
1096
- return windowsPathsNoEscape
1097
- ? s.replace(/\[([^\/\\])\]/g, '$1')
1098
- : s
1099
- .replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2')
1100
- .replace(/\\([^\/])/g, '$1');
1101
- }
1102
- return windowsPathsNoEscape
1103
- ? s.replace(/\[([^\/\\{}])\]/g, '$1')
1104
- : s
1105
- .replace(/((?!\\).|^)\[([^\/\\{}])\]/g, '$1$2')
1106
- .replace(/\\([^\/{}])/g, '$1');
1107
- };
1108
-
1109
- // parse a single path portion
1110
- const types = new Set(['!', '?', '+', '*', '@']);
1111
- const isExtglobType = (c) => types.has(c);
1112
- // Patterns that get prepended to bind to the start of either the
1113
- // entire string, or just a single path portion, to prevent dots
1114
- // and/or traversal patterns, when needed.
1115
- // Exts don't need the ^ or / bit, because the root binds that already.
1116
- const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
1117
- const startNoDot = '(?!\\.)';
1118
- // characters that indicate a start of pattern needs the "no dots" bit,
1119
- // because a dot *might* be matched. ( is not in the list, because in
1120
- // the case of a child extglob, it will handle the prevention itself.
1121
- const addPatternStart = new Set(['[', '.']);
1122
- // cases where traversal is A-OK, no dot prevention needed
1123
- const justDots = new Set(['..', '.']);
1124
- const reSpecials = new Set('().*{}+?[]^$\\!');
1125
- const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
1126
- // any single thing other than /
1127
- const qmark$1 = '[^/]';
1128
- // * => any number of characters
1129
- const star$1 = qmark$1 + '*?';
1130
- // use + when we need to ensure that *something* matches, because the * is
1131
- // the only thing in the path portion.
1132
- const starNoEmpty = qmark$1 + '+?';
1133
- // remove the \ chars that we added if we end up doing a nonmagic compare
1134
- // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
1135
- class AST {
1136
- type;
1137
- #root;
1138
- #hasMagic;
1139
- #uflag = false;
1140
- #parts = [];
1141
- #parent;
1142
- #parentIndex;
1143
- #negs;
1144
- #filledNegs = false;
1145
- #options;
1146
- #toString;
1147
- // set to true if it's an extglob with no children
1148
- // (which really means one child of '')
1149
- #emptyExt = false;
1150
- constructor(type, parent, options = {}) {
1151
- this.type = type;
1152
- // extglobs are inherently magical
1153
- if (type)
1154
- this.#hasMagic = true;
1155
- this.#parent = parent;
1156
- this.#root = this.#parent ? this.#parent.#root : this;
1157
- this.#options = this.#root === this ? options : this.#root.#options;
1158
- this.#negs = this.#root === this ? [] : this.#root.#negs;
1159
- if (type === '!' && !this.#root.#filledNegs)
1160
- this.#negs.push(this);
1161
- this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
1162
- }
1163
- get hasMagic() {
1164
- /* c8 ignore start */
1165
- if (this.#hasMagic !== undefined)
1166
- return this.#hasMagic;
1167
- /* c8 ignore stop */
1168
- for (const p of this.#parts) {
1169
- if (typeof p === 'string')
1170
- continue;
1171
- if (p.type || p.hasMagic)
1172
- return (this.#hasMagic = true);
1173
- }
1174
- // note: will be undefined until we generate the regexp src and find out
1175
- return this.#hasMagic;
1176
- }
1177
- // reconstructs the pattern
1178
- toString() {
1179
- if (this.#toString !== undefined)
1180
- return this.#toString;
1181
- if (!this.type) {
1182
- return (this.#toString = this.#parts.map(p => String(p)).join(''));
1183
- }
1184
- else {
1185
- return (this.#toString =
1186
- this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
1187
- }
1188
- }
1189
- #fillNegs() {
1190
- /* c8 ignore start */
1191
- if (this !== this.#root)
1192
- throw new Error('should only call on root');
1193
- if (this.#filledNegs)
1194
- return this;
1195
- /* c8 ignore stop */
1196
- // call toString() once to fill this out
1197
- this.toString();
1198
- this.#filledNegs = true;
1199
- let n;
1200
- while ((n = this.#negs.pop())) {
1201
- if (n.type !== '!')
1202
- continue;
1203
- // walk up the tree, appending everthing that comes AFTER parentIndex
1204
- let p = n;
1205
- let pp = p.#parent;
1206
- while (pp) {
1207
- for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
1208
- for (const part of n.#parts) {
1209
- /* c8 ignore start */
1210
- if (typeof part === 'string') {
1211
- throw new Error('string part in extglob AST??');
1212
- }
1213
- /* c8 ignore stop */
1214
- part.copyIn(pp.#parts[i]);
1215
- }
1216
- }
1217
- p = pp;
1218
- pp = p.#parent;
1219
- }
1220
- }
1221
- return this;
1222
- }
1223
- push(...parts) {
1224
- for (const p of parts) {
1225
- if (p === '')
1226
- continue;
1227
- /* c8 ignore start */
1228
- if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
1229
- throw new Error('invalid part: ' + p);
1230
- }
1231
- /* c8 ignore stop */
1232
- this.#parts.push(p);
1233
- }
1234
- }
1235
- toJSON() {
1236
- const ret = this.type === null
1237
- ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
1238
- : [this.type, ...this.#parts.map(p => p.toJSON())];
1239
- if (this.isStart() && !this.type)
1240
- ret.unshift([]);
1241
- if (this.isEnd() &&
1242
- (this === this.#root ||
1243
- (this.#root.#filledNegs && this.#parent?.type === '!'))) {
1244
- ret.push({});
1245
- }
1246
- return ret;
1247
- }
1248
- isStart() {
1249
- if (this.#root === this)
1250
- return true;
1251
- // if (this.type) return !!this.#parent?.isStart()
1252
- if (!this.#parent?.isStart())
1253
- return false;
1254
- if (this.#parentIndex === 0)
1255
- return true;
1256
- // if everything AHEAD of this is a negation, then it's still the "start"
1257
- const p = this.#parent;
1258
- for (let i = 0; i < this.#parentIndex; i++) {
1259
- const pp = p.#parts[i];
1260
- if (!(pp instanceof AST && pp.type === '!')) {
1261
- return false;
1262
- }
1263
- }
1264
- return true;
1265
- }
1266
- isEnd() {
1267
- if (this.#root === this)
1268
- return true;
1269
- if (this.#parent?.type === '!')
1270
- return true;
1271
- if (!this.#parent?.isEnd())
1272
- return false;
1273
- if (!this.type)
1274
- return this.#parent?.isEnd();
1275
- // if not root, it'll always have a parent
1276
- /* c8 ignore start */
1277
- const pl = this.#parent ? this.#parent.#parts.length : 0;
1278
- /* c8 ignore stop */
1279
- return this.#parentIndex === pl - 1;
1280
- }
1281
- copyIn(part) {
1282
- if (typeof part === 'string')
1283
- this.push(part);
1284
- else
1285
- this.push(part.clone(this));
1286
- }
1287
- clone(parent) {
1288
- const c = new AST(this.type, parent);
1289
- for (const p of this.#parts) {
1290
- c.copyIn(p);
1291
- }
1292
- return c;
1293
- }
1294
- static #parseAST(str, ast, pos, opt) {
1295
- let escaping = false;
1296
- let inBrace = false;
1297
- let braceStart = -1;
1298
- let braceNeg = false;
1299
- if (ast.type === null) {
1300
- // outside of a extglob, append until we find a start
1301
- let i = pos;
1302
- let acc = '';
1303
- while (i < str.length) {
1304
- const c = str.charAt(i++);
1305
- // still accumulate escapes at this point, but we do ignore
1306
- // starts that are escaped
1307
- if (escaping || c === '\\') {
1308
- escaping = !escaping;
1309
- acc += c;
1310
- continue;
1311
- }
1312
- if (inBrace) {
1313
- if (i === braceStart + 1) {
1314
- if (c === '^' || c === '!') {
1315
- braceNeg = true;
1316
- }
1317
- }
1318
- else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
1319
- inBrace = false;
1320
- }
1321
- acc += c;
1322
- continue;
1323
- }
1324
- else if (c === '[') {
1325
- inBrace = true;
1326
- braceStart = i;
1327
- braceNeg = false;
1328
- acc += c;
1329
- continue;
1330
- }
1331
- if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
1332
- ast.push(acc);
1333
- acc = '';
1334
- const ext = new AST(c, ast);
1335
- i = AST.#parseAST(str, ext, i, opt);
1336
- ast.push(ext);
1337
- continue;
1338
- }
1339
- acc += c;
1340
- }
1341
- ast.push(acc);
1342
- return i;
1343
- }
1344
- // some kind of extglob, pos is at the (
1345
- // find the next | or )
1346
- let i = pos + 1;
1347
- let part = new AST(null, ast);
1348
- const parts = [];
1349
- let acc = '';
1350
- while (i < str.length) {
1351
- const c = str.charAt(i++);
1352
- // still accumulate escapes at this point, but we do ignore
1353
- // starts that are escaped
1354
- if (escaping || c === '\\') {
1355
- escaping = !escaping;
1356
- acc += c;
1357
- continue;
1358
- }
1359
- if (inBrace) {
1360
- if (i === braceStart + 1) {
1361
- if (c === '^' || c === '!') {
1362
- braceNeg = true;
1363
- }
1364
- }
1365
- else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
1366
- inBrace = false;
1367
- }
1368
- acc += c;
1369
- continue;
1370
- }
1371
- else if (c === '[') {
1372
- inBrace = true;
1373
- braceStart = i;
1374
- braceNeg = false;
1375
- acc += c;
1376
- continue;
1377
- }
1378
- if (isExtglobType(c) && str.charAt(i) === '(') {
1379
- part.push(acc);
1380
- acc = '';
1381
- const ext = new AST(c, part);
1382
- part.push(ext);
1383
- i = AST.#parseAST(str, ext, i, opt);
1384
- continue;
1385
- }
1386
- if (c === '|') {
1387
- part.push(acc);
1388
- acc = '';
1389
- parts.push(part);
1390
- part = new AST(null, ast);
1391
- continue;
1392
- }
1393
- if (c === ')') {
1394
- if (acc === '' && ast.#parts.length === 0) {
1395
- ast.#emptyExt = true;
1396
- }
1397
- part.push(acc);
1398
- acc = '';
1399
- ast.push(...parts, part);
1400
- return i;
1401
- }
1402
- acc += c;
1403
- }
1404
- // unfinished extglob
1405
- // if we got here, it was a malformed extglob! not an extglob, but
1406
- // maybe something else in there.
1407
- ast.type = null;
1408
- ast.#hasMagic = undefined;
1409
- ast.#parts = [str.substring(pos - 1)];
1410
- return i;
1411
- }
1412
- static fromGlob(pattern, options = {}) {
1413
- const ast = new AST(null, undefined, options);
1414
- AST.#parseAST(pattern, ast, 0, options);
1415
- return ast;
1416
- }
1417
- // returns the regular expression if there's magic, or the unescaped
1418
- // string if not.
1419
- toMMPattern() {
1420
- // should only be called on root
1421
- /* c8 ignore start */
1422
- if (this !== this.#root)
1423
- return this.#root.toMMPattern();
1424
- /* c8 ignore stop */
1425
- const glob = this.toString();
1426
- const [re, body, hasMagic, uflag] = this.toRegExpSource();
1427
- // if we're in nocase mode, and not nocaseMagicOnly, then we do
1428
- // still need a regular expression if we have to case-insensitively
1429
- // match capital/lowercase characters.
1430
- const anyMagic = hasMagic ||
1431
- this.#hasMagic ||
1432
- (this.#options.nocase &&
1433
- !this.#options.nocaseMagicOnly &&
1434
- glob.toUpperCase() !== glob.toLowerCase());
1435
- if (!anyMagic) {
1436
- return body;
1437
- }
1438
- const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
1439
- return Object.assign(new RegExp(`^${re}$`, flags), {
1440
- _src: re,
1441
- _glob: glob,
1442
- });
1443
- }
1444
- get options() {
1445
- return this.#options;
1446
- }
1447
- // returns the string match, the regexp source, whether there's magic
1448
- // in the regexp (so a regular expression is required) and whether or
1449
- // not the uflag is needed for the regular expression (for posix classes)
1450
- // TODO: instead of injecting the start/end at this point, just return
1451
- // the BODY of the regexp, along with the start/end portions suitable
1452
- // for binding the start/end in either a joined full-path makeRe context
1453
- // (where we bind to (^|/), or a standalone matchPart context (where
1454
- // we bind to ^, and not /). Otherwise slashes get duped!
1455
- //
1456
- // In part-matching mode, the start is:
1457
- // - if not isStart: nothing
1458
- // - if traversal possible, but not allowed: ^(?!\.\.?$)
1459
- // - if dots allowed or not possible: ^
1460
- // - if dots possible and not allowed: ^(?!\.)
1461
- // end is:
1462
- // - if not isEnd(): nothing
1463
- // - else: $
1464
- //
1465
- // In full-path matching mode, we put the slash at the START of the
1466
- // pattern, so start is:
1467
- // - if first pattern: same as part-matching mode
1468
- // - if not isStart(): nothing
1469
- // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
1470
- // - if dots allowed or not possible: /
1471
- // - if dots possible and not allowed: /(?!\.)
1472
- // end is:
1473
- // - if last pattern, same as part-matching mode
1474
- // - else nothing
1475
- //
1476
- // Always put the (?:$|/) on negated tails, though, because that has to be
1477
- // there to bind the end of the negated pattern portion, and it's easier to
1478
- // just stick it in now rather than try to inject it later in the middle of
1479
- // the pattern.
1480
- //
1481
- // We can just always return the same end, and leave it up to the caller
1482
- // to know whether it's going to be used joined or in parts.
1483
- // And, if the start is adjusted slightly, can do the same there:
1484
- // - if not isStart: nothing
1485
- // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
1486
- // - if dots allowed or not possible: (?:/|^)
1487
- // - if dots possible and not allowed: (?:/|^)(?!\.)
1488
- //
1489
- // But it's better to have a simpler binding without a conditional, for
1490
- // performance, so probably better to return both start options.
1491
- //
1492
- // Then the caller just ignores the end if it's not the first pattern,
1493
- // and the start always gets applied.
1494
- //
1495
- // But that's always going to be $ if it's the ending pattern, or nothing,
1496
- // so the caller can just attach $ at the end of the pattern when building.
1497
- //
1498
- // So the todo is:
1499
- // - better detect what kind of start is needed
1500
- // - return both flavors of starting pattern
1501
- // - attach $ at the end of the pattern when creating the actual RegExp
1502
- //
1503
- // Ah, but wait, no, that all only applies to the root when the first pattern
1504
- // is not an extglob. If the first pattern IS an extglob, then we need all
1505
- // that dot prevention biz to live in the extglob portions, because eg
1506
- // +(*|.x*) can match .xy but not .yx.
1507
- //
1508
- // So, return the two flavors if it's #root and the first child is not an
1509
- // AST, otherwise leave it to the child AST to handle it, and there,
1510
- // use the (?:^|/) style of start binding.
1511
- //
1512
- // Even simplified further:
1513
- // - Since the start for a join is eg /(?!\.) and the start for a part
1514
- // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
1515
- // or start or whatever) and prepend ^ or / at the Regexp construction.
1516
- toRegExpSource(allowDot) {
1517
- const dot = allowDot ?? !!this.#options.dot;
1518
- if (this.#root === this)
1519
- this.#fillNegs();
1520
- if (!this.type) {
1521
- const noEmpty = this.isStart() &&
1522
- this.isEnd() &&
1523
- !this.#parts.some(s => typeof s !== 'string');
1524
- const src = this.#parts
1525
- .map(p => {
1526
- const [re, _, hasMagic, uflag] = typeof p === 'string'
1527
- ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
1528
- : p.toRegExpSource(allowDot);
1529
- this.#hasMagic = this.#hasMagic || hasMagic;
1530
- this.#uflag = this.#uflag || uflag;
1531
- return re;
1532
- })
1533
- .join('');
1534
- let start = '';
1535
- if (this.isStart()) {
1536
- if (typeof this.#parts[0] === 'string') {
1537
- // this is the string that will match the start of the pattern,
1538
- // so we need to protect against dots and such.
1539
- // '.' and '..' cannot match unless the pattern is that exactly,
1540
- // even if it starts with . or dot:true is set.
1541
- const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
1542
- if (!dotTravAllowed) {
1543
- const aps = addPatternStart;
1544
- // check if we have a possibility of matching . or ..,
1545
- // and prevent that.
1546
- const needNoTrav =
1547
- // dots are allowed, and the pattern starts with [ or .
1548
- (dot && aps.has(src.charAt(0))) ||
1549
- // the pattern starts with \., and then [ or .
1550
- (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
1551
- // the pattern starts with \.\., and then [ or .
1552
- (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
1553
- // no need to prevent dots if it can't match a dot, or if a
1554
- // sub-pattern will be preventing it anyway.
1555
- const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
1556
- start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
1557
- }
1558
- }
1559
- }
1560
- // append the "end of path portion" pattern to negation tails
1561
- let end = '';
1562
- if (this.isEnd() &&
1563
- this.#root.#filledNegs &&
1564
- this.#parent?.type === '!') {
1565
- end = '(?:$|\\/)';
1566
- }
1567
- const final = start + src + end;
1568
- return [
1569
- final,
1570
- unescape(src),
1571
- (this.#hasMagic = !!this.#hasMagic),
1572
- this.#uflag,
1573
- ];
1574
- }
1575
- // We need to calculate the body *twice* if it's a repeat pattern
1576
- // at the start, once in nodot mode, then again in dot mode, so a
1577
- // pattern like *(?) can match 'x.y'
1578
- const repeated = this.type === '*' || this.type === '+';
1579
- // some kind of extglob
1580
- const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
1581
- let body = this.#partsToRegExp(dot);
1582
- if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
1583
- // invalid extglob, has to at least be *something* present, if it's
1584
- // the entire path portion.
1585
- const s = this.toString();
1586
- this.#parts = [s];
1587
- this.type = null;
1588
- this.#hasMagic = undefined;
1589
- return [s, unescape(this.toString()), false, false];
1590
- }
1591
- // XXX abstract out this map method
1592
- let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
1593
- ? ''
1594
- : this.#partsToRegExp(true);
1595
- if (bodyDotAllowed === body) {
1596
- bodyDotAllowed = '';
1597
- }
1598
- if (bodyDotAllowed) {
1599
- body = `(?:${body})(?:${bodyDotAllowed})*?`;
1600
- }
1601
- // an empty !() is exactly equivalent to a starNoEmpty
1602
- let final = '';
1603
- if (this.type === '!' && this.#emptyExt) {
1604
- final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
1605
- }
1606
- else {
1607
- const close = this.type === '!'
1608
- ? // !() must match something,but !(x) can match ''
1609
- '))' +
1610
- (this.isStart() && !dot && !allowDot ? startNoDot : '') +
1611
- star$1 +
1612
- ')'
1613
- : this.type === '@'
1614
- ? ')'
1615
- : this.type === '?'
1616
- ? ')?'
1617
- : this.type === '+' && bodyDotAllowed
1618
- ? ')'
1619
- : this.type === '*' && bodyDotAllowed
1620
- ? `)?`
1621
- : `)${this.type}`;
1622
- final = start + body + close;
1623
- }
1624
- return [
1625
- final,
1626
- unescape(body),
1627
- (this.#hasMagic = !!this.#hasMagic),
1628
- this.#uflag,
1629
- ];
1630
- }
1631
- #partsToRegExp(dot) {
1632
- return this.#parts
1633
- .map(p => {
1634
- // extglob ASTs should only contain parent ASTs
1635
- /* c8 ignore start */
1636
- if (typeof p === 'string') {
1637
- throw new Error('string type in extglob ast??');
1638
- }
1639
- /* c8 ignore stop */
1640
- // can ignore hasMagic, because extglobs are already always magic
1641
- const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
1642
- this.#uflag = this.#uflag || uflag;
1643
- return re;
1644
- })
1645
- .filter(p => !(this.isStart() && this.isEnd()) || !!p)
1646
- .join('|');
1647
- }
1648
- static #parseGlob(glob, hasMagic, noEmpty = false) {
1649
- let escaping = false;
1650
- let re = '';
1651
- let uflag = false;
1652
- for (let i = 0; i < glob.length; i++) {
1653
- const c = glob.charAt(i);
1654
- if (escaping) {
1655
- escaping = false;
1656
- re += (reSpecials.has(c) ? '\\' : '') + c;
1657
- continue;
1658
- }
1659
- if (c === '\\') {
1660
- if (i === glob.length - 1) {
1661
- re += '\\\\';
1662
- }
1663
- else {
1664
- escaping = true;
1665
- }
1666
- continue;
1667
- }
1668
- if (c === '[') {
1669
- const [src, needUflag, consumed, magic] = parseClass(glob, i);
1670
- if (consumed) {
1671
- re += src;
1672
- uflag = uflag || needUflag;
1673
- i += consumed - 1;
1674
- hasMagic = hasMagic || magic;
1675
- continue;
1676
- }
1677
- }
1678
- if (c === '*') {
1679
- re += noEmpty && glob === '*' ? starNoEmpty : star$1;
1680
- hasMagic = true;
1681
- continue;
1682
- }
1683
- if (c === '?') {
1684
- re += qmark$1;
1685
- hasMagic = true;
1686
- continue;
1687
- }
1688
- re += regExpEscape$1(c);
1689
- }
1690
- return [re, unescape(glob), !!hasMagic, uflag];
1691
- }
1692
- }
1693
-
1694
- /**
1695
- * Escape all magic characters in a glob pattern.
1696
- *
1697
- * If the {@link MinimatchOptions.windowsPathsNoEscape}
1698
- * option is used, then characters are escaped by wrapping in `[]`, because
1699
- * a magic character wrapped in a character class can only be satisfied by
1700
- * that exact character. In this mode, `\` is _not_ escaped, because it is
1701
- * not interpreted as a magic character, but instead as a path separator.
1702
- *
1703
- * If the {@link MinimatchOptions.magicalBraces} option is used,
1704
- * then braces (`{` and `}`) will be escaped.
1705
- */
1706
- const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => {
1707
- // don't need to escape +@! because we escape the parens
1708
- // that make those magic, and escaping ! as [!] isn't valid,
1709
- // because [!]] is a valid glob class meaning not ']'.
1710
- if (magicalBraces) {
1711
- return windowsPathsNoEscape
1712
- ? s.replace(/[?*()[\]{}]/g, '[$&]')
1713
- : s.replace(/[?*()[\]\\{}]/g, '\\$&');
1714
- }
1715
- return windowsPathsNoEscape
1716
- ? s.replace(/[?*()[\]]/g, '[$&]')
1717
- : s.replace(/[?*()[\]\\]/g, '\\$&');
1718
- };
1719
-
1720
- const minimatch = (p, pattern, options = {}) => {
1721
- assertValidPattern(pattern);
1722
- // shortcut: comments match nothing.
1723
- if (!options.nocomment && pattern.charAt(0) === '#') {
1724
- return false;
1725
- }
1726
- return new Minimatch(pattern, options).match(p);
1727
- };
1728
- // Optimized checking for the most common glob patterns.
1729
- const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
1730
- const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
1731
- const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
1732
- const starDotExtTestNocase = (ext) => {
1733
- ext = ext.toLowerCase();
1734
- return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
1735
- };
1736
- const starDotExtTestNocaseDot = (ext) => {
1737
- ext = ext.toLowerCase();
1738
- return (f) => f.toLowerCase().endsWith(ext);
1739
- };
1740
- const starDotStarRE = /^\*+\.\*+$/;
1741
- const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
1742
- const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
1743
- const dotStarRE = /^\.\*+$/;
1744
- const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
1745
- const starRE = /^\*+$/;
1746
- const starTest = (f) => f.length !== 0 && !f.startsWith('.');
1747
- const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
1748
- const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
1749
- const qmarksTestNocase = ([$0, ext = '']) => {
1750
- const noext = qmarksTestNoExt([$0]);
1751
- if (!ext)
1752
- return noext;
1753
- ext = ext.toLowerCase();
1754
- return (f) => noext(f) && f.toLowerCase().endsWith(ext);
1755
- };
1756
- const qmarksTestNocaseDot = ([$0, ext = '']) => {
1757
- const noext = qmarksTestNoExtDot([$0]);
1758
- if (!ext)
1759
- return noext;
1760
- ext = ext.toLowerCase();
1761
- return (f) => noext(f) && f.toLowerCase().endsWith(ext);
1762
- };
1763
- const qmarksTestDot = ([$0, ext = '']) => {
1764
- const noext = qmarksTestNoExtDot([$0]);
1765
- return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
1766
- };
1767
- const qmarksTest = ([$0, ext = '']) => {
1768
- const noext = qmarksTestNoExt([$0]);
1769
- return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
1770
- };
1771
- const qmarksTestNoExt = ([$0]) => {
1772
- const len = $0.length;
1773
- return (f) => f.length === len && !f.startsWith('.');
1774
- };
1775
- const qmarksTestNoExtDot = ([$0]) => {
1776
- const len = $0.length;
1777
- return (f) => f.length === len && f !== '.' && f !== '..';
1778
- };
1779
- /* c8 ignore start */
1780
- const defaultPlatform = (typeof process === 'object' && process
1781
- ? (typeof process.env === 'object' &&
1782
- process.env &&
1783
- process.env.__MINIMATCH_TESTING_PLATFORM__) ||
1784
- process.platform
1785
- : 'posix');
1786
- const path = {
1787
- win32: { sep: '\\' },
1788
- posix: { sep: '/' },
1789
- };
1790
- /* c8 ignore stop */
1791
- const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
1792
- minimatch.sep = sep;
1793
- const GLOBSTAR = Symbol('globstar **');
1794
- minimatch.GLOBSTAR = GLOBSTAR;
1795
- // any single thing other than /
1796
- // don't need to escape / when using new RegExp()
1797
- const qmark = '[^/]';
1798
- // * => any number of characters
1799
- const star = qmark + '*?';
1800
- // ** when dots are allowed. Anything goes, except .. and .
1801
- // not (^ or / followed by one or two dots followed by $ or /),
1802
- // followed by anything, any number of times.
1803
- const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
1804
- // not a ^ or / followed by a dot,
1805
- // followed by anything, any number of times.
1806
- const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
1807
- const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
1808
- minimatch.filter = filter;
1809
- const ext = (a, b = {}) => Object.assign({}, a, b);
1810
- const defaults = (def) => {
1811
- if (!def || typeof def !== 'object' || !Object.keys(def).length) {
1812
- return minimatch;
1813
- }
1814
- const orig = minimatch;
1815
- const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
1816
- return Object.assign(m, {
1817
- Minimatch: class Minimatch extends orig.Minimatch {
1818
- constructor(pattern, options = {}) {
1819
- super(pattern, ext(def, options));
1820
- }
1821
- static defaults(options) {
1822
- return orig.defaults(ext(def, options)).Minimatch;
1823
- }
1824
- },
1825
- AST: class AST extends orig.AST {
1826
- /* c8 ignore start */
1827
- constructor(type, parent, options = {}) {
1828
- super(type, parent, ext(def, options));
1829
- }
1830
- /* c8 ignore stop */
1831
- static fromGlob(pattern, options = {}) {
1832
- return orig.AST.fromGlob(pattern, ext(def, options));
1833
- }
1834
- },
1835
- unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
1836
- escape: (s, options = {}) => orig.escape(s, ext(def, options)),
1837
- filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
1838
- defaults: (options) => orig.defaults(ext(def, options)),
1839
- makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
1840
- braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
1841
- match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
1842
- sep: orig.sep,
1843
- GLOBSTAR: GLOBSTAR,
1844
- });
1845
- };
1846
- minimatch.defaults = defaults;
1847
- // Brace expansion:
1848
- // a{b,c}d -> abd acd
1849
- // a{b,}c -> abc ac
1850
- // a{0..3}d -> a0d a1d a2d a3d
1851
- // a{b,c{d,e}f}g -> abg acdfg acefg
1852
- // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
1853
- //
1854
- // Invalid sets are not expanded.
1855
- // a{2..}b -> a{2..}b
1856
- // a{b}c -> a{b}c
1857
- const braceExpand = (pattern, options = {}) => {
1858
- assertValidPattern(pattern);
1859
- // Thanks to Yeting Li <https://github.com/yetingli> for
1860
- // improving this regexp to avoid a ReDOS vulnerability.
1861
- if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
1862
- // shortcut. no need to expand.
1863
- return [pattern];
1864
- }
1865
- return expand(pattern);
1866
- };
1867
- minimatch.braceExpand = braceExpand;
1868
- // parse a component of the expanded set.
1869
- // At this point, no pattern may contain "/" in it
1870
- // so we're going to return a 2d array, where each entry is the full
1871
- // pattern, split on '/', and then turned into a regular expression.
1872
- // A regexp is made at the end which joins each array with an
1873
- // escaped /, and another full one which joins each regexp with |.
1874
- //
1875
- // Following the lead of Bash 4.1, note that "**" only has special meaning
1876
- // when it is the *only* thing in a path portion. Otherwise, any series
1877
- // of * is equivalent to a single *. Globstar behavior is enabled by
1878
- // default, and can be disabled by setting options.noglobstar.
1879
- const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
1880
- minimatch.makeRe = makeRe;
1881
- const match = (list, pattern, options = {}) => {
1882
- const mm = new Minimatch(pattern, options);
1883
- list = list.filter(f => mm.match(f));
1884
- if (mm.options.nonull && !list.length) {
1885
- list.push(pattern);
1886
- }
1887
- return list;
1888
- };
1889
- minimatch.match = match;
1890
- // replace stuff like \* with *
1891
- const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
1892
- const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
1893
- class Minimatch {
1894
- options;
1895
- set;
1896
- pattern;
1897
- windowsPathsNoEscape;
1898
- nonegate;
1899
- negate;
1900
- comment;
1901
- empty;
1902
- preserveMultipleSlashes;
1903
- partial;
1904
- globSet;
1905
- globParts;
1906
- nocase;
1907
- isWindows;
1908
- platform;
1909
- windowsNoMagicRoot;
1910
- regexp;
1911
- constructor(pattern, options = {}) {
1912
- assertValidPattern(pattern);
1913
- options = options || {};
1914
- this.options = options;
1915
- this.pattern = pattern;
1916
- this.platform = options.platform || defaultPlatform;
1917
- this.isWindows = this.platform === 'win32';
1918
- this.windowsPathsNoEscape =
1919
- !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
1920
- if (this.windowsPathsNoEscape) {
1921
- this.pattern = this.pattern.replace(/\\/g, '/');
1922
- }
1923
- this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
1924
- this.regexp = null;
1925
- this.negate = false;
1926
- this.nonegate = !!options.nonegate;
1927
- this.comment = false;
1928
- this.empty = false;
1929
- this.partial = !!options.partial;
1930
- this.nocase = !!this.options.nocase;
1931
- this.windowsNoMagicRoot =
1932
- options.windowsNoMagicRoot !== undefined
1933
- ? options.windowsNoMagicRoot
1934
- : !!(this.isWindows && this.nocase);
1935
- this.globSet = [];
1936
- this.globParts = [];
1937
- this.set = [];
1938
- // make the set of regexps etc.
1939
- this.make();
1940
- }
1941
- hasMagic() {
1942
- if (this.options.magicalBraces && this.set.length > 1) {
1943
- return true;
1944
- }
1945
- for (const pattern of this.set) {
1946
- for (const part of pattern) {
1947
- if (typeof part !== 'string')
1948
- return true;
1949
- }
1950
- }
1951
- return false;
1952
- }
1953
- debug(..._) { }
1954
- make() {
1955
- const pattern = this.pattern;
1956
- const options = this.options;
1957
- // empty patterns and comments match nothing.
1958
- if (!options.nocomment && pattern.charAt(0) === '#') {
1959
- this.comment = true;
1960
- return;
1961
- }
1962
- if (!pattern) {
1963
- this.empty = true;
1964
- return;
1965
- }
1966
- // step 1: figure out negation, etc.
1967
- this.parseNegate();
1968
- // step 2: expand braces
1969
- this.globSet = [...new Set(this.braceExpand())];
1970
- if (options.debug) {
1971
- this.debug = (...args) => console.error(...args);
1972
- }
1973
- this.debug(this.pattern, this.globSet);
1974
- // step 3: now we have a set, so turn each one into a series of
1975
- // path-portion matching patterns.
1976
- // These will be regexps, except in the case of "**", which is
1977
- // set to the GLOBSTAR object for globstar behavior,
1978
- // and will not contain any / characters
1979
- //
1980
- // First, we preprocess to make the glob pattern sets a bit simpler
1981
- // and deduped. There are some perf-killing patterns that can cause
1982
- // problems with a glob walk, but we can simplify them down a bit.
1983
- const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
1984
- this.globParts = this.preprocess(rawGlobParts);
1985
- this.debug(this.pattern, this.globParts);
1986
- // glob --> regexps
1987
- let set = this.globParts.map((s, _, __) => {
1988
- if (this.isWindows && this.windowsNoMagicRoot) {
1989
- // check if it's a drive or unc path.
1990
- const isUNC = s[0] === '' &&
1991
- s[1] === '' &&
1992
- (s[2] === '?' || !globMagic.test(s[2])) &&
1993
- !globMagic.test(s[3]);
1994
- const isDrive = /^[a-z]:/i.test(s[0]);
1995
- if (isUNC) {
1996
- return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
1997
- }
1998
- else if (isDrive) {
1999
- return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
2000
- }
2001
- }
2002
- return s.map(ss => this.parse(ss));
2003
- });
2004
- this.debug(this.pattern, set);
2005
- // filter out everything that didn't compile properly.
2006
- this.set = set.filter(s => s.indexOf(false) === -1);
2007
- // do not treat the ? in UNC paths as magic
2008
- if (this.isWindows) {
2009
- for (let i = 0; i < this.set.length; i++) {
2010
- const p = this.set[i];
2011
- if (p[0] === '' &&
2012
- p[1] === '' &&
2013
- this.globParts[i][2] === '?' &&
2014
- typeof p[3] === 'string' &&
2015
- /^[a-z]:$/i.test(p[3])) {
2016
- p[2] = '?';
2017
- }
2018
- }
2019
- }
2020
- this.debug(this.pattern, this.set);
2021
- }
2022
- // various transforms to equivalent pattern sets that are
2023
- // faster to process in a filesystem walk. The goal is to
2024
- // eliminate what we can, and push all ** patterns as far
2025
- // to the right as possible, even if it increases the number
2026
- // of patterns that we have to process.
2027
- preprocess(globParts) {
2028
- // if we're not in globstar mode, then turn all ** into *
2029
- if (this.options.noglobstar) {
2030
- for (let i = 0; i < globParts.length; i++) {
2031
- for (let j = 0; j < globParts[i].length; j++) {
2032
- if (globParts[i][j] === '**') {
2033
- globParts[i][j] = '*';
2034
- }
2035
- }
2036
- }
2037
- }
2038
- const { optimizationLevel = 1 } = this.options;
2039
- if (optimizationLevel >= 2) {
2040
- // aggressive optimization for the purpose of fs walking
2041
- globParts = this.firstPhasePreProcess(globParts);
2042
- globParts = this.secondPhasePreProcess(globParts);
2043
- }
2044
- else if (optimizationLevel >= 1) {
2045
- // just basic optimizations to remove some .. parts
2046
- globParts = this.levelOneOptimize(globParts);
2047
- }
2048
- else {
2049
- // just collapse multiple ** portions into one
2050
- globParts = this.adjascentGlobstarOptimize(globParts);
2051
- }
2052
- return globParts;
2053
- }
2054
- // just get rid of adjascent ** portions
2055
- adjascentGlobstarOptimize(globParts) {
2056
- return globParts.map(parts => {
2057
- let gs = -1;
2058
- while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
2059
- let i = gs;
2060
- while (parts[i + 1] === '**') {
2061
- i++;
2062
- }
2063
- if (i !== gs) {
2064
- parts.splice(gs, i - gs);
2065
- }
2066
- }
2067
- return parts;
2068
- });
2069
- }
2070
- // get rid of adjascent ** and resolve .. portions
2071
- levelOneOptimize(globParts) {
2072
- return globParts.map(parts => {
2073
- parts = parts.reduce((set, part) => {
2074
- const prev = set[set.length - 1];
2075
- if (part === '**' && prev === '**') {
2076
- return set;
2077
- }
2078
- if (part === '..') {
2079
- if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
2080
- set.pop();
2081
- return set;
2082
- }
2083
- }
2084
- set.push(part);
2085
- return set;
2086
- }, []);
2087
- return parts.length === 0 ? [''] : parts;
2088
- });
2089
- }
2090
- levelTwoFileOptimize(parts) {
2091
- if (!Array.isArray(parts)) {
2092
- parts = this.slashSplit(parts);
2093
- }
2094
- let didSomething = false;
2095
- do {
2096
- didSomething = false;
2097
- // <pre>/<e>/<rest> -> <pre>/<rest>
2098
- if (!this.preserveMultipleSlashes) {
2099
- for (let i = 1; i < parts.length - 1; i++) {
2100
- const p = parts[i];
2101
- // don't squeeze out UNC patterns
2102
- if (i === 1 && p === '' && parts[0] === '')
2103
- continue;
2104
- if (p === '.' || p === '') {
2105
- didSomething = true;
2106
- parts.splice(i, 1);
2107
- i--;
2108
- }
2109
- }
2110
- if (parts[0] === '.' &&
2111
- parts.length === 2 &&
2112
- (parts[1] === '.' || parts[1] === '')) {
2113
- didSomething = true;
2114
- parts.pop();
2115
- }
2116
- }
2117
- // <pre>/<p>/../<rest> -> <pre>/<rest>
2118
- let dd = 0;
2119
- while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
2120
- const p = parts[dd - 1];
2121
- if (p && p !== '.' && p !== '..' && p !== '**') {
2122
- didSomething = true;
2123
- parts.splice(dd - 1, 2);
2124
- dd -= 2;
2125
- }
2126
- }
2127
- } while (didSomething);
2128
- return parts.length === 0 ? [''] : parts;
2129
- }
2130
- // First phase: single-pattern processing
2131
- // <pre> is 1 or more portions
2132
- // <rest> is 1 or more portions
2133
- // <p> is any portion other than ., .., '', or **
2134
- // <e> is . or ''
2135
- //
2136
- // **/.. is *brutal* for filesystem walking performance, because
2137
- // it effectively resets the recursive walk each time it occurs,
2138
- // and ** cannot be reduced out by a .. pattern part like a regexp
2139
- // or most strings (other than .., ., and '') can be.
2140
- //
2141
- // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
2142
- // <pre>/<e>/<rest> -> <pre>/<rest>
2143
- // <pre>/<p>/../<rest> -> <pre>/<rest>
2144
- // **/**/<rest> -> **/<rest>
2145
- //
2146
- // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
2147
- // this WOULD be allowed if ** did follow symlinks, or * didn't
2148
- firstPhasePreProcess(globParts) {
2149
- let didSomething = false;
2150
- do {
2151
- didSomething = false;
2152
- // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
2153
- for (let parts of globParts) {
2154
- let gs = -1;
2155
- while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
2156
- let gss = gs;
2157
- while (parts[gss + 1] === '**') {
2158
- // <pre>/**/**/<rest> -> <pre>/**/<rest>
2159
- gss++;
2160
- }
2161
- // eg, if gs is 2 and gss is 4, that means we have 3 **
2162
- // parts, and can remove 2 of them.
2163
- if (gss > gs) {
2164
- parts.splice(gs + 1, gss - gs);
2165
- }
2166
- let next = parts[gs + 1];
2167
- const p = parts[gs + 2];
2168
- const p2 = parts[gs + 3];
2169
- if (next !== '..')
2170
- continue;
2171
- if (!p ||
2172
- p === '.' ||
2173
- p === '..' ||
2174
- !p2 ||
2175
- p2 === '.' ||
2176
- p2 === '..') {
2177
- continue;
2178
- }
2179
- didSomething = true;
2180
- // edit parts in place, and push the new one
2181
- parts.splice(gs, 1);
2182
- const other = parts.slice(0);
2183
- other[gs] = '**';
2184
- globParts.push(other);
2185
- gs--;
2186
- }
2187
- // <pre>/<e>/<rest> -> <pre>/<rest>
2188
- if (!this.preserveMultipleSlashes) {
2189
- for (let i = 1; i < parts.length - 1; i++) {
2190
- const p = parts[i];
2191
- // don't squeeze out UNC patterns
2192
- if (i === 1 && p === '' && parts[0] === '')
2193
- continue;
2194
- if (p === '.' || p === '') {
2195
- didSomething = true;
2196
- parts.splice(i, 1);
2197
- i--;
2198
- }
2199
- }
2200
- if (parts[0] === '.' &&
2201
- parts.length === 2 &&
2202
- (parts[1] === '.' || parts[1] === '')) {
2203
- didSomething = true;
2204
- parts.pop();
2205
- }
2206
- }
2207
- // <pre>/<p>/../<rest> -> <pre>/<rest>
2208
- let dd = 0;
2209
- while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
2210
- const p = parts[dd - 1];
2211
- if (p && p !== '.' && p !== '..' && p !== '**') {
2212
- didSomething = true;
2213
- const needDot = dd === 1 && parts[dd + 1] === '**';
2214
- const splin = needDot ? ['.'] : [];
2215
- parts.splice(dd - 1, 2, ...splin);
2216
- if (parts.length === 0)
2217
- parts.push('');
2218
- dd -= 2;
2219
- }
2220
- }
2221
- }
2222
- } while (didSomething);
2223
- return globParts;
2224
- }
2225
- // second phase: multi-pattern dedupes
2226
- // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
2227
- // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
2228
- // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
2229
- //
2230
- // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
2231
- // ^-- not valid because ** doens't follow symlinks
2232
- secondPhasePreProcess(globParts) {
2233
- for (let i = 0; i < globParts.length - 1; i++) {
2234
- for (let j = i + 1; j < globParts.length; j++) {
2235
- const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
2236
- if (matched) {
2237
- globParts[i] = [];
2238
- globParts[j] = matched;
2239
- break;
2240
- }
2241
- }
2242
- }
2243
- return globParts.filter(gs => gs.length);
2244
- }
2245
- partsMatch(a, b, emptyGSMatch = false) {
2246
- let ai = 0;
2247
- let bi = 0;
2248
- let result = [];
2249
- let which = '';
2250
- while (ai < a.length && bi < b.length) {
2251
- if (a[ai] === b[bi]) {
2252
- result.push(which === 'b' ? b[bi] : a[ai]);
2253
- ai++;
2254
- bi++;
2255
- }
2256
- else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
2257
- result.push(a[ai]);
2258
- ai++;
2259
- }
2260
- else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
2261
- result.push(b[bi]);
2262
- bi++;
2263
- }
2264
- else if (a[ai] === '*' &&
2265
- b[bi] &&
2266
- (this.options.dot || !b[bi].startsWith('.')) &&
2267
- b[bi] !== '**') {
2268
- if (which === 'b')
2269
- return false;
2270
- which = 'a';
2271
- result.push(a[ai]);
2272
- ai++;
2273
- bi++;
2274
- }
2275
- else if (b[bi] === '*' &&
2276
- a[ai] &&
2277
- (this.options.dot || !a[ai].startsWith('.')) &&
2278
- a[ai] !== '**') {
2279
- if (which === 'a')
2280
- return false;
2281
- which = 'b';
2282
- result.push(b[bi]);
2283
- ai++;
2284
- bi++;
2285
- }
2286
- else {
2287
- return false;
2288
- }
2289
- }
2290
- // if we fall out of the loop, it means they two are identical
2291
- // as long as their lengths match
2292
- return a.length === b.length && result;
2293
- }
2294
- parseNegate() {
2295
- if (this.nonegate)
2296
- return;
2297
- const pattern = this.pattern;
2298
- let negate = false;
2299
- let negateOffset = 0;
2300
- for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
2301
- negate = !negate;
2302
- negateOffset++;
2303
- }
2304
- if (negateOffset)
2305
- this.pattern = pattern.slice(negateOffset);
2306
- this.negate = negate;
2307
- }
2308
- // set partial to true to test if, for example,
2309
- // "/a/b" matches the start of "/*/b/*/d"
2310
- // Partial means, if you run out of file before you run
2311
- // out of pattern, then that's fine, as long as all
2312
- // the parts match.
2313
- matchOne(file, pattern, partial = false) {
2314
- const options = this.options;
2315
- // UNC paths like //?/X:/... can match X:/... and vice versa
2316
- // Drive letters in absolute drive or unc paths are always compared
2317
- // case-insensitively.
2318
- if (this.isWindows) {
2319
- const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
2320
- const fileUNC = !fileDrive &&
2321
- file[0] === '' &&
2322
- file[1] === '' &&
2323
- file[2] === '?' &&
2324
- /^[a-z]:$/i.test(file[3]);
2325
- const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
2326
- const patternUNC = !patternDrive &&
2327
- pattern[0] === '' &&
2328
- pattern[1] === '' &&
2329
- pattern[2] === '?' &&
2330
- typeof pattern[3] === 'string' &&
2331
- /^[a-z]:$/i.test(pattern[3]);
2332
- const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
2333
- const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
2334
- if (typeof fdi === 'number' && typeof pdi === 'number') {
2335
- const [fd, pd] = [file[fdi], pattern[pdi]];
2336
- if (fd.toLowerCase() === pd.toLowerCase()) {
2337
- pattern[pdi] = fd;
2338
- if (pdi > fdi) {
2339
- pattern = pattern.slice(pdi);
2340
- }
2341
- else if (fdi > pdi) {
2342
- file = file.slice(fdi);
2343
- }
2344
- }
2345
- }
2346
- }
2347
- // resolve and reduce . and .. portions in the file as well.
2348
- // don't need to do the second phase, because it's only one string[]
2349
- const { optimizationLevel = 1 } = this.options;
2350
- if (optimizationLevel >= 2) {
2351
- file = this.levelTwoFileOptimize(file);
2352
- }
2353
- this.debug('matchOne', this, { file, pattern });
2354
- this.debug('matchOne', file.length, pattern.length);
2355
- for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
2356
- this.debug('matchOne loop');
2357
- var p = pattern[pi];
2358
- var f = file[fi];
2359
- this.debug(pattern, p, f);
2360
- // should be impossible.
2361
- // some invalid regexp stuff in the set.
2362
- /* c8 ignore start */
2363
- if (p === false) {
2364
- return false;
2365
- }
2366
- /* c8 ignore stop */
2367
- if (p === GLOBSTAR) {
2368
- this.debug('GLOBSTAR', [pattern, p, f]);
2369
- // "**"
2370
- // a/**/b/**/c would match the following:
2371
- // a/b/x/y/z/c
2372
- // a/x/y/z/b/c
2373
- // a/b/x/b/x/c
2374
- // a/b/c
2375
- // To do this, take the rest of the pattern after
2376
- // the **, and see if it would match the file remainder.
2377
- // If so, return success.
2378
- // If not, the ** "swallows" a segment, and try again.
2379
- // This is recursively awful.
2380
- //
2381
- // a/**/b/**/c matching a/b/x/y/z/c
2382
- // - a matches a
2383
- // - doublestar
2384
- // - matchOne(b/x/y/z/c, b/**/c)
2385
- // - b matches b
2386
- // - doublestar
2387
- // - matchOne(x/y/z/c, c) -> no
2388
- // - matchOne(y/z/c, c) -> no
2389
- // - matchOne(z/c, c) -> no
2390
- // - matchOne(c, c) yes, hit
2391
- var fr = fi;
2392
- var pr = pi + 1;
2393
- if (pr === pl) {
2394
- this.debug('** at the end');
2395
- // a ** at the end will just swallow the rest.
2396
- // We have found a match.
2397
- // however, it will not swallow /.x, unless
2398
- // options.dot is set.
2399
- // . and .. are *never* matched by **, for explosively
2400
- // exponential reasons.
2401
- for (; fi < fl; fi++) {
2402
- if (file[fi] === '.' ||
2403
- file[fi] === '..' ||
2404
- (!options.dot && file[fi].charAt(0) === '.'))
2405
- return false;
2406
- }
2407
- return true;
2408
- }
2409
- // ok, let's see if we can swallow whatever we can.
2410
- while (fr < fl) {
2411
- var swallowee = file[fr];
2412
- this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
2413
- // XXX remove this slice. Just pass the start index.
2414
- if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
2415
- this.debug('globstar found match!', fr, fl, swallowee);
2416
- // found a match.
2417
- return true;
2418
- }
2419
- else {
2420
- // can't swallow "." or ".." ever.
2421
- // can only swallow ".foo" when explicitly asked.
2422
- if (swallowee === '.' ||
2423
- swallowee === '..' ||
2424
- (!options.dot && swallowee.charAt(0) === '.')) {
2425
- this.debug('dot detected!', file, fr, pattern, pr);
2426
- break;
2427
- }
2428
- // ** swallows a segment, and continue.
2429
- this.debug('globstar swallow a segment, and continue');
2430
- fr++;
2431
- }
2432
- }
2433
- // no match was found.
2434
- // However, in partial mode, we can't say this is necessarily over.
2435
- /* c8 ignore start */
2436
- if (partial) {
2437
- // ran out of file
2438
- this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
2439
- if (fr === fl) {
2440
- return true;
2441
- }
2442
- }
2443
- /* c8 ignore stop */
2444
- return false;
2445
- }
2446
- // something other than **
2447
- // non-magic patterns just have to match exactly
2448
- // patterns with magic have been turned into regexps.
2449
- let hit;
2450
- if (typeof p === 'string') {
2451
- hit = f === p;
2452
- this.debug('string match', p, f, hit);
2453
- }
2454
- else {
2455
- hit = p.test(f);
2456
- this.debug('pattern match', p, f, hit);
2457
- }
2458
- if (!hit)
2459
- return false;
2460
- }
2461
- // Note: ending in / means that we'll get a final ""
2462
- // at the end of the pattern. This can only match a
2463
- // corresponding "" at the end of the file.
2464
- // If the file ends in /, then it can only match a
2465
- // a pattern that ends in /, unless the pattern just
2466
- // doesn't have any more for it. But, a/b/ should *not*
2467
- // match "a/b/*", even though "" matches against the
2468
- // [^/]*? pattern, except in partial mode, where it might
2469
- // simply not be reached yet.
2470
- // However, a/b/ should still satisfy a/*
2471
- // now either we fell off the end of the pattern, or we're done.
2472
- if (fi === fl && pi === pl) {
2473
- // ran out of pattern and filename at the same time.
2474
- // an exact hit!
2475
- return true;
2476
- }
2477
- else if (fi === fl) {
2478
- // ran out of file, but still had pattern left.
2479
- // this is ok if we're doing the match as part of
2480
- // a glob fs traversal.
2481
- return partial;
2482
- }
2483
- else if (pi === pl) {
2484
- // ran out of pattern, still have file left.
2485
- // this is only acceptable if we're on the very last
2486
- // empty segment of a file with a trailing slash.
2487
- // a/* should match a/b/
2488
- return fi === fl - 1 && file[fi] === '';
2489
- /* c8 ignore start */
2490
- }
2491
- else {
2492
- // should be unreachable.
2493
- throw new Error('wtf?');
2494
- }
2495
- /* c8 ignore stop */
2496
- }
2497
- braceExpand() {
2498
- return braceExpand(this.pattern, this.options);
2499
- }
2500
- parse(pattern) {
2501
- assertValidPattern(pattern);
2502
- const options = this.options;
2503
- // shortcuts
2504
- if (pattern === '**')
2505
- return GLOBSTAR;
2506
- if (pattern === '')
2507
- return '';
2508
- // far and away, the most common glob pattern parts are
2509
- // *, *.*, and *.<ext> Add a fast check method for those.
2510
- let m;
2511
- let fastTest = null;
2512
- if ((m = pattern.match(starRE))) {
2513
- fastTest = options.dot ? starTestDot : starTest;
2514
- }
2515
- else if ((m = pattern.match(starDotExtRE))) {
2516
- fastTest = (options.nocase
2517
- ? options.dot
2518
- ? starDotExtTestNocaseDot
2519
- : starDotExtTestNocase
2520
- : options.dot
2521
- ? starDotExtTestDot
2522
- : starDotExtTest)(m[1]);
2523
- }
2524
- else if ((m = pattern.match(qmarksRE))) {
2525
- fastTest = (options.nocase
2526
- ? options.dot
2527
- ? qmarksTestNocaseDot
2528
- : qmarksTestNocase
2529
- : options.dot
2530
- ? qmarksTestDot
2531
- : qmarksTest)(m);
2532
- }
2533
- else if ((m = pattern.match(starDotStarRE))) {
2534
- fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
2535
- }
2536
- else if ((m = pattern.match(dotStarRE))) {
2537
- fastTest = dotStarTest;
2538
- }
2539
- const re = AST.fromGlob(pattern, this.options).toMMPattern();
2540
- if (fastTest && typeof re === 'object') {
2541
- // Avoids overriding in frozen environments
2542
- Reflect.defineProperty(re, 'test', { value: fastTest });
2543
- }
2544
- return re;
2545
- }
2546
- makeRe() {
2547
- if (this.regexp || this.regexp === false)
2548
- return this.regexp;
2549
- // at this point, this.set is a 2d array of partial
2550
- // pattern strings, or "**".
2551
- //
2552
- // It's better to use .match(). This function shouldn't
2553
- // be used, really, but it's pretty convenient sometimes,
2554
- // when you just want to work with a regex.
2555
- const set = this.set;
2556
- if (!set.length) {
2557
- this.regexp = false;
2558
- return this.regexp;
2559
- }
2560
- const options = this.options;
2561
- const twoStar = options.noglobstar
2562
- ? star
2563
- : options.dot
2564
- ? twoStarDot
2565
- : twoStarNoDot;
2566
- const flags = new Set(options.nocase ? ['i'] : []);
2567
- // regexpify non-globstar patterns
2568
- // if ** is only item, then we just do one twoStar
2569
- // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
2570
- // if ** is last, append (\/twoStar|) to previous
2571
- // if ** is in the middle, append (\/|\/twoStar\/) to previous
2572
- // then filter out GLOBSTAR symbols
2573
- let re = set
2574
- .map(pattern => {
2575
- const pp = pattern.map(p => {
2576
- if (p instanceof RegExp) {
2577
- for (const f of p.flags.split(''))
2578
- flags.add(f);
2579
- }
2580
- return typeof p === 'string'
2581
- ? regExpEscape(p)
2582
- : p === GLOBSTAR
2583
- ? GLOBSTAR
2584
- : p._src;
2585
- });
2586
- pp.forEach((p, i) => {
2587
- const next = pp[i + 1];
2588
- const prev = pp[i - 1];
2589
- if (p !== GLOBSTAR || prev === GLOBSTAR) {
2590
- return;
2591
- }
2592
- if (prev === undefined) {
2593
- if (next !== undefined && next !== GLOBSTAR) {
2594
- pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
2595
- }
2596
- else {
2597
- pp[i] = twoStar;
2598
- }
2599
- }
2600
- else if (next === undefined) {
2601
- pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + ')?';
2602
- }
2603
- else if (next !== GLOBSTAR) {
2604
- pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
2605
- pp[i + 1] = GLOBSTAR;
2606
- }
2607
- });
2608
- const filtered = pp.filter(p => p !== GLOBSTAR);
2609
- // For partial matches, we need to make the pattern match
2610
- // any prefix of the full path. We do this by generating
2611
- // alternative patterns that match progressively longer prefixes.
2612
- if (this.partial && filtered.length >= 1) {
2613
- const prefixes = [];
2614
- for (let i = 1; i <= filtered.length; i++) {
2615
- prefixes.push(filtered.slice(0, i).join('/'));
2616
- }
2617
- return '(?:' + prefixes.join('|') + ')';
2618
- }
2619
- return filtered.join('/');
2620
- })
2621
- .join('|');
2622
- // need to wrap in parens if we had more than one thing with |,
2623
- // otherwise only the first will be anchored to ^ and the last to $
2624
- const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
2625
- // must match entire pattern
2626
- // ending in a * or ** will make it less strict.
2627
- re = '^' + open + re + close + '$';
2628
- // In partial mode, '/' should always match as it's a valid prefix for any pattern
2629
- if (this.partial) {
2630
- re = '^(?:\\/|' + open + re.slice(1, -1) + close + ')$';
2631
- }
2632
- // can match anything, as long as it's not this.
2633
- if (this.negate)
2634
- re = '^(?!' + re + ').+$';
2635
- try {
2636
- this.regexp = new RegExp(re, [...flags].join(''));
2637
- /* c8 ignore start */
2638
- }
2639
- catch (ex) {
2640
- // should be impossible
2641
- this.regexp = false;
2642
- }
2643
- /* c8 ignore stop */
2644
- return this.regexp;
2645
- }
2646
- slashSplit(p) {
2647
- // if p starts with // on windows, we preserve that
2648
- // so that UNC paths aren't broken. Otherwise, any number of
2649
- // / characters are coalesced into one, unless
2650
- // preserveMultipleSlashes is set to true.
2651
- if (this.preserveMultipleSlashes) {
2652
- return p.split('/');
2653
- }
2654
- else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
2655
- // add an extra '' for the one we lose
2656
- return ['', ...p.split(/\/+/)];
2657
- }
2658
- else {
2659
- return p.split(/\/+/);
2660
- }
2661
- }
2662
- match(f, partial = this.partial) {
2663
- this.debug('match', f, this.pattern);
2664
- // short-circuit in the case of busted things.
2665
- // comments, etc.
2666
- if (this.comment) {
2667
- return false;
2668
- }
2669
- if (this.empty) {
2670
- return f === '';
2671
- }
2672
- if (f === '/' && partial) {
2673
- return true;
2674
- }
2675
- const options = this.options;
2676
- // windows: need to use /, not \
2677
- if (this.isWindows) {
2678
- f = f.split('\\').join('/');
2679
- }
2680
- // treat the test path as a set of pathparts.
2681
- const ff = this.slashSplit(f);
2682
- this.debug(this.pattern, 'split', ff);
2683
- // just ONE of the pattern sets in this.set needs to match
2684
- // in order for it to be valid. If negating, then just one
2685
- // match means that we have failed.
2686
- // Either way, return on the first hit.
2687
- const set = this.set;
2688
- this.debug(this.pattern, 'set', set);
2689
- // Find the basename of the path by looking for the last non-empty segment
2690
- let filename = ff[ff.length - 1];
2691
- if (!filename) {
2692
- for (let i = ff.length - 2; !filename && i >= 0; i--) {
2693
- filename = ff[i];
2694
- }
2695
- }
2696
- for (let i = 0; i < set.length; i++) {
2697
- const pattern = set[i];
2698
- let file = ff;
2699
- if (options.matchBase && pattern.length === 1) {
2700
- file = [filename];
2701
- }
2702
- const hit = this.matchOne(file, pattern, partial);
2703
- if (hit) {
2704
- if (options.flipNegate) {
2705
- return true;
2706
- }
2707
- return !this.negate;
2708
- }
2709
- }
2710
- // didn't get any hits. this is success if it's a negative
2711
- // pattern, failure otherwise.
2712
- if (options.flipNegate) {
2713
- return false;
2714
- }
2715
- return this.negate;
2716
- }
2717
- static defaults(def) {
2718
- return minimatch.defaults(def).Minimatch;
2719
- }
2720
- }
2721
- /* c8 ignore stop */
2722
- minimatch.AST = AST;
2723
- minimatch.Minimatch = Minimatch;
2724
- minimatch.escape = escape;
2725
- minimatch.unescape = unescape;
2726
-
2727
673
  /**
2728
674
  * Default configuration for rules when defaultConfig is not specified.
2729
675
  * Custom rules can omit defaultConfig and will use these defaults.
@@ -5510,34 +3456,104 @@ class HTMLNoBlockInsideInlineRule extends ParserRule {
5510
3456
  }
5511
3457
  }
5512
3458
 
5513
- class NoDuplicateAttributesVisitor extends AttributeVisitorMixin {
5514
- attributeNames = new Map();
3459
+ class NoDuplicateAttributesVisitor extends ControlFlowTrackingVisitor {
3460
+ tagAttributes = new Set();
3461
+ currentBranchAttributes = new Set();
3462
+ controlFlowAttributes = new Set();
5515
3463
  visitHTMLOpenTagNode(node) {
5516
- this.attributeNames.clear();
3464
+ this.tagAttributes = new Set();
3465
+ this.currentBranchAttributes = new Set();
3466
+ this.controlFlowAttributes = new Set();
5517
3467
  super.visitHTMLOpenTagNode(node);
5518
- this.reportDuplicates();
5519
3468
  }
5520
- checkStaticAttributeStaticValue({ attributeName, attributeNode }) {
5521
- this.trackAttributeName(attributeName, attributeNode);
3469
+ visitHTMLAttributeNode(node) {
3470
+ this.checkAttribute(node);
5522
3471
  }
5523
- checkStaticAttributeDynamicValue({ attributeName, attributeNode }) {
5524
- this.trackAttributeName(attributeName, attributeNode);
3472
+ onEnterControlFlow(_controlFlowType, wasAlreadyInControlFlow) {
3473
+ const stateToRestore = {
3474
+ previousBranchAttributes: this.currentBranchAttributes,
3475
+ previousControlFlowAttributes: this.controlFlowAttributes,
3476
+ };
3477
+ this.currentBranchAttributes = new Set();
3478
+ if (!wasAlreadyInControlFlow) {
3479
+ this.controlFlowAttributes = new Set();
3480
+ }
3481
+ return stateToRestore;
5525
3482
  }
5526
- trackAttributeName(attributeName, attributeNode) {
5527
- if (!this.attributeNames.has(attributeName)) {
5528
- this.attributeNames.set(attributeName, []);
3483
+ onExitControlFlow(controlFlowType, wasAlreadyInControlFlow, stateToRestore) {
3484
+ if (controlFlowType === ControlFlowType.CONDITIONAL && !wasAlreadyInControlFlow) {
3485
+ this.controlFlowAttributes.forEach((attr) => this.tagAttributes.add(attr));
5529
3486
  }
5530
- this.attributeNames.get(attributeName).push(attributeNode);
3487
+ this.currentBranchAttributes = stateToRestore.previousBranchAttributes;
3488
+ this.controlFlowAttributes = stateToRestore.previousControlFlowAttributes;
5531
3489
  }
5532
- reportDuplicates() {
5533
- for (const [attributeName, attributeNodes] of this.attributeNames) {
5534
- if (attributeNodes.length > 1) {
5535
- for (let i = 1; i < attributeNodes.length; i++) {
5536
- const attributeNode = attributeNodes[i];
5537
- this.addOffense(`Duplicate attribute \`${attributeName}\` found on tag. Remove the duplicate occurrence.`, attributeNode.name.location);
5538
- }
5539
- }
3490
+ onEnterBranch() {
3491
+ const stateToRestore = {
3492
+ previousBranchAttributes: this.currentBranchAttributes,
3493
+ };
3494
+ if (this.isInControlFlow) {
3495
+ this.currentBranchAttributes = new Set();
3496
+ }
3497
+ return stateToRestore;
3498
+ }
3499
+ onExitBranch(_stateToRestore) { }
3500
+ checkAttribute(attributeNode) {
3501
+ const identifier = getAttributeName(attributeNode);
3502
+ if (!identifier)
3503
+ return;
3504
+ this.processAttributeDuplicate(identifier, attributeNode);
3505
+ }
3506
+ processAttributeDuplicate(identifier, attributeNode) {
3507
+ if (!this.isInControlFlow) {
3508
+ this.handleHTMLAttribute(identifier, attributeNode);
3509
+ return;
3510
+ }
3511
+ if (this.currentControlFlowType === ControlFlowType.LOOP) {
3512
+ this.handleLoopAttribute(identifier, attributeNode);
3513
+ }
3514
+ else {
3515
+ this.handleConditionalAttribute(identifier, attributeNode);
3516
+ }
3517
+ this.currentBranchAttributes.add(identifier);
3518
+ }
3519
+ handleHTMLAttribute(identifier, attributeNode) {
3520
+ if (this.tagAttributes.has(identifier)) {
3521
+ this.addDuplicateAttributeOffense(identifier, attributeNode.name.location);
3522
+ }
3523
+ this.tagAttributes.add(identifier);
3524
+ }
3525
+ handleLoopAttribute(identifier, attributeNode) {
3526
+ if (this.currentBranchAttributes.has(identifier)) {
3527
+ this.addSameLoopIterationOffense(identifier, attributeNode.name.location);
3528
+ return;
3529
+ }
3530
+ if (this.tagAttributes.has(identifier)) {
3531
+ this.addDuplicateAttributeOffense(identifier, attributeNode.name.location);
3532
+ return;
3533
+ }
3534
+ this.addLoopWillDuplicateOffense(identifier, attributeNode.name.location);
3535
+ }
3536
+ handleConditionalAttribute(identifier, attributeNode) {
3537
+ if (this.currentBranchAttributes.has(identifier)) {
3538
+ this.addSameBranchOffense(identifier, attributeNode.name.location);
3539
+ return;
3540
+ }
3541
+ if (this.tagAttributes.has(identifier)) {
3542
+ this.addDuplicateAttributeOffense(identifier, attributeNode.name.location);
5540
3543
  }
3544
+ this.controlFlowAttributes.add(identifier);
3545
+ }
3546
+ addDuplicateAttributeOffense(identifier, location) {
3547
+ this.addOffense(`Duplicate attribute \`${identifier}\`. Browsers only use the first occurrence and ignore duplicate attributes. Remove the duplicate or merge the values.`, location);
3548
+ }
3549
+ addSameLoopIterationOffense(identifier, location) {
3550
+ this.addOffense(`Duplicate attribute \`${identifier}\` in same loop iteration. Each iteration will produce an element with duplicate attributes. Remove one or merge the values.`, location);
3551
+ }
3552
+ addLoopWillDuplicateOffense(identifier, location) {
3553
+ this.addOffense(`Attribute \`${identifier}\` inside loop will appear multiple times on this element. Use a dynamic attribute name like \`${identifier}-<%= index %>\` or move the attribute outside the loop.`, location);
3554
+ }
3555
+ addSameBranchOffense(identifier, location) {
3556
+ this.addOffense(`Duplicate attribute \`${identifier}\` in same branch. This branch will produce an element with duplicate attributes. Remove one or merge the values.`, location);
5541
3557
  }
5542
3558
  }
5543
3559
  class HTMLNoDuplicateAttributesRule extends ParserRule {
@@ -6858,7 +4874,7 @@ class Linter {
6858
4874
  if (context?.fileName && !this.config?.linter?.rules?.[rule.name]?.exclude) {
6859
4875
  const defaultExclude = rule.defaultConfig?.exclude ?? DEFAULT_RULE_CONFIG.exclude;
6860
4876
  if (defaultExclude && defaultExclude.length > 0) {
6861
- const isExcluded = defaultExclude.some((pattern) => minimatch(context.fileName, pattern));
4877
+ const isExcluded = defaultExclude.some(pattern => picomatch.isMatch(context.fileName, pattern));
6862
4878
  if (isExcluded) {
6863
4879
  return [];
6864
4880
  }