Merge report results into a summary
@param {Object} linter - markdown linter
@param {Object} summary - summary of results
@param {String} filePath - path to file to lint
@returns {Object} summary
3515
function reportReducer (linter, summary, filePath) {
  const fileContents = fs.readFileSync(filePath, {encoding: 'utf8'})
  const file = linter.process(fileContents)

  if (file.messages.length !== 0) {
    this.printFilePath(filePath)

    file.messages.forEach((message) => {
      const severity = message.fatal ? 'error' : 'warning'
      this.printLintItem(message.line, message.column, severity, message.message, message.ruleId)

      if (message.fatal) {
        summary.errors += 1
      } else {
        summary.warnings += 1
      }
    })

    console.log('') // logging empty line
  }

  return summary
}
1004189
function lintFileContents (messages, js) {
  // what was messages imported as
  let importedAtRootAs = false
  let importedMembersAs
  const importedMembersLookup = new Map()

  let namedMatcher, rootMatcher

  // TODO handle importing members, e.g. import { analysis } from messages

  const foundMessages = []

  let lineNumber = 0 // first increment lands at 0

  for (const line of js.split('\n')) {
    lineNumber++
    const parsedImport = parseImportLine(line)
    if (parsedImport) {
      ;[importedAtRootAs, importedMembersAs] = parsedImport
      // make sure we don't catch things like display_messages by making sure there's a diff char before
      rootMatcher = new RegExp(
        `[^a-zA-Z0-9_$]${importedAtRootAs}\\.([^ ,\\(\\)\\[}]+)`,
        'g'
      )
      namedMatcher = new RegExp(
        `[^a-zA-Z0-9_$](${importedMembersAs
          .map(a => a[1])
          .join('|')})\\.([^ ,\\(\\)\\[}]+)`,
        'g'
      )
      importedMembersAs.forEach(([member, importedAs]) =>
        importedMembersLookup.set(importedAs, member)
      )
    } else if (importedAtRootAs || importedMembersAs) {
      let result
      // each subsequent call gets next match
      if (importedAtRootAs) {
        while ((result = rootMatcher.exec(line)) != null) {
          foundMessages.push([result[1], lineNumber])
        }
      }

      // do the same for imported members
      if (importedMembersAs.length > 0) {
        while ((result = namedMatcher.exec(line)) != null) {
          // map back to the names in the messages file
          foundMessages.push([
            `${importedMembersLookup.get(result[1])}.${result[2]}`,
            lineNumber
          ])
        }
      }
    }
  }

  // filter to only the missing ones
  return foundMessages.filter(([message, lineNumber]) => {
    let current = messages
    for (const sub of message.split('.')) {
      current = current[sub]
      if (current == null) {
        return true // something in the chain is undefined
      }
    }

    return false
  })
}
203607
function exportReadme(readmePath) {
    const readmePaths = path.resolve(process.cwd(), srcDir);

    glob(readmePaths, void(0), function(error, files) {
        files.forEach((filePath) => {
            let documentation = startFile;
            const markdown = fs.readFileSync(filePath, "utf8");
            const exportPath = filePath.replace(/README\.md/, readmePath);

            if (markdown.length !== 0) {
                documentation += md.render(markdown);
            } else {
                documentation += emptyFile;
            }

            documentation += endFile;
            
            if (!fs.existsSync(exportPath)){
                fs.mkdirSync(exportPath);
            }

            fs.writeFileSync(path.resolve(exportPath, "documentation.tsx"), documentation);
        });
    });
}
78697
function toFileStats(componentName, filepath) {
			return {
				src: path.relative(bowerDir, filepath),
				component: componentName,
				size: getFileSize(filepath)
			};
		}
1256835
function collectDeclarations (filePath) {
    const declarationRegexp = /(?:\$)([\w-]+)(?:[\s\n\r\t])*(?::)(?:[\s\n\r\t])*(.+)(?:[\s\n\r\t])*(?:;)/gm;
    const fileSource = fs.readFileSync(filePath, 'utf8');

    return fileSource.match(declarationRegexp);
}
1060866
function (filepath) {

            // console.log('processing: ' + filepath);

            // read file source, saved in RAM
            var content = grunt.file.read(filepath);

            /*
             * Reset pattern's last search index to 0
             * at the beginning for each file content.
             *
             * NOTE:
             *   Since the pattern is always the same regex instance,
             *   property 'lastIndex' changes each time when .exec() is performed.
             *   To avoid 'lastIndex' affected by recursive function call,
             *   its value MUST be cached for each file content.
             */
            var cacheLastIndex = 0;
            _.pattern.lastIndex = cacheLastIndex;
            var matches = _.pattern.exec(content);
            cacheLastIndex = _.pattern.lastIndex;

            // While there are matches (of import-links) in file content
            while (matches !== null) {

                /*
                 * Construct the imported file's absolute path
                 *   (doesn't matter whether or not a relative path),
                 * and recursively search in imported file. (dept-first)
                 *
                 * NOTE:
                 *    - the regex uses capture group, the first match is the fragment file path.
                 */
                var currentDir = path.dirname(filepath),
                    relativeFilepath = matches[1].trim(),
                    importedFilepath = path.resolve(currentDir, relativeFilepath);

                var returnContent = getReplacedFileContent(importedFilepath);


                /*
                 * For current file content,
                 * replace import-link tag with return value.
                 *
                 * NOTE:
                 *   Because of dept-first search,
                 *   should ONLY replace the first match in current content.
                 *   rather than search globally.
                 */
                content = content.replace(_.patternNonGlobal, returnContent);
                // console.log(content);
                // console.log(matches);
                // console.log('-----');


                /*
                 * Keep searching in current file.
                 *
                 * NOTE:
                 *   After replacing part of the content (the step above),
                 *   the content's length changes accordingly.
                 *   Thus the 'lastIndex' property should shift to
                 *   the proper position to ensure next search.
                 */
                var deltaLength = returnContent.length - matches[0].length;

                _.pattern.lastIndex = cacheLastIndex + deltaLength;
                matches = _.pattern.exec(content);
                cacheLastIndex = _.pattern.lastIndex;
            }

            // When searching and replacing is done, return the result.
            return content;
        }
757672
function getPageByPath(filePath) {
        var page = output.getPage(filePath);
        if (!page) return undefined;

        return JSONUtils.encodePage(page, summary);
    }
644455
function parse(html, script, filePath){
  var m, index = 0;//the index in the html string
  while(m = reDelim.exec(html)) {
    addLiteral(script, html.slice(index, m.index));//string
    addCode(script, m, filePath);
    index = m.index + m[0].length;
  }
  addLiteral(script, html.slice(index));
  script.push('\n}return __r.join("");');
  script = script.join('');
  return script;
}
537560
function mergeAtLevel(summary, level, newValue) {
    var levelParts = level.split('.');
    var partIndex = Number(levelParts[0]) -1;

    var parts = summary.getParts();
    var part = parts.get(partIndex);
    if (!part) {
        return summary;
    }

    var isEditingPart = levelParts.length < 2;
    if (isEditingPart) {
        part = part.merge(newValue);
    } else {
        part = editArticleInPart(part, level, newValue);
    }

    parts = parts.set(partIndex, part);
    return summary.set('parts', parts);
}
1020304
function initBook(rootFolder) {
    var extension = '.md';

    return fs.mkdirp(rootFolder)

    // Parse the summary and readme
    .then(function() {
        var fs = createNodeFS(rootFolder);
        var book = Book.createForFS(fs);

        return Parse.parseReadme(book)

        // Setup default readme if doesn't found one
        .fail(function() {
            var readmeFile = File.createWithFilepath('README' + extension);
            var readme = Readme.create(readmeFile);
            return book.setReadme(readme);
        });
    })
    .then(Parse.parseSummary)

    .then(function(book) {
        var logger = book.getLogger();
        var summary = book.getSummary();
        var summaryFile = summary.getFile();
        var summaryFilename = summaryFile.getPath() || ('SUMMARY' + extension);

        var articles = summary.getArticlesAsList();

        // Write pages
        return Promise.forEach(articles, function(article) {
            var articlePath = article.getPath();
            var filePath = articlePath? path.join(rootFolder, articlePath) : null;
            if (!filePath) {
                return;
            }

            return fs.assertFile(filePath, function() {
                return fs.ensureFile(filePath)
                .then(function() {
                    logger.info.ln('create', article.getPath());
                    return fs.writeFile(filePath, '# ' + article.getTitle() + '\n\n');
                });
            });
        })

        // Write summary
        .then(function() {
            var filePath = path.join(rootFolder, summaryFilename);

            return fs.ensureFile(filePath)
            .then(function() {
                logger.info.ln('create ' + path.basename(filePath));
                return fs.writeFile(filePath, summary.toText(extension));
            });
        })

        // Log end
        .then(function() {
            logger.info.ln('initialization is finished');
        });
    });
}
1009339
function stat(filepath, callback) {
  return fs.lstat(filepath, function(err, stats) {
    if (err) {
      return callback(err);
    }
    stats.path = filepath;
    stats.filename = path.basename(filepath);
    stats.mime = mime.lookup(filepath);
    return callback(null, stats);
  });
}
838051
function (filePath, callback) {
        fs.readFile(filePath, function (err, data) {
            if (err)
                return callback(err);
            var message = parse(data.toString());
            callback(null, message);
        })
    }
8621
def lint(relative_path_to_file,
         contents,
         linter_functions,
         **kwargs):
    
    """
    lines = contents.splitlines(True)

    errors = list()
    for (code, info) in linter_functions.items():
        error = info.function(relative_path_to_file, lines, kwargs)
        if error:
            if isinstance(error, list):
                errors.extend([(code, e) for e in error])
            else:
                errors.append((code, error))

    errors = [e for e in errors if not _error_is_suppressed(e[1], e[0], lines)]
    return sorted(errors, key=lambda e: e[1].line)
1083953
def lint():
    ""
    # report according to file extension
    report_formats = {
        ".html": "html",
        ".log": "parseable",
        ".txt": "text",
    }

    lint_build_dir = easy.path("build/lint")
    lint_build_dir.exists() or lint_build_dir.makedirs()  # pylint: disable=expression-not-assigned

    argv = []
    rcfile = easy.options.lint.get("rcfile")
    if not rcfile and easy.path("pylint.cfg").exists():
        rcfile = "pylint.cfg"
    if rcfile:
        argv += ["--rcfile", os.path.abspath(rcfile)]
    if easy.options.lint.get("msg_only", False):
        argv += ["-rn"]
    argv += [
        "--import-graph", (lint_build_dir / "imports.dot").abspath(),
    ]
    argv += support.toplevel_packages()

    sys.stderr.write("Running %s::pylint '%s'\n" % (sys.argv[0], "' '".join(argv)))
    outfile = easy.options.lint.get("output", None)
    if outfile:
        outfile = os.path.abspath(outfile)

    try:
        with easy.pushd("src" if easy.path("src").exists() else "."):
            if outfile:
                argv.extend(["-f", report_formats.get(easy.path(outfile).ext, "text")])
                sys.stderr.write("Writing output to %r\n" % (str(outfile),))
                outhandle = open(outfile, "w")
                try:
                    subprocess.check_call(["pylint"] + argv, stdout=outhandle)
                finally:
                    outhandle.close()
            else:
                subprocess.check_call(["pylint"] + argv, )
            sys.stderr.write("paver::lint - No problems found.\n")
    except subprocess.CalledProcessError as exc:
        if exc.returncode & 32:
            # usage error (internal error in this code)
            sys.stderr.write("paver::lint - Usage error, bad arguments %r?!\n" % (argv,))
            sys.exit(exc.returncode)
        else:
            bits = {
                1: "fatal",
                2: "error",
                4: "warning",
                8: "refactor",
                16: "convention",
            }
            sys.stderr.write("paver::lint - Some %s message(s) issued.\n" % (
                ", ".join([text for bit, text in bits.items() if exc.returncode & bit])
            ))
            if exc.returncode & 3:
                sys.stderr.write("paver::lint - Exiting due to fatal / error message.\n")
                sys.exit(exc.returncode)
229701
function readFileStats(filePath) {
  return new Promise((resolve, reject) => {
    fs.stat(filePath, (err, fstat) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(fstat);
    });
  });
}
557835
function _filesToFile (files, target, separator, callback) {

			if ("undefined" === typeof files) {
				throw new ReferenceError("missing \"files\" argument");
			}
				else if ("object" !== typeof files || !(files instanceof Array)) {
					throw new TypeError("\"files\" argument is not an Array");
				}
			else if ("undefined" === typeof target) {
				throw new ReferenceError("missing \"target\" argument");
			}
				else if ("string" !== typeof target) {
					throw new TypeError("\"target\" argument is not a string");
				}
			else if ("undefined" === typeof callback && "undefined" === typeof separator) {
				throw new ReferenceError("missing \"callback\" argument");
			}
				else if ("function" !== typeof callback && "function" !== typeof separator) {
					throw new TypeError("\"callback\" argument is not a function");
				}
			else {

				const _target = target.trim();

				if ("" === _target) {
					throw new Error("\"target\" argument is empty");
				}
				else {

					const _callback = "undefined" === typeof callback ? separator : callback;

					Promise.resolve().then(() => {
						return isFileProm(_target);
					}).then((exists) => {

						return !exists ? Promise.resolve() : new Promise((resolve, reject) => {

							fs.unlink(_target, (err) => {
								return err ? reject(err) : resolve();
							});

						});

					}).then(() => {

						if (!files.length) {

							return new Promise((resolve, reject) => {

								fs.writeFile(_target, "", (err) => {
									return err ? reject(err) : resolve();
								});

							});

						}
						else {

							return filesToStreamProm(files, "string" === typeof separator ? separator : " ").then((readStream) => {

								return new Promise((resolve, reject) => {

									let error = false;
									readStream.once("error", (_err) => {
										error = true; reject(_err);
									}).pipe(fs.createWriteStream(_target, { "flags": "a" }).once("error", (_err) => {
										error = true; reject(_err);
									}).once("close", () => {

										if (!error) {
											resolve();
										}

									}));

								});

							});

						}

					}).then(() => {
						_callback(null);
					}).catch(_callback);

				}

			}

		}
104963
function lintFiles (src)
{
    gulp.src(src)
        .pipe(scssLint({
            config: __dirname + "/../config/scss-lint.yml",
            customReport: issueCountReporter
        }))
        .on('error', function (error)
        {
            gulpUtil.log(gulpUtil.colors.red('An error has occurred while executing scss-lint: ' + error.message));
        })
        .on('end', reportTotalIssueCount);
}