summaryrefslogtreecommitdiff
path: root/bin/coderay
blob: e0a47885dcd1cbfdd5f218415a58fa5b21aa024f (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
#!/usr/bin/env ruby
# CodeRay Executable
# 
# Version: 0.1
# Author: murphy

def err msg
	$stderr.puts msg
end

begin
	require 'coderay'

	if ARGV.empty?
		puts <<-USAGE
CodeRay #{CodeRay::Version} (http://rd.cYcnus.de/coderay)
Usage:
  coderay -<lang> [-<format>] < file > output
  coderay file [-<format>]
Example:
  coderay -ruby -statistic < foo.rb
  coderay codegen.c  # generates codegen.c.html
		USAGE
	end
	
	first, second = ARGV

	if first
		if first[/-(\w+)/] == first
			lang = $1.to_sym
			input = $stdin.read
			tokens = CodeRay.scan input, lang
		elsif first == '-'
			lang = $1.to_sym
			input = $stdin.read
			tokens = CodeRay.scan input, lang
		else
			file = first
			tokens = CodeRay.scan_file file
			output_filename, output_ext = file, /#{Regexp.escape(File.extname(file))}$/
		end
	else
		puts 'No lang/file given.'
		exit 1
	end

	if second
		if second[/-(\w+)/] == second
			format = $1.to_sym
		else
			raise 'Invalid format (must be -xxx).'
		end
	else
		$stderr.puts 'No format given; setting to default (HTML Page)'
		format = :page
	end

	output = tokens.encode format
	out = $stdout
	if output_filename
		output_filename += '.' + CodeRay::Encoders[format]::FILE_EXTENSION
		if File.exist? output_filename
			err 'File %s already exists.' % output_filename
			exit
		else
			out = File.open output_filename, 'w'
		end
	else
		
	end
	out.print output

rescue => boom
	err "Error: #{boom.message}\n"
	err boom.backtrace
	err '-' * 50
	err ARGV.options
	exit 1
end