applyxrefs.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. if len(lines) < 1:
  43. print("Not touching empty file %s." % fn)
  44. return (True, None)
  45. if lines[0].startswith('.. _'):
  46. return (True, None)
  47. return (False, lines)
  48. def main(argv=None):
  49. if argv is None:
  50. argv = sys.argv
  51. if len(argv) == 1:
  52. argv.extend('.')
  53. files = []
  54. for root in argv[1:]:
  55. for (dirpath, dirnames, filenames) in os.walk(root):
  56. files.extend([(dirpath, f) for f in filenames])
  57. files.sort()
  58. files = [os.path.join(p, fn) for p, fn in files if fn.endswith('.txt')]
  59. for fn in files:
  60. if fn in DONT_TOUCH:
  61. print("Skipping blacklisted file %s." % fn)
  62. continue
  63. target_found, lines = has_target(fn)
  64. if not target_found:
  65. if testing:
  66. print '%s: %s' % (fn, lines[0]),
  67. else:
  68. print "Adding xref to %s" % fn
  69. process_file(fn, lines)
  70. else:
  71. print "Skipping %s: already has a xref" % fn
  72. if __name__ == '__main__':
  73. sys.exit(main())