githublog.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/env python
  2. """
  3. File: githublog.py
  4. Hugo assistance to generate a special README file, including all posts title inside
  5. as a TOC.
  6. This will make blog repo to be a blog inplace.
  7. """
  8. import os
  9. import string
  10. import subprocess
  11. from posixpath import join as urljoin
  12. POSTS_ROOT = 'content'
  13. EXTS = ['.md', '.rst']
  14. README = 'README.md'
  15. GITREPO = 'http://git.wanbits.io/joe/blog'
  16. def get_git_remote():
  17. proc = subprocess.Popen(['git', 'remote', '-v'], stdout=subprocess.PIPE, shell=True)
  18. (out, err) = proc.communicate()
  19. if err:
  20. return None
  21. lines = out.decode('utf-8').split('\n')
  22. if len(lines) < 2:
  23. return None
  24. parts = lines[1].split('\t')
  25. if len(parts) < 2:
  26. return None
  27. values = parts[1].split(' ')
  28. return None if len(values) < 1 else values[0]
  29. def get_category(dir):
  30. ''' '''
  31. parts = dir.split(os.sep)
  32. return os.sep.join(parts[1:])
  33. remote = get_git_remote() if not GITREPO else GITREPO
  34. if not remote:
  35. print('not a git repo, quit')
  36. exit(1)
  37. posts = {}
  38. # find out all non-draft posts
  39. for r, dl, fl in os.walk(POSTS_ROOT):
  40. if fl:
  41. cate = get_category(r)
  42. posts[cate] = []
  43. for f in fl:
  44. _, ext = os.path.splitext(f)
  45. if ext.lower() not in EXTS:
  46. continue
  47. fullname = os.path.join(r, f)
  48. comment_started = False
  49. metas = {}
  50. with open(fullname, 'r', encoding='utf-8') as h:
  51. line = h.readline().strip()
  52. while line:
  53. if line == '---':
  54. if not comment_started:
  55. comment_started = True
  56. else:
  57. break
  58. else:
  59. parts = line.split(': ')
  60. if len(parts) != 2:
  61. break
  62. metas[parts[0].strip().lower()] = parts[1].strip().lower()
  63. metas['file'] = f
  64. line = h.readline().strip()
  65. if metas.get('draft') == 'false':
  66. posts[cate].append(metas)
  67. # generate README.md
  68. with open(README, 'wt', encoding='utf-8') as h:
  69. h.write('')
  70. for k, v in posts.items():
  71. h.write('## {}\n\n'.format(k))
  72. v = sorted(v, key=lambda metas: metas.get('date'), reverse=True)
  73. for metas in v:
  74. h.write('- [{}]({})\n'.format(metas.get('title'), urljoin(remote, 'src/master', POSTS_ROOT, k, metas.get('file'))))
  75. h.write('\n')
  76. print('done.')