Compare lint output with lines changed in commit
 @param lint [Hash] output lint data
 @param files [Hash<String: String>] filename: filepath
 @return [Array] lints that match the lines in commit
972631
def relevant_output(lint, files)
        all_files = {}
        files.each do |file|

          # sometimes data will be blank but this is good - it means no errors were raised in the lint
          next if lint.blank? || file.blank? || !file.is_a?(Hash) || !file.key?(:filename)
          lint_file = lint[file[:filename]]

          next if lint_file.blank?

          expanded = lines_added_to_range(file)
          revert_name = strip_working_dir(file[:filename])

          all_files[revert_name] = []

          lint_file.each do |l|
            if expanded.include?(l['line'].to_i)
              all_files[revert_name] << l
            end
          end

          # If there's nothing there, then it definitely isn't a relevant lint
          all_files.delete(revert_name) if all_files[revert_name].blank?
        end
        @output[:files_linted] = all_files.keys
        all_files
      end
155209
def file(ui, repo, clname, pat, *pats, **opts):
	
	if codereview_disabled:
		raise hg_util.Abort(codereview_disabled)

	pats = tuple([pat] + list(pats))
	if not GoodCLName(clname):
		return "invalid CL name " + clname

	dirty = {}
	cl, err = LoadCL(ui, repo, clname, web=False)
	if err != '':
		return err
	if not cl.local:
		return "cannot change non-local CL " + clname

	files = ChangedFiles(ui, repo, pats)

	if opts["delete"]:
		oldfiles = Intersect(files, cl.files)
		if oldfiles:
			if not ui.quiet:
				ui.status("# Removing files from CL.  To undo:\n")
				ui.status("#	cd %s\n" % (repo.root))
				for f in oldfiles:
					ui.status("#	hg file %s %s\n" % (cl.name, f))
			cl.files = Sub(cl.files, oldfiles)
			cl.Flush(ui, repo)
		else:
			ui.status("no such files in CL")
		return

	if not files:
		return "no such modified files"

	files = Sub(files, cl.files)
	taken = Taken(ui, repo)
	warned = False
	for f in files:
		if f in taken:
			if not warned and not ui.quiet:
				ui.status("# Taking files from other CLs.  To undo:\n")
				ui.status("#	cd %s\n" % (repo.root))
				warned = True
			ocl = taken[f]
			if not ui.quiet:
				ui.status("#	hg file %s %s\n" % (ocl.name, f))
			if ocl not in dirty:
				ocl.files = Sub(ocl.files, files)
				dirty[ocl] = True
	cl.files = Add(cl.files, files)
	dirty[cl] = True
	for d, _ in dirty.items():
		d.Flush(ui, repo)
	return
248522
def get_user_modified_lines(self):
        
        # I assume that git diff:
        # - doesn't mix diffs from different files,
        # - diffs are not overlapping
        # - diffs are sorted based on line numbers
        output = {}

        FILE_NAME_RE = r'^\+\+\+ (.+)$'
        CHANGED_LINES_RE = r'^@@ -[0-9,]+ \+([0-9]+)(?:,([0-9]+))? @@'
        current_file_name = None

        for line in self.git_wrapper.get_min_diff(self.remote_sha1, self.local_sha1).split('\n'):
            file_name_match = re.match(FILE_NAME_RE, line)
            if file_name_match:
                current_file_name, = file_name_match.groups()
                output[current_file_name] = []
                continue

            line_number_match = re.match(CHANGED_LINES_RE, line)
            if line_number_match:
                assert current_file_name
                if current_file_name == '/dev/null':
                    continue
                line_start, diff_len = line_number_match.groups()
                line_start, diff_len = int(line_start), int(diff_len or 0)
                output[current_file_name].append(LinesRange(line_start, line_start + diff_len))
                continue

        return output
1171377
def lint(files, inline_mode = false, options = {})
      final_options = options.merge(json: true)

      issues = files
               .map { |file| Shellwords.escape(file) }
               .map { |file| `hlint lint #{file} #{to_hlint_options(final_options)} 2>/dev/null` }
               .reject { |s| s == '' }
               .map { |lint_result| JSON.parse(lint_result).flatten }
               .flatten

      self.suggestions = issues.select { |issue| issue['severity'] == 'Suggestion' }
      self.warnings = issues.select { |issue| issue['severity'] == 'Warning' }
      self.errors = issues.select { |issue| issue['severity'] == 'Error' }

      if inline_mode
        # Reprt with inline comment
        send_inline_comment(suggestions, 'warn')
        send_inline_comment(warnings, 'warn')
        send_inline_comment(errors, 'fail')

      else
        # Report if any suggestions, warnings or errors
        if suggestions.count > 0 || warnings.count > 0 || errors.count > 0
          message = "### hlint found issues\n\n"
          message << markdown_issues(warnings, 'Suggestions') unless suggestions.empty?
          message << markdown_issues(warnings, 'Warnings') unless warnings.empty?
          message << markdown_issues(errors, 'Errors') unless errors.empty?
          markdown message
        end
      end
    end
402893
def get_changed_files(self, first_sha, second_sha, exclude_paths=None):
        
        if not exclude_paths:
            exclude_paths = []

        first_commit = self.repo.commit(first_sha)
        second_commit = self.repo.commit(second_sha)

        diffs = first_commit.diff(second_commit)
        changed_files = []

        for diff in diffs:
            excluded = False
            for exclude in exclude_paths:
                if diff.a_path.startswith(exclude):
                    excluded = True

            if not excluded:
                changed_files.append(diff.a_path)

        return changed_files
55138
def get_changed_files(self) -> List[str]:
        
        out = shell_tools.output_of(
            'git',
            'diff',
            '--name-only',
            self.compare_commit_id,
            self.actual_commit_id,
            '--',
            cwd=self.destination_directory)
        return [e for e in out.split('\n') if e.strip()]
298035
def files(obj, commit='HEAD', skip_merge_commits=False):
    """"""
    from ..kwalitee import check_file, SUPPORTED_FILES
    from ..hooks import run
    options = obj.options
    repository = obj.repository

    if options.get('colors') is not False:
        colorama.init(autoreset=True)
        reset = colorama.Style.RESET_ALL
        yellow = colorama.Fore.YELLOW
        green = colorama.Fore.GREEN
        red = colorama.Fore.RED
    else:
        reset = yellow = green = red = ''

    try:
        sha = 'oid'
        commits = _pygit2_commits(commit, repository)
    except ImportError:
        try:
            sha = 'hexsha'
            commits = _git_commits(commit, repository)
        except ImportError:
            click.echo(
                'To use this feature, please install pygit2. GitPython will '
                'also work but is not recommended (python <= 2.7 only).',
                file=sys.stderr)
            click.exit(2)

    template = '{0}commit {{commit.{1}}}{2}\n\n'.format(yellow, sha, reset)
    template += '{message}{errors}\n'

    error_template = '\n{0}{{filename}}\n{1}{{errors}}{0}'.format(reset, red)
    no_errors = ['\n{0}Everything is OK.{1}'.format(green, reset)]
    msg_file_excluded = '\n{0}{{filename}} excluded.{1}'.format(yellow, reset)

    def _get_files_modified(commit):
        """Get the list of modified files that are Python or Jinja2."""
        cmd = "git show --no-commit-id --name-only --diff-filter=ACMRTUXB {0}"
        _, files_modified, _ = run(cmd.format(commit))

        extensions = [re.escape(ext)
                      for ext in list(SUPPORTED_FILES) + [".rst"]]
        test = "(?:{0})$".format("|".join(extensions))
        return list(filter(lambda f: re.search(test, f), files_modified))

    def _ensure_directory(filename):
        dir_ = os.path.dirname(filename)
        if not os.path.exists(dir_):
            os.makedirs(dir_)

    def _format_errors(args):
        filename, errors = args
        if errors is None:
            return msg_file_excluded.format(filename=filename)
        else:
            return error_template.format(filename=filename, errors='\n'.join(
                errors if len(errors) else no_errors))

    count = 0
    ident = '    '
    re_line = re.compile('^', re.MULTILINE)
    for commit in commits:
        if skip_merge_commits and _is_merge_commit(commit):
            continue
        message = commit.message
        commit_sha = getattr(commit, sha)
        tmpdir = mkdtemp()
        errors = {}
        try:
            for filename in _get_files_modified(commit):
                cmd = "git show {commit_sha}:{filename}"
                _, out, _ = run(cmd.format(commit_sha=commit_sha,
                                           filename=filename),
                                raw_output=True)

                destination = os.path.join(tmpdir, filename)
                _ensure_directory(destination)

                with open(destination, 'w+') as f:
                    f.write(out)

                errors[filename] = check_file(destination, **options)
        finally:
            shutil.rmtree(tmpdir, ignore_errors=True)

        message = re.sub(re_line, ident, message)
        if len(errors):
            count += 1
            errors = map(_format_errors, errors.items())
        else:
            errors = no_errors

        click.echo(template.format(commit=commit,
                                   message=message.encode('utf-8'),
                                   errors='\n'.join(errors)))

    if min(count, 1):
        raise click.Abort
69498
def get_files_in_commit(git_folder, commit_id="HEAD"):
    
    repo = Repo(str(git_folder))
    output = repo.git.diff("--name-only", commit_id+"^", commit_id)
    return output.splitlines()
1273098
public function preCommitHook($changed_files) {
    $collection = $this->collectionBuilder();
    $collection->setProgressIndicator(NULL);
    $collection->addCode(
      function () use ($changed_files) {
        return $this->invokeCommands([
          'tests:phpcs:sniff:files' => ['file_list' => $changed_files],
          'tests:twig:lint:files' => ['file_list' => $changed_files],
          'tests:yaml:lint:files' => ['file_list' => $changed_files],
        ]);
      }
    );

    $changed_files_list = explode("\n", $changed_files);
    if (in_array('composer.json', $changed_files_list)
      || in_array('composer.lock', $changed_files_list)) {
      $collection->addCode(
        function () use ($changed_files) {
          return $this->invokeCommand('tests:composer:validate');
        }
      );
    }

    $result = $collection
      ->setVerbosityThreshold(VerbosityThresholdInterface::VERBOSITY_VERBOSE)
      ->run();

    if ($result->wasSuccessful()) {
      $this->say("<info>Your local code has passed git pre-commit validation.</info>");
    }

    return $result;
  }
546278
def collect_lints(file, linter_selector, config)
      begin
        document = HamlLint::Document.new(File.read(file), file: file, config: config)
      rescue HamlLint::Exceptions::ParseError => e
        return [HamlLint::Lint.new(HamlLint::Linter::Syntax.new(config), file,
                                   e.line, e.to_s, :error)]
      end

      linter_selector.linters_for_file(file).map do |linter|
        linter.run(document)
      end.flatten
    end
264080
def yamline_delete!(lines = nil)
      lines = file_lines unless lines
      return unless lines
      lines_readed = yamline_read(lines, false)
      lines_readed.each {|lr| lines.delete(lr) } if lines_readed
      save_file(lines)
    end
984064
def current_files
      if commit_range.is_range?
        execute("git #{git_directory_params} -c diff.renames=0 -c diff.renameLimit=1000 diff -M -C -c --name-only --ignore-submodules=all --diff-filter=AM #{encoding_opt} #{default_params} #{commit_range.to_s}") do |result|
          filter_files(result.to_s.split(/\n/))
        end
      else
        submodules = current_submodules
        execute("git #{git_directory_params} ls-tree -r #{commit_range.to_s} --name-only") do |result|
          filter_files(result.to_s.split(/\n/).select { |f| !submodules.index(f) })
        end
      end
    end
873764
def lint
      return if target_files.empty?

      bin = textlint_path
      result_json = run_textlint(bin, target_files)
      errors = parse(result_json)
      send_comment(errors)
    end
200525
def lint
      lint_results
        .reject { |r| r.nil? || r['messages'].length.zero? }
        .reject { |r| r['messages'].first['message'].include? 'matching ignore pattern' }
        .map { |r| send_comment r }
    end
295479
def execute!
      files_to_check = parse_options.leftovers

      YamlLint.logger.level = Logger::DEBUG if opts.debug

      no_yamls_to_check_msg = "Error: need at least one YAML file to check.\n"\
                              'Try --help for help.'
      abort(no_yamls_to_check_msg) if files_to_check.empty?
      lint(files_to_check)
    end
1018181
function lint(input, options) {
  // Run sassLint via lintFiles, which takes a glob
  var report = sassLint.lintFiles(input, {}, options.configFile);
  var fileReport = [];

  if (report.length) {
    report.forEach(function(file) {
      // Skip report if file is ignored
      if (options.ignoreFiles &&
        -1 !== options.ignoreFiles.indexOf(file.filePath)
      ) {
        return;
      }

      if (file.warningCount && options.quiet) {
        file.warningCount = 0;
      }

      if ((file.errorCount || file.warningCount) && !options.testing) {
        // We can't easily use webpack's outputing for info,
        // so this get's prettified, and dumped to terminal
        console.log(formatter(file.messages, file.filePath));
      }

      // Push seperate error counts and warning counts w/ filenames return
      if (file.errorCount) {
        fileReport.push({
          'error': true,
          'file': file.filePath
        });
      }

      if (file.warningCount) {
        fileReport.push({
          'error': false,
          'file': file.filePath
        });
      }

      // Allow dying on sasslint error of set
      if (options.failOnError && file.errorCount) {
        throw new Error('Failed because of a sasslint error.\n');
      } else if (options.failOnWarning && file.warningCount) {
        throw new Error('Failed because of a sasslint warning.\n');
      }
    });
  }

  return fileReport;
}
563356
def changeset
      @changeset ||= git_diff.map do |diff_file|
        file_diff = FileDiff.new(diff_file)
        file_diff unless FormattingChecker.pure_formatting?(file_diff)
      end.compact
    end