~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/__init__.py

(gz) Override Py_FileSystemDefaultEncoding to utf-8 from ascii for the bzr
 script (Martin Packman)

Show diffs side-by-side

added added

removed removed

Lines of Context:
37
37
# timestamps relative to program start in the log file kept by bzrlib.trace.
38
38
_start_time = time.time()
39
39
 
 
40
import codecs
40
41
import sys
41
42
 
42
43
 
131
132
__version__ = _format_version_tuple(version_info)
132
133
version_string = __version__
133
134
 
 
135
 
 
136
def _patch_filesystem_default_encoding(new_enc):
 
137
    """Change the Python process global encoding for filesystem names
 
138
    
 
139
    The effect is to change how open() and other builtin functions handle
 
140
    unicode filenames on posix systems. This should only be done near startup.
 
141
 
 
142
    The new encoding string passed to this function must survive until process
 
143
    termination, otherwise the interpreter may access uninitialized memory.
 
144
    The use of intern() may defer breakage is but is not enough, the string
 
145
    object should be secure against module reloading and during teardown.
 
146
    """
 
147
    try:
 
148
        import ctypes
 
149
    except ImportError:
 
150
        return
 
151
    pythonapi = getattr(ctypes, "pythonapi", None)
 
152
    if pythonapi is None:
 
153
        # Not CPython ctypes implementation
 
154
        return
 
155
    old_ptr = ctypes.c_void_p.in_dll(pythonapi, "Py_FileSystemDefaultEncoding")
 
156
    new_ptr = ctypes.cast(ctypes.c_char_p(intern(new_enc)), ctypes.c_void_p)
 
157
    old_ptr.value = new_ptr.value
 
158
    if sys.getfilesystemencoding() != new_enc:
 
159
        raise RuntimeError("Failed to change the filesystem default encoding")
 
160
    return new_enc
 
161
 
 
162
 
 
163
# When running under the bzr script, override bad filesystem default encoding.
 
164
# This is not safe to do for all users of bzrlib, other scripts should instead
 
165
# just ensure a usable locale is set via the $LANG variable on posix systems.
 
166
_fs_enc = sys.getfilesystemencoding()
 
167
if getattr(sys, "_bzr_default_fs_enc", None) is not None:
 
168
    if (_fs_enc is None or codecs.lookup(_fs_enc).name == "ascii"):
 
169
        _fs_enc = _patch_filesystem_default_encoding(sys._bzr_default_fs_enc)
 
170
if _fs_enc is None:
 
171
    _fs_enc = "ascii"
 
172
else:
 
173
    _fs_enc = codecs.lookup(_fs_enc).name
 
174
 
 
175
 
134
176
# bzr has various bits of global state that are slowly being eliminated.
135
177
# This variable is intended to permit any new state-like things to be attached
136
178
# to a library_state.BzrLibraryState object rather than getting new global