GrampsLocale: Simplify the file-finding functions

Making use of the fact that GrampsLocale now knows what
encoding to use, and noting that filesystems don't use
more than one encoding to write filenames in directories.

Also specify the encoding on some more files

svn: r21148
This commit is contained in:
John Ralls 2013-01-17 19:47:59 +00:00
parent cc4ec85b4d
commit 09a875db11
11 changed files with 44 additions and 95 deletions

@ -124,7 +124,7 @@ class FilterList(object):
return l.replace('"', '"') return l.replace('"', '"')
def save(self): def save(self):
f = open(self.file.encode(sys.getfilesystemencoding()), 'w') f = open(self.file.encode(glocale.getfilesystemencoding()), 'w')
f.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n") f.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
f.write('<filters>\n') f.write('<filters>\n')
for namespace in self.filter_namespaces: for namespace in self.filter_namespaces:

@ -36,6 +36,7 @@ import os
import sys import sys
import re import re
import traceback import traceback
import codecs
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -1093,21 +1094,10 @@ class PluginRegister(object):
if sys.version_info[0] < 3: if sys.version_info[0] < 3:
full_filename = full_filename.encode(glocale.getfilesystemencoding()) full_filename = full_filename.encode(glocale.getfilesystemencoding())
local_gettext = glocale.get_addon_translator(full_filename).gettext local_gettext = glocale.get_addon_translator(full_filename).gettext
try:
stream = open(full_filename).read()
except UnicodeError as err:
if sys.version_info[0] < 3:
print(_("ERROR: Failed to read file %s, %s") % (full_filename, str(err)))
continue
else:
try:
stream = open(full_filename, encoding = 'utf-8').read()
except ValueError as err:
print(_("ERROR: Failed to read file %s, %s") % (full_filename, str(err)))
continue
try: try:
#execfile(full_filename, #execfile(full_filename,
exec(compile(stream, full_filename, 'exec'), exec(compile(codecs.open(full_filename, 'r', 'utf-8').read(),
full_filename, 'exec'),
make_environment(_=local_gettext), make_environment(_=local_gettext),
{}) {})
except ValueError as msg: except ValueError as msg:

@ -29,6 +29,7 @@
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import time import time
import io
from xml.parsers.expat import ParserCreate from xml.parsers.expat import ParserCreate
try: try:
@ -181,7 +182,7 @@ class RecentFiles(object):
""" """
Saves the current GRAMPS RecentFiles collection to the associated file. Saves the current GRAMPS RecentFiles collection to the associated file.
""" """
xml_file = file(os.path.expanduser(GRAMPS_FILENAME),'w') xml_file = io.open(os.path.expanduser(GRAMPS_FILENAME),'w', encoding="utf-8")
if use_lock: if use_lock:
fcntl.lockf(xml_file,fcntl.LOCK_EX) fcntl.lockf(xml_file,fcntl.LOCK_EX)
xml_file.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n") xml_file.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
@ -215,7 +216,8 @@ class RecentParser(object):
self.recent_files = [] self.recent_files = []
try: try:
xml_file = open(os.path.expanduser(GRAMPS_FILENAME)) xml_file = io.open(os.path.expanduser(GRAMPS_FILENAME), "r",
encoding = 'utf-8')
if use_lock: if use_lock:
fcntl.lockf(xml_file,fcntl.LOCK_SH) fcntl.lockf(xml_file,fcntl.LOCK_SH)
@ -229,7 +231,8 @@ class RecentParser(object):
fcntl.lockf(xml_file,fcntl.LOCK_UN) fcntl.lockf(xml_file,fcntl.LOCK_UN)
xml_file.close() xml_file.close()
except: except:
pass if xml_file:
xml_file.close()
def get(self): def get(self):
return self.recent_files return self.recent_files

@ -42,6 +42,7 @@ else:
import errno import errno
import copy import copy
import logging import logging
import io
from ..constfunc import STRTYPE from ..constfunc import STRTYPE
from ..const import GRAMPS_LOCALE as glocale from ..const import GRAMPS_LOCALE as glocale
@ -335,10 +336,7 @@ class ConfigManager(object):
except OSError as exp: except OSError as exp:
if exp.errno != errno.EEXIST: if exp.errno != errno.EEXIST:
raise raise
if sys.version_info[0] < 3: key_file = io.open(filename, "w", encoding = "utf-8")
key_file = open(filename, "w")
else:
key_file = open(filename, "w", encoding="utf-8")
key_file.write(";; Gramps key file\n") key_file.write(";; Gramps key file\n")
key_file.write((";; Automatically created at %s" % key_file.write((";; Automatically created at %s" %
time.strftime("%Y/%m/%d %H:%M:%S")) + "\n\n") time.strftime("%Y/%m/%d %H:%M:%S")) + "\n\n")

@ -64,31 +64,12 @@ def find_file( filename):
fname = filename fname = filename
if os.path.isfile(filename): if os.path.isfile(filename):
return(filename) return(filename)
except: except UnicodeError:
pass
# Build list of alternate encodings
encodings = set()
#Darwin returns "mac roman" for preferredencoding, but since it
#returns "UTF-8" for filesystemencoding, and that's first, this
#works.
for enc in [sys.getfilesystemencoding, locale.getpreferredencoding]:
try: try:
encodings.add(enc) fname = filename.encode(glocale.getfilesystemencoding())
except:
pass
encodings.add('UTF-8')
encodings.add('ISO-8859-1')
for enc in encodings:
try:
fname = filename.encode(enc)
if os.path.isfile(fname): if os.path.isfile(fname):
return fname return fname
except: except UnicodeError:
pass
# not found
return '' return ''
def find_folder( filename): def find_folder( filename):
@ -97,26 +78,12 @@ def find_folder( filename):
fname = filename fname = filename
if os.path.isdir(filename): if os.path.isdir(filename):
return(filename) return(filename)
except: except UnicodeError:
pass
# Build list of alternate encodings
try: try:
encodings = [sys.getfilesystemencoding(), fname = filename.encode(glocale.getfilesystemencoding())
locale.getpreferredencoding(),
'UTF-8', 'ISO-8859-1']
except:
encodings = [sys.getfilesystemencoding(), 'UTF-8', 'ISO-8859-1']
encodings = list(set(encodings))
for enc in encodings:
try:
fname = filename.encode(enc)
if os.path.isdir(fname): if os.path.isdir(fname):
return fname return fname
except: except UnicodeError:
pass
# not found
return '' return ''
def get_unicode_path_from_file_chooser(path): def get_unicode_path_from_file_chooser(path):

@ -87,7 +87,7 @@ if win():
pass # ok pass # ok
elif not os.path.isdir(HOME_DIR): elif not os.path.isdir(HOME_DIR):
os.makedirs(HOME_DIR) os.makedirs(HOME_DIR)
sys.stdout = sys.stderr = open(logfile, "w") sys.stdout = sys.stderr = io.open(logfile, "w", encoding='utf-8')
stderrh = logging.StreamHandler(sys.stderr) stderrh = logging.StreamHandler(sys.stderr)
stderrh.setFormatter(form) stderrh.setFormatter(form)
stderrh.setLevel(logging.DEBUG) stderrh.setLevel(logging.DEBUG)

@ -157,12 +157,12 @@ class AsciiDoc(BaseDoc,TextDoc):
self.filename = filename self.filename = filename
try: try:
self.f = open(self.filename,"w") self.f = io.open(self.filename,"w",
except IOError as msg: encoding='ascii',
errors = 'backslashreplace')
except Exception as msg:
errmsg = "%s\n%s" % (_("Could not create %s") % self.filename, msg) errmsg = "%s\n%s" % (_("Could not create %s") % self.filename, msg)
raise ReportError(errmsg) raise ReportError(errmsg)
except:
raise ReportError(_("Could not create %s") % self.filename)
self.in_cell = 0 self.in_cell = 0
self.text = "" self.text = ""

@ -33,16 +33,17 @@
# Standard Python Modules # Standard Python Modules
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.get_translation().gettext
import os import os
import time import time
import io
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
# GRAMPS modules # GRAMPS modules
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.get_translation().gettext
from gramps.gen.lib import AttributeType, ChildRefType, Citation, Date, EventRoleType, EventType, LdsOrd, NameType, NoteType, Person, UrlType from gramps.gen.lib import AttributeType, ChildRefType, Citation, Date, EventRoleType, EventType, LdsOrd, NameType, NoteType, Person, UrlType
from gramps.gen.const import VERSION from gramps.gen.const import VERSION
import gramps.plugins.lib.libgedcom as libgedcom import gramps.plugins.lib.libgedcom as libgedcom
@ -235,7 +236,7 @@ class GedcomWriter(UpdateCallback):
""" """
self.dirname = os.path.dirname (filename) self.dirname = os.path.dirname (filename)
self.gedcom_file = open(filename, "w") self.gedcom_file = io.open(filename, "w", encoding='utf-8')
self._header(filename) self._header(filename)
self._submitter() self._submitter()
self._individuals() self._individuals()

@ -90,8 +90,7 @@ class CalendarWriter(object):
self.oldval = newval self.oldval = newval
def writeln(self, text): def writeln(self, text):
#self.g.write('%s\n' % (text.encode('iso-8859-1'))) self.g.write('%s\n' % text.encode('ascii', 'backslashreplace'))
self.g.write('%s\n' % (text.encode(sys.getfilesystemencoding())))
def export_data(self, filename): def export_data(self, filename):

@ -145,12 +145,11 @@ class VCardWriter(object):
Can't cope with nested VCards, section 2.4.2 of RFC 2426. Can't cope with nested VCards, section 2.4.2 of RFC 2426.
""" """
sysencoding = sys.getfilesystemencoding()
self.filehandle.write('%s\r\n' % '\r\n'.join( self.filehandle.write('%s\r\n' % '\r\n'.join(
[line.encode(sysencoding) for line in self.txtwrp.wrap(text)])) [line.encode('utf-8') for line in self.txtwrp.wrap(text)]))
def export_data(self): def export_data(self):
"""Open the file and loop over everyone two write their VCards.""" """Open the file and loop over everyone too write their VCards."""
with OpenFileOrStdout(self.filename) as self.filehandle: with OpenFileOrStdout(self.filename) as self.filehandle:
if self.filehandle: if self.filehandle:
self.count = 0 self.count = 0

@ -81,7 +81,7 @@ except ImportError:
import time, datetime import time, datetime
import locale import locale
import shutil import shutil
import codecs import io
import tarfile import tarfile
import tempfile import tempfile
if sys.version_info[0] < 3: if sys.version_info[0] < 3:
@ -7829,12 +7829,8 @@ class NavWebReport(Report):
self.cur_fname = fname + ext self.cur_fname = fname + ext
if self.archive: if self.archive:
string_io = StringIO() string_io = StringIO()
if sys.version_info[0] < 3: of = io.open(fname, "w", encoding = self.encoding,
of = open(fname, "w") errors = 'xmlcharrefreplace')
else:
of = open(fname, "w", encoding='utf-8')
# of = codecs.EncodedFile(string_io, 'utf-8',
# self.encoding, 'xmlcharrefreplace')
else: else:
string_io = None string_io = None
if subdir: if subdir:
@ -7842,12 +7838,8 @@ class NavWebReport(Report):
if not os.path.isdir(subdir): if not os.path.isdir(subdir):
os.makedirs(subdir) os.makedirs(subdir)
fname = os.path.join(self.html_dir, self.cur_fname) fname = os.path.join(self.html_dir, self.cur_fname)
if sys.version_info[0] < 3: of = io.open(fname, "w", encoding = self.encoding,
of = open(fname, "w") errors = 'xmlcharrefreplace')
else:
of = open(fname, "w", encoding='utf-8')
# of = codecs.EncodedFile(string_io, 'utf-8',
# self.encoding, 'xmlcharrefreplace')
return (of, string_io) return (of, string_io)
def close_file(self, of, string_io): def close_file(self, of, string_io):