~lovesyao/bzr/windows-utf8

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#! /usr/bin/env python

# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

"""Bazaar -- a free distributed version-control tool"""

import os
import sys

# update this on each release
_script_version = (1, 10, 0)

if __doc__ is None:
    print "bzr does not support python -OO."
    sys.exit(2)
try:
    version_info = sys.version_info
except AttributeError:
    version_info = 1, 5 # 1.5 or older

REINVOKE = "__BZR_REINVOKE"
NEED_VERS = (2, 4)
KNOWN_PYTHONS = ('python2.4', 'python2.5')

if version_info < NEED_VERS:
    if not os.environ.has_key(REINVOKE):
        # mutating os.environ doesn't work in old Pythons
        os.putenv(REINVOKE, "1")
        for python in KNOWN_PYTHONS:
            try:
                os.execvp(python, [python] + sys.argv)
            except OSError:
                pass
    sys.stderr.write("bzr: error: cannot find a suitable python interpreter\n")
    sys.stderr.write("  (need %d.%d or later)\n" % NEED_VERS)
    sys.exit(1)
if hasattr(os, "unsetenv"):
    os.unsetenv(REINVOKE)


if sys.platform == 'win32':
    from ctypes import windll, Structure, c_short, c_ushort, byref
    import codecs

    class COORD(Structure):
        _fields_ = [
            ("X", c_short),
            ("Y", c_short)
        ]

    class SMALL_RECT(Structure):
        _fields_ = [
            ("Left", c_short),
            ("Top", c_short),
            ("Right", c_short),
            ("Bottom", c_short)
        ]

    class CONSOLE_SCREEN_BUFFER_INFO(Structure):
        _fields_ = [
            ("dwSize", COORD),
            ("dwCursorPosition", COORD),
            ("wAttributes", c_ushort),
            ("srWindow", SMALL_RECT),
            ("dwMaximumWindowSize", COORD)
        ]

    STD_OUTPUT_HANDLE = -11
    STD_ERROR_HANDLE = -12

    def consolereplace_errors(exception):
        if not isinstance(exception, UnicodeDecodeError):
            raise TypeError("consolereplace() cannot handle %r" % exception)
        l = [u"\\%x" % ord(exception.object[pos]) for pos in xrange(exception.start, exception.end)]
        return (u"\ufffe%s\ufeff" % u"".join(l), exception.end)

    codecs.register_error("consolereplace", consolereplace_errors)

    FOREGROUND_RED = 4

    class WindowsConsoleWriter:
        def __init__(self, stdhandle, errors='strict'):
            self.errors = errors
            self.encoding = 'utf_16'
            self.handle = windll.kernel32.GetStdHandle(stdhandle)

            csbi = CONSOLE_SCREEN_BUFFER_INFO()
            windll.kernel32.GetConsoleScreenBufferInfo(self.handle, byref(csbi))

            self.defattr = csbi.wAttributes

        def writelines(self, text):
            self.write(text + "\n")

        def _write(self, text):
            windll.kernel32.WriteConsoleW(self.handle, text, len(text), 0, 0)

        def _color(self, color):
            windll.kernel32.SetConsoleTextAttribute(self.handle, color)

        def write(self, text):
            text = unicode(text, 'utf_8', errors='consolereplace')
            i = 0
            j = 0
            for c in text:
                if c == u'\ufffe':
                    self._write(text[i:j])
                    i = j+1
                    self._color(FOREGROUND_RED)
                elif c == u'\ufeff':
                    self._write(text[i:j])
                    i = j+1
                    self._color(self.defattr)
                j+=1
            self._write(text[i:j])

        def isatty(self): return True 

        def flush(self): pass

    if sys.stdout.isatty():
        sys.stdout = WindowsConsoleWriter(STD_OUTPUT_HANDLE)
    if sys.stderr.isatty():
        sys.stderr = WindowsConsoleWriter(STD_ERROR_HANDLE)

profiling = False
if '--profile-imports' in sys.argv:
    sys.argv.remove('--profile-imports')
    import profile_imports
    profile_imports.install()
    profiling = True

if sys.platform == 'darwin':
    # jameinel says this hack is to force python to honor the LANG setting,
    # even on Darwin.  Otherwise it is apparently hardcoded to Mac-Roman,
    # which is incorrect for the normal Terminal.app which wants UTF-8.  
    #
    # "It might be that I should be setting the "system locale" somewhere else
    # on the system, rather than setting LANG=en_US.UTF-8 in .bashrc.
    # Switching to 'posix' and setting LANG worked for me." 
    #
    # So we can remove this if someone works out the right way to tell Mac
    # Python which encoding to use.  -- mbp 20080703
    sys.platform = 'posix'
    try:
        import locale
    finally:
        sys.platform = 'darwin'
else:
    import locale

try:
    locale.setlocale(locale.LC_ALL, '')
except locale.Error, e:
    sys.stderr.write('bzr: warning: %s\n'
                     '  bzr could not set the application locale.\n'
                     '  Although this should be no problem for bzr itself,\n'
                     '  it might cause problems with some plugins.\n'
                     '  To investigate the issue, look at the output\n'
                     '  of the locale(1p) tool available on POSIX systems.\n'
                     % e)

# instruct bzrlib/__init__.py to install lazy_regex
sys._bzr_lazy_regex = True
try:
    import bzrlib
except ImportError, e:
    sys.stderr.write("bzr: ERROR: "
        "Couldn't import bzrlib and dependencies.\n"
        "Please check the directory containing bzrlib is on your PYTHONPATH.\n"
        "\n")
    raise

if bzrlib.version_info[:3] != _script_version:
    sys.stderr.write("bzr: WARNING: bzrlib version doesn't match the bzr program.\n"
            "This may indicate an installation problem.\n"
            "bzrlib from %s is version %r\n"
            % (bzrlib.__path__, bzrlib.version_info))

import bzrlib.inspect_for_copy
bzrlib.inspect_for_copy.import_copy_with_hacked_inspect()

import bzrlib.breakin
bzrlib.breakin.hook_sigquit()

import bzrlib.decorators
if ('--lsprof' in sys.argv
    or '--lsprof-file' in sys.argv
    or '--profile' in sys.argv
    or '--lsprof-timed' in sys.argv):
    bzrlib.decorators.use_pretty_decorators()
else:
    bzrlib.decorators.use_fast_decorators()

import bzrlib.commands
import bzrlib.trace


if __name__ == '__main__':
    bzrlib.trace.enable_default_logging()
    exit_val = bzrlib.commands.main(sys.argv)

    if profiling:
        profile_imports.log_stack_info(sys.stderr)

    # run anything registered by atexit, because it won't be run in the normal
    # way
    sys.exitfunc()

    # By this point we really have completed everything we want to do, and
    # there's no point doing any additional cleanup.  Abruptly exiting here
    # stops any background threads getting into trouble as code is unloaded,
    # and it may also be slightly faster, through avoiding gc of objects that
    # are just about to be discarded anyhow.  This does mean that atexit hooks
    # won't run but we don't use them.  Also file buffers won't be flushed,
    # but our policy is to always close files from a finally block. -- mbp 20070215
    try:
        sys.stdout.flush()
        sys.stderr.flush()
    except IOError, e:
        import errno
        if e.errno in [errno.EINVAL, errno.EPIPE]:
            pass
        else:
            raise
    if bzrlib.trace._trace_file:
        # this is also _bzr_log
        bzrlib.trace._trace_file.flush()
    os._exit(exit_val)
else:
    raise ImportError("The bzr script cannot be imported.")