summaryrefslogtreecommitdiff
path: root/scripts/context/ruby/base/ctx.rb
blob: e39751fb6e16c558b93070a85f8d54a2e12b9b28 (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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# module    : base/ctx
# copyright : PRAGMA Advanced Document Engineering
# version   : 2005
# author    : Hans Hagen
#
# project   : ConTeXt / eXaMpLe
# concept   : Hans Hagen
# info      : j.hagen@xs4all.nl
# www       : www.pragma-ade.com

# todo: write systemcall for mpost to file so that it can be run
# faster

# report ?

require 'base/system'
require 'base/file'
require 'base/switch' # has needsupdate, bad place

require 'rexml/document'

class CtxRunner

    attr_reader :environments, :modules, :filters

    @@suffix = 'prep'

    def initialize(jobname=nil,logger=nil)
        if @logger = logger then
            def report(str='')
                @logger.report(str)
            end
        else
            def report(str='')
                puts(str)
            end
        end
        @jobname = jobname
        @ctxname = nil
        @xmldata = nil
        @prepfiles = Hash.new
        @environments = Array.new
        @modules = Array.new
        @filters = Array.new
    end

    def manipulate(ctxname=nil,defaultname=nil)

        if ctxname then
            @ctxname = ctxname
            @jobname = File.suffixed(@ctxname,'tex') unless @jobname
        else
            @ctxname = File.suffixed(@jobname,'ctx') if @jobname
        end

        if not @ctxname then
            report('no ctx file specified')
            return
        end

        # name can be kpse:res-make.ctx

        if not FileTest.file?(@ctxname) then
            fullname, done = '', false
            if @ctxname =~ /^kpse:/ then
                begin
                    if fullname = Kpse.found(@ctxname.sub(/^kpse:/,'')) then
                        @ctxname, done = fullname, true
                    end
                rescue
                    # should not happen
                end
            else
                ['..','../..'].each do |path|
                    begin
                        fullname = File.join(path,@ctxname)
                        if FileTest.file?(fullname) then
                            @ctxname, done = fullname, true
                        end
                    rescue
                        # probably strange join
                    end
                    break if done
                end
            end
            if ! done && defaultname && FileTest.file?(defaultname) then
                report("using default ctxfile #{defaultname}")
                @ctxname = defaultname
            end
            if not done then
                report('no ctx file found')
                return false
            end
        end

        @xmldata = IO.read(@ctxname)

        unless @xmldata =~ /^.*<\?xml.*?\?>/moi then
            report("ctx file #{@ctxname} is no xml file, skipping")
            return
        else
            report("loading ctx file #{@ctxname}")
        end

        begin
            @xmldata = REXML::Document.new(@xmldata)
        rescue
            report('provide valid ctx file (xml error)')
            return
        else
            include(@xmldata,'ctx:include','name')
        end

        begin
            variables = Hash.new
            if @jobname then
                variables['job'] = @jobname
            end
            REXML::XPath.each(@xmldata.root,"//ctx:value[@name='job']") do |val|
                substititute(val,variables['job'])
            end
            REXML::XPath.each(@xmldata.root,"/ctx:job/ctx:message") do |mes|
                report("preprocessing: #{justtext(mes)}")
            end
            REXML::XPath.each(@xmldata.root,"/ctx:job/ctx:process/ctx:resources/ctx:environment") do |sty|
                @environments << justtext(sty)
            end
            REXML::XPath.each(@xmldata.root,"/ctx:job/ctx:process/ctx:resources/ctx:module") do |mod|
                @modules << justtext(mod)
            end
            REXML::XPath.each(@xmldata.root,"/ctx:job/ctx:process/ctx:resources/ctx:filter") do |fil|
                @filters << justtext(fil)
            end
            commands = Hash.new
            REXML::XPath.each(@xmldata.root,"/ctx:job/ctx:preprocess/ctx:processors/ctx:processor") do |pre|
                begin
                    commands[pre.attributes['name']] = pre
                rescue
                end
            end
            suffix = @@suffix
            begin
                suffix = REXML::XPath.match(@xmldata.root,"/ctx:job/ctx:preprocess/@suffix").to_s
            rescue
            puts $!
                suffix = @@suffix
            else
                if suffix && suffix.empty? then suffix = @@suffix end
            end
            REXML::XPath.each(@xmldata.root,"/ctx:job/ctx:preprocess/ctx:files") do |files|
                REXML::XPath.each(files,"ctx:file") do |pattern|
                    preprocessor = pattern.attributes['processor']
                    if preprocessor and not preprocessor.empty? then
                        pattern = justtext(pattern)
                        Dir.glob(pattern).each do |oldfile|
                            newfile = "#{oldfile}.#{suffix}"
                            if File.needsupdate(oldfile,newfile) then
                                begin
                                    File.delete(newfile)
                                rescue
                                    # hope for the best
                                end
                                # there can be a sequence of processors
                                preprocessor.split(',').each do |pp|
                                    if command = commands[pp] then
                                        # a lie: no <?xml ...?>
                                        command = REXML::Document.new(command.to_s) # don't infect original
                                        command = command.elements["ctx:processor"]
                                        begin
                                            if suf = command.attributes['suffix'] then
                                                newfile = "#{oldfile}.#{suf}"
                                            end
                                        rescue
                                        end
                                        report("preprocessing #{oldfile} into #{newfile} using #{pp}")
                                        REXML::XPath.each(command,"ctx:old") do |value| replace(value,oldfile) end
                                        REXML::XPath.each(command,"ctx:new") do |value| replace(value,newfile) end
                                        variables['old'] = oldfile
                                        variables['new'] = newfile
                                        REXML::XPath.each(command,"ctx:value") do |value|
                                            if name = value.attributes['name'] then
                                                substititute(value,variables[name.to_s])
                                            end
                                        end
                                        command = justtext(command)
                                        report(command)
                                        unless ok = System.run(command) then
                                            report("error in preprocessing file #{oldfile}")
                                        end
                                    end
                                end
                                if FileTest.file?(newfile) then
                                    File.syncmtimes(oldfile,newfile)
                                else
                                    report("preprocessing #{oldfile} gave no #{newfile}")
                                end
                            else
                                report("#{oldfile} needs no preprocessing")
                            end
                            @prepfiles[oldfile] = FileTest.file?(newfile)
                        end
                    end
                end
            end
        rescue
            report("fatal error in preprocessing #{@ctxname}: #{$!}")
        end
    end

    def savelog(ctlname=nil)
        unless ctlname then
            if @jobname then
                ctlname = File.suffixed(@jobname,'ctl')
            elsif @ctxname then
                ctlname = File.suffixed(@ctxname,'ctl')
            else
                return
            end
        end
        if @prepfiles.length > 0 then
            if log = File.open(ctlname,'w') then
                log << "<?xml version='1.0' standalone='yes'?>\n\n"
                log << "<ctx:preplist>\n"
                @prepfiles.keys.sort.each do |prep|
                    log << "\t<ctx:prepfile done='#{yes_or_no(@prepfiles[prep])}'>#{File.basename(prep)}</ctx:prepfile>\n"
                end
                log << "</ctx:preplist>\n"
                log.close
            end
        else
            begin
                File.delete(ctlname)
            rescue
            end
        end
    end

    private

    def include(xmldata,element='ctx:include',attribute='name')
        loop do
            begin
                more = false
                REXML::XPath.each(xmldata.root,element) do |e|
                    begin
                        name = e.attributes.get_attribute(attribute).to_s
                        name = e.text.to_s if name.empty?
                        name.strip! if name
                        done = false
                        if name and not name.empty? then
                            ['.',File.dirname(@ctxname),'..','../..'].each do |path|
                                begin
                                    fullname = if path == '.' then name else File.join(path,name) end
                                    if FileTest.file?(fullname) then
                                        if f = File.open(fullname,'r') and i = REXML::Document.new(f) then
                                            report("including ctx file #{name}")
                                            REXML::XPath.each(i.root,"*") do |ii|
                                                xmldata.root.insert_after(e,ii)
                                                more = true
                                            end
                                        end
                                        done = true
                                    end
                                rescue
                                end
                            end
                            break if done
                        end
                        report("no valid ctx inclusion file #{name}") unless done
                    rescue Exception
                        # skip this file
                    ensure
                        xmldata.root.delete(e)
                    end
                end
                break unless more
            rescue Exception
                break # forget about inclusion
            end
        end
    end

    private

    def yes_or_no(b)
        if b then 'yes' else 'no' end
    end

    private # copied from rlxtools.rb

    def justtext(str)
        str = str.to_s
        str.gsub!(/<[^>]*?>/o, '')
        str.gsub!(/\s+/o, ' ')
        str.gsub!(/&lt;/o, '<')
        str.gsub!(/&gt;/o, '>')
        str.gsub!(/&amp;/o, '&')
        str.gsub!(/&quot;/o, '"')
        str.gsub!(/[\/\\]+/o, '/')
        return str.strip
    end

    def substititute(value,str)
        if str then
            begin
                if value.attributes.key?('method') then
                    str = filtered(str.to_s,value.attributes['method'].to_s)
                end
                if str.empty? && value.attributes.key?('default') then
                    str = value.attributes['default'].to_s
                end
                value.insert_after(value,REXML::Text.new(str.to_s))
            rescue Exception
            end
        end
    end

    def replace(value,str)
        if str then
            begin
                value.insert_after(value,REXML::Text.new(str.to_s))
            rescue Exception
            end
        end
    end

    def filtered(str,method)
        str = str.to_s # to be sure
        case method
            when 'name' then # no path, no suffix
                case str
                    when /^.*[\\\/](.+?)\..*?$/o then $1
                    when /^.*[\\\/](.+?)$/o      then $1
                    when /^(.*)\..*?$/o          then $1
                    else                              str
                end
            when 'path'     then if str =~ /^(.+)([\\\/])(.*?)$/o then $1 else ''  end
            when 'suffix'   then if str =~ /^.*\.(.*?)$/o         then $1 else ''  end
            when 'nosuffix' then if str =~ /^(.*)\..*?$/o         then $1 else str end
            when 'nopath'   then if str =~ /^.*[\\\/](.*?)$/o     then $1 else str end
            else                                                               str
        end
    end

end