Class: Xcop::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/xcop/cli.rb

Overview

Command line interface.

Author

Yegor Bugayenko (yegor256@gmail.com)

Copyright

Copyright (c) 2017-2026 Yegor Bugayenko

License

MIT

Constant Summary collapse

EXTENSIONS =
%w[xml xsd xhtml xsl html].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(files, nocolor: false) ⇒ CLI

Returns a new instance of CLI.



17
18
19
20
# File 'lib/xcop/cli.rb', line 17

def initialize(files, nocolor: false)
  @files = files.flat_map { |f| File.directory?(f) ? Xcop::CLI.expand(f) : [f] }
  @nocolor = nocolor
end

Class Method Details

.expand(dir) ⇒ Object

Recursively collect XML-like files inside a directory.



23
24
25
# File 'lib/xcop/cli.rb', line 23

def self.expand(dir)
  EXTENSIONS.flat_map { |ext| Dir.glob(File.join(dir, '**', "*.#{ext}")) }.sort
end

Instance Method Details

#fixObject

Fix them all. The block, when given, receives the file path and a status symbol that is :fixed when the file was rewritten and :untouched when the file was already canonical.



54
55
56
57
58
59
# File 'lib/xcop/cli.rb', line 54

def fix
  @files.each do |f|
    status = Xcop::Document.new(f).fix
    yield(f, status) if block_given?
  end
end

#runObject

Check them all. The block, when given, receives the file path and a status symbol that is :good when the file is clean and :malformed when the file is not XML at all and was skipped.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/xcop/cli.rb', line 30

def run
  @files.each do |f|
    doc = Xcop::Document.new(f)
    unless doc.wellformed?
      yield(f, :malformed) if block_given?
      next
    end
    diff = doc.diff(nocolor: @nocolor)
    unless diff.empty?
      puts(diff)
      raise(StandardError, "Invalid XML formatting in #{f}")
    end
    errors = doc.validate
    unless errors.empty?
      puts(errors.join("\n"))
      raise(StandardError, "XSD validation failed in #{f}")
    end
    yield(f, :good) if block_given?
  end
end