2008-08-24 06:25:40 +08:00
|
|
|
"""Adds xref targets to the top of files."""
|
|
|
|
|
|
|
|
import os
|
2015-02-10 02:19:34 +08:00
|
|
|
import sys
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
testing = False
|
|
|
|
|
|
|
|
DONT_TOUCH = (
|
2013-10-20 07:33:10 +08:00
|
|
|
'./index.txt',
|
|
|
|
)
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
def target_name(fn):
|
|
|
|
if fn.endswith('.txt'):
|
|
|
|
fn = fn[:-4]
|
|
|
|
return '_' + fn.lstrip('./').replace('/', '-')
|
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
def process_file(fn, lines):
|
|
|
|
lines.insert(0, '\n')
|
|
|
|
lines.insert(0, '.. %s:\n' % target_name(fn))
|
|
|
|
try:
|
2012-05-05 20:01:38 +08:00
|
|
|
with open(fn, 'w') as fp:
|
|
|
|
fp.writelines(lines)
|
2008-08-24 06:25:40 +08:00
|
|
|
except IOError:
|
|
|
|
print("Can't open %s for writing. Not touching it." % fn)
|
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
def has_target(fn):
|
|
|
|
try:
|
2012-05-05 20:01:38 +08:00
|
|
|
with open(fn, 'r') as fp:
|
|
|
|
lines = fp.readlines()
|
2008-08-24 06:25:40 +08:00
|
|
|
except IOError:
|
2012-05-05 20:01:38 +08:00
|
|
|
print("Can't open or read %s. Not touching it." % fn)
|
2008-08-24 06:25:40 +08:00
|
|
|
return (True, None)
|
|
|
|
|
2015-02-06 02:25:34 +08:00
|
|
|
# print fn, len(lines)
|
2008-08-24 06:25:40 +08:00
|
|
|
if len(lines) < 1:
|
|
|
|
print("Not touching empty file %s." % fn)
|
|
|
|
return (True, None)
|
|
|
|
if lines[0].startswith('.. _'):
|
|
|
|
return (True, None)
|
|
|
|
return (False, lines)
|
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
def main(argv=None):
|
|
|
|
if argv is None:
|
|
|
|
argv = sys.argv
|
|
|
|
|
|
|
|
if len(argv) == 1:
|
|
|
|
argv.extend('.')
|
|
|
|
|
|
|
|
files = []
|
|
|
|
for root in argv[1:]:
|
|
|
|
for (dirpath, dirnames, filenames) in os.walk(root):
|
2014-12-07 05:00:09 +08:00
|
|
|
files.extend((dirpath, f) for f in filenames)
|
2008-08-24 06:25:40 +08:00
|
|
|
files.sort()
|
|
|
|
files = [os.path.join(p, fn) for p, fn in files if fn.endswith('.txt')]
|
2015-02-06 02:25:34 +08:00
|
|
|
# print files
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
for fn in files:
|
|
|
|
if fn in DONT_TOUCH:
|
|
|
|
print("Skipping blacklisted file %s." % fn)
|
|
|
|
continue
|
|
|
|
|
|
|
|
target_found, lines = has_target(fn)
|
|
|
|
if not target_found:
|
|
|
|
if testing:
|
2012-04-29 00:02:01 +08:00
|
|
|
print('%s: %s' % (fn, lines[0]))
|
2008-08-24 06:25:40 +08:00
|
|
|
else:
|
2012-04-29 00:02:01 +08:00
|
|
|
print("Adding xref to %s" % fn)
|
2008-08-24 06:25:40 +08:00
|
|
|
process_file(fn, lines)
|
|
|
|
else:
|
2012-05-05 20:01:38 +08:00
|
|
|
print("Skipping %s: already has a xref" % fn)
|
2008-08-24 06:25:40 +08:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2012-04-29 00:02:01 +08:00
|
|
|
sys.exit(main())
|