navgen.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #!/usr/bin/env python
  2. import os
  3. def dirbasename(s, sep='/'):
  4. if s[-1] == sep:
  5. s = s[:-1]
  6. if not sep in s:
  7. return '.', s
  8. else:
  9. idx = s.rindex(sep)
  10. return s[:idx], s[idx+1:]
  11. def defaultFilt(dirEntry):
  12. pathname = dirEntry.path
  13. filename = dirEntry.name
  14. if filename[0] in '_.':
  15. return (False, None, None)
  16. if not dirEntry.is_dir():
  17. if len(filename) > 4 and filename[-4:] in ['.rst', '.htm']:
  18. pathname = pathname[:-4] + '.htm'
  19. filename = filename[:-4]
  20. elif len(filename) > 3 and filename[-3:] == '.md':
  21. pathname = pathname[:-3] + '.htm'
  22. filename = filename[:-3]
  23. else:
  24. return (False, None, None)
  25. if filename == "index":
  26. return (False, None, None)
  27. else:
  28. pathname = pathname + '/'
  29. filename = filename + '/'
  30. if pathname[0:2] == './':
  31. pathname = pathname[2:]
  32. return (True, pathname, filename)
  33. def navgen(base, path, filterConv = None, sub=None):
  34. curdir, fn = dirbasename(path)
  35. basePathLen = len(base)
  36. if len(curdir) < len(base):
  37. curdir = base
  38. fn = ""
  39. files = []
  40. for d in os.scandir(curdir):
  41. if filterConv is not None:
  42. visible, newpath, newname = filterConv(d)
  43. if not visible:
  44. continue
  45. else:
  46. newpath = d.path
  47. newname = d.name
  48. if newpath[0:basePathLen] == base:
  49. newpath = newpath[basePathLen:]
  50. if newpath[0] == '/':
  51. newpath = newpath[1:]
  52. thisPath = (d.name == fn)
  53. if thisPath:
  54. sublist = sub
  55. else:
  56. sublist = None
  57. files.append((newpath, newname, thisPath, sublist))
  58. if curdir == base:
  59. return files
  60. else:
  61. return navgen(base, curdir, filterConv, files)
  62. def emitPath(path, name, thisPath):
  63. if thisPath:
  64. sym = '&raquo;'
  65. append = ' class="thisPage"'
  66. else:
  67. sym = '&rsaquo;'
  68. append = ''
  69. print('<li><a href="/{}"{}>{} {}</a></li>'.format(path, append, sym, name))
  70. def printnav(navlist):
  71. print('<ul>')
  72. for (Path, Name, thisPath, Sub) in navlist:
  73. if thisPath:
  74. emitPath(Path, Name, True)
  75. if Sub is not None:
  76. print('<li>')
  77. printnav(Sub)
  78. print('</li>')
  79. else:
  80. emitPath(Path, Name, False)
  81. print('</ul>')
  82. if __name__ == '__main__':
  83. import sys
  84. nav = navgen(sys.argv[1], sys.argv[2], defaultFilt)
  85. printnav(nav)