19
19
Only one dependency: ctypes should be installed.
30
from breezy.i18n import gettext
28
if sys.platform == 'win32':
29
_major,_minor,_build,_platform,_text = sys.getwindowsversion()
32
# The operating system platform.
33
# This member can be one of the following values.
34
# ========================== ======================================
36
# -------------------------- --------------------------------------
37
# VER_PLATFORM_WIN32_NT The operating system is Windows Vista,
38
# 2 Windows Server "Longhorn",
39
# Windows Server 2003, Windows XP,
40
# Windows 2000, or Windows NT.
42
# VER_PLATFORM_WIN32_WINDOWS The operating system is Windows Me,
43
# 1 Windows 98, or Windows 95.
44
# ========================== ======================================
48
# don't care about real Windows name, just to force safe operations
54
# We can cope without it; use a separate variable to help pyflakes
61
if winver == 'Windows 98':
62
create_buffer = ctypes.create_string_buffer
65
create_buffer = ctypes.create_unicode_buffer
79
# pulling in win32com.shell is a bit of overhead, and normally we don't need
80
# it as ctypes is preferred and common. lazy_imports and "optional"
81
# modules don't work well, so we do our own lazy thing...
82
has_win32com_shell = None # Set to True or False once we know for sure...
33
84
# Special Win32 API constants
34
85
# Handles of std streams
55
105
def debug_memory_win32api(message='', short=True):
56
106
"""Use trace.note() to dump the running memory info."""
58
from breezy import trace
59
class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
60
"""Used by GetProcessMemoryInfo"""
61
_fields_ = [('cb', ctypes.c_ulong),
62
('PageFaultCount', ctypes.c_ulong),
63
('PeakWorkingSetSize', ctypes.c_size_t),
64
('WorkingSetSize', ctypes.c_size_t),
65
('QuotaPeakPagedPoolUsage', ctypes.c_size_t),
66
('QuotaPagedPoolUsage', ctypes.c_size_t),
67
('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t),
68
('QuotaNonPagedPoolUsage', ctypes.c_size_t),
69
('PagefileUsage', ctypes.c_size_t),
70
('PeakPagefileUsage', ctypes.c_size_t),
71
('PrivateUsage', ctypes.c_size_t),
73
cur_process = ctypes.windll.kernel32.GetCurrentProcess()
74
mem_struct = PROCESS_MEMORY_COUNTERS_EX()
75
ret = ctypes.windll.psapi.GetProcessMemoryInfo(
76
cur_process, ctypes.byref(mem_struct), ctypes.sizeof(mem_struct))
78
trace.note(gettext('Failed to GetProcessMemoryInfo()'))
107
from bzrlib import trace
109
class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
110
"""Used by GetProcessMemoryInfo"""
111
_fields_ = [('cb', ctypes.c_ulong),
112
('PageFaultCount', ctypes.c_ulong),
113
('PeakWorkingSetSize', ctypes.c_size_t),
114
('WorkingSetSize', ctypes.c_size_t),
115
('QuotaPeakPagedPoolUsage', ctypes.c_size_t),
116
('QuotaPagedPoolUsage', ctypes.c_size_t),
117
('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t),
118
('QuotaNonPagedPoolUsage', ctypes.c_size_t),
119
('PagefileUsage', ctypes.c_size_t),
120
('PeakPagefileUsage', ctypes.c_size_t),
121
('PrivateUsage', ctypes.c_size_t),
123
cur_process = ctypes.windll.kernel32.GetCurrentProcess()
124
mem_struct = PROCESS_MEMORY_COUNTERS_EX()
125
ret = ctypes.windll.psapi.GetProcessMemoryInfo(cur_process,
126
ctypes.byref(mem_struct),
127
ctypes.sizeof(mem_struct))
129
trace.note('Failed to GetProcessMemoryInfo()')
131
info = {'PageFaultCount': mem_struct.PageFaultCount,
132
'PeakWorkingSetSize': mem_struct.PeakWorkingSetSize,
133
'WorkingSetSize': mem_struct.WorkingSetSize,
134
'QuotaPeakPagedPoolUsage': mem_struct.QuotaPeakPagedPoolUsage,
135
'QuotaPagedPoolUsage': mem_struct.QuotaPagedPoolUsage,
136
'QuotaPeakNonPagedPoolUsage': mem_struct.QuotaPeakNonPagedPoolUsage,
137
'QuotaNonPagedPoolUsage': mem_struct.QuotaNonPagedPoolUsage,
138
'PagefileUsage': mem_struct.PagefileUsage,
139
'PeakPagefileUsage': mem_struct.PeakPagefileUsage,
140
'PrivateUsage': mem_struct.PrivateUsage,
144
# win32process does not return PrivateUsage, because it doesn't use
145
# PROCESS_MEMORY_COUNTERS_EX (it uses the one without _EX).
146
proc = win32process.GetCurrentProcess()
147
info = win32process.GetProcessMemoryInfo(proc)
149
trace.note('Cannot debug memory on win32 without ctypes'
80
info = {'PageFaultCount': mem_struct.PageFaultCount,
81
'PeakWorkingSetSize': mem_struct.PeakWorkingSetSize,
82
'WorkingSetSize': mem_struct.WorkingSetSize,
83
'QuotaPeakPagedPoolUsage': mem_struct.QuotaPeakPagedPoolUsage,
84
'QuotaPagedPoolUsage': mem_struct.QuotaPagedPoolUsage,
85
'QuotaPeakNonPagedPoolUsage':
86
mem_struct.QuotaPeakNonPagedPoolUsage,
87
'QuotaNonPagedPoolUsage': mem_struct.QuotaNonPagedPoolUsage,
88
'PagefileUsage': mem_struct.PagefileUsage,
89
'PeakPagefileUsage': mem_struct.PeakPagefileUsage,
90
'PrivateUsage': mem_struct.PrivateUsage,
93
# using base-2 units (see HACKING.txt).
94
trace.note(gettext('WorkingSize {0:>7}KiB'
95
'\tPeakWorking {1:>7}KiB\t{2}').format(
153
trace.note('WorkingSize %7dKB'
154
'\tPeakWorking %7dKB\t%s',
96
155
info['WorkingSetSize'] / 1024,
97
156
info['PeakWorkingSetSize'] / 1024,
101
160
trace.note('%s', message)
102
trace.note(gettext('WorkingSize %8d KiB'),
103
info['WorkingSetSize'] / 1024)
104
trace.note(gettext('PeakWorking %8d KiB'),
105
info['PeakWorkingSetSize'] / 1024)
106
trace.note(gettext('PagefileUsage %8d KiB'),
107
info.get('PagefileUsage', 0) / 1024)
108
trace.note(gettext('PeakPagefileUsage %8d KiB'),
109
info.get('PeakPagefileUsage', 0) / 1024)
110
trace.note(gettext('PrivateUsage %8d KiB'),
111
info.get('PrivateUsage', 0) / 1024)
112
trace.note(gettext('PageFaultCount %8d'), info.get('PageFaultCount', 0))
161
trace.note('WorkingSize %8d KB', info['WorkingSetSize'] / 1024)
162
trace.note('PeakWorking %8d KB', info['PeakWorkingSetSize'] / 1024)
163
trace.note('PagefileUsage %8d KB', info.get('PagefileUsage', 0) / 1024)
164
trace.note('PeakPagefileUsage %8d KB', info.get('PeakPagefileUsage', 0) / 1024)
165
trace.note('PrivateUsage %8d KB', info.get('PrivateUsage', 0) / 1024)
166
trace.note('PageFaultCount %8d', info.get('PageFaultCount', 0))
115
169
def get_console_size(defaultx=80, defaulty=25):
143
199
Result is always unicode (or None).
147
SHGetSpecialFolderPath = \
148
ctypes.windll.shell32.SHGetSpecialFolderPathW
149
except AttributeError:
152
buf = ctypes.create_unicode_buffer(MAX_PATH)
153
if SHGetSpecialFolderPath(None, buf, csidl, 0):
203
SHGetSpecialFolderPath = \
204
ctypes.windll.shell32.SHGetSpecialFolderPathW
205
except AttributeError:
208
buf = ctypes.create_unicode_buffer(MAX_PATH)
209
if SHGetSpecialFolderPath(None,buf,csidl,0):
212
global has_win32com_shell
213
if has_win32com_shell is None:
215
from win32com.shell import shell
216
has_win32com_shell = True
218
has_win32com_shell = False
219
if has_win32com_shell:
220
# still need to bind the name locally, but this is fast.
221
from win32com.shell import shell
223
return shell.SHGetSpecialFolderPath(0, csidl, 0)
225
# possibly E_NOTIMPL meaning we can't load the function pointer,
226
# or E_FAIL meaning the function failed - regardless, just ignore it
157
231
def get_appdata_location():
195
290
Assume on win32 it's the <My Documents> folder.
196
291
If location cannot be obtained return system drive root,
294
Returned value can be unicode or plain string.
295
To convert plain string to unicode use
296
s.decode(osutils.get_user_encoding())
199
298
home = _get_sh_special_folder_path(CSIDL_PERSONAL)
202
home = os.environ.get('HOME')
301
# try for HOME env variable
302
home = os.path.expanduser('~')
205
homepath = os.environ.get('HOMEPATH')
206
if homepath is not None:
207
return os.path.join(os.environ.get('HOMEDIR', ''), home)
208
305
# at least return windows root directory
209
windir = os.environ.get('WINDIR')
306
windir = os.environ.get('windir')
211
308
return os.path.splitdrive(windir)[0] + '/'
212
309
# otherwise C:\ is good enough for 98% users
216
313
def get_user_name():
217
314
"""Return user name as login name.
218
315
If name cannot be obtained return None.
317
Returned value can be unicode or plain string.
318
To convert plain string to unicode use
319
s.decode(osutils.get_user_encoding())
221
advapi32 = ctypes.windll.advapi32
222
GetUserName = getattr(advapi32, 'GetUserNameW')
223
except AttributeError:
226
buf = ctypes.create_unicode_buffer(UNLEN + 1)
227
n = ctypes.c_int(UNLEN + 1)
228
if GetUserName(buf, ctypes.byref(n)):
323
advapi32 = ctypes.windll.advapi32
324
GetUserName = getattr(advapi32, 'GetUserName'+suffix)
325
except AttributeError:
328
buf = create_buffer(UNLEN+1)
329
n = ctypes.c_int(UNLEN+1)
330
if GetUserName(buf, ctypes.byref(n)):
230
332
# otherwise try env variables
231
return os.environ.get('USERNAME')
333
return os.environ.get('USERNAME', None)
234
336
# 1 == ComputerNameDnsHostname, which returns "The DNS host name of the local
235
337
# computer or the cluster associated with the local computer."
236
338
_WIN32_ComputerNameDnsHostname = 1
239
340
def get_host_name():
240
341
"""Return host machine name.
241
342
If name cannot be obtained return None.
243
:return: A unicode string representing the host name.
344
:return: A unicode string representing the host name. On win98, this may be
345
a plain string as win32 api doesn't support unicode.
246
buf = ctypes.create_unicode_buffer(MAX_COMPUTERNAME_LENGTH + 1)
247
n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH + 1)
249
# Try GetComputerNameEx which gives a proper Unicode hostname
250
GetComputerNameEx = getattr(
251
ctypes.windll.kernel32, 'GetComputerNameExW', None)
252
if (GetComputerNameEx is not None
253
and GetComputerNameEx(_WIN32_ComputerNameDnsHostname,
254
buf, ctypes.byref(n))):
256
return os.environ.get('COMPUTERNAME')
349
return win32api.GetComputerNameEx(_WIN32_ComputerNameDnsHostname)
350
except (NotImplementedError, win32api.error):
351
# NotImplemented will happen on win9x...
355
kernel32 = ctypes.windll.kernel32
356
except AttributeError:
357
pass # Missing the module we need
359
buf = create_buffer(MAX_COMPUTERNAME_LENGTH+1)
360
n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH+1)
362
# Try GetComputerNameEx which gives a proper Unicode hostname
363
GetComputerNameEx = getattr(kernel32, 'GetComputerNameEx'+suffix,
365
if (GetComputerNameEx is not None
366
and GetComputerNameEx(_WIN32_ComputerNameDnsHostname,
367
buf, ctypes.byref(n))):
370
# Try GetComputerName in case GetComputerNameEx wasn't found
371
# It returns the NETBIOS name, which isn't as good, but still ok.
372
# The first GetComputerNameEx might have changed 'n', so reset it
373
n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH+1)
374
GetComputerName = getattr(kernel32, 'GetComputerName'+suffix,
376
if (GetComputerName is not None
377
and GetComputerName(buf, ctypes.byref(n))):
379
# otherwise try env variables, which will be 'mbcs' encoded
380
# on Windows (Python doesn't expose the native win32 unicode environment)
382
# http://msdn.microsoft.com/en-us/library/aa246807.aspx
383
# environment variables should always be encoded in 'mbcs'.
385
return os.environ['COMPUTERNAME'].decode("mbcs")
390
def _ensure_unicode(s):
391
from bzrlib import osutils
392
if s and type(s) != unicode:
393
from bzrlib import osutils
394
s = s.decode(osutils.get_user_encoding())
398
def get_appdata_location_unicode():
399
return _ensure_unicode(get_appdata_location())
401
def get_home_location_unicode():
402
return _ensure_unicode(get_home_location())
404
def get_user_name_unicode():
405
return _ensure_unicode(get_user_name())
407
def get_host_name_unicode():
408
return _ensure_unicode(get_host_name())
259
411
def _ensure_with_dir(path):
260
if (not os.path.split(path)[0] or path.startswith(u'*')
261
or path.startswith(u'?')):
412
if not os.path.split(path)[0] or path.startswith(u'*') or path.startswith(u'?'):
262
413
return u'./' + path, True
264
415
return path, False
267
417
def _undo_ensure_with_dir(path, corrected):
300
431
:param file_list: A list of filenames which may include shell globs.
301
432
:return: An expanded list of filenames.
303
Introduced in breezy 0.18.
434
Introduced in bzrlib 0.18.
305
436
if not file_list:
307
439
expanded_file_list = []
308
440
for possible_glob in file_list:
309
expanded_file_list.extend(glob_one(possible_glob))
310
return expanded_file_list
441
# work around bugs in glob.glob()
442
# - Python bug #1001604 ("glob doesn't return unicode with ...")
443
# - failing expansion for */* with non-iso-8859-* chars
444
possible_glob, corrected = _ensure_with_dir(possible_glob)
445
glob_files = glob.glob(possible_glob)
448
# special case to let the normal code path handle
449
# files that do not exists
450
expanded_file_list.append(
451
_undo_ensure_with_dir(possible_glob, corrected))
453
glob_files = [_undo_ensure_with_dir(elem, corrected) for elem in glob_files]
454
expanded_file_list += glob_files
456
return [elem.replace(u'\\', u'/') for elem in expanded_file_list]
313
459
def get_app_path(appname):
314
r"""Look up in Windows registry for full path to application executable.
460
"""Look up in Windows registry for full path to application executable.
315
461
Typically, applications create subkey with their basename
316
462
in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\
344
490
if type_id == REG_SZ:
492
if type_id == REG_EXPAND_SZ and has_win32api:
493
fullpath = win32api.ExpandEnvironmentStrings(path)
494
if len(fullpath) > 1 and fullpath[0] == '"' and fullpath[-1] == '"':
495
fullpath = fullpath[1:-1] # remove quotes around value
349
500
def set_file_attr_hidden(path):
350
501
"""Set file attributes to hidden if possible"""
351
from ctypes.wintypes import BOOL, DWORD, LPWSTR
353
# <https://docs.microsoft.com/windows/desktop/api/fileapi/nf-fileapi-setfileattributesw>
354
SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW
355
SetFileAttributes.argtypes = LPWSTR, DWORD
356
SetFileAttributes.restype = BOOL
357
FILE_ATTRIBUTE_HIDDEN = 2
358
if not SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN):
359
e = ctypes.WinError()
361
trace.mutter('Unable to set hidden attribute on %r: %s', path, e)
364
def _command_line_to_argv(command_line, argv, single_quotes_allowed=False):
365
"""Convert a Unicode command line into a list of argv arguments.
367
It performs wildcard expansion to make wildcards act closer to how they
368
work in posix shells, versus how they work by default on Windows. Quoted
369
arguments are left untouched.
371
:param command_line: The unicode string to split into an arg list.
372
:param single_quotes_allowed: Whether single quotes are accepted as quoting
373
characters like double quotes. False by
375
:return: A list of unicode strings.
377
# First, split the command line
378
s = cmdline.Splitter(
379
command_line, single_quotes_allowed=single_quotes_allowed)
381
# Bug #587868 Now make sure that the length of s agrees with sys.argv
382
# we do this by simply counting the number of arguments in each. The counts should
383
# agree no matter what encoding sys.argv is in (AFAIK)
384
# len(arguments) < len(sys.argv) should be an impossibility since python gets
385
# args from the very same PEB as does GetCommandLineW
388
# Now shorten the command line we get from GetCommandLineW to match sys.argv
389
if len(arguments) < len(argv):
390
raise AssertionError("Split command line can't be shorter than argv")
391
arguments = arguments[len(arguments) - len(argv):]
393
# Carry on to process globs (metachars) in the command line
394
# expand globs if necessary
395
# TODO: Use 'globbing' instead of 'glob.glob', this gives us stuff like
398
for is_quoted, arg in arguments:
399
if is_quoted or not glob.has_magic(arg):
503
if winver != 'Windows 98':
504
SetFileAttributes = win32file.SetFileAttributesW
402
args.extend(glob_one(arg))
406
def _ctypes_is_local_pid_dead(pid):
408
kernel32 = ctypes.wintypes.windll.kernel32
409
"""True if pid doesn't correspond to live process on this machine"""
410
handle = kernel32.OpenProcess(1, False, pid)
412
errorcode = ctypes.GetLastError()
413
if errorcode == 5: # ERROR_ACCESS_DENIED
414
# Probably something alive we're not allowed to kill
416
elif errorcode == 87: # ERROR_INVALID_PARAMETER
418
raise ctypes.WinError(errorcode)
419
Kernel32.CloseHandle(handle)
422
is_local_pid_dead = _ctypes_is_local_pid_dead
506
SetFileAttributes = win32file.SetFileAttributes
508
SetFileAttributes(path, win32file.FILE_ATTRIBUTE_HIDDEN)
509
except pywintypes.error, e:
510
from bzrlib import trace
511
trace.mutter('Unable to set hidden attribute on %r: %s', path, e)
514
if has_ctypes and winver != 'Windows 98':
515
def get_unicode_argv():
516
LPCWSTR = ctypes.c_wchar_p
518
POINTER = ctypes.POINTER
519
prototype = ctypes.WINFUNCTYPE(LPCWSTR)
520
GetCommandLine = prototype(("GetCommandLineW",
521
ctypes.windll.kernel32))
522
prototype = ctypes.WINFUNCTYPE(POINTER(LPCWSTR), LPCWSTR, POINTER(INT))
523
CommandLineToArgv = prototype(("CommandLineToArgvW",
524
ctypes.windll.shell32))
526
pargv = CommandLineToArgv(GetCommandLine(), ctypes.byref(c))
527
# Skip the first argument, since we only care about parameters
528
argv = [pargv[i] for i in range(1, c.value)]
529
if getattr(sys, 'frozen', None) is None:
530
# Invoked via 'python.exe' which takes the form:
531
# python.exe [PYTHON_OPTIONS] C:\Path\bzr [BZR_OPTIONS]
532
# we need to get only BZR_OPTIONS part,
533
# so let's using sys.argv[1:] as reference to get the tail
535
tail_len = len(sys.argv[1:])
536
ix = len(argv) - tail_len
540
get_unicode_argv = None