fabfile.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. 'file': '17-more.pd',
  90. 'slug': "python_en-more",
  91. 'title': "Python : More",
  92. },
  93. {
  94. 'file': '18-what-next.pd',
  95. 'slug': "python_en-what_next",
  96. 'title': "Python : What Next",
  97. },
  98. {
  99. 'file': '19-appendix-floss.pd',
  100. 'slug': "python_en-appendix_floss",
  101. 'title': "Python : Appendix : FLOSS",
  102. },
  103. {
  104. 'file': '20-appendix-about.pd',
  105. 'slug': "python_en-appendix_about",
  106. 'title': "Python : Appendix : About",
  107. },
  108. {
  109. 'file': '21-revision-history.pd',
  110. 'slug': "python_en-appendix_revision_history",
  111. 'title': "Python : Appendix : Revision History",
  112. },
  113. ]
  114. ## NOTES
  115. ## 1. This assumes that you have already created the S3 bucket whose name
  116. ## is stored in AWS_S3_BUCKET_NAME environment variable.
  117. ## 2. Under that S3 bucket, you have created a folder whose name is stored
  118. ## above as SHORT_PROJECT_NAME.
  119. ## 3. Under that S3 bucket, you have created a folder whose name is stored as
  120. ## SHORT_PROJECT_NAME/assets.
  121. ##### Imports ####################################
  122. import os
  123. import glob
  124. import subprocess
  125. try:
  126. from xmlrpc.client import ServerProxy
  127. except ImportError:
  128. from xmlrpclib import ServerProxy
  129. from pprint import pprint
  130. import boto
  131. import boto.s3.bucket
  132. import boto.s3.key
  133. from bs4 import BeautifulSoup
  134. from fabric.api import task, local
  135. ##### Start with checks ##########################
  136. for chapter in MARKDOWN_FILES:
  137. assert (chapter['slug'].lower() == chapter['slug']), \
  138. "Slug must be lower case : {}".format(chapter['slug'])
  139. if str(os.environ.get('AWS_ENABLED')).lower() == 'false':
  140. AWS_ENABLED = False
  141. elif os.environ.get('AWS_ACCESS_KEY_ID') is not None \
  142. and len(os.environ['AWS_ACCESS_KEY_ID']) > 0 \
  143. and os.environ.get('AWS_SECRET_ACCESS_KEY') is not None \
  144. and len(os.environ['AWS_SECRET_ACCESS_KEY']) > 0 \
  145. and os.environ.get('AWS_S3_BUCKET_NAME') is not None \
  146. and len(os.environ['AWS_S3_BUCKET_NAME']) > 0:
  147. AWS_ENABLED = True
  148. else:
  149. AWS_ENABLED = False
  150. print("NOTE: S3 uploading is disabled because of missing " +
  151. "AWS key environment variables.")
  152. # In my case, they are the same - 'files.swaroopch.com'
  153. # http://docs.amazonwebservices.com/AmazonS3/latest/dev/VirtualHosting.html#VirtualHostingCustomURLs
  154. S3_PUBLIC_URL = os.environ['AWS_S3_BUCKET_NAME']
  155. # else
  156. #S3_PUBLIC_URL = 's3.amazonaws.com/{}'.format(os.environ['AWS_S3_BUCKET_NAME'])
  157. if os.environ.get('WORDPRESS_RPC_URL') is not None \
  158. and len(os.environ['WORDPRESS_RPC_URL']) > 0 \
  159. and os.environ.get('WORDPRESS_BASE_URL') is not None \
  160. and len(os.environ['WORDPRESS_BASE_URL']) > 0 \
  161. and os.environ.get('WORDPRESS_BLOG_ID') is not None \
  162. and len(os.environ['WORDPRESS_BLOG_ID']) > 0 \
  163. and os.environ.get('WORDPRESS_USERNAME') is not None \
  164. and len(os.environ['WORDPRESS_USERNAME']) > 0 \
  165. and os.environ.get('WORDPRESS_PASSWORD') is not None \
  166. and len(os.environ['WORDPRESS_PASSWORD']) > 0 \
  167. and os.environ.get('WORDPRESS_PARENT_PAGE_ID') is not None \
  168. and len(os.environ['WORDPRESS_PARENT_PAGE_ID']) > 0 \
  169. and os.environ.get('WORDPRESS_PARENT_PAGE_SLUG') is not None \
  170. and len(os.environ['WORDPRESS_PARENT_PAGE_SLUG']) > 0:
  171. WORDPRESS_ENABLED = True
  172. else:
  173. WORDPRESS_ENABLED = False
  174. print("NOTE: Wordpress uploading is disabled because of " +
  175. "missing environment variables.")
  176. ##### Helper methods #############################
  177. def _upload_to_s3(filename, key):
  178. """http://docs.pythonboto.org/en/latest/s3_tut.html#storing-data"""
  179. conn = boto.connect_s3()
  180. b = boto.s3.bucket.Bucket(conn, os.environ['AWS_S3_BUCKET_NAME'])
  181. k = boto.s3.key.Key(b)
  182. k.key = key
  183. k.set_contents_from_filename(filename)
  184. k.set_acl('public-read')
  185. url = 'http://{}/{}'.format(S3_PUBLIC_URL, key)
  186. print("Uploaded to S3 : {}".format(url))
  187. return url
  188. def upload_output_to_s3(filename):
  189. key = "{}/{}".format(SHORT_PROJECT_NAME, filename.split('/')[-1])
  190. return _upload_to_s3(filename, key)
  191. def upload_asset_to_s3(filename):
  192. key = "{}/assets/{}".format(SHORT_PROJECT_NAME, filename.split('/')[-1])
  193. return _upload_to_s3(filename, key)
  194. def replace_images_with_s3_urls(text):
  195. """http://www.crummy.com/software/BeautifulSoup/bs4/doc/"""
  196. soup = BeautifulSoup(text)
  197. for image in soup.find_all('img'):
  198. image['src'] = upload_asset_to_s3(image['src'])
  199. return soup.prettify()
  200. def markdown_to_html(source_text, upload_assets_to_s3=False):
  201. """Convert from Markdown to HTML; optional: upload images, etc. to S3."""
  202. args = ['pandoc',
  203. '-f', 'markdown',
  204. '-t', 'html5']
  205. p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  206. output = p.communicate(source_text)[0]
  207. # http://wordpress.org/extend/plugins/raw-html/
  208. output = '<!--raw-->\n' + output + '\n<!--/raw-->'
  209. if upload_assets_to_s3:
  210. output = replace_images_with_s3_urls(output)
  211. return output
  212. def _wordpress_get_pages():
  213. server = ServerProxy(os.environ['WORDPRESS_RPC_URL'])
  214. print("(Fetching list of pages from WP)")
  215. return server.wp.getPosts(os.environ['WORDPRESS_BLOG_ID'],
  216. os.environ['WORDPRESS_USERNAME'],
  217. os.environ['WORDPRESS_PASSWORD'],
  218. {
  219. 'post_type': 'page',
  220. 'number': pow(10, 5),
  221. })
  222. def wordpress_new_page(slug, title, content):
  223. """Create a new Wordpress page.
  224. https://codex.wordpress.org/XML-RPC_WordPress_API/Posts#wp.newPost
  225. https://codex.wordpress.org/Function_Reference/wp_insert_post
  226. http://docs.python.org/library/xmlrpclib.html
  227. """
  228. server = ServerProxy(os.environ['WORDPRESS_RPC_URL'])
  229. return server.wp.newPost(os.environ['WORDPRESS_BLOG_ID'],
  230. os.environ['WORDPRESS_USERNAME'],
  231. os.environ['WORDPRESS_PASSWORD'],
  232. {
  233. 'post_name': slug,
  234. 'post_content': content,
  235. 'post_title': title,
  236. 'post_parent':
  237. os.environ['WORDPRESS_PARENT_PAGE_ID'],
  238. 'post_type': 'page',
  239. 'post_status': 'publish',
  240. 'comment_status': 'closed',
  241. 'ping_status': 'closed',
  242. })
  243. def wordpress_edit_page(post_id, title, content):
  244. """Edit a Wordpress page.
  245. https://codex.wordpress.org/XML-RPC_WordPress_API/Posts#wp.editPost
  246. https://codex.wordpress.org/Function_Reference/wp_insert_post
  247. http://docs.python.org/library/xmlrpclib.html
  248. """
  249. server = ServerProxy(os.environ['WORDPRESS_RPC_URL'])
  250. return server.wp.editPost(os.environ['WORDPRESS_BLOG_ID'],
  251. os.environ['WORDPRESS_USERNAME'],
  252. os.environ['WORDPRESS_PASSWORD'],
  253. post_id,
  254. {
  255. 'post_content': content,
  256. 'post_title': title,
  257. })
  258. ##### Tasks ######################################
  259. @task
  260. def wp():
  261. """https://codex.wordpress.org/XML-RPC_WordPress_API/Posts"""
  262. if WORDPRESS_ENABLED:
  263. existing_pages = _wordpress_get_pages()
  264. existing_page_slugs = [i.get('post_name') for i in existing_pages]
  265. def page_slug_to_id(slug):
  266. pages = [i for i in existing_pages if i.get('post_name') == slug]
  267. page = pages[0]
  268. return page['post_id']
  269. for chapter in MARKDOWN_FILES:
  270. html = markdown_to_html(open(chapter['file']).read(),
  271. upload_assets_to_s3=True)
  272. # TODO Add previous and next links at end of html
  273. if chapter['slug'] in existing_page_slugs:
  274. page_id = page_slug_to_id(chapter['slug'])
  275. print("Existing page to be updated: {} : {}".format(
  276. chapter['slug'],
  277. page_id))
  278. result = wordpress_edit_page(page_id,
  279. chapter['title'],
  280. html)
  281. print("Result: {}".format(result))
  282. else:
  283. print("New page to be created: {}".format(chapter['slug']))
  284. result = wordpress_new_page(chapter['slug'],
  285. chapter['title'],
  286. html)
  287. print("Result: {}".format(result))
  288. page_url = "{}/{}/{}".format(os.environ['WORDPRESS_BASE_URL'],
  289. os.environ['WORDPRESS_PARENT_PAGE_SLUG'],
  290. chapter['slug'])
  291. print(page_url)
  292. print()
  293. @task
  294. def html():
  295. """HTML5 output."""
  296. args = ['pandoc',
  297. '-f', 'markdown',
  298. '-t', 'html5',
  299. '-o', '{}.html'.format(FULL_PROJECT_NAME),
  300. '-s',
  301. '--toc'] + [i['file'] for i in MARKDOWN_FILES]
  302. local(' '.join(args))
  303. local('open {}.html'.format(FULL_PROJECT_NAME))
  304. @task
  305. def epub():
  306. """http://johnmacfarlane.net/pandoc/epub.html"""
  307. args = ['pandoc',
  308. '-f', 'markdown',
  309. '-t', 'epub',
  310. '-o', '{}.epub'.format(FULL_PROJECT_NAME)] + \
  311. [i['file'] for i in MARKDOWN_FILES]
  312. # TODO --epub-cover-image
  313. # TODO --epub-metadata
  314. # TODO --epub-stylesheet
  315. local(' '.join(args))
  316. if AWS_ENABLED:
  317. upload_output_to_s3('{}.epub'.format(FULL_PROJECT_NAME))
  318. @task
  319. def pdf():
  320. """http://johnmacfarlane.net/pandoc/README.html#creating-a-pdf"""
  321. args = ['pandoc',
  322. '-f', 'markdown',
  323. # https://github.com/jgm/pandoc/issues/571
  324. #'-t', 'pdf',
  325. '-o', '{}.pdf'.format(FULL_PROJECT_NAME)] + \
  326. [i['file'] for i in MARKDOWN_FILES]
  327. local(' '.join(args))
  328. if AWS_ENABLED:
  329. upload_output_to_s3('{}.pdf'.format(FULL_PROJECT_NAME))
  330. @task
  331. def docx():
  332. """OOXML document format."""
  333. args = ['pandoc',
  334. '-f', 'markdown',
  335. '-t', 'docx',
  336. '-o', '{}.docx'.format(FULL_PROJECT_NAME)] + \
  337. [i['file'] for i in MARKDOWN_FILES]
  338. local(' '.join(args))
  339. if AWS_ENABLED:
  340. upload_output_to_s3('{}.docx'.format(FULL_PROJECT_NAME))
  341. @task
  342. def odt():
  343. """OpenDocument document format."""
  344. args = ['pandoc',
  345. '-f', 'markdown',
  346. '-t', 'odt',
  347. '-o', '{}.odt'.format(FULL_PROJECT_NAME)] + \
  348. [i['file'] for i in MARKDOWN_FILES]
  349. local(' '.join(args))
  350. if AWS_ENABLED:
  351. upload_output_to_s3('{}.odt'.format(FULL_PROJECT_NAME))
  352. @task
  353. def clean():
  354. """Remove generated output files"""
  355. possible_outputs = (
  356. '{}.html'.format(FULL_PROJECT_NAME),
  357. '{}.epub'.format(FULL_PROJECT_NAME),
  358. '{}.pdf'.format(FULL_PROJECT_NAME),
  359. '{}.docx'.format(FULL_PROJECT_NAME),
  360. '{}.odt'.format(FULL_PROJECT_NAME),
  361. )
  362. for filename in possible_outputs:
  363. if os.path.exists(filename):
  364. os.remove(filename)
  365. print("Removed {}".format(filename))