#!/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 [-] [input] [-] [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