### ErbSafety: Configuration Example Source: https://github.com/shopify/erb_lint/blob/main/README.md Example configuration to enable the ErbSafety linter and specify a custom better-html configuration file. ```yaml --- linters: ErbSafety: enabled: true better_html_config: .better-html.yml ``` -------------------------------- ### inspect() Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/offense.md Shows an example of calling the `inspect` method and the format of the returned string. ```ruby offense = # ... create offense ... puts offense.inspect # => "# severity=warning" ``` -------------------------------- ### Runner Example Usage Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/runner.md Demonstrates how to initialize a Runner, process a source file, and iterate over the found offenses. This example shows the typical workflow for linting a file. ```ruby file_loader = ERBLint::FileLoader.new("/path/to/project") config = ERBLint::RunnerConfig.default runner = ERBLint::Runner.new(file_loader, config) source = ERBLint::ProcessedSource.new("app/views/index.html.erb", file_content) runner.run(source) runner.offenses.each do |offense| puts "#{offense.simple_name}: #{offense.message} at line #{offense.line_number}" end ``` -------------------------------- ### File Pattern Matching Examples Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/types.md Illustrates the use of `File.fnmatch?` with glob patterns for matching file paths, including examples with `**`, `*`, and `?`. ```ruby File.fnmatch?("**/*.erb", "app/views/index.html.erb") # => true ``` ```ruby File.fnmatch?("**/vendor/**/*", "vendor/lib/file.erb") # => true ``` ```ruby File.fnmatch?("spec/**/*", "test/helper.erb") # => false ``` -------------------------------- ### Check All Templates (Example) Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Demonstrates running the lint process on all templates using Bundler. ```bash bundle exec erb_lint --lint-all ``` -------------------------------- ### Offense Initialization Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/offense.md Demonstrates how to create an instance of the Offense class with all parameters. ```ruby linter_instance = MyLinter.new(file_loader, config) range = processed_source.to_source_range(5...15) offense = ERBLint::Offense.new( linter_instance, range, "Found a problem", context_data, :warning ) ``` -------------------------------- ### Check Only Specific Linters (Example) Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Demonstrates how to enable and run only a predefined set of linters. ```bash bundle exec erb_lint --enable-linters FinalNewline,SpaceAroundErbTag --lint-all ``` -------------------------------- ### ERB Lint Command-Line Output Example Source: https://github.com/shopify/erb_lint/blob/main/README.md Example output from running ERB Lint on a project, showing linting progress and specific errors found. ```text Linting 15 files with 1 linters... This file isn't fine. We suggest you change this file. In file: app/views/layouts/application.html.erb:1 Errors were found in ERB files ``` -------------------------------- ### Stats Initialization Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/stats.md Demonstrates how to create and initialize a Stats object with specific values for a linting run. ```ruby stats = ERBLint::Stats.new( files: 15, linters: 12, autocorrectable_linters: 8, found: 5, ignored: 2, corrected: 0, exceptions: 0 ) ``` -------------------------------- ### Check with Custom Configuration (Example) Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Illustrates using a specific configuration file for linting, allowing for tailored rule sets. ```bash bundle exec erb_lint --config config/.erb_lint_strict.yml --lint-all ``` -------------------------------- ### Initialize Linter Instance Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/linter.md Example of initializing a specific linter, `FinalNewline`, with a `FileLoader` and its configuration. ```ruby file_loader = ERBLint::FileLoader.new("/path/to/project") config = ERBLint::Linters::FinalNewline::ConfigSchema.new(enabled: true, present: true) linter = ERBLint::Linters::FinalNewline.new(file_loader, config) ``` -------------------------------- ### DeprecatedClasses RuleSet Configuration Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/types.md Shows how to configure the DeprecatedClasses linter using a RuleSet. This example specifies deprecated patterns and a suggestion for replacement. ```yaml linters: DeprecatedClasses: enabled: true rule_set: - deprecated: ['badge[-_\w]*'] suggestion: "Use the ui_badge() component instead" ``` -------------------------------- ### Check from Stdin (Example) Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Demonstrates linting ERB content directly from standard input, providing the filename for context. ```bash erb_lint --stdin app/views/index.html.erb < app/views/index.html.erb ``` -------------------------------- ### line_range() Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/offense.md Demonstrates calling the `line_range` method and its output for an offense spanning multiple lines. ```ruby offense = # ... create offense ... puts offense.line_range # => 5..7 (spans lines 5 to 7) ``` -------------------------------- ### JUnit XML Reporter Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/reporter.md Example output of the JUnit reporter, suitable for CI integration. It details test suites, cases, and failures. ```xml ... ``` -------------------------------- ### Stats Usage Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/types.md Demonstrates how to instantiate and populate the Stats object. This is useful for tracking linting run metrics. ```ruby stats = ERBLint::Stats.new stats.files = 10 stats.found = 3 stats.linters = 12 reporter = MultilineReporter.new(stats, autocorrect=false) ``` -------------------------------- ### Install ERB Lint via RubyGems Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Install the erb_lint gem globally on your system. ```bash gem install erb_lint ``` -------------------------------- ### ERB Lint Configuration Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/README.md Example of an .erb_lint.yml configuration file. It enables default linters, specifies file glob patterns, and configures specific linters like FinalNewline and Rubocop. ```yaml --- EnableDefaultLinters: true glob: "**/*.html{+*,}.erb" exclude: - "**/vendor/**/*" linters: FinalNewline: enabled: true present: true Rubocop: enabled: true rubocop_config: inherit_from: .rubocop.yml ``` -------------------------------- ### HardCodedString Corrector File Example Source: https://github.com/shopify/erb_lint/blob/main/README.md Example implementation of a custom corrector file for the HardCodedString linter. The autocorrect method should be implemented as needed. ```ruby class I18nCorrector attr_reader :node def initialize(node, filename, i18n_load_path, range) end def autocorrect(tag_start:, tag_end:) ->(corrector) do node end end end ``` -------------------------------- ### SmartProperties Hash Type Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/types.md Demonstrates defining a property that accepts a Hash object. ```ruby property :config, accepts: Hash ``` -------------------------------- ### Configuration Inheritance Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/configuration.md Demonstrates how to inherit configuration from other YAML files. Later files in the list override settings from earlier ones. Files are loaded relative to the base path. ```yaml inherit_from: - .erb_lint_base.yml - config/.erb_lint_custom.yml ``` -------------------------------- ### Fix All Auto-Correctable Issues (Example) Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Shows how to automatically fix all issues that can be corrected by the linter. ```bash bundle exec erb_lint --autocorrect --lint-all ``` -------------------------------- ### Reporter#preview Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/reporter.md Displays a preview message before linting starts. This method is intended to be overridden by subclasses to print an intro message. ```APIDOC ## Reporter#preview ### Description Displays a preview message before linting starts. This method is intended to be overridden by subclasses to print an intro message. ### Method `preview()` ### Return Type `void` ### Override in subclass Print header or intro message. ### Example ```ruby def preview puts "Starting lint run..." end ``` ``` -------------------------------- ### Minimal Custom Linter Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/README.md Demonstrates the basic structure for creating a custom linter by extending the `Linter` class and implementing the `run` method. Includes optional autocorrection support. ```ruby # .erb_linters/my_custom_linter.rb module ERBLint module Linters class MyCustomLinter < Linter include LinterRegistry class ConfigSchema < LinterConfig property :enabled, accepts: [true, false], default: false, reader: :enabled? end self.config_schema = ConfigSchema def run(processed_source) if problematic_pattern(processed_source) add_offense( processed_source.to_source_range(0...10), "Description of the problem" ) end end # Optional: autocorrection support def autocorrect(_processed_source, offense) lambda do |corrector| corrector.replace(offense.source_range, "corrected_text") end end private def problematic_pattern(processed_source) # Custom linting logic end end end end ``` -------------------------------- ### SmartProperties Primitive Type Examples Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/types.md Demonstrates defining properties with primitive types like booleans, integers, and numerics. ```ruby property :enabled, accepts: [true, false] property :count, accepts: Integer property :threshold, accepts: Numeric ``` -------------------------------- ### SmartProperties Syntax Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/types.md Illustrates the general syntax for defining properties using SmartProperties, including type validation, default values, converters, and custom readers. ```ruby property :name, accepts: Type, default: value, converts: converter, reader: :method_name ``` -------------------------------- ### SmartProperties Collection Type Examples Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/types.md Shows how to define properties that accept arrays of strings, using `array_of?` for validation. ```ruby property :patterns, accepts: array_of?(String) property :items, accepts: LinterConfig.array_of?(String) ``` -------------------------------- ### Check Specific Files with Caching (Example) Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Combines linting specific files with the caching mechanism to improve performance on subsequent runs. ```bash bundle exec erb_lint --cache app/views/posts/**/*.erb ``` -------------------------------- ### GitLab Code Quality Reporter Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/reporter.md Example output of the GitLab reporter, formatted for GitLab's Code Quality feature. It includes offense details and location. ```json [ { "description": "Missing trailing newline", "check_name": "FinalNewline", "severity": "warning", "location": { "path": "app/views/index.html.erb", "lines": { "begin": 10, "end": 10 } } } ] ``` -------------------------------- ### Runner clear_offenses Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/runner.md An example demonstrating how to call the clear_offenses method on a runner instance to reset its offense list. ```ruby runner.clear_offenses ``` -------------------------------- ### CLI Cache Usage Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/cache.md Demonstrates how caching can be optionally enabled and utilized within the ERB Lint command-line interface. ```ruby # The CLI uses caching optionally: # ... (code omitted in source) ``` -------------------------------- ### Generate JUnit XML for CI (Example) Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Illustrates generating a JUnit XML report, commonly used by CI/CD systems for test result aggregation. ```bash bundle exec erb_lint --format junit --lint-all > junit_results.xml ``` -------------------------------- ### Show Version Number Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Displays the currently installed version of the erb_lint gem. ```bash erb_lint --version ``` -------------------------------- ### Example Linter Usage Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/processed-source.md Demonstrates how a linter interacts with ProcessedSource to access file information, check content for patterns, and traverse the AST to identify issues. ```ruby class MyLinter < ERBLint::Linter def run(processed_source) # Access the file path puts "Linting: #{processed_source.filename}" # Access raw content if processed_source.file_content.include?("dangerous_pattern") add_offense( processed_source.to_source_range(0...10), "Found dangerous pattern" ) end # Traverse the AST processed_source.ast.descendants(:tag).each do |tag_node| # Process tag nodes end end end ``` -------------------------------- ### Generate JSON Report (Example) Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Shows how to generate a lint report in JSON format, suitable for programmatic processing or CI integration. ```bash bundle exec erb_lint --format json --lint-all > lint_report.json ``` -------------------------------- ### Parser::Source::Range Creation Examples Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/types.md Shows two methods for creating a Parser::Source::Range object from a processed source. ```ruby range = processed_source.to_source_range(0...10) range = processed_source.to_source_range(parser_range) ``` -------------------------------- ### File Statistics Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/MANIFEST.md Displays file statistics including total lines, average lines per file, median lines per file, and lists of the largest and smallest files. ```text total lines: 4,860 avg per file: 270 median per file: 320 Largest files: - linters.md (350 lines) - configuration.md (320 lines) - README.md (310 lines) Smallest files: - file-loader.md (110 lines) - runner.md (120 lines) ``` -------------------------------- ### Linter Configuration Loading Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/file-loader.md Example of how a linter uses FileLoader to load its specific configuration file based on a custom_config_file setting. ```ruby class MyLinter < ERBLint::Linter def initialize(file_loader, config) super # Load linter-specific configuration file if @config.custom_config_file @additional_config = @file_loader.yaml(@config.custom_config_file) end end end ``` -------------------------------- ### Check with Warnings Only (Example) Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Configures the linter to only fail on violations of 'error' severity or higher, allowing warnings and conventions to pass. ```bash bundle exec erb_lint --fail-level error --lint-all ``` -------------------------------- ### Caching Workflow Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/cached-offense.md Demonstrates the typical workflow for caching offense data to disk and restoring it later. This involves converting offenses to a cacheable format and parsing JSON from a file. ```ruby # When caching results offense = runner.offenses[0] cached_hash = offense.to_cached_offense_hash # => calls CachedOffense.new_from_offense(offense).to_h json_str = JSON.generate(cached_hash) File.write(cache_file, json_str) # When loading from cache json_str = File.read(cache_file) cached_hashes = JSON.parse(json_str) cached_offenses = cached_hashes.map { |h| CachedOffense.new(h) } runner.restore_offenses(cached_offenses) ``` -------------------------------- ### Cache File Format Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/cache.md Illustrates the JSON structure of a single cached offense entry within the cache file. ```json [ { "message": "Missing trailing newline", "line_number": 10, "column": 0, "severity": "warning", "simple_name": "FinalNewline", "last_line": 10, "last_column": 0, "length": 1 } ] ``` -------------------------------- ### Stats Constructor Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/stats.md Initializes a new Stats object with optional starting values for various statistics. ```APIDOC ## Constructor ### Description Initializes a new Stats object with optional starting values for various statistics. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **ignored** (Integer) - Optional - Offenses below fail threshold - **found** (Integer) - Optional - Offenses at or above fail threshold - **corrected** (Integer) - Optional - Violations auto-corrected - **exceptions** (Integer) - Optional - Processing errors encountered - **linters** (Integer) - Optional - Number of active linters - **autocorrectable_linters** (Integer) - Optional - Linters supporting auto-correction - **files** (Integer) - Optional - Total files linted - **processed_files** (Hash) - Optional - Map of filenames to offense arrays ### Request Example ```ruby stats = ERBLint::Stats.new( files: 15, linters: 12, autocorrectable_linters: 8, found: 5, ignored: 2, corrected: 0, exceptions: 0 ) ``` ### Response #### Success Response (N/A) This is a constructor, not an endpoint. #### Response Example N/A ``` -------------------------------- ### Add Offense with Severity Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/types.md Demonstrates how to add an offense with a specified severity level using the `add_offense` method. ```ruby add_offense( range, "Message", context, :warning # Severity level ) ``` -------------------------------- ### to_cached_offense_hash() Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/offense.md Shows how to call the `to_cached_offense_hash` method on an offense object and the expected output format. ```ruby offense = # ... create offense ... cached_hash = offense.to_cached_offense_hash # => {message: "...", line_number: 5, severity: :warning, ...} ``` -------------------------------- ### Enabling a Custom Linter in Configuration Source: https://github.com/shopify/erb_lint/blob/main/README.md YAML configuration to enable a custom linter and set its properties. This example enables 'CustomLinter' and provides a 'custom_message'. ```yaml --- linters: CustomLinter: enabled: true custom_message: We suggest you change this file. ``` -------------------------------- ### Display erb-lint version Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Check the installed version of erb-lint. This command also shows the minimum required Ruby version. ```bash erb_lint --version # erb_lint 0.9.0 ``` -------------------------------- ### Processed Files Structure Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/stats.md Illustrates the expected structure of the `processed_files` hash, mapping filenames to arrays of offenses. ```ruby { "app/views/index.html.erb" => [offense1, offense2], "app/views/show.html.erb" => [offense3], ... } ``` -------------------------------- ### Compact Reporter Output Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/reporter.md Compact format displaying offenses one per line with file path, line number, and message. Includes a summary of total errors. ```text Linting 8 files with 12 linters... app/views/users/show.html.erb:95:0: Missing trailing newline at the end of the file. app/views/subscriptions/index.html.erb:38:37: Extra space detected where there should be no space 2 error(s) were found in ERB files ``` -------------------------------- ### Typical Stat Values After Linting Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/stats.md Provides example values for Stats attributes after a complete ERBLint run, illustrating what each attribute represents. ```ruby stats.files # 25 (number of ERB files processed) stats.linters # 12 (number of enabled linters) stats.autocorrectable_linters # 8 (linters that can fix issues) stats.found # 5 (violations matching fail level) stats.ignored # 2 (violations below fail level) stats.corrected # 0 (only > 0 in autocorrect mode) stats.exceptions # 0 (processing errors) stats.processed_files.size # 10 (files with violations) ``` -------------------------------- ### SmartProperties Enum/Symbol Type Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/types.md Illustrates defining a property that accepts a limited set of symbols, with a converter to ensure the correct type. ```ruby property :style, converts: :to_sym, accepts: [:foo, :bar, :baz] ``` -------------------------------- ### JSON Reporter Output Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/reporter.md Formats linting results as a JSON array, where each object represents an offense with details like filename, message, line, column, and linter. ```json [ { "filename": "app/views/index.html.erb", "message": "Missing trailing newline", "line": 10, "column": 0, "linter": "FinalNewline" } ] ``` -------------------------------- ### SmartProperties Custom Object Type Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/types.md Shows how to define a property that accepts an array of custom objects, using a converter to ensure proper type conversion. ```ruby property :rules, accepts: array_of?(RuleSet), converts: to_array_of(RuleSet) ``` -------------------------------- ### Multiline Reporter Output Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/reporter.md Detailed format showing one offense per line, including file path and line number. Displays a summary of total errors found. ```text Linting 8 files with 12 linters... [FinalNewline] Missing trailing newline at the end of the file. In file: app/views/users/show.html.erb:95 2 error(s) were found in ERB files ``` -------------------------------- ### Corrector Example Usage Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/corrector.md Demonstrates how to use the Corrector class to autocorrect offenses in a file. It processes the source, creates a corrector, gets the corrected content, and writes it back to the file. ```ruby processed_source = ERBLint::ProcessedSource.new("file.erb", content) runner.run(processed_source) # Autocorrect all offenses corrector = ERBLint::Corrector.new(processed_source, runner.offenses) corrected_content = corrector.corrected_content File.write("file.erb", corrected_content) ``` -------------------------------- ### Get Available Reporter Formats Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/reporter.md Retrieve a list of all available reporter format names. This is derived from the available reporter class names. ```ruby def self.available_formats() ``` ```ruby formats = ERBLint::Reporter.available_formats # => ["compact", "gitlab", "json", "junit", "multiline"] ``` -------------------------------- ### Corrector Context Examples Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/types.md Provides examples of how context data is added to offenses for autocorrection in linters like FinalNewline, SelfClosingTag, and AllowedScriptType. ```ruby add_offense(range, message, :insert) # or :remove ``` ```ruby add_offense(range, message, "/") # or "" ``` ```ruby add_offense(range, message, [type_attribute]) ``` ```ruby context = { rubocop_correction: correction, offset: offset, bound_range: range } ``` ```ruby def autocorrect(_processed_source, offense) context = offense.context lambda do |corrector| # Use context to perform correction end end ``` -------------------------------- ### context Attribute Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/offense.md Illustrates how the `context` attribute might be used by a linter, such as the `FinalNewline` linter storing an action like `:insert` or `:remove`. ```ruby # The `FinalNewline` linter stores `:insert` or `:remove` in context to tell the corrector what action to take. ``` -------------------------------- ### Permissive Configuration Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/configuration.md A permissive configuration that disables default linters and enables only a few specific ones with relaxed settings. This example enables 'FinalNewline' with 'present: false' and 'TrailingWhitespace'. ```yaml --- EnableDefaultLinters: false linters: FinalNewline: enabled: true present: false TrailingWhitespace: enabled: true ``` -------------------------------- ### Example Usage of LinterConfig Error Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/linter-config.md Demonstrates how to catch and handle `ERBLint::LinterConfig::Error` when an invalid configuration property is provided. The error message indicates the specific issue, such as an unknown property. ```ruby begin config = MyLinterConfig.new(unknown_prop: true) rescue ERBLint::LinterConfig::Error => e puts e.message # "Given key is not allowed: unknown_prop" end ``` -------------------------------- ### Implement Reporter Preview Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/reporter.md Override this method in subclasses to display a message before linting begins. The base implementation does nothing. ```ruby def preview() ``` ```ruby def preview puts "Starting lint run..." end ``` -------------------------------- ### Initialize FileLoader Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/file-loader.md Instantiate FileLoader with a base path to resolve relative file paths. All file paths will be resolved relative to this project root. ```ruby file_loader = ERBLint::FileLoader.new("/path/to/project") ``` -------------------------------- ### Get Entire Configuration Hash Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/runner-config.md Returns a copy of the internal configuration hash managed by RunnerConfig. ```ruby def to_hash() end ``` -------------------------------- ### Reporter#initialize Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/reporter.md Initializes a new Reporter instance. It requires statistics and autocorrect status, with an optional parameter to show linter names. ```APIDOC ## Reporter#initialize ### Description Initializes a new Reporter instance. It requires statistics and autocorrect status, with an optional parameter to show linter names. ### Constructor `initialize(stats, autocorrect, show_linter_names = false)` ### Parameters #### Arguments - **stats** (`Stats`) - Required - Statistics about linting run - **autocorrect** (`Boolean`) - Required - Whether autocorrect mode is active - **show_linter_names** (`Boolean`) - Optional - Default: `false` - Whether to include linter names in output ### Example ```ruby stats = ERBLint::Stats.new(files: 10, linters: 12, found: 5) reporter = MultilineReporter.new(stats, autocorrect=false, show_linter_names=true) ``` ``` -------------------------------- ### Create Reporter Instance Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/reporter.md Use this factory method to instantiate a reporter based on the desired output format. Pass the format name and any necessary constructor arguments. ```ruby def self.create_reporter(format, *args) ``` ```ruby stats = ERBLint::Stats.new reporter = ERBLint::Reporter.create_reporter(:multiline, stats, autocorrect=false) ``` -------------------------------- ### Display Help Information Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Shows the help message, detailing all available commands and options for the erb_lint CLI. ```bash erb_lint --help ``` -------------------------------- ### Initialize RunnerConfig Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/runner-config.md Instantiate RunnerConfig with a configuration hash and an optional file loader for inheritance. ```ruby def initialize(config = nil, file_loader = nil) end ``` ```ruby config_hash = { "linters" => { "FinalNewline" => { "enabled" => true, "present" => true }, "Rubocop" => { "enabled" => false } }, "inherit_from" => [".erb_lint.yml"] } runner_config = ERBLint::RunnerConfig.new(config_hash, file_loader) ``` -------------------------------- ### Stats attr_accessor Examples Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/stats.md Shows the declaration of attributes for the Stats class using attr_accessor, allowing read and write access. ```ruby attr_accessor :ignored ``` ```ruby attr_accessor :found ``` ```ruby attr_accessor :corrected ``` ```ruby attr_accessor :exceptions ``` ```ruby attr_accessor :linters ``` ```ruby attr_accessor :autocorrectable_linters ``` ```ruby attr_accessor :files ``` ```ruby attr_accessor :processed_files ``` -------------------------------- ### Initialize LinterConfig Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/linter-config.md Instantiate LinterConfig with a configuration hash. Unknown properties, invalid values, or missing required properties will raise LinterConfig::Error. ```ruby config = ERBLint::LinterConfig.new( enabled: true, exclude: ["app/views/admin/**/*"] ) ``` -------------------------------- ### Runner offenses Attribute Example Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/runner.md Shows how to access the offenses attribute after running the linter to retrieve the list of found violations. ```ruby runner.run(source) found_offenses = runner.offenses ``` -------------------------------- ### Implement Reporter Show Method Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/reporter.md Override this method in subclasses to display the final linting results and summary after all files have been processed. The base implementation does nothing. ```ruby def show() ``` ```ruby def show processed_files.each do |filename, offenses| offenses.each do |offense| puts "#{filename}:#{offense.line_number}: #{offense.message}" end end puts "Found #{stats.found} errors" end ``` -------------------------------- ### Get Global Exclude Patterns Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/runner-config.md Retrieves an array of glob patterns that specify files to be excluded from linting across all linters. ```ruby def global_exclude() end ``` ```ruby config = RunnerConfig.new({ "exclude" => ["vendor/**/*", "node_modules/**/*"], "linters" => { ... } }) patterns = config.global_exclude # => ["vendor/**/*", "node_modules/**/*"] ``` -------------------------------- ### Configure NoJavascriptTagHelper correction style Source: https://github.com/shopify/erb_lint/blob/main/README.md Example configuration for the `NoJavascriptTagHelper` linter, specifically setting the `correction_style` to 'plain' to disable CDATA markers. ```yaml --- linters: NoJavascriptTagHelper: enabled: true correction_style: 'plain' ``` -------------------------------- ### Use Alternative Configuration File Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Specifies a different configuration file to use instead of the default .erb_lint.yml. Useful for managing different linting rulesets. ```bash erb_lint --config config/.erb_lint.yml --lint-all ``` -------------------------------- ### Create RunnerConfig with Defaults Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/runner-config.md Merges user-provided configuration with default settings. Useful for initializing a RunnerConfig with sensible defaults that can be overridden by user input. ```ruby def self.default_for(config) end ``` ```ruby user_config = RunnerConfig.new({ "EnableDefaultLinters" => true, "linters" => { "FinalNewline" => { "enabled" => false } } }) config = RunnerConfig.default_for(user_config) # Default linters enabled, except FinalNewline is disabled ``` -------------------------------- ### LinterConfig Instance Methods Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/linter-config.md Provides instance methods for accessing configuration properties, converting the configuration to a hash, and checking file exclusions. ```APIDOC ## Instance Methods: [](name) ### Description Accesses a property value by name. ### Method `self[](name)` ### Parameters #### Path Parameters - **name** (String or Symbol) - Property name ### Return Type: `Object` ### Raises: `LinterConfig::Error` if property doesn't exist. ### Example: ```ruby config = MyLinterConfig.new(my_option: "value") puts config[:my_option] # => "value" ``` ## Instance Methods: to_hash() ### Description Converts the configuration to a hash representation. ### Method `self.to_hash()` ### Return Type: `Hash` ### Description: Returns all properties as a hash with string keys. ### Example: ```ruby config = MyLinterConfig.new(enabled: true, exclude: ["vendor/**/*"]) config.to_hash # => {"enabled"=>true, "exclude"=>["vendor/**/*"]} ``` ## Instance Methods: excludes_file?(absolute_filename, base_path) ### Description Checks if a file matches any exclude patterns. ### Method `self.excludes_file?(absolute_filename, base_path)` ### Parameters #### Path Parameters - **absolute_filename** (String) - Full path to the file - **base_path** (String) - Base directory path for relative matching ### Return Type: `Boolean` ### Behavior: - Matches against absolute paths - Also matches against relative paths (relative to `base_path`) - Uses glob-style patterns via `File.fnmatch?` ### Example: ```ruby config = MyLinterConfig.new( enabled: true, exclude: ["**/vendor/**/*", "spec/**/*"] ) config.excludes_file?("/project/vendor/lib/file.erb", "/project") # => true config.excludes_file?("/project/app/views/file.erb", "/project") # => false ``` ``` -------------------------------- ### Get Linter Configuration Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/runner-config.md Retrieve the specific configuration for a given linter, identified by its class or name. Raises an error if the linter is not found. ```ruby def for_linter(klass) end ``` ```ruby config = ERBLint::RunnerConfig.new(config_hash) # Using linter class final_newline_config = config.for_linter(ERBLint::Linters::FinalNewline) # Using string name rubocop_config = config.for_linter("Rubocop") puts final_newline_config.enabled? # => true puts final_newline_config.present? # => true ``` -------------------------------- ### Basic ERB Lint CLI Usage Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Run erb_lint with optional arguments and specify files to lint. ```bash erb_lint [options] [files...] ``` -------------------------------- ### Get All Linters Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/linter-registry.md Retrieves all registered linter classes. This method lazily loads custom linters on its first call and caches the result. ```ruby all_linters = ERBLint::LinterRegistry.linters all_linters.each do |linter_class| puts linter_class.simple_name end ``` -------------------------------- ### Enable Custom Linter Configuration Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/README.md Shows how to enable a custom linter by adding its configuration to the `.erb_lint.yml` file. ```yaml # .erb_lint.yml linters: MyCustomLinter: enabled: true ``` -------------------------------- ### Configure SelfClosingTag enforced style Source: https://github.com/shopify/erb_lint/blob/main/README.md Example configuration for the `SelfClosingTag` linter, setting `enforced_style` to 'always' to enforce XHTML style self-closing tags. ```yaml --- linters: SelfClosingTag: enabled: true enforced_style: 'always' ``` -------------------------------- ### Initialize Reporter Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/reporter.md Constructor for the Reporter class. Requires statistics and autocorrect status, with an optional flag to show linter names. ```ruby def initialize(stats, autocorrect, show_linter_names = false) ``` ```ruby stats = ERBLint::Stats.new(files: 10, linters: 12, found: 5) reporter = MultilineReporter.new(stats, autocorrect=false, show_linter_names=true) ``` -------------------------------- ### CachedOffense#to_h Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/cached-offense.md Converts the CachedOffense instance into a hash. This method is useful for serializing the cached offense data, for example, into JSON format for storage. ```APIDOC ## CachedOffense#to_h ### Description Converts the cached offense object into a hash with string keys, suitable for serialization. ### Parameters None ### Return Type Hash ### Response Example ```json { "message": "Missing trailing newline", "line_number": 10, "column": 0, "severity": "warning", "simple_name": "FinalNewline", "last_line": 10, "last_column": 0, "length": 1 } ``` ``` -------------------------------- ### ERB Lint Multiline Output Format Source: https://github.com/shopify/erb_lint/blob/main/README.md Example of the default multiline output format for ERB Lint. It lists errors with file paths and descriptions. ```sh $ erb_lint Linting 8 files with 12 linters... Remove multiple trailing newline at the end of the file. In file: app/views/users/show.html.erb:95 Remove newline before `%>` to match start of tag. In file: app/views/subscriptions/index.html.erb:38 2 error(s) were found in ERB files ``` -------------------------------- ### RunnerConfig for Linter Configuration Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/README.md Ruby code demonstrating how to create a RunnerConfig from a YAML hash and file loader, and how to retrieve specific linter configurations. ```ruby config = RunnerConfig.new(yaml_hash, file_loader) linter_config = config.for_linter("FinalNewline") ``` -------------------------------- ### Runner Constructor Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/runner.md Initializes a new instance of the Runner class. It takes a file loader, configuration, and an optional flag to disable inline configurations. ```APIDOC ## Runner Constructor ### Description Initializes a new instance of the Runner class. It takes a file loader, configuration, and an optional flag to disable inline configurations. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature `initialize(file_loader, config, disable_inline_configs = false)` ### Parameters - **file_loader** (`FileLoader`) - Required - Loads configuration and other files from disk - **config** (`RunnerConfig`) - Required - Configuration object defining which linters to run and their settings - **disable_inline_configs** (`Boolean`) - Optional - When true, ignores inline disable/enable comments in ERB files ### Raises `ArgumentError` if `config` is not a `RunnerConfig` instance. ``` -------------------------------- ### ERB Comment Syntax Examples Source: https://github.com/shopify/erb_lint/blob/main/README.md Demonstrates correct and incorrect ERB comment syntax. Ruby comments with a leading space are invalid ERB comments. ```erb <% # This is a Ruby comment %> <%# This is an ERB comment %> <% # This is a Ruby comment; it can fail to parse. %> <%# This is an ERB comment; it is parsed correctly. %> <% # This is a multi-line ERB comment. %> ``` -------------------------------- ### Enforce HTML5 style self-closing tags Source: https://github.com/shopify/erb_lint/blob/main/README.md Example of enforcing HTML5 style (non-self-closing) for void elements, such as ``. ```erb Bad ❌
Good ✅ ``` -------------------------------- ### Linter Constructor Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/linter.md Initializes a new Linter instance. It requires a FileLoader for handling additional configuration files and a LinterConfig object specific to the linter's settings. It raises an ArgumentError if the provided config does not match the linter's expected configuration schema. ```APIDOC ## Constructor Linter ### Description Initializes a new Linter instance with a file loader and configuration. ### Signature ```ruby def initialize(file_loader, config) ``` ### Parameters #### Path Parameters - **file_loader** (`FileLoader`) - Required - For loading additional configuration files - **config** (`LinterConfig`) - Required - Configuration specific to this linter ### Raises - `ArgumentError` if `config` is not an instance of the linter's `config_schema` class. ### Example ```ruby file_loader = ERBLint::FileLoader.new("/path/to/project") config = ERBLint::Linters::FinalNewline::ConfigSchema.new(enabled: true, present: true) linter = ERBLint::Linters::FinalNewline.new(file_loader, config) ``` ``` -------------------------------- ### Key Classes in ERB Lint Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/README.md Illustrates the core classes and their relationships within the ERB Lint framework, showing the flow from configuration to reporting. ```text RunnerConfig Configuration management ↓ Runner Orchestrates linters ↓ Linter Individual linting rules (20+ built-in) ↓ Offense Violations found ↓ Reporter Results display (5 formats) ``` -------------------------------- ### Basic ERB Lint CLI Usage with Bundle Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Execute erb_lint using Bundler to ensure consistent dependency versions. ```bash bundle exec erb_lint [options] [files...] ``` -------------------------------- ### Running ERB Lint with Custom Linters Source: https://github.com/shopify/erb_lint/blob/main/README.md Command-line instruction to run ERB Lint, enabling custom linters and linting all files. This is used to test custom linter functionality. ```bash bundle exec erb_lint --enable-linters custom_linter --lint-all ``` -------------------------------- ### Custom ERB Linter Implementation Source: https://github.com/shopify/erb_lint/blob/main/README.md Example of a custom linter written in Ruby for ERB Lint. This linter checks for a specific string and can be configured with a custom message. ```ruby # .erb_linters/custom_linter.rb module ERBLint module Linters class CustomLinter < Linter include LinterRegistry class ConfigSchema < LinterConfig property :custom_message, accepts: String end self.config_schema = ConfigSchema def run(processed_source) unless processed_source.file_content.include?('this file is fine') add_offense( processed_source.to_source_range(0 ... processed_source.file_content.size), "This file isn't fine. #{@config.custom_message}" ) end end end end end ``` -------------------------------- ### RunnerConfig Constructor Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/runner-config.md Initializes a new RunnerConfig instance. It can load configurations from a hash, resolve inheritance from files or gems, and deep stringifies keys. ```APIDOC ## RunnerConfig Constructor ### Description Initializes a new RunnerConfig instance. It can load configurations from a hash, resolve inheritance from files or gems, and deep stringifies keys. ### Method `initialize(config = nil, file_loader = nil)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config** (`Hash`) - Optional - Configuration hash with `linters` key and `inherit_from`/`inherit_gem` - **file_loader** (`FileLoader`) - Optional - Used to load inherited configuration files ### Request Example ```ruby config_hash = { "linters" => { "FinalNewline" => { "enabled" => true, "present" => true }, "Rubocop" => { "enabled" => false } }, "inherit_from" => [".erb_lint.yml"] } runner_config = ERBLint::RunnerConfig.new(config_hash, file_loader) ``` ### Response None ### Error Handling None explicitly documented for constructor. ``` -------------------------------- ### Register Custom Linter Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/linter-registry.md Demonstrates how to create and automatically register a custom linter by including the `LinterRegistry` module within the linter class definition. ```ruby # .erb_linters/my_custom_linter.rb module ERBLint module Linters class MyCustomLinter < Linter include LinterRegistry # Automatically registers this linter class ConfigSchema < LinterConfig property :enabled, accepts: [true, false], default: false, reader: :enabled? end self.config_schema = ConfigSchema def run(processed_source) # Linting logic here end end end end ``` -------------------------------- ### Add Offense in Linter Subclass Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/linter.md Example of how a linter subclass should implement the `run` method to add offenses, specifying the source range, message, context, and severity. ```ruby def run(processed_source) if problematic_condition(processed_source) add_offense( processed_source.to_source_range(0...10), "This is a problem", :correction_context, :warning ) end end ``` -------------------------------- ### ERB Lint Compact Output Format Source: https://github.com/shopify/erb_lint/blob/main/README.md Example of the compact output format for ERB Lint. Errors are listed on a single line with file, line, column, and message. ```sh erb_lint --format compact Linting 8 files with 12 linters... app/views/users/show.html.erb:95:0: Remove multiple trailing newline at the end of the file. app/views/users/_graph.html.erb:27:37: Extra space detected where there should be no space 2 error(s) were found in ERB files ``` -------------------------------- ### Create a Custom ERBLint Reporter Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/reporter.md Extend the `Reporter` class to create a custom reporter. Override `preview` and `show` methods for custom output formatting. ```ruby module ERBLint module Reporters class CustomReporter < Reporter def preview puts "Starting custom report..." end def show processed_files.each do |filename, offenses| offenses.each do |offense| formatted = format_offense(filename, offense) puts formatted end end puts summary end private def format_offense(filename, offense) "#{filename}:#{offense.line_number}: #{offense.message}" end def summary "Total errors: #{stats.found}" end end end end ``` -------------------------------- ### get(filename, file_content) Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/api-reference/cache.md Retrieves cached offenses for a given file if the cache is valid. Returns an array of CachedOffense objects on a cache hit, or false on a cache miss. ```APIDOC ## get(filename, file_content) ### Description Retrieves cached offenses for a given file if the cache is valid. Returns an array of CachedOffense objects on a cache hit, or false on a cache miss. Cache hits occur when file content and configuration remain unchanged. ### Method Signature ```ruby def get(filename, file_content) ``` ### Parameters #### Path Parameters - **filename** (String) - Required - Path to the file to check. - **file_content** (String) - Required - Current content of the file. ### Return Type `Array` or `false` ### Example ```ruby cache = Cache.new(config) offenses = cache.get("app/views/index.html.erb", file_content) if offenses puts "Cache hit: #{offenses.count} offenses" else # Run linters normally runner.run(processed_source) end ``` ``` -------------------------------- ### Cache Operations Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/README.md Ruby code for interacting with the Cache system. It shows how to get offenses from the cache, store new results, and close the cache to prune old files. ```ruby cache = Cache.new(config) offenses = cache.get(filename, content) # Retrieve or false cache.set(filename, content, json_str) # Store cache.close() # Prune old files ``` -------------------------------- ### Specify file glob pattern Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/cli-usage.md Resolve the 'no files found' error by explicitly providing a glob pattern for the ERB files to be linted, such as 'app/views/**/*.erb'. ```bash erb_lint --lint-all # Uses configured glob erb_lint app/views/**/*.erb # Specify pattern ``` -------------------------------- ### ERB Lint JUnit Output Format Source: https://github.com/shopify/erb_lint/blob/main/README.md Example of the JUnit output format for ERB Lint, suitable for CI/CD systems. It uses XML to report test cases and failures. ```sh erb_lint --format junit ``` -------------------------------- ### Custom Linters Only Configuration Source: https://github.com/shopify/erb_lint/blob/main/_autodocs/configuration.md Configures ERB Lint to disable default linters and enable only specific custom linters. This example enables 'MyCustomLinter' and 'Rubocop', with custom RuboCop settings. ```yaml --- EnableDefaultLinters: false linters: MyCustomLinter: enabled: true Rubocop: enabled: true rubocop_config: inherit_from: .rubocop.yml ```