applyxrefs.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. """Adds xref targets to the top of files."""
  2. from __future__ import absolute_import, unicode_literals
  3. import sys
  4. import os
  5. testing = False
  6. DONT_TOUCH = (
  7. './index.txt',
  8. )
  9. def target_name(fn):
  10. if fn.endswith('.txt'):
  11. fn = fn[:-4]
  12. return '_' + fn.lstrip('./').replace('/', '-')
  13. def process_file(fn, lines):
  14. lines.insert(0, '\n')
  15. lines.insert(0, '.. %s:\n' % target_name(fn))
  16. try:
  17. f = open(fn, 'w')
  18. except IOError:
  19. print("Can't open %s for writing. Not touching it." % fn)
  20. return
  21. try:
  22. f.writelines(lines)
  23. except IOError:
  24. print("Can't write to %s. Not touching it." % fn)
  25. finally:
  26. f.close()
  27. def has_target(fn):
  28. try:
  29. f = open(fn, 'r')
  30. except IOError:
  31. print("Can't open %s. Not touching it." % fn)
  32. return (True, None)
  33. readok = True
  34. try:
  35. lines = f.readlines()
  36. except IOError:
  37. print("Can't read %s. Not touching it." % fn)
  38. readok = False
  39. finally:
  40. f.close()
  41. if not readok:
  42. return (True, None)
  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. for fn in files:
  61. if fn in DONT_TOUCH:
  62. print('Skipping blacklisted file %s.' % fn)
  63. continue
  64. target_found, lines = has_target(fn)
  65. if not target_found:
  66. if testing:
  67. print '%s: %s' % (fn, lines[0]),
  68. else:
  69. print 'Adding xref to %s' % fn
  70. process_file(fn, lines)
  71. else:
  72. print 'Skipping %s: already has a xref' % fn
  73. if __name__ == '__main__':
  74. sys.exit(main())