summaryrefslogtreecommitdiff
path: root/bin/coderay
blob: 70baa993d9020d51a0895526095febb0945ac0ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/env ruby
require 'coderay'

$options, $args = ARGV.partition { |arg| arg[/^-[hv]$|--\w+/] }
subcommand = $args.detect { |arg| arg[/^\w/] }
subcommand = nil if subcommand && File.exist?(subcommand)
$args.delete subcommand

def option? *options
  !($options & options).empty?
end

def tty?
  $stdout.tty? || option?('--tty')
end

def version
  puts <<-USAGE
CodeRay #{CodeRay::VERSION}
  USAGE
end

def help
  puts <<-HELP
Usage:
  coderay [-<language>] [input] [-<format>] [output]

Examples:
  coderay -ruby file -loc              # count lines of code in Ruby file
  coderay -ruby < foo.rb               # colorized output to terminal
  coderay -ruby foo.rb -page foo.html  # HTML page output to file
  coderay stylesheet                   # CSS stylesheet
  HELP
end

def commands
  puts <<-COMMANDS
  General:
    help        print some help
    version     print CodeRay version
    commands    print this list
    stylesheet  print the CSS stylesheet with the given name
  COMMANDS
end

if option? '-v', '--version'
  version
end

if option? '-h', '--help'
  help
end

case subcommand
when 'highlight', nil
  if ARGV.empty?
    version
    help
  else
    signature = $args.map { |arg| arg[/^-/] ? '-' : 'f' }.join
    names     = $args.map { |arg| arg.sub(/^-/, '') }
    case signature
    when /^$/
      exit
    when /^ff?$/
      input_file, output_file, = *names
    when /^-ff?$/
      input_filetype, input_file, output_file, = *names
    when /^-f-f?$/
      input_filetype, input_file, output_filetype, output_file, = *names
    when /^--?f?$/
      input_filetype, output_filetype, output_file, = *names
    else
      raise signature
    end
    
    if input_file
      input_filetype ||= CodeRay::FileType.fetch input_file, :text, true
    end
    
    if output_file
      output_filetype ||= CodeRay::FileType[output_file]
    else
      output_filetype ||= tty? ? :term : :page
    end
    
    if input_file
      input = File.read input_file
    else
      input = $stdin.read
    end
    
    output = CodeRay.scan(input, input_filetype).encode(output_filetype)
    
    if output_file
      File.open output_file, 'w' do |file|
        file.puts output
      end
    else
      puts output
    end
  end
when 'stylesheet'
  puts CodeRay::Encoders[:html]::CSS.new($args.first).stylesheet
when 'commands'
  commands
when 'help'
  help
else
  puts "Unknown command: #{subcommand}"
  help
end