Improved handling of output to terminal and files.

New module file_io which takes care of this.  All output should go
through file_io.write, which encodes it using the appropriate
character encoding.  For output to a temporary file, use "with
file_io.tmpfile('name')".

Moved WorblehatException to new module exc, so all modules can access
it without importing worblehat.
This commit is contained in:
2011-10-12 19:26:21 +00:00
parent 1f2c52bb47
commit 9a733ef73a
5 changed files with 130 additions and 56 deletions

View File

@@ -1,7 +1,6 @@
import re
import types
file_encoding = 'utf8'
from exc import WorblehatException
# The possible fields for each type of object.
#
@@ -54,10 +53,13 @@ action_fields = {
{ 'type': 'category',
'required': ['id'] } }
class CommitFormatSyntaxError(Exception):
class CommitFormatSyntaxError(WorblehatException):
def __init__(self, msg, linenr):
super(CommitFormatSyntaxError, self).__init__(self, 'Syntax error on line %d: %s' %
(linenr, msg))
WorblehatException.__init__(self, 'Syntax error on line %d: %s' % (linenr, msg))
class CommitFormatError(WorblehatException):
def __init__(self, msg):
WorblehatException.__init__(self, msg)
def read_field_value_str(val):
if val.strip() == '':
@@ -67,7 +69,10 @@ def read_field_value_str(val):
def read_field_value_int(val):
if val.strip() == '':
return None
return int(val.strip())
try:
return int(val.strip())
except ValueError, TypeError:
raise WorblehatException('%s is not an integer' % val)
def read_field_value_dict(val):
d = {}
@@ -216,10 +221,9 @@ def write_action(d):
'd': write_field_value_dict,
'l': write_field_value_list}[ftype]
lines += field + ':' + value_writer(d[field])
return lines.encode(file_encoding)
return lines
def write_actionlist(actions):
encoding_comment = '# -*- coding: %s -*-\n' % file_encoding
return encoding_comment + '\n'.join(map(write_action, actions))
return '\n'.join(map(write_action, actions))
# test: print write_actionlist([{'comment':'Foo!\nBar!','action':'new-book','isbn':'434545'},{'action':'edit-book','isbn':'654654745','persons':{'author':['ab','foo'],'illustrator':['moo']}},'This\nis\na\ncomment.',{'action':'edit-category','id':'matematikk','name':'Matematikk','placement':['T10','T11']}])