25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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