~bzr-pqm/bzr/bzr.dev

2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
1
# Copyright (C) 2006, 2007 Canonical Ltd
2
#
2052.3.1 by John Arbash Meinel
Add tests to cleanup the copyright of all source files
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2052.3.1 by John Arbash Meinel
Add tests to cleanup the copyright of all source files
16
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
17
"""Win32-specific helper functions
18
19
Only one dependency: ctypes should be installed.
20
"""
21
4786.1.1 by John Arbash Meinel
Work on doing globbing, etc for all commands on Windows.
22
import glob
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
23
import os
4786.1.1 by John Arbash Meinel
Work on doing globbing, etc for all commands on Windows.
24
import re
25
import shlex
1185.16.86 by mbp at sourcefrog
- win32 get_console_size from Alexander
26
import struct
4786.1.1 by John Arbash Meinel
Work on doing globbing, etc for all commands on Windows.
27
import StringIO
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
28
import sys
29
30
31
# Windows version
32
if sys.platform == 'win32':
33
    _major,_minor,_build,_platform,_text = sys.getwindowsversion()
2245.4.11 by Alexander Belchenko
Small fixes after John's review; added NEWS entry
34
    # from MSDN:
35
    # dwPlatformId
36
    #   The operating system platform.
37
    #   This member can be one of the following values.
38
    #   ==========================  ======================================
39
    #   Value                       Meaning
40
    #   --------------------------  --------------------------------------
41
    #   VER_PLATFORM_WIN32_NT       The operating system is Windows Vista,
42
    #   2                           Windows Server "Longhorn",
43
    #                               Windows Server 2003, Windows XP,
44
    #                               Windows 2000, or Windows NT.
45
    #
46
    #   VER_PLATFORM_WIN32_WINDOWS  The operating system is Windows Me,
47
    #   1                           Windows 98, or Windows 95.
48
    #   ==========================  ======================================
49
    if _platform == 2:
50
        winver = 'Windows NT'
51
    else:
52
        # don't care about real Windows name, just to force safe operations
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
53
        winver = 'Windows 98'
54
else:
55
    winver = None
56
1185.16.86 by mbp at sourcefrog
- win32 get_console_size from Alexander
57
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
58
# We can cope without it; use a separate variable to help pyflakes
1185.16.86 by mbp at sourcefrog
- win32 get_console_size from Alexander
59
try:
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
60
    import ctypes
61
    has_ctypes = True
1185.16.86 by mbp at sourcefrog
- win32 get_console_size from Alexander
62
except ImportError:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
63
    has_ctypes = False
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
64
else:
65
    if winver == 'Windows 98':
66
        create_buffer = ctypes.create_string_buffer
67
        suffix = 'A'
68
    else:
69
        create_buffer = ctypes.create_unicode_buffer
70
        suffix = 'W'
3023.1.2 by Alexander Belchenko
Martin's review.
71
try:
72
    import win32file
4505.2.1 by Alexander Belchenko
Set hidden attribute on .bzr directory below unicode path should never fail with error. The operation should succeed even if bzr unable to set the attribute. (related to bug #335362).
73
    import pywintypes
3023.1.2 by Alexander Belchenko
Martin's review.
74
    has_win32file = True
75
except ImportError:
76
    has_win32file = False
3626.1.2 by skip
win32utils.get_host_name() uses 'mbcs' encoding when decoding env vars
77
try:
78
    import win32api
79
    has_win32api = True
80
except ImportError:
81
    has_win32api = False
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
82
3638.4.1 by Mark Hammond
Add win32utils.get_local_appdata_location() so bzr and plugins can
83
# pulling in win32com.shell is a bit of overhead, and normally we don't need
84
# it as ctypes is preferred and common.  lazy_imports and "optional"
85
# modules don't work well, so we do our own lazy thing...
86
has_win32com_shell = None # Set to True or False once we know for sure...
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
87
88
# Special Win32 API constants
89
# Handles of std streams
1704.2.3 by Martin Pool
(win32) Detect terminal width using GetConsoleScreenBufferInfo (Alexander)
90
WIN32_STDIN_HANDLE = -10
91
WIN32_STDOUT_HANDLE = -11
92
WIN32_STDERR_HANDLE = -12
93
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
94
# CSIDL constants (from MSDN 2003)
95
CSIDL_APPDATA = 0x001A      # Application Data folder
3638.4.10 by Aaron Bentley
Correct spelling of 'Application Data'
96
CSIDL_LOCAL_APPDATA = 0x001c# <user name>\Local Settings\Application Data (non roaming)
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
97
CSIDL_PERSONAL = 0x0005     # My Documents folder
98
99
# from winapi C headers
100
MAX_PATH = 260
101
UNLEN = 256
102
MAX_COMPUTERNAME_LENGTH = 31
103
4476.2.1 by Alexander Belchenko
win32utils.py: get_app_path() can read path for wordpad.exe (data type_id is REG_EXPAND_SZ).
104
# Registry data type ids
105
REG_SZ = 1
106
REG_EXPAND_SZ = 2
107
1704.2.3 by Martin Pool
(win32) Detect terminal width using GetConsoleScreenBufferInfo (Alexander)
108
4011.1.1 by John Arbash Meinel
Implement -Dmemory for win32
109
def debug_memory_win32api(message='', short=True):
110
    """Use trace.note() to dump the running memory info."""
111
    from bzrlib import trace
4011.1.2 by John Arbash Meinel
Fix some small bugs, and prefer the ctypes form.
112
    if has_ctypes:
4011.1.1 by John Arbash Meinel
Implement -Dmemory for win32
113
        class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
114
            """Used by GetProcessMemoryInfo"""
115
            _fields_ = [('cb', ctypes.c_ulong),
116
                        ('PageFaultCount', ctypes.c_ulong),
117
                        ('PeakWorkingSetSize', ctypes.c_size_t),
118
                        ('WorkingSetSize', ctypes.c_size_t),
119
                        ('QuotaPeakPagedPoolUsage', ctypes.c_size_t),
120
                        ('QuotaPagedPoolUsage', ctypes.c_size_t),
121
                        ('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t),
122
                        ('QuotaNonPagedPoolUsage', ctypes.c_size_t),
123
                        ('PagefileUsage', ctypes.c_size_t),
124
                        ('PeakPagefileUsage', ctypes.c_size_t),
125
                        ('PrivateUsage', ctypes.c_size_t),
126
                       ]
127
        cur_process = ctypes.windll.kernel32.GetCurrentProcess()
128
        mem_struct = PROCESS_MEMORY_COUNTERS_EX()
129
        ret = ctypes.windll.psapi.GetProcessMemoryInfo(cur_process,
130
            ctypes.byref(mem_struct),
131
            ctypes.sizeof(mem_struct))
132
        if not ret:
133
            trace.note('Failed to GetProcessMemoryInfo()')
134
            return
135
        info = {'PageFaultCount': mem_struct.PageFaultCount,
136
                'PeakWorkingSetSize': mem_struct.PeakWorkingSetSize,
137
                'WorkingSetSize': mem_struct.WorkingSetSize,
138
                'QuotaPeakPagedPoolUsage': mem_struct.QuotaPeakPagedPoolUsage,
139
                'QuotaPagedPoolUsage': mem_struct.QuotaPagedPoolUsage,
140
                'QuotaPeakNonPagedPoolUsage': mem_struct.QuotaPeakNonPagedPoolUsage,
141
                'QuotaNonPagedPoolUsage': mem_struct.QuotaNonPagedPoolUsage,
142
                'PagefileUsage': mem_struct.PagefileUsage,
143
                'PeakPagefileUsage': mem_struct.PeakPagefileUsage,
144
                'PrivateUsage': mem_struct.PrivateUsage,
145
               }
4011.1.2 by John Arbash Meinel
Fix some small bugs, and prefer the ctypes form.
146
    elif has_win32api:
147
        import win32process
148
        # win32process does not return PrivateUsage, because it doesn't use
149
        # PROCESS_MEMORY_COUNTERS_EX (it uses the one without _EX).
150
        proc = win32process.GetCurrentProcess()
151
        info = win32process.GetProcessMemoryInfo(proc)
4011.1.1 by John Arbash Meinel
Implement -Dmemory for win32
152
    else:
153
        trace.note('Cannot debug memory on win32 without ctypes'
154
                   ' or win32process')
155
        return
4163.1.1 by John Arbash Meinel
Some small fixes for the win32 'trace.debug_mem()' code.
156
    if short:
4163.1.2 by John Arbash Meinel
Merge bzr.dev, which changed kB => KB.
157
        trace.note('WorkingSize %7dKB'
158
                   '\tPeakWorking %7dKB\t%s',
4163.1.1 by John Arbash Meinel
Some small fixes for the win32 'trace.debug_mem()' code.
159
                   info['WorkingSetSize'] / 1024,
160
                   info['PeakWorkingSetSize'] / 1024,
161
                   message)
162
        return
163
    if message:
164
        trace.note('%s', message)
4170.2.1 by Alexander Belchenko
Use KB not kB for 1024 bytes
165
    trace.note('WorkingSize       %8d KB', info['WorkingSetSize'] / 1024)
166
    trace.note('PeakWorking       %8d KB', info['PeakWorkingSetSize'] / 1024)
167
    trace.note('PagefileUsage     %8d KB', info.get('PagefileUsage', 0) / 1024)
168
    trace.note('PeakPagefileUsage %8d KB', info.get('PeakPagefileUsage', 0) / 1024)
169
    trace.note('PrivateUsage      %8d KB', info.get('PrivateUsage', 0) / 1024)
4011.1.1 by John Arbash Meinel
Implement -Dmemory for win32
170
    trace.note('PageFaultCount    %8d', info.get('PageFaultCount', 0))
171
172
1185.16.86 by mbp at sourcefrog
- win32 get_console_size from Alexander
173
def get_console_size(defaultx=80, defaulty=25):
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
174
    """Return size of current console.
175
176
    This function try to determine actual size of current working
177
    console window and return tuple (sizex, sizey) if success,
178
    or default size (defaultx, defaulty) otherwise.
179
    """
180
    if not has_ctypes:
181
        # no ctypes is found
182
        return (defaultx, defaulty)
183
184
    # To avoid problem with redirecting output via pipe
185
    # need to use stderr instead of stdout
186
    h = ctypes.windll.kernel32.GetStdHandle(WIN32_STDERR_HANDLE)
187
    csbi = ctypes.create_string_buffer(22)
188
    res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
189
190
    if res:
191
        (bufx, bufy, curx, cury, wattr,
1185.16.86 by mbp at sourcefrog
- win32 get_console_size from Alexander
192
        left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
193
        sizex = right - left + 1
194
        sizey = bottom - top + 1
195
        return (sizex, sizey)
196
    else:
197
        return (defaultx, defaulty)
198
199
3638.4.1 by Mark Hammond
Add win32utils.get_local_appdata_location() so bzr and plugins can
200
def _get_sh_special_folder_path(csidl):
201
    """Call SHGetSpecialFolderPathW if available, or return None.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
202
3638.4.1 by Mark Hammond
Add win32utils.get_local_appdata_location() so bzr and plugins can
203
    Result is always unicode (or None).
204
    """
205
    if has_ctypes:
206
        try:
207
            SHGetSpecialFolderPath = \
208
                ctypes.windll.shell32.SHGetSpecialFolderPathW
209
        except AttributeError:
210
            pass
211
        else:
212
            buf = ctypes.create_unicode_buffer(MAX_PATH)
213
            if SHGetSpecialFolderPath(None,buf,csidl,0):
214
                return buf.value
215
216
    global has_win32com_shell
217
    if has_win32com_shell is None:
218
        try:
219
            from win32com.shell import shell
220
            has_win32com_shell = True
221
        except ImportError:
222
            has_win32com_shell = False
223
    if has_win32com_shell:
224
        # still need to bind the name locally, but this is fast.
225
        from win32com.shell import shell
226
        try:
227
            return shell.SHGetSpecialFolderPath(0, csidl, 0)
228
        except shell.error:
229
            # possibly E_NOTIMPL meaning we can't load the function pointer,
230
            # or E_FAIL meaning the function failed - regardless, just ignore it
231
            pass
232
    return None
233
234
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
235
def get_appdata_location():
236
    """Return Application Data location.
237
    Return None if we cannot obtain location.
238
3638.4.1 by Mark Hammond
Add win32utils.get_local_appdata_location() so bzr and plugins can
239
    Windows defines two 'Application Data' folders per user - a 'roaming'
240
    one that moves with the user as they logon to different machines, and
241
    a 'local' one that stays local to the machine.  This returns the 'roaming'
242
    directory, and thus is suitable for storing user-preferences, etc.
243
244
    Returned value can be unicode or plain string.
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
245
    To convert plain string to unicode use
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
246
    s.decode(osutils.get_user_encoding())
3638.4.2 by Mark Hammond
Add a reference to bug 262874 noting 'mbcs' may be the correct encoding.
247
    (XXX - but see bug 262874, which asserts the correct encoding is 'mbcs')
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
248
    """
3638.4.1 by Mark Hammond
Add win32utils.get_local_appdata_location() so bzr and plugins can
249
    appdata = _get_sh_special_folder_path(CSIDL_APPDATA)
250
    if appdata:
251
        return appdata
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
252
    # from env variable
253
    appdata = os.environ.get('APPDATA')
254
    if appdata:
255
        return appdata
256
    # if we fall to this point we on win98
257
    # at least try C:/WINDOWS/Application Data
258
    windir = os.environ.get('windir')
259
    if windir:
260
        appdata = os.path.join(windir, 'Application Data')
261
        if os.path.isdir(appdata):
262
            return appdata
263
    # did not find anything
264
    return None
265
266
3638.4.1 by Mark Hammond
Add win32utils.get_local_appdata_location() so bzr and plugins can
267
def get_local_appdata_location():
268
    """Return Local Application Data location.
269
    Return the same as get_appdata_location() if we cannot obtain location.
270
271
    Windows defines two 'Application Data' folders per user - a 'roaming'
272
    one that moves with the user as they logon to different machines, and
273
    a 'local' one that stays local to the machine.  This returns the 'local'
274
    directory, and thus is suitable for caches, temp files and other things
275
    which don't need to move with the user.
276
277
    Returned value can be unicode or plain string.
278
    To convert plain string to unicode use
4385.4.1 by Alexander Belchenko
removed all references to bzrlib.user_encoding
279
    s.decode(osutils.get_user_encoding())
3638.4.2 by Mark Hammond
Add a reference to bug 262874 noting 'mbcs' may be the correct encoding.
280
    (XXX - but see bug 262874, which asserts the correct encoding is 'mbcs')
3638.4.1 by Mark Hammond
Add win32utils.get_local_appdata_location() so bzr and plugins can
281
    """
282
    local = _get_sh_special_folder_path(CSIDL_LOCAL_APPDATA)
283
    if local:
284
        return local
285
    # Vista supplies LOCALAPPDATA, but XP and earlier do not.
286
    local = os.environ.get('LOCALAPPDATA')
287
    if local:
288
        return local
289
    return get_appdata_location()
290
291
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
292
def get_home_location():
293
    """Return user's home location.
294
    Assume on win32 it's the <My Documents> folder.
295
    If location cannot be obtained return system drive root,
296
    i.e. C:\
297
4031.3.1 by Frank Aspell
Fixing various typos
298
    Returned value can be unicode or plain string.
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
299
    To convert plain string to unicode use
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
300
    s.decode(osutils.get_user_encoding())
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
301
    """
3638.4.1 by Mark Hammond
Add win32utils.get_local_appdata_location() so bzr and plugins can
302
    home = _get_sh_special_folder_path(CSIDL_PERSONAL)
303
    if home:
304
        return home
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
305
    # try for HOME env variable
306
    home = os.path.expanduser('~')
307
    if home != '~':
308
        return home
309
    # at least return windows root directory
310
    windir = os.environ.get('windir')
311
    if windir:
2610.1.1 by Martin Pool
Fix get_home_location on Win98 (gzlist,r=john,r=alexander)
312
        return os.path.splitdrive(windir)[0] + '/'
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
313
    # otherwise C:\ is good enough for 98% users
314
    return 'C:/'
315
316
317
def get_user_name():
318
    """Return user name as login name.
319
    If name cannot be obtained return None.
320
4031.3.1 by Frank Aspell
Fixing various typos
321
    Returned value can be unicode or plain string.
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
322
    To convert plain string to unicode use
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
323
    s.decode(osutils.get_user_encoding())
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
324
    """
325
    if has_ctypes:
326
        try:
327
            advapi32 = ctypes.windll.advapi32
328
            GetUserName = getattr(advapi32, 'GetUserName'+suffix)
329
        except AttributeError:
330
            pass
331
        else:
332
            buf = create_buffer(UNLEN+1)
333
            n = ctypes.c_int(UNLEN+1)
334
            if GetUserName(buf, ctypes.byref(n)):
335
                return buf.value
336
    # otherwise try env variables
337
    return os.environ.get('USERNAME', None)
338
339
3626.1.3 by John Arbash Meinel
Use GetComputerNameEx from ctypes when available.
340
# 1 == ComputerNameDnsHostname, which returns "The DNS host name of the local
341
# computer or the cluster associated with the local computer."
342
_WIN32_ComputerNameDnsHostname = 1
343
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
344
def get_host_name():
345
    """Return host machine name.
346
    If name cannot be obtained return None.
347
3626.1.3 by John Arbash Meinel
Use GetComputerNameEx from ctypes when available.
348
    :return: A unicode string representing the host name. On win98, this may be
349
        a plain string as win32 api doesn't support unicode.
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
350
    """
3626.1.2 by skip
win32utils.get_host_name() uses 'mbcs' encoding when decoding env vars
351
    if has_win32api:
352
        try:
3626.1.3 by John Arbash Meinel
Use GetComputerNameEx from ctypes when available.
353
            return win32api.GetComputerNameEx(_WIN32_ComputerNameDnsHostname)
3626.1.2 by skip
win32utils.get_host_name() uses 'mbcs' encoding when decoding env vars
354
        except (NotImplementedError, win32api.error):
355
            # NotImplemented will happen on win9x...
356
            pass
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
357
    if has_ctypes:
358
        try:
359
            kernel32 = ctypes.windll.kernel32
360
        except AttributeError:
3626.1.3 by John Arbash Meinel
Use GetComputerNameEx from ctypes when available.
361
            pass # Missing the module we need
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
362
        else:
363
            buf = create_buffer(MAX_COMPUTERNAME_LENGTH+1)
364
            n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH+1)
3626.1.3 by John Arbash Meinel
Use GetComputerNameEx from ctypes when available.
365
366
            # Try GetComputerNameEx which gives a proper Unicode hostname
367
            GetComputerNameEx = getattr(kernel32, 'GetComputerNameEx'+suffix,
368
                                        None)
369
            if (GetComputerNameEx is not None
370
                and GetComputerNameEx(_WIN32_ComputerNameDnsHostname,
371
                                      buf, ctypes.byref(n))):
372
                return buf.value
373
374
            # Try GetComputerName in case GetComputerNameEx wasn't found
375
            # It returns the NETBIOS name, which isn't as good, but still ok.
376
            # The first GetComputerNameEx might have changed 'n', so reset it
377
            n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH+1)
378
            GetComputerName = getattr(kernel32, 'GetComputerName'+suffix,
379
                                      None)
380
            if (GetComputerName is not None
381
                and GetComputerName(buf, ctypes.byref(n))):
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
382
                return buf.value
3626.1.2 by skip
win32utils.get_host_name() uses 'mbcs' encoding when decoding env vars
383
    # otherwise try env variables, which will be 'mbcs' encoded
384
    # on Windows (Python doesn't expose the native win32 unicode environment)
3626.1.3 by John Arbash Meinel
Use GetComputerNameEx from ctypes when available.
385
    # According to this:
386
    # http://msdn.microsoft.com/en-us/library/aa246807.aspx
387
    # environment variables should always be encoded in 'mbcs'.
3626.1.2 by skip
win32utils.get_host_name() uses 'mbcs' encoding when decoding env vars
388
    try:
389
        return os.environ['COMPUTERNAME'].decode("mbcs")
390
    except KeyError:
391
        return None
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
392
393
394
def _ensure_unicode(s):
3794.1.1 by Martin Pool
Update osutils imports to fix setup.py on Windows
395
    from bzrlib import osutils
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
396
    if s and type(s) != unicode:
3788.1.1 by John Arbash Meinel
Fix a missing import
397
        from bzrlib import osutils
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
398
        s = s.decode(osutils.get_user_encoding())
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
399
    return s
3626.1.3 by John Arbash Meinel
Use GetComputerNameEx from ctypes when available.
400
2245.4.1 by Alexander Belchenko
win32utils: Windows-specific functions that use Win32 API via ctypes
401
402
def get_appdata_location_unicode():
403
    return _ensure_unicode(get_appdata_location())
404
405
def get_home_location_unicode():
406
    return _ensure_unicode(get_home_location())
407
408
def get_user_name_unicode():
409
    return _ensure_unicode(get_user_name())
410
411
def get_host_name_unicode():
412
    return _ensure_unicode(get_host_name())
2568.2.2 by Robert Collins
* New method ``_glob_expand_file_list_if_needed`` on the ``Command`` class
413
414
2617.5.8 by Kuno Meyer
Extended tests for unicode chars outside of the iso-8859-* range
415
def _ensure_with_dir(path):
416
    if not os.path.split(path)[0] or path.startswith(u'*') or path.startswith(u'?'):
417
        return u'./' + path, True
418
    else:
419
        return path, False
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
420
2617.5.8 by Kuno Meyer
Extended tests for unicode chars outside of the iso-8859-* range
421
def _undo_ensure_with_dir(path, corrected):
422
    if corrected:
423
        return path[2:]
424
    else:
425
        return path
426
427
428
4786.1.2 by John Arbash Meinel
Refactor the glob_expand code a bit, making the inner function more reusable.
429
def glob_one(possible_glob):
430
    """Same as glob.glob().
431
432
    work around bugs in glob.glob()
433
    - Python bug #1001604 ("glob doesn't return unicode with ...")
434
    - failing expansion for */* with non-iso-8859-* chars
435
    """
436
    corrected_glob, corrected = _ensure_with_dir(possible_glob)
437
    glob_files = glob.glob(corrected_glob)
438
439
    if not glob_files:
440
        # special case to let the normal code path handle
441
        # files that do not exist, etc.
442
        glob_files = [possible_glob]
443
    elif corrected:
444
        glob_files = [_undo_ensure_with_dir(elem, corrected)
445
                      for elem in glob_files]
446
    return [elem.replace(u'\\', u'/') for elem in glob_files]
447
448
2598.3.1 by Kuno Meyer
fix method rename glob_expand_for_win32 -> win32utils.glob_expand
449
def glob_expand(file_list):
2568.2.2 by Robert Collins
* New method ``_glob_expand_file_list_if_needed`` on the ``Command`` class
450
    """Replacement for glob expansion by the shell.
451
452
    Win32's cmd.exe does not do glob expansion (eg ``*.py``), so we do our own
453
    here.
454
455
    :param file_list: A list of filenames which may include shell globs.
456
    :return: An expanded list of filenames.
457
458
    Introduced in bzrlib 0.18.
459
    """
460
    if not file_list:
461
        return []
462
    expanded_file_list = []
463
    for possible_glob in file_list:
4786.1.2 by John Arbash Meinel
Refactor the glob_expand code a bit, making the inner function more reusable.
464
        expanded_file_list.extend(glob_one(possible_glob))
465
    return expanded_file_list
2681.4.1 by Alexander Belchenko
win32: looking for full path of mail client executable in registry
466
467
468
def get_app_path(appname):
469
    """Look up in Windows registry for full path to application executable.
4031.3.1 by Frank Aspell
Fixing various typos
470
    Typically, applications create subkey with their basename
2681.4.1 by Alexander Belchenko
win32: looking for full path of mail client executable in registry
471
    in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\
472
473
    :param  appname:    name of application (if no filename extension
474
                        is specified, .exe used)
475
    :return:    full path to aplication executable from registry,
476
                or appname itself if nothing found.
477
    """
2681.4.3 by Alexander Belchenko
move import _winreg into function get_app_path to avoid ImportError on non-win32 platforms
478
    import _winreg
4476.2.1 by Alexander Belchenko
win32utils.py: get_app_path() can read path for wordpad.exe (data type_id is REG_EXPAND_SZ).
479
480
    basename = appname
481
    if not os.path.splitext(basename)[1]:
482
        basename = appname + '.exe'
483
2681.4.1 by Alexander Belchenko
win32: looking for full path of mail client executable in registry
484
    try:
485
        hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
4476.2.1 by Alexander Belchenko
win32utils.py: get_app_path() can read path for wordpad.exe (data type_id is REG_EXPAND_SZ).
486
            'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' +
487
            basename)
2681.4.1 by Alexander Belchenko
win32: looking for full path of mail client executable in registry
488
    except EnvironmentError:
489
        return appname
490
491
    try:
492
        try:
4476.2.1 by Alexander Belchenko
win32utils.py: get_app_path() can read path for wordpad.exe (data type_id is REG_EXPAND_SZ).
493
            path, type_id = _winreg.QueryValueEx(hkey, '')
2681.4.1 by Alexander Belchenko
win32: looking for full path of mail client executable in registry
494
        except WindowsError:
4476.2.1 by Alexander Belchenko
win32utils.py: get_app_path() can read path for wordpad.exe (data type_id is REG_EXPAND_SZ).
495
            return appname
2681.4.1 by Alexander Belchenko
win32: looking for full path of mail client executable in registry
496
    finally:
497
        _winreg.CloseKey(hkey)
498
4476.2.1 by Alexander Belchenko
win32utils.py: get_app_path() can read path for wordpad.exe (data type_id is REG_EXPAND_SZ).
499
    if type_id == REG_SZ:
500
        return path
501
    if type_id == REG_EXPAND_SZ and has_win32api:
502
        fullpath = win32api.ExpandEnvironmentStrings(path)
4476.2.2 by Alexander Belchenko
remove quotes around value only if there is pair of quotes (igc review)
503
        if len(fullpath) > 1 and fullpath[0] == '"' and fullpath[-1] == '"':
4476.2.1 by Alexander Belchenko
win32utils.py: get_app_path() can read path for wordpad.exe (data type_id is REG_EXPAND_SZ).
504
            fullpath = fullpath[1:-1]   # remove quotes around value
505
        return fullpath
506
    return appname
3023.1.2 by Alexander Belchenko
Martin's review.
507
508
509
def set_file_attr_hidden(path):
510
    """Set file attributes to hidden if possible"""
511
    if has_win32file:
4505.2.1 by Alexander Belchenko
Set hidden attribute on .bzr directory below unicode path should never fail with error. The operation should succeed even if bzr unable to set the attribute. (related to bug #335362).
512
        if winver != 'Windows 98':
513
            SetFileAttributes = win32file.SetFileAttributesW
514
        else:
515
            SetFileAttributes = win32file.SetFileAttributes
516
        try:
517
            SetFileAttributes(path, win32file.FILE_ATTRIBUTE_HIDDEN)
518
        except pywintypes.error, e:
4505.2.2 by Alexander Belchenko
forgotten import
519
            from bzrlib import trace
4505.2.1 by Alexander Belchenko
Set hidden attribute on .bzr directory below unicode path should never fail with error. The operation should succeed even if bzr unable to set the attribute. (related to bug #335362).
520
            trace.mutter('Unable to set hidden attribute on %r: %s', path, e)
4355.2.1 by Alexander Belchenko
Using unicode Windows API to obtain command-line arguments.
521
522
4786.1.1 by John Arbash Meinel
Work on doing globbing, etc for all commands on Windows.
523
524
class UnicodeShlex(object):
525
    """This is a very simplified version of shlex.shlex.
526
527
    The main change is that it supports non-ascii input streams. The internal
528
    structure is quite simplified relative to shlex.shlex, since we aren't
529
    trying to handle multiple input streams, etc. In fact, we don't use a
530
    file-like api either.
531
    """
532
533
    def __init__(self, uni_string):
534
        self._input = uni_string
535
        self._input_iter = iter(self._input)
536
        self._whitespace_match = re.compile(u'\s').match
537
        self._word_match = re.compile(u'\S').match
4789.1.1 by Alexander Belchenko
In standard windows shell single quote is not supported as quote. Restored standard windows behavior.
538
        self._quote_chars = u'"'
4786.1.1 by John Arbash Meinel
Work on doing globbing, etc for all commands on Windows.
539
        # self._quote_match = re.compile(u'[\'"]').match
540
        self._escape_match = lambda x: None # Never matches
541
        self._escape = '\\'
542
        # State can be
543
        #   ' ' - after whitespace, starting a new token
544
        #   'a' - after text, currently working on a token
545
        #   '"' - after ", currently in a "-delimited quoted section
546
        #   "\" - after '\', checking the next char
547
        self._state = ' '
548
        self._token = [] # Current token being parsed
549
550
    def _get_token(self):
551
        # Were there quote chars as part of this token?
552
        quoted = False
553
        quoted_state = None
554
        for nextchar in self._input_iter:
555
            if self._state == ' ':
556
                if self._whitespace_match(nextchar):
557
                    # if self._token: return token
558
                    continue
559
                elif nextchar in self._quote_chars:
560
                    self._state = nextchar # quoted state
561
                elif self._word_match(nextchar):
562
                    self._token.append(nextchar)
563
                    self._state = 'a'
564
                else:
565
                    raise AssertionError('wtttf?')
566
            elif self._state in self._quote_chars:
567
                quoted = True
568
                if nextchar == self._state: # End of quote
569
                    self._state = 'a' # posix allows 'foo'bar to translate to
570
                                      # foobar
571
                elif self._state == '"' and nextchar == self._escape:
572
                    quoted_state = self._state
573
                    self._state = nextchar
574
                else:
575
                    self._token.append(nextchar)
576
            elif self._state == self._escape:
577
                if nextchar == '\\':
578
                    self._token.append('\\')
579
                elif nextchar == '"':
580
                    self._token.append(nextchar)
581
                else:
582
                    self._token.append('\\' + nextchar)
583
                self._state = quoted_state
584
            elif self._state == 'a':
585
                if self._whitespace_match(nextchar):
586
                    if self._token:
587
                        break # emit this token
588
                    else:
589
                        continue # no token to emit
590
                elif nextchar in self._quote_chars:
591
                    # Start a new quoted section
592
                    self._state = nextchar
593
                # escape?
594
                elif (self._word_match(nextchar)
595
                      or nextchar in self._quote_chars
596
                      # or whitespace_split?
597
                      ):
598
                    self._token.append(nextchar)
599
                else:
600
                    raise AssertionError('state == "a", char: %r'
601
                                         % (nextchar,))
602
            else:
603
                raise AssertionError('unknown state: %r' % (self._state,))
604
        result = ''.join(self._token)
605
        self._token = []
606
        if not quoted and result == '':
607
            result = None
608
        return quoted, result
609
610
    def __iter__(self):
611
        return self
612
613
    def next(self):
614
        quoted, token = self._get_token()
615
        if token is None:
616
            raise StopIteration
617
        return quoted, token
618
619
620
def _command_line_to_argv(command_line):
621
    """Convert a Unicode command line into a set of argv arguments.
622
623
    This does wildcard expansion, etc. It is intended to make wildcards act
624
    closer to how they work in posix shells, versus how they work by default on
625
    Windows.
626
    """
627
    s = UnicodeShlex(command_line)
628
    # Now that we've split the content, expand globs
629
    # TODO: Use 'globbing' instead of 'glob.glob', this gives us stuff like
630
    #       '**/' style globs
631
    args = []
632
    for is_quoted, arg in s:
4786.1.2 by John Arbash Meinel
Refactor the glob_expand code a bit, making the inner function more reusable.
633
        if is_quoted or not glob.has_magic(arg):
634
            args.append(arg.replace(u'\\', u'/'))
4786.1.1 by John Arbash Meinel
Work on doing globbing, etc for all commands on Windows.
635
        else:
4786.1.2 by John Arbash Meinel
Refactor the glob_expand code a bit, making the inner function more reusable.
636
            args.extend(glob_one(arg))
4786.1.1 by John Arbash Meinel
Work on doing globbing, etc for all commands on Windows.
637
    return args
638
639
4355.2.1 by Alexander Belchenko
Using unicode Windows API to obtain command-line arguments.
640
if has_ctypes and winver != 'Windows 98':
641
    def get_unicode_argv():
642
        LPCWSTR = ctypes.c_wchar_p
643
        INT = ctypes.c_int
644
        POINTER = ctypes.POINTER
645
        prototype = ctypes.WINFUNCTYPE(LPCWSTR)
646
        GetCommandLine = prototype(("GetCommandLineW",
647
                                    ctypes.windll.kernel32))
648
        prototype = ctypes.WINFUNCTYPE(POINTER(LPCWSTR), LPCWSTR, POINTER(INT))
4786.1.3 by John Arbash Meinel
Remove '_maybe_glob' in favor of globbing at the commandline level.
649
        command_line = GetCommandLine()
4355.2.4 by Alexander Belchenko
win32utils.py: get_unicode_argv: get bzr options as tail of argv list based on the number of items in sys.argv[1:] list.
650
        # Skip the first argument, since we only care about parameters
4786.1.3 by John Arbash Meinel
Remove '_maybe_glob' in favor of globbing at the commandline level.
651
        argv = _command_line_to_argv(GetCommandLine())[1:]
4355.2.1 by Alexander Belchenko
Using unicode Windows API to obtain command-line arguments.
652
        if getattr(sys, 'frozen', None) is None:
4355.2.4 by Alexander Belchenko
win32utils.py: get_unicode_argv: get bzr options as tail of argv list based on the number of items in sys.argv[1:] list.
653
            # Invoked via 'python.exe' which takes the form:
654
            #   python.exe [PYTHON_OPTIONS] C:\Path\bzr [BZR_OPTIONS]
655
            # we need to get only BZR_OPTIONS part,
4786.1.3 by John Arbash Meinel
Remove '_maybe_glob' in favor of globbing at the commandline level.
656
            # We already removed 'python.exe' so we remove everything up to and
657
            # including the first non-option ('-') argument.
658
            for idx in xrange(len(argv)):
659
                if argv[idx][:1] != '-':
660
                    break
661
            argv = argv[idx+1:]
4355.2.1 by Alexander Belchenko
Using unicode Windows API to obtain command-line arguments.
662
        return argv
4355.2.2 by Alexander Belchenko
osutils.py: get_unicode_argv function (to obtain unicode command line arguments from sys.argv) moved to the beginning of module based on suggestions from review of John Meinel.
663
else:
664
    get_unicode_argv = None