1 | module SM
|
---|
2 |
|
---|
3 | ##
|
---|
4 | # Handle common directives that can occur in a block of text:
|
---|
5 | #
|
---|
6 | # : include : filename
|
---|
7 | #
|
---|
8 |
|
---|
9 | class PreProcess
|
---|
10 |
|
---|
11 | def initialize(input_file_name, include_path)
|
---|
12 | @input_file_name = input_file_name
|
---|
13 | @include_path = include_path
|
---|
14 | end
|
---|
15 |
|
---|
16 | # Look for common options in a chunk of text. Options that
|
---|
17 | # we don't handle are passed back to our caller
|
---|
18 | # as |directive, param|
|
---|
19 |
|
---|
20 | def handle(text)
|
---|
21 | text.gsub!(/^([ \t#]*):(\w+):\s*(.+)?\n/) do
|
---|
22 | prefix = $1
|
---|
23 | directive = $2.downcase
|
---|
24 | param = $3
|
---|
25 |
|
---|
26 | case directive
|
---|
27 | when "include"
|
---|
28 | filename = param.split[0]
|
---|
29 | include_file(filename, prefix)
|
---|
30 |
|
---|
31 | else
|
---|
32 | yield(directive, param)
|
---|
33 | end
|
---|
34 | end
|
---|
35 | end
|
---|
36 |
|
---|
37 | #######
|
---|
38 | private
|
---|
39 | #######
|
---|
40 |
|
---|
41 | # Include a file, indenting it correctly
|
---|
42 |
|
---|
43 | def include_file(name, indent)
|
---|
44 | if (full_name = find_include_file(name))
|
---|
45 | content = File.open(full_name) {|f| f.read}
|
---|
46 | # strip leading '#'s, but only if all lines start with them
|
---|
47 | if content =~ /^[^#]/
|
---|
48 | content.gsub(/^/, indent)
|
---|
49 | else
|
---|
50 | content.gsub(/^#?/, indent)
|
---|
51 | end
|
---|
52 | else
|
---|
53 | $stderr.puts "Couldn't find file to include: '#{name}'"
|
---|
54 | ''
|
---|
55 | end
|
---|
56 | end
|
---|
57 |
|
---|
58 | # Look for the given file in the directory containing the current
|
---|
59 | # file, and then in each of the directories specified in the
|
---|
60 | # RDOC_INCLUDE path
|
---|
61 |
|
---|
62 | def find_include_file(name)
|
---|
63 | to_search = [ File.dirname(@input_file_name) ].concat @include_path
|
---|
64 | to_search.each do |dir|
|
---|
65 | full_name = File.join(dir, name)
|
---|
66 | stat = File.stat(full_name) rescue next
|
---|
67 | return full_name if stat.readable?
|
---|
68 | end
|
---|
69 | nil
|
---|
70 | end
|
---|
71 |
|
---|
72 | end
|
---|
73 | end
|
---|