applyxrefs.py 2.1 KB

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