negate = !negate; negateOffset ++; } if (negateOffset) this.pattern = pattern.substr(negateOffset); this.negate = negate; } // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac // a{0..3}d -> a0d a1d a2d a3d // a{b,c{d,e}f}g -> abg acdfg acefg // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg // // Invalid sets are not expanded. // a{2..}b -> a{2..}b // a{b}c -> a{b}c minimatch.braceExpand = function (pattern, options) { return new Minimatch(pattern, options).braceExpand() }; Minimatch.prototype.braceExpand = braceExpand; function braceExpand (pattern, options) { options = options || this.options; pattern = typeof pattern === "undefined" ? this.pattern : pattern; if (typeof pattern === "undefined") { throw new Error("undefined pattern") } if (options.nobrace || !pattern.match(/\{.*\}/)) { // shortcut. no need to expand. return [pattern] } var escaping = false; // examples and comments refer to this crazy pattern: // a{b,c{d,e},{f,g}h}x{y,z} // expected: // abxy // abxz // acdxy // acdxz // acexy // acexz // afhxy // afhxz // aghxy // aghxz // everything before the first \{ is just a prefix. // So, we pluck that off, and work with the rest, // and then prepend it to everything we find. if (pattern.charAt(0) !== "{") { // console.error(pattern) var prefix = null; for (var i = 0, l = pattern.length; i < l; i ++) { var c = pattern.charAt(i); // console.error(i, c) if (c === "\\") { escaping = !escaping; } else if (c === "{" && !escaping) { prefix = pattern.substr(0, i); break } } // actually no sets, all { were escaped. if (prefix === null) { // console.error("no sets") return [pattern] } var tail = braceExpand(pattern.substr(i), options); return tail.map(function (t) { return prefix + t }) } // now we have something like: // {b,c{d,e},{f,g}h}x{y,z} // walk through the set, expanding each part, until // the set ends. then, we'll expand the suffix. // If the set only has a single member, then'll put the {} back // first, handle numeric sets, since they're easier var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/); if (numset) { // console.error("numset", numset[1], numset[2]) var suf = braceExpand(pattern.substr(numset[0].length), options) , start = +numset[1] , end = +numset[2] , inc = start > end ? -1 : 1 , set = []; for (var i = start; i != (end + inc); i += inc) { // append all the suffixes for (var ii = 0, ll = suf.length; ii < ll; ii ++) { set.push(i + suf[ii]); } } return set } // ok, walk through the set // We hope, somewhat optimistically, that there // will be a } at the end. // If the closing brace isn't found, then the pattern is // interpreted as braceExpand("\\" + pattern) so that // the leading \{ will be interpreted literally. var i = 1 // skip the \{ , depth = 1 , set = [] , member = "" , sawEnd = false , escaping = false; function addMember () { set.push(member); member = ""; } // console.error("Entering for") FOR: for (i = 1, l = pattern.length; i < l; i ++) { var c = pattern.charAt(i); // console.error("", i, c) if (escaping) { escaping = false; member += "\\" + c; } else { switch (c) { case "\\": escaping = true; continue case "{": depth ++; member += "{"; continue case "}": depth --; // if this closes the actual set, then we're done if (depth === 0) { addMember(); // pluck off the close-brace i ++; break FOR } else { member += c; continue } case ",": if (depth === 1) { addMember(); } else { member += c; } continue default: member += c; continue } // switch } // else } // for // now we've either finished the set, and the suffix is // pattern.substr(i), or we have *not* closed the set, // and need to escape the leading brace if (depth !== 0) { // console.error("didn't close", pattern) return braceExpand("\\" + pattern, options) } // x{y,z} -> ["xy", "xz"] // console.error("set", set) // console.error("suffix", pattern.substr(i)) var suf = braceExpand(pattern.substr(i), options); // ["b", "c{d,e}","{f,g}h"] -> // [["b"], ["cd", "ce"], ["fh", "gh"]] var addBraces = set.length === 1; // console.error("set pre-expanded", set) set = set.map(function (p) { return braceExpand(p, options) }); // console.error("set expanded", set) // [["b"], ["cd", "ce"], ["fh", "gh"]] -> // ["b", "cd", "ce", "fh", "gh"] set = set.reduce(function (l, r) { return l.concat(r) }); if (addBraces) { set = set.map(function (s) { return "{" + s + "}" }); } // now attach the suffixes. var ret = []; for (var i = 0, l = set.length; i < l; i ++) { for (var ii = 0, ll = suf.length; ii < ll; ii ++) { ret.push(set[i] + suf[ii]); } } return ret } // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full // pattern, split on '/', and then turned into a regular expression. // A regexp is made at the end which joins each array with an // escaped /, and another full one which joins each regexp with |. // // Following the lead of Bash 4.1, note that "**" only has special meaning // when it is the *only* thing in a path portion. Otherwise, any series // of * is equivalent to a single *. Globstar behavior is enabled by // default, and can be disabled by setting options.noglobstar. Minimatch.prototype.parse = parse; var SUBPARSE = {}; function parse (pattern, isSub) { var options = this.options; // shortcuts if (!options.noglobstar && pattern === "**") return GLOBSTAR if (pattern === "") return "" var re = "" , hasMagic = !!options.nocase , escaping = false // ? => one single character , patternListStack = [] , plType , stateChar , inClass = false , reClassStart = -1 , classStart = -1 // . and .. never match anything that doesn't start with ., // even when options.dot is set. , patternStart = pattern.charAt(0) === "." ? "" // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" : "(?!\\.)"; function clearStateChar () { if (stateChar) { // we had some state-tracking character // that wasn't consumed by this pass. switch (stateChar) { case "*": re += star; hasMagic = true; break case "?": re += qmark; hasMagic = true; break default: re += "\\"+stateChar; break } stateChar = false; } } for ( var i = 0, len = pattern.length, c ; (i < len) && (c = pattern.charAt(i)) ; i ++ ) { if (options.debug) { console.error("%s\t%s %s %j", pattern, i, re, c); } // skip over any that are escaped. if (escaping && reSpecials[c]) { re += "\\" + c; escaping = false; continue } SWITCH: switch (c) { case "/": // completely not allowed, even escaped. // Should already be path-split by now. return false case "\\": clearStateChar(); escaping = true; continue // the various stateChar values // for the "extglob" stuff. case "?": case "*": case "+": case "@": case "!": if (options.debug) { console.error("%s\t%s %s %j <-- stateChar", pattern, i, re, c); } // all of those are literals inside a class, except that // the glob [!a] means [^a] in regexp if (inClass) { if (c === "!" && i === classStart + 1) c = "^"; re += c; continue } // if we already have a stateChar, then it means // that there was something like ** or +? in there. // Handle the stateChar, then proceed with this one. clearStateChar(); stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing. // just clear the statechar *now*, rather than even diving into // the patternList stuff. if (options.noext) clearStateChar(); continue case "(": if (inClass) { re += "("; continue } if (!stateChar) { re += "\\("; continue } plType = stateChar; patternListStack.push({ type: plType , start: i - 1 , reStart: re.length }); // negation is (?:(?!js)[^/]*) re += stateChar === "!" ? "(?:(?!" : "(?:"; stateChar = false; continue case ")": if (inClass || !patternListStack.length) { re += "\\)"; continue } hasMagic = true; re += ")"; plType = patternListStack.pop().type; // negation is (?:(?!js)[^/]*) // The others are (?:<pattern>)<type> switch (plType) { case "!": re += "[^/]*?)"; break case "?": case "+": case "*": re += plType; case "@": break // the default anyway } continue case "|": if (inClass || !patternListStack.length || escaping) { re += "\\|"; escaping = false; continue } re += "|"; continue // these are mostly the same in regexp and glob case "[": // swallow any state-tracking char before the [ clearStateChar(); if (inClass) { re += "\\" + c; continue } inClass = true; classStart = i; reClassStart = re.length; re += c; continue case "]": // a right bracket shall lose its special // meaning and represent itself in // a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 if (i === classStart + 1 || !inClass) { re += "\\" + c; escaping = false; continue } // finish up the class. hasMagic = true; inClass = false; re += c; continue default: // swallow any state char that wasn't consumed clearStateChar(); if (escaping) { // no need escaping = false; } else if (reSpecials[c] && !(c === "^" && inClass)) { re += "\\"; } re += c; } // switch } // for // handle the case where we left a class open. // "[abc" is valid, equivalent to "\[abc" if (inClass) { // split where the last [ was, and escape it // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is var cs = pattern.substr(classStart + 1) , sp = this.parse(cs, SUBPARSE); re = re.substr(0, reClassStart) + "\\[" + sp[0]; hasMagic = hasMagic || sp[1]; } // handle the case where we had a +( thing at the *end* // of the pattern. // each pattern list stack adds 3 chars, and we need to go through // and escape any | chars that were passed through as-is for the regexp. // Go through and escape them, taking care not to double-escape any // | chars that were already escaped. var pl; while (pl = patternListStack.pop()) { var tail = re.slice(pl.reStart + 3); // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) { if (!$2) { // the | isn't already escaped, so escape it. $2 = "\\"; } // need to escape all those slashes *again*, without escaping the // one that we need for escaping the | character. As it works out, // escaping an even number of slashes can be done by simply repeating // it exactly after itself. That's why this trick works. // // I am sorry that you have to see this. return $1 + $1 + $2 + "|" }); // console.error("tail=%j\n %s", tail, tail) var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type; hasMagic = true; re = re.slice(0, pl.reStart) + t + "\\(" + tail; } // handle trailing things that only matter at the very end. clearStateChar(); if (escaping) { // trailing \\ re += "\\\\"; } // only need to apply the nodot start if the re starts with // something that could conceivably capture a dot var addPatternStart = false; switch (re.charAt(0)) { case ".": case "[": case "(": addPatternStart = true; } // if the re is not "" at this point, then we need to make sure // it doesn't match against an empty path part. // Otherwise a/* will match a/, which it should not. if (re !== "" && hasMagic) re = "(?=.)" + re; if (addPatternStart) re = patternStart + re; // parsing just a piece of a larger pattern. if (isSub === SUBPARSE) { return [ re, hasMagic ] } // skip the regexp for non-magical patterns // unescape anything in it, though, so that it'll be // an exact match against a file etc. if (!hasMagic) { return globUnescape(pattern) } var flags = options.nocase ? "i" : "" , regExp = new RegExp("^" + re + "$", flags); regExp._glob = pattern; regExp._src = re; return regExp } minimatch.makeRe = function (pattern, options) { return new Minimatch(pattern, options || {}).makeRe() }; Minimatch.prototype.makeRe = makeRe; function makeRe () { if (this.regexp || this.regexp === false) return this.regexp // at this point, this.set is a 2d array of partial // pattern strings, or "**". // // It's better to use .match(). This function shouldn't // be used, really, but it's pretty convenient sometimes, // when you just want to work with a regex. var set = this.set; if (!set.length) return this.regexp = false var options = this.options; var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot , flags = options.nocase ? "i" : ""; var re = set.map(function (pattern) { return pattern.map(function (p) { return (p === GLOBSTAR) ? twoStar : (typeof p === "string") ? regExpEscape(p) : p._src }).join("\\\/") }).join("|"); // must match entire pattern // ending in a * or ** will make it less strict. re = "^(?:" + re + ")$"; // can match anything, as long as it's not this. if (this.negate) re = "^(?!" + re + ").*$"; try { return this.regexp = new RegExp(re, flags) } catch (ex) { return this.regexp = false } } minimatch.match = function (list, pattern, options) { var mm = new Minimatch(pattern, options); list = list.filter(function (f) { return mm.match(f) }); if (options.nonull && !list.length) { list.push(pattern); } return list }; Minimatch.prototype.match = match; function match (f, partial) { // console.error("match", f, this.pattern) // short-circuit in the case of busted things. // comments, etc. if (this.comment) return false if (this.empty) return f === "" if (f === "/" && partial) return true var options = this.options; // windows: need to use /, not \ // On other platforms, \ is a valid (albeit bad) filename char. if (platform === "win32") { f = f.split("\\").join("/"); } // treat the test path as a set of pathparts. f = f.split(slashSplit); if (options.debug) { console.error(this.pattern, "split", f); } // just ONE of the pattern sets in this.set needs to match // in order for it to be valid. If negating, then just one // match means that we have failed. // Either way, return on the first hit. var set = this.set; // console.error(this.pattern, "set", set) for (var i = 0, l = set.length; i < l; i ++) { var pattern = set[i]; var hit = this.matchOne(f, pattern, partial); if (hit) { if (options.flipNegate) return true return !this.negate } } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.flipNegate) return false return this.negate } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. Minimatch.prototype.matchOne = function (file, pattern, partial) { var options = this.options; if (options.debug) { console.error("matchOne", { "this": this , file: file , pattern: pattern }); } if (options.matchBase && pattern.length === 1) { file = path.basename(file.join("/")).split("/"); } if (options.debug) { console.error("matchOne", file.length, pattern.length); } for ( var fi = 0 , pi = 0 , fl = file.length , pl = pattern.length ; (fi < fl) && (pi < pl) ; fi ++, pi ++ ) { if (options.debug) { console.error("matchOne loop"); } var p = pattern[pi] , f = file[fi]; if (options.debug) { console.error(pattern, p, f); } // should be impossible. // some invalid regexp stuff in the set. if (p === false) return false if (p === GLOBSTAR) { if (options.debug) console.error('GLOBSTAR', [pattern, p, f]); // "**" // a/**/b/**/c would match the following: // a/b/x/y/z/c // a/x/y/z/b/c // a/b/x/b/x/c // a/b/c // To do this, take the rest of the pattern after // the **, and see if it would match the file remainder. // If so, return success. // If not, the ** "swallows" a segment, and try again. // This is recursively awful. // // a/**/b/**/c matching a/b/x/y/z/c // - a matches a // - doublestar // - matchOne(b/x/y/z/c, b/**/c) // - b matches b // - doublestar // - matchOne(x/y/z/c, c) -> no // - matchOne(y/z/c, c) -> no // - matchOne(z/c, c) -> no // - matchOne(c, c) yes, hit var fr = fi , pr = pi + 1; if (pr === pl) { if (options.debug) console.error('** at the end'); // a ** at the end will just swallow the rest. // We have found a match. // however, it will not swallow /.x, unless // options.dot is set. // . and .. are *never* matched by **, for explosively // exponential reasons. for ( ; fi < fl; fi ++) { if (file[fi] === "." || file[fi] === ".." || (!options.dot && file[fi].charAt(0) === ".")) return false } return true } // ok, let's see if we can swallow whatever we can. WHILE: while (fr < fl) { var swallowee = file[fr]; if (options.debug) { console.error('\nglobstar while', file, fr, pattern, pr, swallowee); } // XXX remove this slice. Just pass the start index. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { if (options.debug) console.error('globstar found match!', fr, fl, swallowee); // found a match. return true } else { // can't swallow "." or ".." ever. // can only swallow ".foo" when explicitly asked. if (swallowee === "." || swallowee === ".." || (!options.dot && swallowee.charAt(0) === ".")) { if (options.debug) console.error("dot detected!", file, fr, pattern, pr); break WHILE } // ** swallows a segment, and continue. if (options.debug) console.error('globstar swallow a segment, and continue'); fr ++; } } // no match was found. // However, in partial mode, we can't say this is necessarily over. // If there's more *pattern* left, then if (partial) { // ran out of file // console.error("\n>>> no match, partial?", file, fr, pattern, pr) if (fr === fl) return true } return false } // something other than ** // non-magic patterns just have to match exactly // patterns with magic have been turned into regexps. var hit; if (typeof p === "string") { if (options.nocase) { hit = f.toLowerCase() === p.toLowerCase(); } else { hit = f === p; } if (options.debug) { console.error("string match", p, f, hit); } } else { hit = f.match(p); if (options.debug) { console.error("pattern match", p, f, hit); } } if (!hit) return false } // Note: ending in / means that we'll get a final "" // at the end of the pattern. This can only match a // corresponding "" at the end of the file. // If the file ends in /, then it can only match a // a pattern that ends in /, unless the pattern just // doesn't have any more for it. But, a/b/ should *not* // match "a/b/*", even though "" matches against the // [^/]*? pattern, except in partial mode, where it might // simply not be reached yet. // However, a/b/ should still satisfy a/* // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. // an exact hit! return true } else if (fi === fl) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial } else if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ var emptyFileEnd = (fi === fl - 1) && (file[fi] === ""); return emptyFileEnd } // should be unreachable. throw new Error("wtf?") }; // replace stuff like \* with * function globUnescape (s) { return s.replace(/\\(.)/g, "$1") } function regExpEscape (s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") } }); var name$1 = "editorconfig"; var version$2 = "0.14.2"; var description$1 = "EditorConfig File Locator and Interpreter for Node.js"; var keywords = ["editorconfig","core"]; var main$1 = "editorconfig.js"; var bin$1 = {"editorconfig":"bin/editorconfig"}; var contributors = ["Hong Xu (topbug.net)","Jed Mao (https://github.com/jedmao/)","Trey Hunner (http://treyhunner.com)"]; var directories = {"bin":"./bin","lib":"./lib"}; var scripts$1 = {"pretest":"cmake .","test":"npm run lint && ctest .","test-verbose":"npm run lint && ctest -VV --output-on-failure .","lint":"eclint check --indent_size ignore editorconfig.js README.md \"bin/**\" \"lib/**\""}; var repository$1 = {"type":"git","url":"git://github.com/editorconfig/editorconfig-core-js.git"}; var bugs$1 = "https://github.com/editorconfig/editorconfig-core-js/issues"; var author$1 = "EditorConfig Team"; var license$1 = "MIT"; var dependencies$1 = {"bluebird":"^3.0.5","commander":"^2.9.0","lru-cache":"^3.2.0","semver":"^5.1.0","sigmund":"^1.0.1"}; var devDependencies$1 = {"eclint":"^1.1.5","mocha":"^2.3.4","should":"^7.1.1"}; var _package$2 = { name: name$1, version: version$2, description: description$1, keywords: keywords, main: main$1, bin: bin$1, contributors: contributors, directories: directories, scripts: scripts$1, repository: repository$1, bugs: bugs$1, author: author$1, license: license$1, dependencies: dependencies$1, devDependencies: devDependencies$1 }; var _package$3 = Object.freeze({ name: name$1, version: version$2, description: description$1, keywords: keywords, main: main$1, bin: bin$1, contributors: contributors, directories: directories, scripts: scripts$1, repository: repository$1, bugs: bugs$1, author: author$1, license: license$1, dependencies: dependencies$1, devDependencies: devDependencies$1, default: _package$2 }); var pkg = ( _package$3 && _package$2 ) || _package$3; var whenReadFile = bluebird_1.promisify(fs.readFile); var knownProps = [ 'end_of_line', 'indent_style', 'indent_size', 'insert_final_newline', 'trim_trailing_whitespace', 'charset' ].reduce(function (set, prop) { set[prop] = true; return set; }, {}); function fnmatch(filepath, glob) { var matchOptions = {matchBase: true, dot: true, noext: true}; glob = glob.replace(/\*\*/g, '{*,**/**/**}'); return fnmatch$1(filepath, glob, matchOptions); } function getConfigFileNames(filepath, options) { var paths = []; do { filepath = path.dirname(filepath); paths.push(path.join(filepath, options.config)); } while (filepath !== options.root); return paths; } function getFilepathRoot(filepath) { if (path.parse !== undefined) { // Node.js >= 0.11.15 return path.parse(filepath).root; } if (os.platform() === 'win32') { return path.resolve(filepath).match(/^(\\\\[^\\]+\\)?[^\\]+\\/)[0]; } return '/'; } function processMatches(matches, version) { // Set indent_size to "tab" if indent_size is unspecified and // indent_style is set to "tab". if ("indent_style" in matches && matches.indent_style === "tab" && !("indent_size" in matches) && semver.gte(version, "0.10.0")) { matches.indent_size = "tab"; } // Set tab_width to indent_size if indent_size is specified and // tab_width is unspecified if ("indent_size" in matches && !("tab_width" in matches) && matches.indent_size !== "tab") matches.tab_width = matches.indent_size; // Set indent_size to tab_width if indent_size is "tab" if("indent_size" in matches && "tab_width" in matches && matches.indent_size === "tab") matches.indent_size = matches.tab_width; return matches; } function processOptions(options, filepath) { options = options || {}; return { config: options.config || '.editorconfig', version: options.version || pkg.version, root: path.resolve(options.root || getFilepathRoot(filepath)) }; } function buildFullGlob(pathPrefix, glob) { switch (glob.indexOf('/')) { case -1: glob = "**/" + glob; break; case 0: glob = glob.substring(1); break; } return path.join(pathPrefix, glob); } function extendProps(props, options) { for (var key in options) { var value = options[key]; key = key.toLowerCase(); if (knownProps[key]) { value = value.toLowerCase(); } try { value = JSON.parse(value); } catch(e) {} if (typeof value === 'undefined' || value === null) { // null and undefined are values specific to JSON (no special meaning // in editorconfig) & should just be returned as regular strings. value = String(value); } props[key] = value; } return props; } function parseFromFiles(filepath, files, options) { return getConfigsForFiles(files).then(function (configs) { return configs.reverse(); }).reduce(function (matches, file) { var pathPrefix = path.dirname(file.name); file.contents.forEach(function (section) { var glob = section[0], options = section[1]; if (!glob) return; var fullGlob = buildFullGlob(pathPrefix, glob); if (!fnmatch(filepath, fullGlob)) return; matches = extendProps(matches, options); }); return matches; }, {}).then(function (matches) { return processMatches(matches, options.version); }); } function parseFromFilesSync(filepath, files, options) { var configs = getConfigsForFilesSync(files); configs.reverse(); var matches = {}; configs.forEach(function(config) { var pathPrefix = path.dirname(config.name); config.contents.forEach(function(section) { var glob = section[0], options = section[1]; if (!glob) return; var fullGlob = buildFullGlob(pathPrefix, glob); if (!fnmatch(filepath, fullGlob)) return; matches = extendProps(matches, options); }); }); return processMatches(matches, options.version); } function StopReduce(array) { this.array = array; } StopReduce.prototype = Object.create(Error.prototype); function getConfigsForFiles(files) { return bluebird_1.reduce(files, function (configs, file) { var contents = ini.parseString(file.contents); configs.push({ name: file.name, contents: contents }); if ((contents[0][1].root || '').toLowerCase() === 'true') { return bluebird_1.reject(new StopReduce(configs)); } return configs; }, []).catch(StopReduce, function (stop) { return stop.array; }); } function getConfigsForFilesSync(files) { var configs = []; for (var i in files) { var file = files[i]; var contents = ini.parseString(file.contents); configs.push({ name: file.name, contents: contents }); if ((contents[0][1].root || '').toLowerCase() === 'true') { break; } } return configs; } function readConfigFiles(filepaths) { return bluebird_1.map(filepaths, function (path$$2) { return whenReadFile(path$$2, 'utf-8').catch(function () { return ''; }).then(function (contents) { return {name: path$$2, contents: contents}; }); }); } function readConfigFilesSync(filepaths) { var files = []; var file; filepaths.forEach(function(filepath) { try { file = fs.readFileSync(filepath, 'utf8'); } catch (e) { file = ''; } files.push({name: filepath, contents: file}); }); return files; } var parseFromFiles_1 = function (filepath, files, options) { return new bluebird_1 (function (resolve, reject) { filepath = path.resolve(filepath); options = processOptions(options, filepath); resolve(parseFromFiles(filepath, files, options)); }); }; var parseFromFilesSync_1 = function (filepath, files, options) { filepath = path.resolve(filepath); options = processOptions(options, filepath); return parseFromFilesSync(filepath, files, options); }; var parse$6 = function (filepath, options) { return new bluebird_1 (function (resolve, reject) { filepath = path.resolve(filepath); options = processOptions(options, filepath); var filepaths = getConfigFileNames(filepath, options); var files = readConfigFiles(filepaths); resolve(parseFromFiles(filepath, files, options)); }); }; var parseSync = function (filepath, options) { filepath = path.resolve(filepath); options = processOptions(options, filepath); var filepaths = getConfigFileNames(filepath, options); var files = readConfigFilesSync(filepaths); return parseFromFilesSync(filepath, files, options); }; var parseString = ini.parseString; var editorconfig = { parseFromFiles: parseFromFiles_1, parseFromFilesSync: parseFromFilesSync_1, parse: parse$6, parseSync: parseSync, parseString: parseString }; var editorconfigToPrettier = editorConfigToPrettier; function editorConfigToPrettier(editorConfig) { if (!editorConfig || Object.keys(editorConfig).length === 0) { return null; } const result = {}; if (editorConfig.indent_style) { result.useTabs = editorConfig.indent_style === "tab"; } if (editorConfig.indent_size === "tab") { result.useTabs = true; } if (result.useTabs && editorConfig.tab_width) { result.tabWidth = editorConfig.tab_width; } else if ( editorConfig.indent_style === "space" && editorConfig.indent_size && editorConfig.indent_size !== "tab" ) { result.tabWidth = editorConfig.indent_size; } else if (editorConfig.tab_width !== undefined) { result.tabWidth = editorConfig.tab_width; } if (editorConfig.max_line_length && editorConfig.max_line_length !== "off") { result.printWidth = editorConfig.max_line_length; } if (editorConfig.quote_type === "single") { result.singleQuote = true; } else if (editorConfig.quote_type === "double") { result.singleQuote = false; } return result; } function markerExists (files, markers) { return markers.some(function(marker) { return files.some(function(file) { return file === marker; }); }); } function traverseFolder (directory, levels, markers) { var files = fs.readdirSync(directory); if (levels === 0) { return null; } else if (markerExists(files, markers)) { return directory; } else { return traverseFolder(path.resolve(directory, '..'), levels - 1, markers); } } var findProjectRoot = function findRoot(dir, opts) { if (!dir) throw new Error("Directory not defined"); opts = opts || {}; var levels = opts.maxDepth || findRoot.MAX_DEPTH; var markers = opts.markers || findRoot.MARKERS; return traverseFolder(dir, levels, markers); }; var MAX_DEPTH = 9; var MARKERS = [ '.git', '.hg' ]; findProjectRoot.MAX_DEPTH = MAX_DEPTH; findProjectRoot.MARKERS = MARKERS; var resolveConfigEditorconfig = createCommonjsModule(function (module) { "use strict"; const maybeParse = (filePath, config, parse) => { const root = findProjectRoot(path.dirname(path.resolve(filePath))); return filePath && parse(filePath, { root }); }; const editorconfigAsyncNoCache = (filePath, config) => { return Promise.resolve(maybeParse(filePath, config, editorconfig.parse)).then( editorconfigToPrettier ); }; const editorconfigAsyncWithCache = mem(editorconfigAsyncNoCache); const editorconfigSyncNoCache = (filePath, config) => { return editorconfigToPrettier( maybeParse(filePath, config, editorconfig.parseSync) ); }; const editorconfigSyncWithCache = mem(editorconfigSyncNoCache); function getLoadFunction(opts) { if (!opts.editorconfig) { return () => null; } if (opts.sync) { return opts.cache ? editorconfigSyncWithCache : editorconfigSyncNoCache; } return opts.cache ? editorconfigAsyncWithCache : editorconfigAsyncNoCache; } function clearCache() { mem.clear(editorconfigSyncWithCache); mem.clear(editorconfigAsyncWithCache); } module.exports = { getLoadFunction, clearCache }; }); var thirdParty$1 = ( thirdParty && thirdParty__default ) || thirdParty; var resolveConfig_1 = createCommonjsModule(function (module) { "use strict"; const getExplorerMemoized = mem(opts => thirdParty$1.cosmiconfig("prettier", { sync: opts.sync, cache: opts.cache, rcExtensions: true, transform: result => { if (result && result.config) { delete result.config.$schema; } return result; } }) ); /** @param {{ cache: boolean, sync: boolean }} opts */ function getLoadFunction(opts) { // Normalize opts before passing to a memoized function opts = Object.assign({ sync: false, cache: false }, opts); return getExplorerMemoized(opts).load; } function _resolveConfig(filePath, opts, sync) { opts = Object.assign({ useCache: true }, opts); const loadOpts = { cache: !!opts.useCache, sync: !!sync, editorconfig: !!opts.editorconfig }; const load = getLoadFunction(loadOpts); const loadEditorConfig = resolveConfigEditorconfig.getLoadFunction(loadOpts); const arr = [load, loadEditorConfig].map(l => l(filePath, opts.config)); const unwrapAndMerge = arr => { const result = arr[0]; const editorConfigured = arr[1]; const merged = Object.assign( {}, editorConfigured, mergeOverrides(Object.assign({}, result), filePath) ); if (!result && !editorConfigured) { return null; } return merged; }; if (loadOpts.sync) { return unwrapAndMerge(arr); } return Promise.all(arr).then(unwrapAndMerge); } const resolveConfig = (filePath, opts) => _resolveConfig(filePath, opts, false); resolveConfig.sync = (filePath, opts) => _resolveConfig(filePath, opts, true); function clearCache() { mem.clear(getExplorerMemoized); resolveConfigEditorconfig.clearCache(); } function resolveConfigFile(filePath) { const load = getLoadFunction({ sync: false }); return load(filePath).then(result => { return result ? result.filepath : null; }); } resolveConfigFile.sync = filePath => { const load = getLoadFunction({ sync: true }); const result = load(filePath); return result ? result.filepath : null; }; function mergeOverrides(configResult, filePath) { const options = Object.assign({}, configResult.config); if (filePath && options.overrides) { const relativeFilePath = path.relative( path.dirname(configResult.filepath), filePath ); for (const override of options.overrides) { if ( pathMatchesGlobs( relativeFilePath, override.files, override.excludeFiles ) ) { Object.assign(options, override.options); } } } delete options.overrides; return options; } // Based on eslint: https://github.com/eslint/eslint/blob/master/lib/config/config-ops.js function pathMatchesGlobs(filePath, patterns, excludedPatterns) { const patternList = [].concat(patterns); const excludedPatternList = [].concat(excludedPatterns || []); const opts = { matchBase: true }; return ( patternList.some(pattern => minimatch_1(filePath, pattern, opts)) && !excludedPatternList.some(excludedPattern => minimatch_1(filePath, excludedPattern, opts) ) ); } module.exports = { resolveConfig, resolveConfigFile, clearCache }; }); const version = require$$0$11.version; const getSupportInfo = support.getSupportInfo; const normalizeOptions = options$12.normalize; const printDocToString = doc.printer.printDocToString; const printDocToDebug = doc.debug.printDocToDebug; function guessLineEnding(text) { const index = text.indexOf("\n"); if (index >= 0 && text.charAt(index - 1) === "\r") { return "\r\n"; } return "\n"; } function attachComments(text, ast, opts) { const astComments = ast.comments; if (astComments) { delete ast.comments; comments.attach(astComments, ast, text, opts); } ast.tokens = []; opts.originalText = text.trimRight(); return astComments; } function hasPragma(text) { const pragmas = Object.keys(build.parse(build.extract(text))); return pragmas.indexOf("prettier") !== -1 || pragmas.indexOf("format") !== -1; } function ensureAllCommentsPrinted(astComments) { if (!astComments) { return; } for (let i = 0; i < astComments.length; ++i) { if (astComments[i].value.trim() === "prettier-ignore") { // If there's a prettier-ignore, we're not printing that sub-tree so we // don't know if the comments was printed or not. return; } } astComments.forEach(comment => { if (!comment.printed) { throw new Error( 'Comment "' + comment.value.trim() + '" was not printed. Please report this error!' ); } delete comment.printed; }); } function formatWithCursor(text, opts, addAlignmentSize) { if (opts.requirePragma && !hasPragma(text)) { return { formatted: text }; } const UTF8BOM = 0xfeff; const hasUnicodeBOM = text.charCodeAt(0) === UTF8BOM; if (hasUnicodeBOM) { text = text.substring(1); } if ( opts.insertPragma && !hasPragma(text) && opts.rangeStart === 0 && opts.rangeEnd === Infinity ) { const parsedDocblock = build.parseWithComments(build.extract(text)); const pragmas = Object.assign({ format: "" }, parsedDocblock.pragmas); const newDocblock = build.print({ pragmas, comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines }); const strippedText = build.strip(text); const separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n"; text = newDocblock + separatingNewlines + strippedText; } addAlignmentSize = addAlignmentSize || 0; const result = parser$3.parse(text, opts); const ast = result.ast; text = result.text; const formattedRangeOnly = formatRange(text, opts, ast); if (formattedRangeOnly) { return { formatted: formattedRangeOnly }; } let cursorOffset; if (opts.cursorOffset >= 0) { const cursorNodeAndParents = findNodeAtOffset(ast, opts.cursorOffset, opts); const cursorNode = cursorNodeAndParents.node; if (cursorNode) { cursorOffset = opts.cursorOffset - opts.locStart(cursorNode); opts.cursorNode = cursorNode; } } const astComments = attachComments(text, ast, opts); const doc$$1 = astToDoc(ast, opts, addAlignmentSize); opts.newLine = guessLineEnding(text); const toStringResult = printDocToString(doc$$1, opts); let str = toStringResult.formatted; if (hasUnicodeBOM) { str = String.fromCharCode(UTF8BOM) + str; } const cursorOffsetResult = toStringResult.cursor; ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline if (addAlignmentSize > 0) { return { formatted: str.trim() + opts.newLine }; } if (cursorOffset !== undefined) { return { formatted: str, cursorOffset: cursorOffsetResult + cursorOffset }; } return { formatted: str }; } function format(text, opts, addAlignmentSize) { return formatWithCursor(text, opts, addAlignmentSize).formatted; } function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) { let resultStartNode = startNodeAndParents.node; let resultEndNode = endNodeAndParents.node; if (resultStartNode === resultEndNode) { return { startNode: resultStartNode, endNode: resultEndNode }; } for (const endParent of endNodeAndParents.parentNodes) { if ( endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node) ) { resultEndNode = endParent; } else { break; } } for (const startParent of startNodeAndParents.parentNodes) { if ( startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node) ) { resultStartNode = startParent; } else { break; } } return { startNode: resultStartNode, endNode: resultEndNode }; } function findNodeAtOffset(node, offset, options, predicate, parentNodes) { predicate = predicate || (() => true); parentNodes = parentNodes || []; const start = options.locStart(node, options.locStart); const end = options.locEnd(node, options.locEnd); if (start <= offset && offset <= end) { for (const childNode of comments.getSortedChildNodes( node, undefined /* text */, options )) { const childResult = findNodeAtOffset( childNode, offset, options, predicate, [node].concat(parentNodes) ); if (childResult) { return childResult; } } if (predicate(node)) { return { node: node, parentNodes: parentNodes }; } } } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 function isSourceElement(opts, node) { if (node == null) { return false; } // JS and JS like to avoid repetitions const jsSourceElements = [ "FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015 "ImportDeclaration", // Module "ExportDefaultDeclaration", // Module "ExportNamedDeclaration", // Module "ExportAllDeclaration", // Module "TypeAlias", // Flow "InterfaceDeclaration", // Flow, TypeScript "TypeAliasDeclaration", // TypeScript "ExportAssignment", // TypeScript "ExportDeclaration" // TypeScript ]; const jsonSourceElements = [ "ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral" ]; const graphqlSourceElements = [ "OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition" ]; switch (opts.parser) { case "flow": case "babylon": case "typescript": return jsSourceElements.indexOf(node.type) > -1; case "json": return jsonSourceElements.indexOf(node.type) > -1; case "graphql": return graphqlSourceElements.indexOf(node.kind) > -1; } return false; } function calculateRange(text, opts, ast) { // Contract the range so that it has non-whitespace characters at its endpoints. // This ensures we can format a range that doesn't end on a node. const rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd); const startNonWhitespace = Math.max( opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart ); let endNonWhitespace; for ( endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace ) { if (text[endNonWhitespace - 1].match(/\S/)) { break; } } const startNodeAndParents = findNodeAtOffset( ast, startNonWhitespace, opts, node => isSourceElement(opts, node) ); const endNodeAndParents = findNodeAtOffset( ast, endNonWhitespace, opts, node => isSourceElement(opts, node) ); if (!startNodeAndParents || !endNodeAndParents) { return { rangeStart: 0, rangeEnd: 0 }; } const siblingAncestors = findSiblingAncestors( startNodeAndParents, endNodeAndParents, opts ); const startNode = siblingAncestors.startNode; const endNode = siblingAncestors.endNode; const rangeStart = Math.min( opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart) ); const rangeEnd = Math.max( opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd) ); return { rangeStart: rangeStart, rangeEnd: rangeEnd }; } function formatRange(text, opts, ast) { if (opts.rangeStart <= 0 && text.length <= opts.rangeEnd) { return; } const range = calculateRange(text, opts, ast); const rangeStart = range.rangeStart; const rangeEnd = range.rangeEnd; const rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line. // This is so we can detect indentation correctly and restore it. // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0 const rangeStart2 = Math.min( rangeStart, text.lastIndexOf("\n", rangeStart) + 1 ); const indentString = text.slice(rangeStart2, rangeStart); const alignmentSize = util$1.getAlignmentSize( indentString, opts.tabWidth ); const rangeFormatted = format( rangeString, Object.assign({}, opts, { rangeStart: 0, rangeEnd: Infinity, printWidth: opts.printWidth - alignmentSize }), alignmentSize ); // Since the range contracts to avoid trailing whitespace, // we need to remove the newline that was inserted by the `format` call. const rangeTrimmed = rangeFormatted.trimRight(); return text.slice(0, rangeStart) + rangeTrimmed + text.slice(rangeEnd); } var prettier = { formatWithCursor: function(text, opts) { return formatWithCursor(text, normalizeOptions(opts)); }, format: function(text, opts) { return format(text, normalizeOptions(opts)); }, check: function(text, opts) { try { const formatted = format(text, normalizeOptions(opts)); return formatted === text; } catch (e) { return false; } }, doc, resolveConfig: resolveConfig_1.resolveConfig, clearConfigCache: resolveConfig_1.clearCache, getSupportInfo, version, util: utilShared, /* istanbul ignore next */ __debug: { parse: function(text, opts) { opts = normalizeOptions(opts); return parser$3.parse(text, opts); }, formatAST: function(ast, opts) { opts = normalizeOptions(opts); const doc$$1 = astToDoc(ast, opts); const str = printDocToString(doc$$1, opts); return str; }, // Doesn't handle shebang for now formatDoc: function(doc$$1, opts) { opts = normalizeOptions(opts); const debug = printDocToDebug(doc$$1); const str = format(debug, opts); return str; }, printToDoc: function(text, opts) { opts = normalizeOptions(opts); const result = parser$3.parse(text, opts); const ast = result.ast; text = result.text; attachComments(text, ast, opts); const doc$$1 = astToDoc(ast, opts); return doc$$1; }, printDocToString: function(doc$$1, opts) { opts = normalizeOptions(opts); const str = printDocToString(doc$$1, opts); return str; } } }; module.exports = prettier; adminSystem - Gogs: Go Git Service

No Description

index.js 692B

    'use strict' var crypto = require('crypto') var MurmurHash3 = require('imurmurhash') module.exports = function (uniq) { if (uniq) { var hash = new MurmurHash3(uniq) return ('00000000' + hash.result().toString(16)).substr(-8) } else { // Called without a callback, because this interface should neither block // nor error (by contrast with randomBytes which will throw an exception // without enough entropy). // // However, due to a change in Node 0.10.27+, pseudoRandomBytes is now the // same as randomBytes, and may in fact block in situations where // insufficent entropy is available. return crypto.pseudoRandomBytes(4).toString('hex') } }