PageRenderTime 24ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/create-manual.py

http://github.com/residuum/PuRestJson
Python | 68 lines | 57 code | 6 blank | 5 comment | 3 complexity | e2cab8dfd6526544c0efc29f73aecff5 MD5 | raw file
  1. # Converts the project Wiki to html and adds it as manual.
  2. #
  3. # Adapted from https://gist.github.com/mrexmelle/659abc02ae1295d60647
  4. import os
  5. import subprocess
  6. import sys
  7. from bs4 import BeautifulSoup
  8. wikiDir = '/tmp/PuRestJson.wiki/'
  9. exportDir = 'manual/'
  10. if len(sys.argv) > 1:
  11. exportDir = sys.argv[1]
  12. if len(sys.argv) > 2:
  13. wikiDir = sys.argv[2]
  14. print 'Input directory: ', wikiDir
  15. print 'Output directory: ', exportDir
  16. # rename all files containing '[' and ']' in names,
  17. # because Windows does not like those.
  18. for f in os.listdir(wikiDir):
  19. cleaned = f.replace('[', '').replace(']', '').replace(':', '')
  20. if f != cleaned:
  21. os.rename(wikiDir + f, wikiDir + cleaned)
  22. # convert md files one-by-one.
  23. for f in os.listdir(wikiDir):
  24. if f.endswith('.md'):
  25. print 'Converting: ', f
  26. baseFile = os.path.splitext(os.path.basename(f))[0];
  27. htmlFile = baseFile + '.html'
  28. subprocess.call(['grip', wikiDir + f, '--export', '--no-inline',
  29. exportDir + htmlFile])
  30. # edit links to css, images and other pages.
  31. htmlDoc = open(exportDir + htmlFile)
  32. soup = BeautifulSoup(htmlDoc, 'lxml')
  33. for s in soup.findAll('link'):
  34. s.extract()
  35. css = soup.new_tag('link')
  36. css.attrs['rel'] = 'stylesheet'
  37. css.attrs['href'] = 'style.css'
  38. soup.head.append(css)
  39. # internal links.
  40. for a in soup.findAll('a'):
  41. if a['href'].startswith('https://github.com/residuum/PuRestJson/wiki/'):
  42. a['href'] = a['href']\
  43. .replace('https://github.com/residuum/PuRestJson/wiki/', '')\
  44. .replace('%5B', '')\
  45. .replace('%5D', '')\
  46. .replace(':', '') + '.html'
  47. # images with link to itself.
  48. for img in soup.findAll('img'):
  49. if img['src'].startswith('https://camo.githubusercontent.com'):
  50. img['src'] = img['data-canonical-src']\
  51. .replace('https://raw.github.com/residuum/PuRestJson/master/manual/','')
  52. del img['data-canonical-src']
  53. a = img.parent
  54. del a['href']
  55. # write changes back to file
  56. htmlDoc.close()
  57. html = soup.prettify('utf-8')
  58. with open(exportDir + htmlFile, 'w') as edited:
  59. edited.write(html)
  60. os.rename(exportDir + "Home.html", exportDir + "index.html")