Skip to content

Commit

Permalink
Switched to optparse
Browse files Browse the repository at this point in the history
Signed-off-by: Guillermo O. Freschi <tordek@tordek.com.ar>
  • Loading branch information
Guillermo O. Freschi committed Dec 6, 2009
1 parent ddf078a commit 73dcd33
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 197 deletions.
246 changes: 58 additions & 188 deletions sparkup
Expand Up @@ -4,9 +4,9 @@ version = "0.1.3"

import os
import fileinput
import getopt
import sys
import re
from optparse import OptionParser

# ===============================================================================

Expand Down Expand Up @@ -280,7 +280,7 @@ class Parser:
# Constructor
# ---------------------------------------------------------------------------

def __init__(self, options=None, str='', dialect=HtmlDialect()):
def __init__(self, options, str, dialect=HtmlDialect()):
"""Constructor.
"""

Expand All @@ -293,17 +293,13 @@ class Parser:
self.caret.append(self.root)
self._last = []

# Methods
# ---------------------------------------------------------------------------

def load_string(self, str):
"""Loads a string to parse.
"""

self.str = str
self._tokenize()
self._parse()


# Methods
# ---------------------------------------------------------------------------

def render(self):
"""Renders.
Called by [[Router]].
Expand All @@ -317,12 +313,12 @@ class Parser:
output = indent + output.replace("\n", "\n" + indent)

# Strip newline if not needed
if self.options.has("no-last-newline") \
if not self.options.last_newline \
or self.prefix or self.suffix:
output = re.sub(r'\n\s*$', '', output)

# TextMate mode
if self.options.has("textmate"):
if self.options.textmate:
output = self._textmatify(output)

return output
Expand Down Expand Up @@ -543,7 +539,7 @@ class Element:
"""

output = ""
try: spaces_count = int(self.parser.options.options['indent-spaces'])
try: spaces_count = int(self.parser.options.options['indent_spaces'])
except: spaces_count = 4
spaces = ' ' * spaces_count
indent = self.depth * spaces
Expand All @@ -553,7 +549,7 @@ class Element:
if self.suffix: suffix = self.suffix

# Make the guide from the ID (/#header), or the class if there's no ID (/.item)
# This is for the start-guide, end-guide and post-tag-guides
# This is for the start-guide, end-guide and post_tag_guides
guide_str = ''
if 'id' in self.attributes:
guide_str += "#%s" % self.attributes['id']
Expand All @@ -568,17 +564,17 @@ class Element:
if ((self.name == 'div') and \
(('id' in self.attributes) or ('class' in self.attributes))):

if (self.parser.options.has('post-tag-guides')):
if (self.parser.options.post_tag_guides):
guide = "<!-- /%s -->" % guide_str

if (self.parser.options.has('start-guide-format')):
format = self.parser.options.get('start-guide-format')
if (self.parser.options.start_guide_format):
format = self.parser.options.start_guide_format
try: start_guide = format % guide_str
except: start_guide = (format + " " + guide_str).strip()
start_guide = "%s<!-- %s -->\n" % (indent, start_guide)

if (self.parser.options.has('end-guide-format')):
format = self.parser.options.get('end-guide-format')
if (self.parser.options.end_guide_format):
format = self.parser.options.end_guide_format
try: end_guide = format % guide_str
except: end_guide = (format + " " + guide_str).strip()
end_guide = "\n%s<!-- %s -->" % (indent, end_guide)
Expand All @@ -592,7 +588,7 @@ class Element:
if len(self.children) > 0 \
or self.expand \
or prefix or suffix \
or (self.parser.options.has('expand-divs') and self.name == 'div'):
or (self.parser.options.expand_divs and self.name == 'div'):

for child in self.children:
output += child.render()
Expand Down Expand Up @@ -828,7 +824,7 @@ class Token:
name = synonyms[name]

if ':' in name:
try: spaces_count = int(self.parser.options.get('indent-spaces'))
try: spaces_count = int(self.parser.options.indent_spaces)
except: spaces_count = 4
indent = ' ' * spaces_count

Expand Down Expand Up @@ -916,172 +912,46 @@ class Token:
SIBLING = 16

# ===============================================================================

class Router:
"""The router.
"""

# Constructor
# ---------------------------------------------------------------------------

def __init__(self):
pass

# Methods
# ---------------------------------------------------------------------------

def start(self, options=None, str=None, ret=None):
if (options):
self.options = Options(router=self, options=options, argv=None)
else:
self.options = Options(router=self, argv=sys.argv[1:], options=None)

if (self.options.has('help')):
return self.help()

elif (self.options.has('version')):
return self.version()

else:
return self.parse(str=str, ret=ret)

def help(self):
print "Usage: %s [OPTIONS]" % sys.argv[0]
print "Expands input into HTML."
print ""
for short, long, info in self.options.cmdline_keys:
if "Deprecated" in info: continue
if not short == '': short = '-%s,' % short
if not long == '': long = '--%s' % long.replace("=", "=XXX")

print "%6s %-25s %s" % (short, long, info)
print ""
print "\n".join(self.help_content)

def version(self):
print "Uhm, yeah."

def parse(self, str=None, ret=None):
self.parser = Parser(self.options)

try:
# Read the files
# for line in fileinput.input(): lines.append(line.rstrip(os.linesep))
if str is not None:
lines = str
else:
lines = [sys.stdin.read()]
lines = " ".join(lines)

except KeyboardInterrupt:
pass

except:
sys.stderr.write("Reading failed.\n")
return

try:
self.parser.load_string(lines)
output = self.parser.render()
if ret: return output
sys.stdout.write(output)

except:
sys.stderr.write("Parse error. Check your input.\n")
print sys.exc_info()[0]
print sys.exc_info()[1]

def exit(self):
sys.exit()

help_content = [
"Please refer to the manual for more information.",
]

# ===============================================================================

class Options:
def __init__(self, router, argv, options=None):
# Init self
self.router = router

# `options` can be given as a dict of stuff to preload
if options:
for k, v in options.iteritems():
self.options[k] = v
return

# Prepare for getopt()
short_keys, long_keys = "", []
for short, long, info in self.cmdline_keys: # 'v', 'version'
short_keys += short
long_keys.append(long)

try:
getoptions, arguments = getopt.getopt(argv, short_keys, long_keys)

except getopt.GetoptError:
err = sys.exc_info()[1]
sys.stderr.write("Options error: %s\n" % err)
sys.stderr.write("Try --help for a list of arguments.\n")
return router.exit()

# Sort them out into options
options = {}
i = 0
for option in getoptions:
key, value = option # '--version', ''
if (value == ''): value = True

# If the key is long, write it
if key[0:2] == '--':
clean_key = key[2:]
options[clean_key] = value

# If the key is short, look for the long version of it
elif key[0:1] == '-':
for short, long, info in self.cmdline_keys:
if short == key[1:]:
print long
options[long] = True

# Done
for k, v in options.iteritems():
self.options[k] = v

def __getattr__(self, attr):
return self.get(attr)

def get(self, attr):
try: return self.options[attr]
except: return None

def has(self, attr):
try: return self.options.has_key(attr)
except: return False

options = {
'indent-spaces': 4
}
cmdline_keys = [
('h', 'help', 'Shows help'),
('v', 'version', 'Shows the version'),
('', 'no-guides', 'Deprecated'),
('', 'post-tag-guides', 'Adds comments at the end of DIV tags'),
('', 'textmate', 'Adds snippet info (textmate mode)'),
('', 'indent-spaces=', 'Indent spaces'),
('', 'expand-divs', 'Automatically expand divs'),
('', 'no-last-newline', 'Skip the trailing newline'),
('', 'start-guide-format=', 'To be documented'),
('', 'end-guide-format=', 'To be documented'),
]

# Property: router
# Router
router = 1

# ===============================================================================
def parse_args():
optparser = OptionParser(version=version)

optparser.add_option('--no-guides', action="store_true", help='Deprecated')
optparser.add_option('--post-tag-guides', action="store_true",
dest="post-tag-guides", help='Adds comments at the end of DIV tags')
optparser.add_option('--textmate', action="store_true", dest='textmate',
help='Adds snippet info (textmate mode)')
optparser.add_option('--indent-spaces', dest='indent_spaces',
help='Indent spaces')
optparser.add_option('--expand-divs', action="store_true",
dest='expand_divs', help='Automatically expand divs')
optparser.add_option('--no-last-newline', action="store_false",
dest='last_newline', help='Skip the trailing newline')
optparser.add_option('--start-guide-format', dest='start_guide_format',
help='To be documented')
optparser.add_option('--end-guide-format', dest='end_guide_format',
help='To be documented')

optparser.set_defaults(post_tag_guides=False, textmate=False,
indent_spaces=4, expand_divs=False, last_newline=True,
start_guide_format="", end_guide_formats="")

return optparser.parse_args()

def main():
(options, _) = parse_args()

lines = [sys.stdin.read()]
lines = " ".join(lines)

parser = Parser(options, lines)

try:
output = parser.render()
sys.stdout.write(output)
except:
sys.stderr.write("Parse error. Check your input.\n")
print sys.exc_info()[0]
print sys.exc_info()[1]

if __name__ == "__main__":
z = Router()
z.start()
main()
15 changes: 6 additions & 9 deletions sparkup-unittest.py
Expand Up @@ -105,18 +105,15 @@ def run(self):
"""Run Forrest run!"""

print "Test results:"
for name, case in self.cases.iteritems():
try: options_key = case['options']
except: options_key = 'default'

try: options = self.options[options_key]
except: options = self.options['default']
(options, _) = sparkup.parse_args()
options.textmate = True
options.post_tag_guides = True
options.last_newline = False

for name, case in self.cases.iteritems():
# Output buffer
r = sparkup.Router()
input = case['input']
output = r.start(options=options, str=input, ret=True)
del r
output = sparkup.Parser(options, input).render()

# Did it work?
result = output == case['output']
Expand Down

0 comments on commit 73dcd33

Please sign in to comment.