App Engine Python SDK version 1.7.4 (2)
[gae.git] / python / lib / django_1_4 / docs / _ext / applyxrefs.py
blob3809088c1f860f75a950cb08a3e37b452f3c0a34
1 """Adds xref targets to the top of files."""
3 import sys
4 import os
6 testing = False
8 DONT_TOUCH = (
9 './index.txt',
12 def target_name(fn):
13 if fn.endswith('.txt'):
14 fn = fn[:-4]
15 return '_' + fn.lstrip('./').replace('/', '-')
17 def process_file(fn, lines):
18 lines.insert(0, '\n')
19 lines.insert(0, '.. %s:\n' % target_name(fn))
20 try:
21 f = open(fn, 'w')
22 except IOError:
23 print("Can't open %s for writing. Not touching it." % fn)
24 return
25 try:
26 f.writelines(lines)
27 except IOError:
28 print("Can't write to %s. Not touching it." % fn)
29 finally:
30 f.close()
32 def has_target(fn):
33 try:
34 f = open(fn, 'r')
35 except IOError:
36 print("Can't open %s. Not touching it." % fn)
37 return (True, None)
38 readok = True
39 try:
40 lines = f.readlines()
41 except IOError:
42 print("Can't read %s. Not touching it." % fn)
43 readok = False
44 finally:
45 f.close()
46 if not readok:
47 return (True, None)
49 #print fn, len(lines)
50 if len(lines) < 1:
51 print("Not touching empty file %s." % fn)
52 return (True, None)
53 if lines[0].startswith('.. _'):
54 return (True, None)
55 return (False, lines)
57 def main(argv=None):
58 if argv is None:
59 argv = sys.argv
61 if len(argv) == 1:
62 argv.extend('.')
64 files = []
65 for root in argv[1:]:
66 for (dirpath, dirnames, filenames) in os.walk(root):
67 files.extend([(dirpath, f) for f in filenames])
68 files.sort()
69 files = [os.path.join(p, fn) for p, fn in files if fn.endswith('.txt')]
70 #print files
72 for fn in files:
73 if fn in DONT_TOUCH:
74 print("Skipping blacklisted file %s." % fn)
75 continue
77 target_found, lines = has_target(fn)
78 if not target_found:
79 if testing:
80 print '%s: %s' % (fn, lines[0]),
81 else:
82 print "Adding xref to %s" % fn
83 process_file(fn, lines)
84 else:
85 print "Skipping %s: already has a xref" % fn
87 if __name__ == '__main__':
88 sys.exit(main())