Class: Aef::Linebreak::CLI::EncodingsCommand

Inherits:
UserChoices::Command
  • Object
show all
Includes:
UserChoices
Defined in:
lib/aef/linebreak/cli/commands/encodings.rb

Overview

Command-line sub command for encoding detection.

Instance Method Summary collapse

Instance Method Details

#add_choices(builder) ⇒ Object

Define configuration options



37
38
39
40
41
42
43
44
# File 'lib/aef/linebreak/cli/commands/encodings.rb', line 37

def add_choices(builder)
  builder.add_choice(:ensure, :type => [:string]) do |cli|
    cli.uses_option('-e', '--ensure SYSTEMLIST',
      "Verify that given encodings are existent. Separated by commas without spaces. Possible settings: #{Aef::Linebreak::BREAK_BY_SYSTEM.keys.join(', ')}.")
  end
      
  builder.add_choice(:files, :type => :pathname) {|cli| cli.uses_arglist}
end

#add_sources(builder) ⇒ Object

Prepare configuration sources



29
30
31
32
33
34
# File 'lib/aef/linebreak/cli/commands/encodings.rb', line 29

def add_sources(builder)
  builder.add_source(CommandLineSource, :usage,
    "Usage: #$PROGRAM_NAME encodings [OPTIONS] [FILE]\n\n",
    "Detect linebreak encoding systems of a file.\n"
  )
end

#executeObject

Main program



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/aef/linebreak/cli/commands/encodings.rb', line 58

def execute
  systems_by_file = {}
      
  @user_choices[:files].each do |file|
    unless systems_by_file[file]
      systems_by_file[file] = Set.new
      
      file.each_line do |line|
        systems_by_file[file] = Aef::Linebreak.encodings(line) + systems_by_file[file]
      end
    end
  end
      
  failed = false
      
  systems_by_file.each do |file, systems|
    print "#{file}: " unless file == STDIN
      
    sorted_systems = systems.sort do |a,b|
      order = [:unix, :windows, :mac]
      order.index(a) <=> order.index(b)
    end
      
    print sorted_systems.join(',')
      
    if @user_choices[:ensure] and systems != @user_choices[:ensure]
      failed = true
      puts ' (failed)'
    else
      puts
    end
  end
  
  exit false if failed
end

#postprocess_user_choicesObject

Manual option post processing



47
48
49
50
51
52
53
54
55
# File 'lib/aef/linebreak/cli/commands/encodings.rb', line 47

def postprocess_user_choices
  if @user_choices[:ensure]
    @user_choices[:ensure] = @user_choices[:ensure].map{|string| string.to_sym }.to_set
  end
      
  if @user_choices[:files].empty? or @user_choices[:files].include?(Pathname('-'))
    @user_choices[:files] = [STDIN]
  end
end