You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

446 line
14 KiB

  1. """Automatically setup docs for a project
  2. Call from command line:
  3. bench setup-docs app path
  4. """
  5. import os, json, frappe, shutil, re
  6. from frappe.website.context import get_context
  7. from frappe.utils import markdown
  8. class setup_docs(object):
  9. def __init__(self, app):
  10. """Generate source templates for models reference and module API
  11. and templates at `templates/autodoc`
  12. """
  13. self.app = app
  14. frappe.local.flags.web_pages_folders = ['docs',]
  15. frappe.local.flags.web_pages_apps = [self.app,]
  16. self.hooks = frappe.get_hooks(app_name = self.app)
  17. self.app_title = self.hooks.get("app_title")[0]
  18. self.setup_app_context()
  19. def setup_app_context(self):
  20. self.docs_config = frappe.get_module(self.app + ".config.docs")
  21. version = self.hooks.get("app_version")[0]
  22. self.app_context = {
  23. "app": frappe._dict({
  24. "name": self.app,
  25. "title": self.app_title,
  26. "description": self.hooks.get("app_description")[0],
  27. "version": version,
  28. "publisher": self.hooks.get("app_publisher")[0],
  29. "icon": self.hooks.get("app_icon")[0],
  30. "email": self.hooks.get("app_email")[0],
  31. "headline": self.docs_config.headline,
  32. "sub_heading": self.docs_config.sub_heading,
  33. "source_link": self.docs_config.source_link,
  34. "hide_install": getattr(self.docs_config, "hide_install", False),
  35. "docs_base_url": self.docs_config.docs_base_url,
  36. "long_description": markdown(getattr(self.docs_config, "long_description", "")),
  37. "license": self.hooks.get("app_license")[0],
  38. "branch": getattr(self.docs_config, "branch", None) or "develop",
  39. "style": getattr(self.docs_config, "style", "")
  40. }),
  41. "metatags": {
  42. "description": self.hooks.get("app_description")[0],
  43. },
  44. "get_doctype_app": frappe.get_doctype_app
  45. }
  46. def build(self, docs_version):
  47. """Build templates for docs models and Python API"""
  48. self.docs_path = frappe.get_app_path(self.app, "docs")
  49. self.path = os.path.join(self.docs_path, docs_version)
  50. self.app_context["app"]["docs_version"] = docs_version
  51. self.app_title = self.hooks.get("app_title")[0]
  52. self.app_path = frappe.get_app_path(self.app)
  53. print "Deleting current..."
  54. shutil.rmtree(self.path, ignore_errors = True)
  55. os.makedirs(self.path)
  56. self.make_home_pages()
  57. for basepath, folders, files in os.walk(self.app_path):
  58. # make module home page
  59. if "/doctype/" not in basepath and "doctype" in folders:
  60. module = os.path.basename(basepath)
  61. module_folder = os.path.join(self.models_base_path, module)
  62. self.make_folder(module_folder,
  63. template = "templates/autodoc/module_home.html",
  64. context = {"name": module})
  65. self.update_index_txt(module_folder)
  66. # make for model files
  67. if "/doctype/" in basepath:
  68. parts = basepath.split("/")
  69. #print parts
  70. module, doctype = parts[-3], parts[-1]
  71. if doctype not in ("doctype", "boilerplate"):
  72. self.write_model_file(basepath, module, doctype)
  73. # standard python module
  74. if self.is_py_module(basepath, folders, files):
  75. self.write_modules(basepath, folders, files)
  76. self.build_user_docs()
  77. def make_home_pages(self):
  78. """Make standard home pages for docs, developer docs, api and models
  79. from templates"""
  80. # make dev home page
  81. with open(os.path.join(self.docs_path, "index.html"), "w") as home:
  82. home.write(frappe.render_template("templates/autodoc/docs_home.html",
  83. self.app_context))
  84. # make dev home page
  85. with open(os.path.join(self.path, "index.html"), "w") as home:
  86. home.write(frappe.render_template("templates/autodoc/dev_home.html",
  87. self.app_context))
  88. # make folders
  89. self.models_base_path = os.path.join(self.path, "models")
  90. self.make_folder(self.models_base_path,
  91. template = "templates/autodoc/models_home.html")
  92. self.api_base_path = os.path.join(self.path, "api")
  93. self.make_folder(self.api_base_path,
  94. template = "templates/autodoc/api_home.html")
  95. # make /user
  96. user_path = os.path.join(self.docs_path, "user")
  97. if not os.path.exists(user_path):
  98. os.makedirs(user_path)
  99. # make /assets/img
  100. img_path = os.path.join(self.docs_path, "assets", "img")
  101. if not os.path.exists(img_path):
  102. os.makedirs(img_path)
  103. def build_user_docs(self):
  104. """Build templates for user docs pages, if missing."""
  105. #user_docs_path = os.path.join(self.docs_path, "user")
  106. # license
  107. with open(os.path.join(self.app_path, "..", "license.txt"), "r") as license_file:
  108. self.app_context["license_text"] = markdown(license_file.read())
  109. html = frappe.render_template("templates/autodoc/license.html",
  110. context = self.app_context)
  111. with open(os.path.join(self.docs_path, "license.html"), "w") as license_file:
  112. license_file.write(html.encode("utf-8"))
  113. # contents
  114. shutil.copy(os.path.join(frappe.get_app_path("frappe", "templates", "autodoc",
  115. "contents.html")), os.path.join(self.docs_path, "contents.html"))
  116. shutil.copy(os.path.join(frappe.get_app_path("frappe", "templates", "autodoc",
  117. "contents.py")), os.path.join(self.docs_path, "contents.py"))
  118. # install
  119. html = frappe.render_template("templates/autodoc/install.md",
  120. context = self.app_context)
  121. with open(os.path.join(self.docs_path, "install.md"), "w") as f:
  122. f.write(html)
  123. self.update_index_txt(self.docs_path)
  124. def make_docs(self, target, local = False):
  125. self.target = target
  126. self.local = local
  127. if self.local:
  128. self.docs_base_url = ""
  129. else:
  130. self.docs_base_url = self.docs_config.docs_base_url
  131. # add for processing static files (full-index)
  132. frappe.local.docs_base_url = self.docs_base_url
  133. # write in target path
  134. self.write_files()
  135. # copy assets/js, assets/css, assets/img
  136. self.copy_assets()
  137. def is_py_module(self, basepath, folders, files):
  138. return "__init__.py" in files \
  139. and (not "/doctype" in basepath) \
  140. and (not "/patches" in basepath) \
  141. and (not "/change_log" in basepath) \
  142. and (not "/report" in basepath) \
  143. and (not "/page" in basepath) \
  144. and (not "/templates" in basepath) \
  145. and (not "/tests" in basepath) \
  146. and (not "/docs" in basepath)
  147. def write_modules(self, basepath, folders, files):
  148. module_folder = os.path.join(self.api_base_path, os.path.relpath(basepath, self.app_path))
  149. self.make_folder(module_folder)
  150. for f in files:
  151. if f.endswith(".py"):
  152. module_name = os.path.relpath(os.path.join(basepath, f),
  153. self.app_path)[:-3].replace("/", ".").replace(".__init__", "")
  154. module_doc_path = os.path.join(module_folder,
  155. self.app + "." + module_name + ".html")
  156. self.make_folder(basepath)
  157. if not os.path.exists(module_doc_path):
  158. print "Writing " + module_doc_path
  159. with open(module_doc_path, "w") as f:
  160. context = {"name": self.app + "." + module_name}
  161. context.update(self.app_context)
  162. f.write(frappe.render_template("templates/autodoc/pymodule.html",
  163. context))
  164. self.update_index_txt(module_folder)
  165. def make_folder(self, path, template=None, context=None):
  166. if not template:
  167. template = "templates/autodoc/package_index.html"
  168. if not os.path.exists(path):
  169. os.makedirs(path)
  170. index_txt_path = os.path.join(path, "index.txt")
  171. print "Writing " + index_txt_path
  172. with open(index_txt_path, "w") as f:
  173. f.write("")
  174. index_html_path = os.path.join(path, "index.html")
  175. if not context:
  176. name = os.path.basename(path)
  177. if name==".":
  178. name = self.app
  179. context = {
  180. "title": name
  181. }
  182. context.update(self.app_context)
  183. print "Writing " + index_html_path
  184. with open(index_html_path, "w") as f:
  185. f.write(frappe.render_template(template, context))
  186. def update_index_txt(self, path):
  187. index_txt_path = os.path.join(path, "index.txt")
  188. pages = filter(lambda d: ((d.endswith(".html") or d.endswith(".md")) and d not in ("index.html",)) \
  189. or os.path.isdir(os.path.join(path, d)), os.listdir(path))
  190. pages = [d.rsplit(".", 1)[0] for d in pages]
  191. index_parts = []
  192. if os.path.exists(index_txt_path):
  193. with open(index_txt_path, "r") as f:
  194. index_parts = filter(None, f.read().splitlines())
  195. if not set(pages).issubset(set(index_parts)):
  196. print "Updating " + index_txt_path
  197. with open(index_txt_path, "w") as f:
  198. f.write("\n".join(pages))
  199. def write_model_file(self, basepath, module, doctype):
  200. model_path = os.path.join(self.models_base_path, module, doctype + ".html")
  201. if not os.path.exists(model_path):
  202. model_json_path = os.path.join(basepath, doctype + ".json")
  203. if os.path.exists(model_json_path):
  204. with open(model_json_path, "r") as j:
  205. doctype_real_name = json.loads(j.read()).get("name")
  206. print "Writing " + model_path
  207. with open(model_path, "w") as f:
  208. context = {"doctype": doctype_real_name}
  209. context.update(self.app_context)
  210. f.write(frappe.render_template("templates/autodoc/doctype.html",
  211. context).encode("utf-8"))
  212. def write_files(self):
  213. """render templates and write files to target folder"""
  214. frappe.local.flags.home_page = "index"
  215. from frappe.website.router import get_pages, make_toc
  216. pages = get_pages()
  217. # clear the user, current folder in target
  218. shutil.rmtree(os.path.join(self.target, "user"), ignore_errors=True)
  219. shutil.rmtree(os.path.join(self.target, "current"), ignore_errors=True)
  220. cnt = 0
  221. for path, context in pages.iteritems():
  222. print "Writing {0}".format(path)
  223. # set this for get_context / website libs
  224. frappe.local.path = path
  225. context.update({
  226. "page_links_with_extn": True,
  227. "relative_links": True,
  228. "docs_base_url": self.docs_base_url,
  229. "url_prefix": self.docs_base_url,
  230. })
  231. context.update(self.app_context)
  232. context = get_context(path, context)
  233. if context.basename:
  234. target_path_fragment = context.route + '.html'
  235. else:
  236. # index.html
  237. target_path_fragment = context.route + '/index.html'
  238. target_filename = os.path.join(self.target, target_path_fragment.strip('/'))
  239. context.brand_html = context.top_bar_items = context.favicon = None
  240. self.docs_config.get_context(context)
  241. if not context.brand_html:
  242. if context.docs_icon:
  243. context.brand_html = '<i class="{0}"></i> {1}'.format(context.docs_icon, context.app.title)
  244. else:
  245. context.brand_html = context.app.title
  246. if not context.top_bar_items:
  247. context.top_bar_items = [
  248. # {"label": "Contents", "url": self.docs_base_url + "/contents.html", "right": 1},
  249. {"label": "User Guide", "url": self.docs_base_url + "/user", "right": 1},
  250. {"label": "Developer Docs", "url": self.docs_base_url + "/current", "right": 1},
  251. ]
  252. context.top_bar_items = [{"label": '<i class="octicon octicon-search"></i>', "url": "#",
  253. "right": 1}] + context.top_bar_items
  254. context.parents = []
  255. parent_route = os.path.dirname(context.route)
  256. if pages[parent_route]:
  257. context.parents = [pages[parent_route]]
  258. if not context.favicon:
  259. context.favicon = "/assets/img/favicon.ico"
  260. context.only_static = True
  261. context.base_template_path = "templates/autodoc/base_template.html"
  262. if '<code>' in context.source:
  263. context.source = re.sub('\<code\>(.*)\</code\>', '<code>{% raw %}\g<1>{% endraw %}</code>', context.source)
  264. html = frappe.render_template(context.source, context)
  265. html = make_toc(context, html)
  266. if not "<!-- autodoc -->" in html:
  267. html = html.replace('<!-- edit-link -->',
  268. edit_link.format(\
  269. source_link = self.docs_config.source_link,
  270. app_name = self.app,
  271. branch = context.app.branch,
  272. target = context.template))
  273. if not os.path.exists(os.path.dirname(target_filename)):
  274. os.makedirs(os.path.dirname(target_filename))
  275. with open(target_filename, "w") as htmlfile:
  276. htmlfile.write(html.encode("utf-8"))
  277. cnt += 1
  278. print "Wrote {0} files".format(cnt)
  279. def copy_assets(self):
  280. """Copy jquery, bootstrap and other assets to files"""
  281. print "Copying assets..."
  282. assets_path = os.path.join(self.target, "assets")
  283. # copy assets from docs
  284. source_assets = frappe.get_app_path(self.app, "docs", "assets")
  285. if os.path.exists(source_assets):
  286. for basepath, folders, files in os.walk(source_assets):
  287. target_basepath = os.path.join(assets_path, os.path.relpath(basepath, source_assets))
  288. # make the base folder
  289. if not os.path.exists(target_basepath):
  290. os.makedirs(target_basepath)
  291. # copy all files in the current folder
  292. for f in files:
  293. shutil.copy(os.path.join(basepath, f), os.path.join(target_basepath, f))
  294. # make missing folders
  295. for fname in ("js", "css", "img"):
  296. path = os.path.join(assets_path, fname)
  297. if not os.path.exists(path):
  298. os.makedirs(path)
  299. copy_files = {
  300. "js/lib/jquery/jquery.min.js": "js/jquery.min.js",
  301. "js/lib/bootstrap.min.js": "js/bootstrap.min.js",
  302. "js/lib/highlight.pack.js": "js/highlight.pack.js",
  303. "js/docs.js": "js/docs.js",
  304. "css/bootstrap.css": "css/bootstrap.css",
  305. "css/font-awesome.css": "css/font-awesome.css",
  306. "css/docs.css": "css/docs.css",
  307. "css/hljs.css": "css/hljs.css",
  308. "css/font": "css/font",
  309. "css/octicons": "css/octicons",
  310. # always overwrite octicons.css to fix the path
  311. "css/octicons/octicons.css": "css/octicons/octicons.css",
  312. "images/frappe-bird-grey.svg": "img/frappe-bird-grey.svg",
  313. "images/background.png": "img/background.png",
  314. "images/smiley.png": "img/smiley.png",
  315. "images/up.png": "img/up.png"
  316. }
  317. for source, target in copy_files.iteritems():
  318. source_path = frappe.get_app_path("frappe", "public", source)
  319. if os.path.isdir(source_path):
  320. if not os.path.exists(os.path.join(assets_path, target)):
  321. shutil.copytree(source_path, os.path.join(assets_path, target))
  322. else:
  323. shutil.copy(source_path, os.path.join(assets_path, target))
  324. # fix path for font-files, background
  325. files = (
  326. os.path.join(assets_path, "css", "octicons", "octicons.css"),
  327. os.path.join(assets_path, "css", "font-awesome.css"),
  328. os.path.join(assets_path, "css", "docs.css"),
  329. )
  330. for path in files:
  331. with open(path, "r") as css_file:
  332. text = css_file.read()
  333. with open(path, "w") as css_file:
  334. if "docs.css" in path:
  335. css_file.write(text.replace("/assets/img/",
  336. self.docs_base_url + '/assets/img/'))
  337. else:
  338. css_file.write(text.replace("/assets/frappe/", self.docs_base_url + '/assets/'))
  339. edit_link = '''
  340. <div class="page-container">
  341. <div class="page-content">
  342. <div class="edit-container text-center">
  343. <i class="icon icon-smile"></i>
  344. <a class="text-muted edit" href="{source_link}/blob/{branch}/{app_name}/{target}">
  345. Improve this page
  346. </a>
  347. </div>
  348. </div>
  349. </div>'''