Permalink
Browse files

Lots of cleanup of file layout based on http://sayspy.blogspot.com/20…

…10/03/various-ways-of-distributing-python.html

Might be runnable from a Zip file now but that's not tested.
Removed todos about loading into and out of Calibre.
  • Loading branch information...
1 parent 71ede57 commit b9d2bc3d53ab4e7f94be8c11167fcd44e390494e @bkidwell committed Jan 29, 2012
View
@@ -1,2 +1,5 @@
*.pyc
-
+sample/Alice in Wonderland/Alice's Adventures in Wonderland.epub
+sample/Alice in Wonderland/Alice's Adventures in Wonderland.html
+sample/Alice in Wonderland/Alice's Adventures in Wonderland.zip
+mdepub.komodoproject
View
@@ -1,5 +1 @@
# Todo
-
-* add action to insert/update epub file in Calibre
-* add action to extract epub file from Calibre
-* clean up argument parsing -- create separate argument parser structure for each available action
View
@@ -0,0 +1,14 @@
+#!/usr/bin/env python
+import os
+import runpy
+
+PKG = 'mdepub'
+
+try:
+ run_globals = runpy.run_module(PKG, run_name='__main__', alter_sys=True)
+ executed = os.path.splitext(os.path.basename(run_globals['__file__']))[0]
+ if executed != '__main__': # For Python 2.5 compatibility
+ raise ImportError('Incorrectly executed %s instead of __main__' %
+ executed)
+except ImportError: # For Python 2.6 compatibility
+ runpy.run_module('%s.__main__' % PKG, run_name='__main__', alter_sys=True)
View
@@ -1,14 +0,0 @@
-#!/usr/bin/env python
-
-import logging
-import mdepub
-import yaml
-import mdepub.actions
-import sys
-
-log = logging.getLogger('main')
-
-log.debug("Arguments: %s", repr(mdepub.arguments))
-
-for action in mdepub.arguments.action:
- getattr(mdepub.actions, action).run()
View
@@ -1,47 +1,69 @@
+"""
+mdepub package
+"""
+
+VERSION = "0.1"
+PROGRAM_NAME = "mdepub"
+
+options = None # global container for project options
+options_loaded = None
+project_path = None # defaults to current working directory
+arguments = None # global container for command line arguments
+log = None
+
import logging
import os
+import sys
+import uuid
import yaml
from mdepub.argumentparser import ArgumentParser
-options = None
-import filename
-import uuid
-import sys
-
-VERSION = "0.1"
+import mdepub.filename
def new_id():
+ """Generate a new random UUID"""
+
return uuid.uuid4()
-logging.basicConfig(level=logging.DEBUG)
-log = logging.getLogger('mdepub')
-
-project_path = os.getcwd()
-log.debug("Working path: %s", project_path)
-
-options_file = os.path.join(project_path, "options.yaml")
-options_loaded = False
-if os.path.exists(options_file):
- options_loaded = True
- log.debug("Loading options.yaml")
- options = yaml.load(open("options.yaml"))
- if VERSION.split(".") < (options.get("require mdepub version") or "").split("."):
- log.fatal("This project requires at least version %s of mdepub.", options["require mdepub version"])
- sys.exit(1)
- #print yaml.dump(options)
- #print options.keys()
- if not options.get('filename'):
- options['filename'] = filename.clean(options['title'])
- log.debug("Filename: %s", options['filename'])
-else:
- options = yaml.load("dummy: 0")
- log.debug("options.yaml not found")
-
-arguments = ArgumentParser().parse_args()
-
-if arguments.filename:
- options['filename'] = arguments.filename
+def init():
+ """Initialize mdepub package and populate options variable."""
+
+ global options
+ global project_path
+ global arguments
+ global log
+ global options_loaded
+
+ logging.basicConfig(level=logging.DEBUG)
+ log = logging.getLogger('mdepub')
+
+ project_path = os.getcwd()
+ log.debug("Working path: %s", project_path)
+
+ options_file = os.path.join(project_path, "options.yaml")
+ options_loaded = False
+ if os.path.exists(options_file):
+ options_loaded = True
+ log.debug("Loading options.yaml")
+ options = yaml.load(open("options.yaml"))
+ if VERSION.split(".") < (options.get("require mdepub version") or "").split("."):
+ log.fatal("This project requires at least version %s of mdepub.", options["require mdepub version"])
+ sys.exit(1)
+ #print yaml.dump(options)
+ #print options.keys()
+ if not options.get('filename'):
+ options['filename'] = filename.clean(options['title'])
+ log.debug("Filename: %s", options['filename'])
+ else:
+ options = yaml.load("dummy: 0")
+ log.debug("options.yaml not found.")
+
+ arguments = ArgumentParser().parse_args()
+ if arguments.filename:
+ options['filename'] = arguments.filename
def require_opts_file():
+ """Exit with error message of an options file was not found for this project."""
+
if options_loaded: return
log.fatal("No options.yaml file found for this project.")
sys.exit(1)
View
@@ -0,0 +1,20 @@
+"""Use Pandoc and Calibre to compile Markdown text to Epub, with source included in the Epub."""
+
+import logging
+import sys
+import yaml
+import mdepub
+import mdepub.actions
+
+def main():
+ log = logging.getLogger('__main__')
+
+ mdepub.init()
+
+ log.debug("Arguments: %s", repr(mdepub.arguments))
+
+ for action in mdepub.arguments.action:
+ getattr(mdepub.actions, action).run()
+
+if __name__ == '__main__':
+ main()
@@ -1,8 +1,10 @@
+"""mdepub actions -- these modules do the actual work."""
+
+import archive
import clean
-import html
+import create
import epub
-import archive
+import extract
+import html
import newid
import version
-import create
-import extract
@@ -1,15 +1,20 @@
+"""Archive source files to zip file."""
+
import logging
-import mdepub
-from mdepub import shell
import os
-from mdepub import options
-from mdepub import project_path
from zipfile import ZipFile
+import mdepub
+from mdepub import shell
from mdepub.filename import getFN
log = logging.getLogger('archive')
def run():
+ """Run this action."""
+
+ options = mdepub.options
+ project_path = mdepub.project_path
+
log.debug("run()")
mdepub.require_opts_file()
@@ -1,15 +1,18 @@
+"""Delete output files except Epub package."""
+
import logging
import os.path
import mdepub
-from mdepub import project_path
from mdepub.filename import getFN
log = logging.getLogger('clean')
def run():
+ """Run this action."""
+
log.debug("run()")
mdepub.require_opts_file()
- os.chdir(project_path)
+ os.chdir(mdepub.project_path)
for ext in ['epub', 'html', 'zip']:
f = getFN(ext)
@@ -1,31 +1,34 @@
+"""Create empty project in this folder."""
+
+from datetime import date
import logging
-import mdepub
-from mdepub import options
-from mdepub.filename import getFN
-from mdepub.filename import clean
import os
-from datetime import date
-import sys
-import shutil
from os.path import join, dirname, exists
-from template import template_path
import re
+import sys
+import shutil
+import mdepub
+from mdepub.filename import clean
+from mdepub.filename import getFN
+from mdepub.template import template_path
log = logging.getLogger('create')
def run():
+ """Run this action."""
+
log.debug("run()")
print "Book title?"
title = raw_input("> ")
print "Author(s)?"
author = raw_input("> ")
print "Path to new book project files?\n[default: current directory]"
- path = raw_input("> ")
+ path = raw_input("> ") or "."
today = re.sub("^0", "", date.today().strftime("%d %b %Y"))
uuid = mdepub.new_id()
- filename = options.get("filename") or clean(title)
+ filename = mdepub.options.get("filename") or clean(title)
log.debug("Creating project in \"%s\".", path)
if not exists(path):
@@ -1,22 +1,29 @@
+"""Convert HTML to Epub and include source zip file."""
+
+from BeautifulSoup import BeautifulSoup
import logging
-import mdepub
-from mdepub import shell
import os
-from mdepub import options
-from mdepub import project_path
-from mdepub import arguments
+import sys
+import uuid
from zipfile import ZipFile
-from BeautifulSoup import BeautifulSoup
+import mdepub
+from mdepub import shell
from mdepub.filename import getFN
-import uuid
-import sys
log = logging.getLogger('epub')
def quote(text):
+ """Change " to '."""
+
return text.replace('"', '\'')
def run():
+ """Run this action."""
+
+ options = mdepub.options
+ project_path = mdepub.project_path
+ arguments = mdepub.arguments
+
log.debug("run()")
mdepub.require_opts_file()
os.chdir(project_path)
@@ -1,28 +1,34 @@
+"""Extract the source files from the given Epub file."""
+
import logging
-from os.path import join, exists, abspath, dirname
import os
-import mdepub
-from mdepub import arguments
-from mdepub import project_path
-from mdepub.filename import getFN
-from mdepub.filename import clean
-import sys
-from zipfile import ZipFile
+from os.path import join, exists, abspath, dirname
from StringIO import StringIO
+import sys
import yaml
+from zipfile import ZipFile
+
+import mdepub
+from mdepub.filename import clean
+from mdepub.filename import getFN
log = logging.getLogger('extract')
def run():
+ """Run this action."""
+
log.debug("run()")
old_cwd = os.getcwd()
- if arguments.fromf is None:
+ arguments = mdepub.arguments
+ project_path = mdepub.project_path
+
+ if arguments.fromfile is None:
log.fatal("No input file specified.")
sys.exit(0)
- fromf = abspath(arguments.fromf)
+ fromf = abspath(arguments.fromfile)
with ZipFile(fromf, 'r') as epub:
with epub.open("META-INF/source.mdepub.zip", 'r') as src_item:
@@ -1,17 +1,19 @@
+"""Translate Markdown text to html."""
+
+from BeautifulSoup import BeautifulSoup
import logging
-import mdepub
-from mdepub import shell
import os
import os.path
-from mdepub import options
-from mdepub import project_path
-from BeautifulSoup import BeautifulSoup
-from mdepub.filename import getFN
import sys
+import mdepub
+from mdepub import shell
+from mdepub.filename import getFN
log = logging.getLogger('html')
def checkForBadLinks(html):
+ """Find all internal bookmarks pointed to by hrefs in html, and make sure they are valid."""
+
soup = BeautifulSoup(html)
ids = [tag['id'] for tag in soup.findAll(id=True)]
@@ -24,6 +26,11 @@ def checkForBadLinks(html):
log.warn("Internal link points to non-existent target '{}'".format(href))
def run():
+ """Run this action."""
+
+ options = mdepub.options
+ project_path = mdepub.project_path
+
log.debug("run()")
mdepub.require_opts_file()
Oops, something went wrong.

0 comments on commit b9d2bc3

Please sign in to comment.