optref.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python
  2. import re
  3. import sys
  4. from pprint import pprint
  5. def enum_options(file):
  6. # key = *opts*, value = refid, remove proceeding -- from long
  7. # option name and s/-/_/g and prepend '_optref'
  8. ref_db = {}
  9. p = re.compile(r'^\*(-[a-zA-Z0-9-]+)\*(?:,\s*\*(-[a-zA-Z0-9-]+)\*)?.*::$')
  10. for line in file:
  11. m = p.match(line)
  12. if m:
  13. if m.group(2) is None:
  14. short_opt = None
  15. long_opt = m.group(1)
  16. else:
  17. short_opt = m.group(1)
  18. long_opt = m.group(2)
  19. ref_id = make_ref_id(long_opt)
  20. if short_opt in ref_db:
  21. print "warn: duplicate short_opt", short_opt
  22. if long_opt in ref_db:
  23. print "warn: duplicate long_opt", log_opt
  24. if short_opt:
  25. ref_db[short_opt] = ref_id
  26. ref_db[long_opt] = ref_id
  27. return ref_db
  28. def make_ref_id(long_opt):
  29. return 'aria2_optref_'+long_opt.strip('*').lstrip('-').replace('-', '_')
  30. def make_cross_ref(out, file, ref_db):
  31. opt_def = re.compile(r'^\*(-[a-zA-Z0-9-]+)\*(?:,\s*\*(-[a-zA-Z0-9-]+)\*)?.*::$')
  32. opt_ref = re.compile(r'\*(-[a-zA-Z0-9-]+)\*')
  33. for line in file:
  34. m = opt_def.match(line)
  35. if m:
  36. if m.group(2) is None:
  37. long_opt = m.group(1)
  38. else:
  39. long_opt = m.group(2)
  40. out.write('[[{0}]]'.format(ref_db[long_opt]))
  41. out.write(line)
  42. continue
  43. pos = 0
  44. while 1:
  45. m = opt_ref.search(line, pos)
  46. if m:
  47. opt = line[m.start(1):m.end(1)]
  48. if opt in ref_db:
  49. out.write(line[pos:m.start(0)])
  50. out.write('*<<{0}, {1}>>*'.format(ref_db[opt], opt))
  51. else:
  52. print "warn: not in ref_db", opt
  53. out.write(line[pos:m.end(0)])
  54. pos = m.end(0)
  55. else:
  56. out.write(line[pos:])
  57. break
  58. if __name__ == '__main__':
  59. with open(sys.argv[1]) as f:
  60. ref_db = enum_options(f)
  61. with open(sys.argv[1]) as f:
  62. with open(sys.argv[2], 'wb') as out:
  63. make_cross_ref(out, f, ref_db)