<commit_before># frozen_string_literal: true

require 'pathname'

module RuboCop
  # Common methods for finding files.
  module FileFinder
    def self.root_level=(level)
      @root_level = level
    end

    def self.root_level?(path)
      @root_level == path.to_s
    end

    def find_file_upwards(filename, start_dir)
      traverse_files_upwards(filename, start_dir) do |file|
        # minimize iteration for performance
        return file if file
      end
    end

    def find_last_file_upwards(filename, start_dir)
      files = []
      traverse_files_upwards(filename, start_dir) do |file|
        files << file
      end
      files.last
    end

    private

    def traverse_files_upwards(filename, start_dir)
      Pathname.new(start_dir).expand_path.ascend do |dir|
        break if FileFinder.root_level?(dir)

        file = dir + filename
        yield(file.to_s) if file.exist?
      end
    end
  end
end
<commit_msg>Refactor `last_file_upwards` to not build an intermmediate array<commit_after># frozen_string_literal: true

require 'pathname'

module RuboCop
  # Common methods for finding files.
  module FileFinder
    def self.root_level=(level)
      @root_level = level
    end

    def self.root_level?(path)
      @root_level == path.to_s
    end

    def find_file_upwards(filename, start_dir)
      traverse_files_upwards(filename, start_dir) do |file|
        # minimize iteration for performance
        return file if file
      end
    end

    def find_last_file_upwards(filename, start_dir)
      last_file = nil
      traverse_files_upwards(filename, start_dir) do |file|
        last_file = file
      end
      last_file
    end

    private

    def traverse_files_upwards(filename, start_dir)
      Pathname.new(start_dir).expand_path.ascend do |dir|
        break if FileFinder.root_level?(dir)

        file = dir + filename
        yield(file.to_s) if file.exist?
      end
    end
  end
end

{'fraction_non_alphanumeric': 0.06797116374871266, 'fraction_numerical': 0.0, 'mean_word_length': 2.6869070208728654, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1522329', 'n_tokens_mistral': 620, 'n_tokens_neox': 613, 'n_words': 156}