fabfile.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. ##### Configuration ##############################
  4. SHORT_PROJECT_NAME = 'python'
  5. FULL_PROJECT_NAME = 'byte_of_{}'.format(SHORT_PROJECT_NAME)
  6. # NOTE Slugs MUST be lower-case
  7. MARKDOWN_FILES = [
  8. {
  9. 'file': '01-frontpage.pd',
  10. 'slug': "python",
  11. 'title': "Python",
  12. },
  13. {
  14. 'file': '02-preface.pd',
  15. 'slug': "python_en-preface",
  16. 'title': "Python : Preface",
  17. },
  18. {
  19. 'file': '03-intro.pd',
  20. 'slug': "python_en-introduction",
  21. 'title': "Python : Introduction",
  22. },
  23. {
  24. 'file': '04-installation.pd',
  25. 'slug': "python_en-installation",
  26. 'title': "Python : Installation",
  27. },
  28. {
  29. 'file': '05-first-steps.pd',
  30. 'slug': "python_en-first_steps",
  31. 'title': "Python : First Steps",
  32. },
  33. {
  34. 'file': '06-basics.pd',
  35. 'slug': "python_en-basics",
  36. 'title': "Python : Basics",
  37. },
  38. {
  39. 'file': '07-operators-expressions.pd',
  40. 'slug': "python_en-operators_and_expressions",
  41. 'title': "Python : Operators and Expressions",
  42. },
  43. {
  44. 'file': '08-control-flow.pd',
  45. 'slug': "python_en-control_flow",
  46. 'title': "Python : Control Flow",
  47. },
  48. {
  49. 'file': '09-functions.pd',
  50. 'slug': "python_en-functions",
  51. 'title': "Python : Functions",
  52. },
  53. {
  54. 'file': '10-modules.pd',
  55. 'slug': "python_en-modules",
  56. 'title': "Python : Modules",
  57. },
  58. {
  59. 'file': '11-data-structures.pd',
  60. 'slug': "python_en-data_structures",
  61. 'title': "Python : Data Structures",
  62. },
  63. {
  64. 'file': '12-problem-solving.pd',
  65. 'slug': "python_en-problem_solving",
  66. 'title': "Python : Problem Solving",
  67. },
  68. {
  69. 'file': '13-oop.pd',
  70. 'slug': "python_en-object_oriented_programming",
  71. 'title': "Python : Object Oriented Programming",
  72. },
  73. {
  74. 'file': '14-io.pd',
  75. 'slug': "python_en-input_output",
  76. 'title': "Python : Input Output",
  77. },
  78. {
  79. 'file': '15-exceptions.pd',
  80. 'slug': "python_en-exceptions",
  81. 'title': "Python : Exceptions",
  82. },
  83. {
  84. 'file': '16-standard-library.pd',
  85. 'slug': "python_en-standard_library",
  86. 'title': "Python : Standard Library",
  87. },
  88. ]
  89. ## NOTES
  90. ## 1. This assumes that you have already created the S3 bucket whose name
  91. ## is stored in AWS_S3_BUCKET_NAME environment variable.
  92. ## 2. Under that S3 bucket, you have created a folder whose name is stored
  93. ## above as SHORT_PROJECT_NAME.
  94. ## 3. Under that S3 bucket, you have created a folder whose name is stored as
  95. ## SHORT_PROJECT_NAME/assets.
  96. ##### Imports ####################################
  97. import os
  98. import glob
  99. import subprocess
  100. try:
  101. from xmlrpc.client import ServerProxy
  102. except ImportError:
  103. from xmlrpclib import ServerProxy
  104. from pprint import pprint
  105. import boto
  106. import boto.s3.bucket
  107. import boto.s3.key
  108. from bs4 import BeautifulSoup
  109. from fabric.api import task, local
  110. ##### Start with checks ##########################
  111. for chapter in MARKDOWN_FILES:
  112. assert (chapter['slug'].lower() == chapter['slug']), \
  113. "Slug must be lower case : {}".format(chapter['slug'])
  114. if str(os.environ.get('AWS_ENABLED')).lower() == 'false':
  115. AWS_ENABLED = False
  116. elif os.environ.get('AWS_ACCESS_KEY_ID') is not None \
  117. and len(os.environ['AWS_ACCESS_KEY_ID']) > 0 \
  118. and os.environ.get('AWS_SECRET_ACCESS_KEY') is not None \
  119. and len(os.environ['AWS_SECRET_ACCESS_KEY']) > 0 \
  120. and os.environ.get('AWS_S3_BUCKET_NAME') is not None \
  121. and len(os.environ['AWS_S3_BUCKET_NAME']) > 0:
  122. AWS_ENABLED = True
  123. else:
  124. AWS_ENABLED = False
  125. print("NOTE: S3 uploading is disabled because of missing " +
  126. "AWS key environment variables.")
  127. # In my case, they are the same - 'files.swaroopch.com'
  128. # http://docs.amazonwebservices.com/AmazonS3/latest/dev/VirtualHosting.html#VirtualHostingCustomURLs
  129. S3_PUBLIC_URL = os.environ['AWS_S3_BUCKET_NAME']
  130. # else
  131. #S3_PUBLIC_URL = 's3.amazonaws.com/{}'.format(os.environ['AWS_S3_BUCKET_NAME'])
  132. if os.environ.get('WORDPRESS_RPC_URL') is not None \
  133. and len(os.environ['WORDPRESS_RPC_URL']) > 0 \
  134. and os.environ.get('WORDPRESS_BASE_URL') is not None \
  135. and len(os.environ['WORDPRESS_BASE_URL']) > 0 \
  136. and os.environ.get('WORDPRESS_BLOG_ID') is not None \
  137. and len(os.environ['WORDPRESS_BLOG_ID']) > 0 \
  138. and os.environ.get('WORDPRESS_USERNAME') is not None \
  139. and len(os.environ['WORDPRESS_USERNAME']) > 0 \
  140. and os.environ.get('WORDPRESS_PASSWORD') is not None \
  141. and len(os.environ['WORDPRESS_PASSWORD']) > 0 \
  142. and os.environ.get('WORDPRESS_PARENT_PAGE_ID') is not None \
  143. and len(os.environ['WORDPRESS_PARENT_PAGE_ID']) > 0 \
  144. and os.environ.get('WORDPRESS_PARENT_PAGE_SLUG') is not None \
  145. and len(os.environ['WORDPRESS_PARENT_PAGE_SLUG']) > 0:
  146. WORDPRESS_ENABLED = True
  147. else:
  148. WORDPRESS_ENABLED = False
  149. print("NOTE: Wordpress uploading is disabled because of " +
  150. "missing environment variables.")
  151. ##### Helper methods #############################
  152. def _upload_to_s3(filename, key):
  153. """http://docs.pythonboto.org/en/latest/s3_tut.html#storing-data"""
  154. conn = boto.connect_s3()
  155. b = boto.s3.bucket.Bucket(conn, os.environ['AWS_S3_BUCKET_NAME'])
  156. k = boto.s3.key.Key(b)
  157. k.key = key
  158. k.set_contents_from_filename(filename)
  159. k.set_acl('public-read')
  160. url = 'http://{}/{}'.format(S3_PUBLIC_URL, key)
  161. print("Uploaded to S3 : {}".format(url))
  162. return url
  163. def upload_output_to_s3(filename):
  164. key = "{}/{}".format(SHORT_PROJECT_NAME, filename.split('/')[-1])
  165. return _upload_to_s3(filename, key)
  166. def upload_asset_to_s3(filename):
  167. key = "{}/assets/{}".format(SHORT_PROJECT_NAME, filename.split('/')[-1])
  168. return _upload_to_s3(filename, key)
  169. def replace_images_with_s3_urls(text):
  170. """http://www.crummy.com/software/BeautifulSoup/bs4/doc/"""
  171. soup = BeautifulSoup(text)
  172. for image in soup.find_all('img'):
  173. image['src'] = upload_asset_to_s3(image['src'])
  174. return soup.prettify()
  175. def markdown_to_html(source_text, upload_assets_to_s3=False):
  176. """Convert from Markdown to HTML; optional: upload images, etc. to S3."""
  177. args = ['pandoc',
  178. '-f', 'markdown',
  179. '-t', 'html5']
  180. p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  181. output = p.communicate(source_text)[0]
  182. # http://wordpress.org/extend/plugins/raw-html/
  183. output = '<!--raw-->\n' + output + '\n<!--/raw-->'
  184. if upload_assets_to_s3:
  185. output = replace_images_with_s3_urls(output)
  186. return output
  187. def _wordpress_get_pages():
  188. server = ServerProxy(os.environ['WORDPRESS_RPC_URL'])
  189. print("(Fetching list of pages from WP)")
  190. return server.wp.getPosts(os.environ['WORDPRESS_BLOG_ID'],
  191. os.environ['WORDPRESS_USERNAME'],
  192. os.environ['WORDPRESS_PASSWORD'],
  193. {
  194. 'post_type': 'page',
  195. 'number': pow(10, 5),
  196. })
  197. def wordpress_new_page(slug, title, content):
  198. """Create a new Wordpress page.
  199. https://codex.wordpress.org/XML-RPC_WordPress_API/Posts#wp.newPost
  200. https://codex.wordpress.org/Function_Reference/wp_insert_post
  201. http://docs.python.org/library/xmlrpclib.html
  202. """
  203. server = ServerProxy(os.environ['WORDPRESS_RPC_URL'])
  204. return server.wp.newPost(os.environ['WORDPRESS_BLOG_ID'],
  205. os.environ['WORDPRESS_USERNAME'],
  206. os.environ['WORDPRESS_PASSWORD'],
  207. {
  208. 'post_name': slug,
  209. 'post_content': content,
  210. 'post_title': title,
  211. 'post_parent':
  212. os.environ['WORDPRESS_PARENT_PAGE_ID'],
  213. 'post_type': 'page',
  214. 'post_status': 'publish',
  215. 'comment_status': 'closed',
  216. 'ping_status': 'closed',
  217. })
  218. def wordpress_edit_page(post_id, title, content):
  219. """Edit a Wordpress page.
  220. https://codex.wordpress.org/XML-RPC_WordPress_API/Posts#wp.editPost
  221. https://codex.wordpress.org/Function_Reference/wp_insert_post
  222. http://docs.python.org/library/xmlrpclib.html
  223. """
  224. server = ServerProxy(os.environ['WORDPRESS_RPC_URL'])
  225. return server.wp.editPost(os.environ['WORDPRESS_BLOG_ID'],
  226. os.environ['WORDPRESS_USERNAME'],
  227. os.environ['WORDPRESS_PASSWORD'],
  228. post_id,
  229. {
  230. 'post_content': content,
  231. 'post_title': title,
  232. })
  233. ##### Tasks ######################################
  234. @task
  235. def wp():
  236. """https://codex.wordpress.org/XML-RPC_WordPress_API/Posts"""
  237. if WORDPRESS_ENABLED:
  238. existing_pages = _wordpress_get_pages()
  239. existing_page_slugs = [i.get('post_name') for i in existing_pages]
  240. def page_slug_to_id(slug):
  241. pages = [i for i in existing_pages if i.get('post_name') == slug]
  242. page = pages[0]
  243. return page['post_id']
  244. for chapter in MARKDOWN_FILES:
  245. html = markdown_to_html(open(chapter['file']).read(),
  246. upload_assets_to_s3=True)
  247. # TODO Add previous and next links at end of html
  248. if chapter['slug'] in existing_page_slugs:
  249. page_id = page_slug_to_id(chapter['slug'])
  250. print("Existing page to be updated: {} : {}".format(
  251. chapter['slug'],
  252. page_id))
  253. result = wordpress_edit_page(page_id,
  254. chapter['title'],
  255. html)
  256. print("Result: {}".format(result))
  257. else:
  258. print("New page to be created: {}".format(chapter['slug']))
  259. result = wordpress_new_page(chapter['slug'],
  260. chapter['title'],
  261. html)
  262. print("Result: {}".format(result))
  263. page_url = "{}/{}/{}".format(os.environ['WORDPRESS_BASE_URL'],
  264. os.environ['WORDPRESS_PARENT_PAGE_SLUG'],
  265. chapter['slug'])
  266. print(page_url)
  267. print()
  268. @task
  269. def html():
  270. """HTML5 output."""
  271. args = ['pandoc',
  272. '-f', 'markdown',
  273. '-t', 'html5',
  274. '-o', '{}.html'.format(FULL_PROJECT_NAME),
  275. '-s',
  276. '--toc'] + [i['file'] for i in MARKDOWN_FILES]
  277. local(' '.join(args))
  278. local('open {}.html'.format(FULL_PROJECT_NAME))
  279. @task
  280. def epub():
  281. """http://johnmacfarlane.net/pandoc/epub.html"""
  282. args = ['pandoc',
  283. '-f', 'markdown',
  284. '-t', 'epub',
  285. '-o', '{}.epub'.format(FULL_PROJECT_NAME)] + \
  286. [i['file'] for i in MARKDOWN_FILES]
  287. # TODO --epub-cover-image
  288. # TODO --epub-metadata
  289. # TODO --epub-stylesheet
  290. local(' '.join(args))
  291. if AWS_ENABLED:
  292. upload_output_to_s3('{}.epub'.format(FULL_PROJECT_NAME))
  293. @task
  294. def pdf():
  295. """http://johnmacfarlane.net/pandoc/README.html#creating-a-pdf"""
  296. args = ['pandoc',
  297. '-f', 'markdown',
  298. # https://github.com/jgm/pandoc/issues/571
  299. #'-t', 'pdf',
  300. '-o', '{}.pdf'.format(FULL_PROJECT_NAME)] + \
  301. [i['file'] for i in MARKDOWN_FILES]
  302. local(' '.join(args))
  303. if AWS_ENABLED:
  304. upload_output_to_s3('{}.pdf'.format(FULL_PROJECT_NAME))
  305. @task
  306. def docx():
  307. """OOXML document format."""
  308. args = ['pandoc',
  309. '-f', 'markdown',
  310. '-t', 'docx',
  311. '-o', '{}.docx'.format(FULL_PROJECT_NAME)] + \
  312. [i['file'] for i in MARKDOWN_FILES]
  313. local(' '.join(args))
  314. if AWS_ENABLED:
  315. upload_output_to_s3('{}.docx'.format(FULL_PROJECT_NAME))
  316. @task
  317. def odt():
  318. """OpenDocument document format."""
  319. args = ['pandoc',
  320. '-f', 'markdown',
  321. '-t', 'odt',
  322. '-o', '{}.odt'.format(FULL_PROJECT_NAME)] + \
  323. [i['file'] for i in MARKDOWN_FILES]
  324. local(' '.join(args))
  325. if AWS_ENABLED:
  326. upload_output_to_s3('{}.odt'.format(FULL_PROJECT_NAME))
  327. @task
  328. def clean():
  329. """Remove generated output files"""
  330. possible_outputs = (
  331. '{}.html'.format(FULL_PROJECT_NAME),
  332. '{}.epub'.format(FULL_PROJECT_NAME),
  333. '{}.pdf'.format(FULL_PROJECT_NAME),
  334. '{}.docx'.format(FULL_PROJECT_NAME),
  335. '{}.odt'.format(FULL_PROJECT_NAME),
  336. )
  337. for filename in possible_outputs:
  338. if os.path.exists(filename):
  339. os.remove(filename)
  340. print("Removed {}".format(filename))