File: manlifter

package info (click to toggle)
doclifter 2.7-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 688 kB
  • sloc: python: 8,307; xml: 970; makefile: 116
file content (679 lines) | stat: -rwxr-xr-x 25,263 bytes parent folder | download
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
#!/usr/bin/python -u
#
# Run doclifter against an entire manual tree.
# Sees all files in section 1 through 8 by default.

import sys, os, getopt, signal, time, re, commands, cStringIO, stat
try:
    import hotshot, hotshot.stats
except ImportError:
    hotshot = False

mandir = "/usr/share/man"
patchdir = os.path.abspath("prepatch")
outdir = None
patched = 0
makehtml = False
xslfragment = None
processed = set([])

def manfile(section, basename=""):
    "Return a manual file or directory based on section name."
    if not basename:
        # Return the directory
        return "%s/man%s/" % (mandir, section)
    elif basename[0] == '/':
        return basename
    elif basename.endswith(".gz") or basename.endswith(".bz2") or basename.endswith(".Z"):
        # We've been handed an actual filename
        return "%s/man%s/%s" % (mandir, section, basename)
    else:
        # We've been handed a filename section
        return "%s/man%s/%s.%s.gz" % (mandir, section[:1], basename, section)

def analyze_manpage(manpage):
    "Provide log annotations based on content."
    exclusions = (
        ("auto-generated by docbook2man-spec", "SGML DocBook"),
        ("Generated by db2man.xsl", "XML DocBook"),
        ("Automatically generated by Pod::Man", "Pod::Man"),
        ("Man page generated from reStructeredText", "reStructeredText."),
        )
    output = ""
    # Check to see if it has DocBook masters
    fp = open(manpage)
    firstline = fp.readline()
    for (pattern, generator) in exclusions:
        if firstline.find(pattern) > -1:
            output += "Generated from %s\n" % generator
    if firstline.startswith("<html>"):
        output += "This page is HTML.\n"
    fp.close()
    return output

def fetch_page(file, localcopy, patch):
    "Grab a local copy of a man page, patching if needed."
    output = ""
    if file[-3:] == ".gz":
        cstat = os.system("gunzip <%s >%s" % (file, localcopy))
    elif file[-4:] == ".bz2":
        cstat = os.system("bunzip2 <%s >%s" % (file, localcopy))
    elif file[-2:] == ".Z":
        cstat = os.system("uncompress <%s >%s" % (file, localcopy))
    else:
        cstat = os.system("cp %s %s" % (file, localcopy))
    if os.WIFSIGNALED(cstat) or os.WEXITSTATUS(cstat):
        return (1, output + "manlifter: copy failed, status %d", cstat)
    if os.path.exists(patch):
        here = os.getcwd()
        os.chdir(outdir)
        patch = commands.getoutput("patch --version-control=never <%s" % (patch,))
        stem = os.path.basename(localcopy)
        os.system("rm -f %s.orig %s.rej" % (stem, stem))
        os.chdir(here)
        if patch:
            output += patch + "\n"
    return (0, output)

def getstem(file):
    "Reduce the name of a man page or generated HTML file to its stem"
    if file.endswith(".xml"):
        file = file[:-4]
    file = ".".join(file.split(".")[:-1])	# Remove section 
    return file

def make_xml(source, options, batchmode):
    "Make XML from specified man page."
    doclifter.stdout = doclifter.stderr = keep_io = cStringIO.StringIO()
    args = ["-I", mandir,] + options.split() + [source,]
    doclifter_status = doclifter.main(args, keep_io, keep_io)
    output = keep_io.getvalue()
    keep_io.close()
    lxmlloc = None
    if doclifter_status == 2:
        fp = open(source)
        contents = fp.read()
        inclusions = re.compile(r"\.so\s+(.*)").search(contents)
        fp.close()
        if inclusions:
            lxmlloc = os.path.join(outdir, getstem(inclusions.group(1)) + ".xml")
        return(2, lxmlloc, output)
    return (doclifter_status, None, output)

def validate(translation):
    "Validate an XML file produced by translation."
    output = ""
    # If it has entity inclusions it won't validate, so don't try.
    # This is only a good idea because man pages that have these are
    # usually trivial wrappers like builtins.1
    try:
        fp = open(translation)
        inclusions = re.compile("<!ENTITY.*SYSTEM '(.*)'>").search(fp.read())
        fp.close()
        if inclusions:
            output += "Won't validate due to entity inclusion of %s\n" % inclusions.group(1)
            return (0, output)
    except IOError:
        output += "%s is missing.\n" % translation
    # Run the validation checker
    (bstat, validate_out) = commands.getstatusoutput("xmllint --xinclude --postvalid %s >/dev/null" % translation)
    if validate_out:
        output += validate_out  + "\n"
    if os.WIFSIGNALED(bstat):
        output += "Bailing out of xmllint...\n"
        return (-1, output)
    xmllint_error_status = os.WEXITSTATUS(bstat)
    if xmllint_error_status:
        output += "xmllint error status:%s\n" % os.WEXITSTATUS(bstat)
    if xmllint_error_status:
        return (6, output)
    return (0, output)

def format(translation, fmt, xslfragment):
    "Format an XML file to a specified format."
    output = ""
    here = os.getcwd()
    os.chdir(os.path.dirname(translation))
    if xslfragment:
        command = "xmlto %s %s" % (fmt, os.path.basename(translation))
    else:
        command = "xmlto -m %s %s %s" % (xslfragment, fmt, os.path.basename(translation))
    (bstat, format_out) = commands.getstatusoutput(command)
    os.chdir(here)
    if format_out:
        output += format_out  + "\n"
    if os.WIFSIGNALED(bstat):
        output += "Bailing out of %s formatting...\n" % fmt
        return (-1, output)
    format_error_status = os.WEXITSTATUS(bstat)
    if format_error_status:
        output += "format error status:%s\n" % os.WEXITSTATUS(bstat)
    if format_error_status:
        return (6, output)
    return (0, output)

def deploy(source, target):
    try:
        os.rename(source, target)
    except OSError, e:
        return(3, "Rename of %s to %s failed, errno = %d" % (source, target, e.errno,))
    return (0, "")

def makelink(source, target):
    try:
        os.symlink(os.path.abspath(source), os.path.abspath(target))
    except OSError:
        pass

def singlerun(file, options, tmpstem="foo"+`os.getpid()`, batchmode=False):
    "Test-format a single file."
    global patched
    foundpatch = False
    if not os.path.exists(file):
        return (0, False, "")
    output = ""
    if file[-3:] == ".gz":
        withsect = os.path.basename(file)[:-3]
    elif file[-4:] == ".bz2":
        withsect = os.path.basename(file)[:-4]
    elif file[-2:] == ".Z":
        withsect = os.path.basename(file)[:-2]
    else:
        withsect = os.path.basename(file)
    dot = withsect.rindex(".")
    section = withsect[dot+1:dot+2]
    subdir = os.path.join(outdir, "man" + section)
    stem = getstem(withsect)
    xmlloc = os.path.join(subdir, stem + ".xml")
    # Count patches here so our stats won't be off
    patch = os.path.join(patchdir, withsect + ".patch")
    if os.path.exists(patch):
        patched += 1
        foundpatch = True
    try:
        global processed
        tmpstem = os.path.join(outdir, tmpstem)
        source = tmpstem + ".man"
        # Save work by doing conversions only as needed
        rebuild_xml = True
        if batchmode and os.path.exists(xmlloc):
            if os.stat(file).st_mtime < os.lstat(xmlloc).st_mtime:
                output += "XML conversion is up to date\n"
                processed.discard(withsect)
                rebuild_xml = False
        htmlloc = os.path.join(subdir, stem + ".html")
        if rebuild_xml:
            # Grab the actual manual page
            localcopy = os.path.join(outdir, withsect)
            (status, output) = fetch_page(file, localcopy, patch)
            if (status):
                return (status, False, output)
            # Note the the patch was used
            processed.discard(withsect)
            # Add any annotations
            output += analyze_manpage(localcopy)
            # Save the location of the page
            loc = tmpstem + ".loc"
            lfp = open(loc, "w")
            lfp.write(withsect)
            lfp.close()
            # Move the source file into the output directory
            os.rename(localcopy, source) 
            # Run the translator
            (doclifter_status, lxmlloc, note) = make_xml(source, options, batchmode)
            output += note
            if doclifter_status not in (0, 2):
                if not batchmode:
                    output +=  "doclifter error status: %s\n" % doclifter_status
                return (doclifter_status, foundpatch, output)
            translation = tmpstem + ".man.xml"
            # Warn about FIX-ME problems
            output += commands.getoutput("grep FIX-ME " + translation + " 2>/dev/null")
            # If the translation went through, cleaning up consists
            # of putting this in its permanent location.
            try:
                # This will foo up if we ever have to symlink between dirs
                if batchmode and not os.path.exists(subdir):
                    os.mkdir(subdir)
            except OSError, e:
                return(3, foundpatch, output + "Creation of %s failed, errno = %d\n"%(subdir,e.errno))
            if doclifter_status == 2:
                makelink(lxmlloc, xmlloc)
            if doclifter_status == 0:
                if not makehtml:
                    (status, more) = validate(translation)
                    output += more
                    if batchmode and status:
                        os.remove(translation)
                        try:
                            os.remove(htmlloc)
                        except OSError:
                            pass
                        return (status, foundpatch, output)
                if batchmode:
                    (status, more) = deploy(translation, xmlloc)
                    translation = xmlloc
                    output += more
                    if status:
                        return (status, foundpatch, output)
        # Save work by doing HTML conversions only as needed
        rebuild_html = makehtml
        if batchmode and os.path.exists(htmlloc):
            if os.stat(xmlloc).st_mtime < os.lstat(htmlloc).st_mtime:
                output += "HTML conversion is up to date\n"
                rebuild_html = False
        if rebuild_html:
            if batchmode:
                htmlloc = os.path.join(subdir, stem + ".html")
            else:
                htmlloc = stem + ".html"
            if batchmode and stat.S_ISLNK(os.lstat(xmlloc).st_mode):
                makelink(os.readlink(xmlloc)[:-4]+".html", htmlloc)
            else:
                (status, more) = format(translation, "xhtml-nochunks", xslfragment)
                output += more
                if status:
                    if batchmode:
                        os.remove(xmlloc)
                        try:
                            os.remove(htmlloc)
                        except OSError:
                            pass
                    return (status, foundpatch, output)
    finally:
        # Clean up
        if batchmode:
            if os.path.exists(source):
                os.remove(source)
    return (0, foundpatch, output)

def sectionfiles(sections):
    "Generate files corresponding to a list of sections."
    files = []
    for section in sections:
        files = files + map(lambda f: manfile(section, f), os.listdir(manfile(section)))
    files.sort()
    return files

total = eligible = starttime = 0

def report_elapsed(elapsed):
    "Report elapsed time in friendly format."
    return "%02dh:%02dm:%02ds" % (elapsed/3600, (elapsed % 3600)/60, elapsed % 60)

def massrun(files, options, profiling):
    "Test against all files in specified sections."
    def bailout(signum, frame):
        print "\nBailing out with signal %d..." % signum
        os.system("rm -f doclifter_test%s.py doclifter_test%s.py[co]" % (os.getpid(), os.getpid()))
        sys.exit(0)
    global total, eligible, starttime
    total = 0
    starttime = int(time.time())
    eligible = len(files)
    doclifter_error_count = xmllint_error_count = total = 0
    def report(sig, frame, out=sys.stderr):
        ftotal = float(total)
        elapsed = int(time.time()) - starttime
        out.write("\n%%%d of %d files in %s, %d OK, %d patched, %d doclifter errors, %d validation failures, %2.2f%% good.\n" % \
              (total, eligible, report_elapsed(elapsed),
               (total - doclifter_error_count - xmllint_error_count),
               patched,
               doclifter_error_count, 
               xmllint_error_count,
               (ftotal-doclifter_error_count-xmllint_error_count-patched)*100.0/ftotal))
    def test(file, options):
            before = time.time()
            (status, patched, output) = singlerun(file=file, options=options, batchmode=True)
            after = time.time()
            sys.stdout.write("! %s=%d%s (%2.2f)\n%s\n" % (file, status, " *"[patched], after-before, output))
            return (status, output)
    signal.signal(signal.SIGUSR2, report)
    signal.signal(signal.SIGHUP, bailout)
    signal.signal(signal.SIGINT, bailout)
    signal.signal(signal.SIGPWR, bailout)
    signal.signal(signal.SIGTERM, bailout)
    print "%Test started", time.ctime()
    if profiling:
        print "%Profiling enabled.\n"
    else:
        print "%Profiling not enabled.\n"
    try:
        for file in files:
            (status, output) = test(file=file, options=options)
            if status == -1:
                break
            elif status in (1, 4):	# Doclifter parse or internal error.
                doclifter_error_count += 1
            elif status == 2:		# .so inclusion
                pass
            elif status in (3, 5):	# File I/O error or keyboard interrupt
                pass
            elif status == 6:
                xmllint_error_count += 1
            total = total + 1
    except KeyboardInterrupt:
        pass
    report(0, sys.stdout)

htmlheader = '''
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Manlifter contents page</title>
</head>
<body>
'''
htmltrailer = "</body>\n</html>\n"

def genindex(ofp):
    # Collect all section/name/description triples
    filelist = []
    section_re = re.compile("/man([^/]*)")
    extract_re = re.compile("<refpurpose>([^<]*)</refpurpose>")
    section_dict = {}
    for (root, dirs, files) in os.walk('xmlman'):
        for file in files:
            try:
                if not file.endswith(".xml"): continue
                # Extract the manual section
                m = section_re.search(root)
                if m:
                    section = m.group(1)
                else:
                    continue
                section_dict[section] = []
                # Extract the manual page name
                name = ".".join(file.split(".")[:-1])
                # Extract the description
                file = os.path.join(root, file)
                fp = open(file)
                contents = fp.read()
                fp.close()
                m = extract_re.search(contents)
                if m:
                    description = m.group(1)
                else:
                    description = "(no description)"
                # Build an index entry
                filelist.append((section, name, description))
            except IOError:
                pass
    filelist.sort()	# In case the directory was pieced together by several runs
    for (section, name, description) in filelist:
        section_dict[section].append((name, description))
    keys = section_dict.keys()
    keys.sort()

    for section in keys:
        ofp.write(htmlheader)
        ofp.write("<h1>%s:</h1>\n<dl>\n" % section)
        for (name, description) in section_dict[section]:
            ofp.write("<dt><a href='man%s/%s.html'>%s</a></dt><dd>%s</dd>\n" \
                  % (section, name, name, description))
        ofp.write("</dl>\n")
        ofp.write(htmltrailer)

def statistics():
    counts = [0] * 7
    legends = (
        "OK ",	# No error
        "???",	# Unliftable (normal error status)
        ".so",	# failure due to inclusion
        "I/O",	# I/O failure, could not reach page
        "!!!",	# Internal error, doclifter blew up
        "^C ",	# Translation interrupted
        "XML",	# XML validation failure 
        )

    patchcount = re.compile("([0-9]+) patched")
    totalcount = 0
    while True:
        line = sys.stdin.readline()
        if not line:
            break
        m = patchcount.search(line)
        if m:
            patched = int(m.group(1))
        if line[0] != '!':
            continue
        line = line[2:]
        rcolon = line.rindex("=")
        file = line[:rcolon]
        retval = line[rcolon+1:].split()[0]
        if retval.endswith("*"):
            retval = retval[:-1]
        if file.endswith(".gz"):
            file = file[:-3]
        elif file.endswith(".bz2"):
            file = file[:-4]
        elif file.endswith(".Z"):
            file = file[:-2]
        file = os.path.basename(file)
        counts[int(retval)] += 1
        totalcount += 1

    total = sum(counts)
    for (i, count) in enumerate(counts):
        print "%d = %s: %5d	%2.2f%%" % (i, legends[i], count, (count * 1.0)*100/total)
    print "Total: %d  Errors: %d " % (totalcount, sum(counts)-counts[0]) 
    print "Patched: %d (%2.2f%%)" % (patched, patched*100/float(totalcount))
    print "With patches: %d (%2.2f%%)" % (counts[0], (counts[0])*100/float(totalcount))
    print "Without patches: %d (%2.2f%%)" % (counts[0]-patched, (counts[0]-patched)*100/float(totalcount))

def errorclean(error_only, pattern):
    if pattern:
        pattern = re.compile(pattern)
    pagename = re.compile(r"! (.*)=([0-9]+)")
    while 1:
        header = sys.stdin.readline()
        if not header:
            break
        # Look for a log leader
        m = pagename.search(header)
        if not m:
           continue 
        subject = m.group(1)
        status = int(m.group(2))
        # Collect following error messages up to a blank line
        trailer = ''
        while 1:
            line = sys.stdin.readline()
            trailer += line
            if not line or line == '\n':
                break
        if pattern:
            # Emit by pattern
            if pattern.search(trailer):
                sys.stdout.write(subject+"\n")
        else:
            # Emit some of them by status
            def matches(s): return trailer.find(s) > -1
            if status == 0 and not matches("warning"):
                continue
            if status == 1 and (matches("page is empty") or matches("page has no text")):
                continue
            if status == 2:
                continue
            # Otherwise, emit
            if error_only:
                print subject
            else:
                sys.stdout.write(header + trailer)

def patchman(stem="foobar"):
    "Make a patch against the last page lifted."
    if not os.path.exists(stem + ".man"):
        sys.stderr.write("manlifter: no trial page waiting.\n")
        raise SystemExit, 1
    if not os.path.exists(stem + ".loc"):
        sys.stderr.write("manlifter: no saved page location.\n")
        raise SystemExit, 1
    # Retrieve the location of the last page
    lfp = open(stem + ".loc")
    withsect = lfp.read()
    lfp.close()
    # Fail if patch already exists
    patch = os.path.join(patchdir, withsect + ".patch")
    if os.path.exists(patch):
        sys.stderr.write("manlifter: patch for %s already exists.\n" % withsect)
        raise SystemExit, 1
    # Make copies for patching and do it
    trialpage = stem + ".man"
    unpatched = withsect + "-unpatched"
    try:
        os.system("cp %s %s" % (trialpage, unpatched))
        os.system("cp %s %s" % (trialpage, withsect))
        if os.system(os.getenv("EDITOR") + " " + withsect) == 0:
            os.system("diff -u %s %s >%s" % (unpatched, withsect, patch))
    finally:
        os.system("rm -f %s %s %s" % (withsect, withsect + "~", unpatched))

citereftemplate = '''
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">

<xsl:param name="citerefentry.link" select="1"/>

<xsl:template name="generate.citerefentry.link">
  <xsl:text>%s</xsl:text>
  <xsl:text>/man</xsl:text>
  <xsl:value-of select="manvolnum"/>
  <xsl:text>/</xsl:text>
  <xsl:value-of select="refentrytitle"/>
  <xsl:text>.html</xsl:text>
</xsl:template>

</xsl:stylesheet>
'''

def doclifter_driver(options, arguments):
    "Lift old markup to new."
    global mandir, makehtml, outdir, xslfragment, patchdir, makepatch
    filelist = []
    sections = []
    callopts = ""
    makehtml = False
    errorfilter = False
    quiet = False
    fval = None
    makepatch = False
    profiling = False
    for (switch, val) in options:
        if (switch == '-d'):
            callopts += " -d " + val
        elif (switch == '-e'):
            errorfilter = True
	elif (switch == '-f'):	# Translate files in the specified list
            fval = val
        elif (switch == '-h'):
            makehtml = True
        elif (switch == '-I'):	# Specify the root of the manual hierarchy
            mandir = val
        elif (switch == '-m'):	# Make a patch from the last fetched page
            makepatch = True
        elif (switch == '-o'):  # Specify output directory
            outdir = val
	elif (switch == '-p'):	# Specify patch directory
	    patchdir = os.path.abspath(val)
        elif (switch == '-P'):
            profiling = True
	elif (switch in ("-q", '-v', '-w')):	# Set verbosity level
            quiet = True
	    callopts += " " + switch
	elif (switch == '-s'):	# Specify search list of sections
	    sections.append(val)
	elif (switch == '-S'):	# Generate statistics from log on stdin
	    statistics()
            sys.exit(0)
    if not sections:
        sections = ["1", "2", "3", "4", "5", "6", "7", "8"]
    if not outdir:
        if not arguments:
            outdir = 'xmlman'
        else:
            outdir = '.'
    # Clean/create the output directory
    if not arguments:
        if not os.path.exists(outdir):
            os.mkdir(outdir)
            # Create XSL fragment for making refentries into links
            xslfragment = os.path.abspath(os.path.join(outdir, "citerefentry.xsl"))
            fp = open(xslfragment, "w")
            fp.write(citereftemplate % outdir)
            fp.close()
    try:
        # Process args, if present
        if arguments: 
            for file in arguments:
                for section in sections:
                    manpage = manfile(section, file)
                    print "Trying", manpage
                    if os.path.exists(manpage):
                        (status, patched, output) = singlerun(manpage, callopts, "foobar", batchmode=False)
                        print output
                        break
        elif makepatch:
            patchman()
        elif errorfilter:
            errorclean(quiet, fval)
        elif fval:
            fp = open(fval)
            filelist = map(lambda x: x.rstrip(), fp.readlines())
            fp.close()
            massrun(filelist, callopts, profiling)
        else:
            global processed 
            processed = set([])
            if os.path.exists(patchdir):
                processed = set(map(lambda x: x.replace(".patch", "").replace(".correction", ""), os.listdir(patchdir)))
            massrun(sectionfiles(sections), callopts, profiling)
            if processed:
                print "%% %d patches not used:" % len(processed)
                for file in processed:
                    print file
    finally:
        pass
        #os.remove(xslfragment)
    # Now, rebuild the index page
    if makehtml:
        fp = open(os.path.join(outdir, "index.html"), "w")
        genindex(fp)
        fp.close()

if __name__ == "__main__":
    # Find a copy of doclifter
    for pathdir in ["."] + os.environ["PATH"].split(":"):
        where = os.path.join(pathdir, "doclifter")
        if os.path.exists(where):
            break
    else:
        sys.stderr.write("manlifter: can't find doclifter!\n")
        sys.exit(1)
    # Import it, so we can modify it while the test is running without
    # screwing up the results
    try:
        os.system("cp %s doclifter_test%s.py" % (where, os.getpid()))
        sys.path.append(".")
        exec 'import doclifter_test%s' % os.getpid()
        exec "doclifter=doclifter_test%s" % os.getpid()
    finally:
        os.system("rm -f doclifter_test%s.py*" % os.getpid())
    # Gather options
    (options, arguments) = getopt.getopt(sys.argv[1:], "d:ef:hI:mo:p:Pqs:Svw")
    # Do the real work
    if "-P" in sys.argv and hotshot:
        prof = hotshot.Profile("manlifter.prof")
        prof.runcall(doclifter_driver, options, arguments)
        prof.close()
        starttime = time.time()
        print "% Digesting profile results...",
        stats = hotshot.stats.load("manlifter.prof")
        stats.sort_stats('time', 'calls')
        print "took %s." % report_elapsed(time.time() - starttime)
        stats.print_stats(30)
    else:
        doclifter_driver(options, arguments)
# End