Debian Codegraph @

hgext/win32mbcs.py

raw
1 # win32mbcs.py -- MBCS filename support for Mercurial
2 #
3 # Copyright (c) 2008 Shun-ichi Goto <[email protected]>
4 #
5 # Version: 0.3
6 # Author: Shun-ichi Goto <[email protected]>
7 #
8 # This software may be used and distributed according to the terms of the
9 # GNU General Public License version 2 or any later version.
10 #
11
12 '''allow the use of MBCS paths with problematic encodings
13
14 Some MBCS encodings are not good for some path operations (i.e.
15 splitting path, case conversion, etc.) with its encoded bytes. We call
16 such a encoding (i.e. shift_jis and big5) as "problematic encoding".
17 This extension can be used to fix the issue with those encodings by
18 wrapping some functions to convert to Unicode string before path
19 operation.
20
21 This extension is useful for:
22
23 - Japanese Windows users using shift_jis encoding.
24 - Chinese Windows users using big5 encoding.
25 - All users who use a repository with one of problematic encodings on
26 case-insensitive file system.
27
28 This extension is not needed for:
29
30 - Any user who use only ASCII chars in path.
31 - Any user who do not use any of problematic encodings.
32
33 Note that there are some limitations on using this extension:
34
35 - You should use single encoding in one repository.
36 - If the repository path ends with 0x5c, .hg/hgrc cannot be read.
37 - win32mbcs is not compatible with fixutf8 extension.
38
39 By default, win32mbcs uses encoding.encoding decided by Mercurial.
40 You can specify the encoding by config option::
41
42 [win32mbcs]
43 encoding = sjis
44
45 It is useful for the users who want to commit with UTF-8 log message.
46 '''
47
48 from __future__ import annotations
49
50 import os
51 import sys
52
53 from mercurial.i18n import _
54 from mercurial import (
55 encoding,
56 error,
57 pycompat,
58 registrar,
59 )
60
61 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
62 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
63 # be specifying the version(s) of Mercurial they are tested with, or
64 # leave the attribute unspecified.
65 testedwith = b'ships-with-hg-core'
66
67 configtable = {}
68 configitem = registrar.configitem(configtable)
69
70 # Encoding.encoding may be updated by --encoding option.
71 # Use a lambda do delay the resolution.
72 configitem(
73 b'win32mbcs',
74 b'encoding',
75 default=lambda: encoding.encoding,
76 )
77
78 _encoding: str = "" # see extsetup
79
80
81 def decode(arg):
82 if isinstance(arg, bytes):
83 uarg = arg.decode(_encoding)
84 if arg == uarg.encode(_encoding):
85 return uarg
86 raise UnicodeError("Not local encoding")
87 elif isinstance(arg, tuple):
88 return tuple(map(decode, arg))
89 elif isinstance(arg, list):
90 return map(decode, arg)
91 elif isinstance(arg, dict):
92 for k, v in arg.items():
93 arg[k] = decode(v)
94 return arg
95
96
97 def encode(arg):
98 if isinstance(arg, str):
99 return arg.encode(_encoding)
100 elif isinstance(arg, tuple):
101 return tuple(map(encode, arg))
102 elif isinstance(arg, list):
103 return map(encode, arg)
104 elif isinstance(arg, dict):
105 for k, v in arg.items():
106 arg[k] = encode(v)
107 return arg
108
109
110 def appendsep(s):
111 # ensure the path ends with os.sep, appending it if necessary.
112 try:
113 us = decode(s)
114 except UnicodeError:
115 us = s # TODO: how to handle this bytes case??
116 if us and us[-1] not in ':/\\':
117 s += pycompat.ossep
118 return s
119
120
121 def basewrapper(func, argtype, enc, dec, args, kwds):
122 # check check already converted, then call original
123 for arg in args:
124 if isinstance(arg, argtype):
125 return func(*args, **kwds)
126
127 try:
128 # convert string arguments, call func, then convert back the
129 # return value.
130 return enc(func(*dec(args), **dec(kwds)))
131 except UnicodeError:
132 raise error.Abort(
133 _(b"[win32mbcs] filename conversion failed with %s encoding\n")
134 % encoding.strtolocal(_encoding)
135 )
136
137
138 def wrapper(func, args, kwds):
139 return basewrapper(func, str, encode, decode, args, kwds)
140
141
142 def reversewrapper(func, args, kwds):
143 return basewrapper(func, str, decode, encode, args, kwds)
144
145
146 def wrapperforlistdir(func, args, kwds):
147 # Ensure 'path' argument ends with os.sep to avoids
148 # misinterpreting last 0x5c of MBCS 2nd byte as path separator.
149 if args:
150 args = list(args)
151 args[0] = appendsep(args[0])
152 if 'path' in kwds:
153 kwds['path'] = appendsep(kwds['path'])
154 return func(*args, **kwds)
155
156
157 def wrapname(name: str, wrapper):
158 module, name = name.rsplit('.', 1)
159 module = sys.modules[module]
160 func = getattr(module, name)
161
162 def f(*args, **kwds):
163 return wrapper(func, args, kwds)
164
165 f.__name__ = func.__name__
166 setattr(module, name, f)
167
168
169 # List of functions to be wrapped.
170 # NOTE: os.path.dirname() and os.path.basename() are safe because
171 # they use result of os.path.split()
172 funcs = '''os.path.join os.path.split os.path.splitext
173 os.path.normpath os.makedirs mercurial.util.endswithsep
174 mercurial.util.splitpath mercurial.util.fscasesensitive
175 mercurial.util.fspath mercurial.util.pconvert mercurial.util.normpath
176 mercurial.util.checkwinfilename mercurial.util.checkosfilename
177 mercurial.util.split'''
178
179 # These functions are required to be called with local encoded string
180 # because they expects argument is local encoded string and cause
181 # problem with unicode string.
182 rfuncs = '''mercurial.encoding.upper mercurial.encoding.lower
183 mercurial.util._filenamebytestr'''
184
185 # List of Windows specific functions to be wrapped.
186 winfuncs = '''os.path.splitunc'''
187
188 # codec and alias names of sjis and big5 to be faked.
189 problematic_encodings = b'''big5 big5-tw csbig5 big5hkscs big5-hkscs
190 hkscs cp932 932 ms932 mskanji ms-kanji shift_jis csshiftjis shiftjis
191 sjis s_jis shift_jis_2004 shiftjis2004 sjis_2004 sjis2004
192 shift_jisx0213 shiftjisx0213 sjisx0213 s_jisx0213 950 cp950 ms950 '''
193
194
195 def extsetup(ui):
196 # TODO: decide use of config section for this extension
197 if (not os.path.supports_unicode_filenames) and (
198 pycompat.sysplatform != b'cygwin'
199 ):
200 ui.warn(_(b"[win32mbcs] cannot activate on this platform.\n"))
201 return
202 # determine encoding for filename
203 global _encoding
204 _encoding = encoding.strfromlocal(ui.config(b'win32mbcs', b'encoding'))
205 # fake is only for relevant environment.
206 if _encoding.lower() in problematic_encodings.split():
207 for f in funcs.split():
208 wrapname(f, wrapper)
209 if pycompat.iswindows:
210 for f in winfuncs.split():
211 wrapname(f, wrapper)
212 wrapname("mercurial.util.listdir", wrapperforlistdir)
213 wrapname("mercurial.windows.listdir", wrapperforlistdir)
214 # wrap functions to be called with local byte string arguments
215 for f in rfuncs.split():
216 wrapname(f, reversewrapper)
217 # Check sys.args manually instead of using ui.debug() because
218 # command line options is not yet applied when
219 # extensions.loadall() is called.
220 if '--debug' in sys.argv:
221 ui.writenoi18n(
222 b"[win32mbcs] activated with encoding: %s\n"
223 % encoding.strtolocal(_encoding)
224 )