Class: Isort::SyntaxValidator
- Inherits:
-
Object
- Object
- Isort::SyntaxValidator
- Defined in:
- lib/isort/syntax_validator.rb
Overview
Validates Ruby syntax using the built-in parser Used by --atomic mode to ensure sorting doesn't introduce syntax errors
Class Method Summary collapse
-
.check_syntax(code) ⇒ Object
Check syntax and return error message if invalid, nil if valid.
-
.check_syntax_with_ruby_c(code) ⇒ Object
Check syntax using ruby -c (more reliable but slower) Returns nil if valid, error message if invalid.
-
.valid?(code) ⇒ Boolean
Check if Ruby code has valid syntax Returns true if valid, false otherwise.
-
.valid_file?(file_path) ⇒ Boolean
Check if a file has valid Ruby syntax.
-
.valid_with_ruby_c?(code) ⇒ Boolean
Use Ruby's built-in -c flag for more accurate syntax checking This is safer than eval-based checking.
Class Method Details
.check_syntax(code) ⇒ Object
Check syntax and return error message if invalid, nil if valid
15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/isort/syntax_validator.rb', line 15 def check_syntax(code) # Use Ruby's built-in syntax check catch(:valid) do eval("BEGIN { throw :valid }; #{code}", nil, "(syntax_check)", 0) end nil rescue SyntaxError => e e. rescue StandardError # Other errors during eval don't indicate syntax errors nil end |
.check_syntax_with_ruby_c(code) ⇒ Object
Check syntax using ruby -c (more reliable but slower) Returns nil if valid, error message if invalid
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/isort/syntax_validator.rb', line 58 def check_syntax_with_ruby_c(code) require "open3" require "tempfile" Tempfile.create(["syntax_check", ".rb"]) do |f| f.write(code) f.flush stdout, stderr, status = Open3.capture3("ruby", "-c", f.path) status.success? ? nil : stderr.strip end rescue StandardError => e # If we can't run ruby -c, fall back to eval-based check check_syntax(code) end |
.valid?(code) ⇒ Boolean
Check if Ruby code has valid syntax Returns true if valid, false otherwise
10 11 12 |
# File 'lib/isort/syntax_validator.rb', line 10 def valid?(code) check_syntax(code).nil? end |
.valid_file?(file_path) ⇒ Boolean
Check if a file has valid Ruby syntax
29 30 31 32 33 34 35 36 |
# File 'lib/isort/syntax_validator.rb', line 29 def valid_file?(file_path) return false unless File.exist?(file_path) content = File.read(file_path, encoding: "UTF-8") valid?(content) rescue Errno::ENOENT, Encoding::InvalidByteSequenceError false end |
.valid_with_ruby_c?(code) ⇒ Boolean
Use Ruby's built-in -c flag for more accurate syntax checking This is safer than eval-based checking
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/isort/syntax_validator.rb', line 40 def valid_with_ruby_c?(code) require "open3" require "tempfile" Tempfile.create(["syntax_check", ".rb"]) do |f| f.write(code) f.flush stdout, stderr, status = Open3.capture3("ruby", "-c", f.path) status.success? end rescue StandardError # If we can't run ruby -c, fall back to eval-based check valid?(code) end |