~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/win32utils.py

  • Committer: Andrew Bennetts
  • Date: 2010-01-15 05:30:30 UTC
  • mto: (4973.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4975.
  • Revision ID: andrew.bennetts@canonical.com-20100115053030-1d6qd89pnj8hmb55
Pass kinds (not pairs) to MergeHookParams.

Show diffs side-by-side

added added

removed removed

Lines of Context:
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""Win32-specific helper functions
18
18
 
19
19
Only one dependency: ctypes should be installed.
20
20
"""
21
21
 
 
22
import glob
22
23
import os
 
24
import re
23
25
import struct
24
26
import sys
25
27
 
66
68
        suffix = 'W'
67
69
try:
68
70
    import win32file
 
71
    import pywintypes
69
72
    has_win32file = True
70
73
except ImportError:
71
74
    has_win32file = False
96
99
UNLEN = 256
97
100
MAX_COMPUTERNAME_LENGTH = 31
98
101
 
 
102
# Registry data type ids
 
103
REG_SZ = 1
 
104
REG_EXPAND_SZ = 2
 
105
 
 
106
 
 
107
def debug_memory_win32api(message='', short=True):
 
108
    """Use trace.note() to dump the running memory info."""
 
109
    from bzrlib import trace
 
110
    if has_ctypes:
 
111
        class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
 
112
            """Used by GetProcessMemoryInfo"""
 
113
            _fields_ = [('cb', ctypes.c_ulong),
 
114
                        ('PageFaultCount', ctypes.c_ulong),
 
115
                        ('PeakWorkingSetSize', ctypes.c_size_t),
 
116
                        ('WorkingSetSize', ctypes.c_size_t),
 
117
                        ('QuotaPeakPagedPoolUsage', ctypes.c_size_t),
 
118
                        ('QuotaPagedPoolUsage', ctypes.c_size_t),
 
119
                        ('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t),
 
120
                        ('QuotaNonPagedPoolUsage', ctypes.c_size_t),
 
121
                        ('PagefileUsage', ctypes.c_size_t),
 
122
                        ('PeakPagefileUsage', ctypes.c_size_t),
 
123
                        ('PrivateUsage', ctypes.c_size_t),
 
124
                       ]
 
125
        cur_process = ctypes.windll.kernel32.GetCurrentProcess()
 
126
        mem_struct = PROCESS_MEMORY_COUNTERS_EX()
 
127
        ret = ctypes.windll.psapi.GetProcessMemoryInfo(cur_process,
 
128
            ctypes.byref(mem_struct),
 
129
            ctypes.sizeof(mem_struct))
 
130
        if not ret:
 
131
            trace.note('Failed to GetProcessMemoryInfo()')
 
132
            return
 
133
        info = {'PageFaultCount': mem_struct.PageFaultCount,
 
134
                'PeakWorkingSetSize': mem_struct.PeakWorkingSetSize,
 
135
                'WorkingSetSize': mem_struct.WorkingSetSize,
 
136
                'QuotaPeakPagedPoolUsage': mem_struct.QuotaPeakPagedPoolUsage,
 
137
                'QuotaPagedPoolUsage': mem_struct.QuotaPagedPoolUsage,
 
138
                'QuotaPeakNonPagedPoolUsage': mem_struct.QuotaPeakNonPagedPoolUsage,
 
139
                'QuotaNonPagedPoolUsage': mem_struct.QuotaNonPagedPoolUsage,
 
140
                'PagefileUsage': mem_struct.PagefileUsage,
 
141
                'PeakPagefileUsage': mem_struct.PeakPagefileUsage,
 
142
                'PrivateUsage': mem_struct.PrivateUsage,
 
143
               }
 
144
    elif has_win32api:
 
145
        import win32process
 
146
        # win32process does not return PrivateUsage, because it doesn't use
 
147
        # PROCESS_MEMORY_COUNTERS_EX (it uses the one without _EX).
 
148
        proc = win32process.GetCurrentProcess()
 
149
        info = win32process.GetProcessMemoryInfo(proc)
 
150
    else:
 
151
        trace.note('Cannot debug memory on win32 without ctypes'
 
152
                   ' or win32process')
 
153
        return
 
154
    if short:
 
155
        trace.note('WorkingSize %7dKB'
 
156
                   '\tPeakWorking %7dKB\t%s',
 
157
                   info['WorkingSetSize'] / 1024,
 
158
                   info['PeakWorkingSetSize'] / 1024,
 
159
                   message)
 
160
        return
 
161
    if message:
 
162
        trace.note('%s', message)
 
163
    trace.note('WorkingSize       %8d KB', info['WorkingSetSize'] / 1024)
 
164
    trace.note('PeakWorking       %8d KB', info['PeakWorkingSetSize'] / 1024)
 
165
    trace.note('PagefileUsage     %8d KB', info.get('PagefileUsage', 0) / 1024)
 
166
    trace.note('PeakPagefileUsage %8d KB', info.get('PeakPagefileUsage', 0) / 1024)
 
167
    trace.note('PrivateUsage      %8d KB', info.get('PrivateUsage', 0) / 1024)
 
168
    trace.note('PageFaultCount    %8d', info.get('PageFaultCount', 0))
 
169
 
99
170
 
100
171
def get_console_size(defaultx=80, defaulty=25):
101
172
    """Return size of current console.
109
180
        return (defaultx, defaulty)
110
181
 
111
182
    # To avoid problem with redirecting output via pipe
112
 
    # need to use stderr instead of stdout
 
183
    # we need to use stderr instead of stdout
113
184
    h = ctypes.windll.kernel32.GetStdHandle(WIN32_STDERR_HANDLE)
114
185
    csbi = ctypes.create_string_buffer(22)
115
186
    res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
126
197
 
127
198
def _get_sh_special_folder_path(csidl):
128
199
    """Call SHGetSpecialFolderPathW if available, or return None.
129
 
    
 
200
 
130
201
    Result is always unicode (or None).
131
202
    """
132
203
    if has_ctypes:
203
274
 
204
275
    Returned value can be unicode or plain string.
205
276
    To convert plain string to unicode use
206
 
    s.decode(bzrlib.user_encoding)
 
277
    s.decode(osutils.get_user_encoding())
207
278
    (XXX - but see bug 262874, which asserts the correct encoding is 'mbcs')
208
279
    """
209
280
    local = _get_sh_special_folder_path(CSIDL_LOCAL_APPDATA)
222
293
    If location cannot be obtained return system drive root,
223
294
    i.e. C:\
224
295
 
225
 
    Returned value can be unicode or plain sring.
 
296
    Returned value can be unicode or plain string.
226
297
    To convert plain string to unicode use
227
298
    s.decode(osutils.get_user_encoding())
228
299
    """
245
316
    """Return user name as login name.
246
317
    If name cannot be obtained return None.
247
318
 
248
 
    Returned value can be unicode or plain sring.
 
319
    Returned value can be unicode or plain string.
249
320
    To convert plain string to unicode use
250
321
    s.decode(osutils.get_user_encoding())
251
322
    """
319
390
 
320
391
 
321
392
def _ensure_unicode(s):
322
 
    from bzrlib import osutils
323
393
    if s and type(s) != unicode:
324
394
        from bzrlib import osutils
325
395
        s = s.decode(osutils.get_user_encoding())
344
414
        return u'./' + path, True
345
415
    else:
346
416
        return path, False
347
 
    
 
417
 
348
418
def _undo_ensure_with_dir(path, corrected):
349
419
    if corrected:
350
420
        return path[2:]
353
423
 
354
424
 
355
425
 
 
426
def glob_one(possible_glob):
 
427
    """Same as glob.glob().
 
428
 
 
429
    work around bugs in glob.glob()
 
430
    - Python bug #1001604 ("glob doesn't return unicode with ...")
 
431
    - failing expansion for */* with non-iso-8859-* chars
 
432
    """
 
433
    corrected_glob, corrected = _ensure_with_dir(possible_glob)
 
434
    glob_files = glob.glob(corrected_glob)
 
435
 
 
436
    if not glob_files:
 
437
        # special case to let the normal code path handle
 
438
        # files that do not exist, etc.
 
439
        glob_files = [possible_glob]
 
440
    elif corrected:
 
441
        glob_files = [_undo_ensure_with_dir(elem, corrected)
 
442
                      for elem in glob_files]
 
443
    return [elem.replace(u'\\', u'/') for elem in glob_files]
 
444
 
 
445
 
356
446
def glob_expand(file_list):
357
447
    """Replacement for glob expansion by the shell.
358
448
 
366
456
    """
367
457
    if not file_list:
368
458
        return []
369
 
    import glob
370
459
    expanded_file_list = []
371
460
    for possible_glob in file_list:
372
 
        
373
 
        # work around bugs in glob.glob()
374
 
        # - Python bug #1001604 ("glob doesn't return unicode with ...")
375
 
        # - failing expansion for */* with non-iso-8859-* chars
376
 
        possible_glob, corrected = _ensure_with_dir(possible_glob)
377
 
        glob_files = glob.glob(possible_glob)
378
 
 
379
 
        if glob_files == []:
380
 
            # special case to let the normal code path handle
381
 
            # files that do not exists
382
 
            expanded_file_list.append(
383
 
                _undo_ensure_with_dir(possible_glob, corrected))
384
 
        else:
385
 
            glob_files = [_undo_ensure_with_dir(elem, corrected) for elem in glob_files]
386
 
            expanded_file_list += glob_files
387
 
            
388
 
    return [elem.replace(u'\\', u'/') for elem in expanded_file_list] 
 
461
        expanded_file_list.extend(glob_one(possible_glob))
 
462
    return expanded_file_list
389
463
 
390
464
 
391
465
def get_app_path(appname):
392
466
    """Look up in Windows registry for full path to application executable.
393
 
    Typicaly, applications create subkey with their basename
 
467
    Typically, applications create subkey with their basename
394
468
    in HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\
395
469
 
396
470
    :param  appname:    name of application (if no filename extension
399
473
                or appname itself if nothing found.
400
474
    """
401
475
    import _winreg
 
476
 
 
477
    basename = appname
 
478
    if not os.path.splitext(basename)[1]:
 
479
        basename = appname + '.exe'
 
480
 
402
481
    try:
403
482
        hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
404
 
                               r'SOFTWARE\Microsoft\Windows'
405
 
                               r'\CurrentVersion\App Paths')
 
483
            'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' +
 
484
            basename)
406
485
    except EnvironmentError:
407
486
        return appname
408
487
 
409
 
    basename = appname
410
 
    if not os.path.splitext(basename)[1]:
411
 
        basename = appname + '.exe'
412
488
    try:
413
489
        try:
414
 
            fullpath = _winreg.QueryValue(hkey, basename)
 
490
            path, type_id = _winreg.QueryValueEx(hkey, '')
415
491
        except WindowsError:
416
 
            fullpath = appname
 
492
            return appname
417
493
    finally:
418
494
        _winreg.CloseKey(hkey)
419
495
 
420
 
    return fullpath
 
496
    if type_id == REG_SZ:
 
497
        return path
 
498
    if type_id == REG_EXPAND_SZ and has_win32api:
 
499
        fullpath = win32api.ExpandEnvironmentStrings(path)
 
500
        if len(fullpath) > 1 and fullpath[0] == '"' and fullpath[-1] == '"':
 
501
            fullpath = fullpath[1:-1]   # remove quotes around value
 
502
        return fullpath
 
503
    return appname
421
504
 
422
505
 
423
506
def set_file_attr_hidden(path):
424
507
    """Set file attributes to hidden if possible"""
425
508
    if has_win32file:
426
 
        win32file.SetFileAttributes(path, win32file.FILE_ATTRIBUTE_HIDDEN)
 
509
        if winver != 'Windows 98':
 
510
            SetFileAttributes = win32file.SetFileAttributesW
 
511
        else:
 
512
            SetFileAttributes = win32file.SetFileAttributes
 
513
        try:
 
514
            SetFileAttributes(path, win32file.FILE_ATTRIBUTE_HIDDEN)
 
515
        except pywintypes.error, e:
 
516
            from bzrlib import trace
 
517
            trace.mutter('Unable to set hidden attribute on %r: %s', path, e)
 
518
 
 
519
 
 
520
 
 
521
class UnicodeShlex(object):
 
522
    """This is a very simplified version of shlex.shlex.
 
523
 
 
524
    The main change is that it supports non-ascii input streams. The internal
 
525
    structure is quite simplified relative to shlex.shlex, since we aren't
 
526
    trying to handle multiple input streams, etc. In fact, we don't use a
 
527
    file-like api either.
 
528
    """
 
529
 
 
530
    def __init__(self, uni_string):
 
531
        self._input = uni_string
 
532
        self._input_iter = iter(self._input)
 
533
        self._whitespace_match = re.compile(u'\s').match
 
534
        self._word_match = re.compile(u'\S').match
 
535
        self._quote_chars = u'"'
 
536
        # self._quote_match = re.compile(u'[\'"]').match
 
537
        self._escape_match = lambda x: None # Never matches
 
538
        self._escape = '\\'
 
539
        # State can be
 
540
        #   ' ' - after whitespace, starting a new token
 
541
        #   'a' - after text, currently working on a token
 
542
        #   '"' - after ", currently in a "-delimited quoted section
 
543
        #   "\" - after '\', checking the next char
 
544
        self._state = ' '
 
545
        self._token = [] # Current token being parsed
 
546
 
 
547
    def _get_token(self):
 
548
        # Were there quote chars as part of this token?
 
549
        quoted = False
 
550
        quoted_state = None
 
551
        for nextchar in self._input_iter:
 
552
            if self._state == ' ':
 
553
                if self._whitespace_match(nextchar):
 
554
                    # if self._token: return token
 
555
                    continue
 
556
                elif nextchar in self._quote_chars:
 
557
                    self._state = nextchar # quoted state
 
558
                elif self._word_match(nextchar):
 
559
                    self._token.append(nextchar)
 
560
                    self._state = 'a'
 
561
                else:
 
562
                    raise AssertionError('wtttf?')
 
563
            elif self._state in self._quote_chars:
 
564
                quoted = True
 
565
                if nextchar == self._state: # End of quote
 
566
                    self._state = 'a' # posix allows 'foo'bar to translate to
 
567
                                      # foobar
 
568
                elif self._state == '"' and nextchar == self._escape:
 
569
                    quoted_state = self._state
 
570
                    self._state = nextchar
 
571
                else:
 
572
                    self._token.append(nextchar)
 
573
            elif self._state == self._escape:
 
574
                if nextchar == '\\':
 
575
                    self._token.append('\\')
 
576
                elif nextchar == '"':
 
577
                    self._token.append(nextchar)
 
578
                else:
 
579
                    self._token.append('\\' + nextchar)
 
580
                self._state = quoted_state
 
581
            elif self._state == 'a':
 
582
                if self._whitespace_match(nextchar):
 
583
                    if self._token:
 
584
                        break # emit this token
 
585
                    else:
 
586
                        continue # no token to emit
 
587
                elif nextchar in self._quote_chars:
 
588
                    # Start a new quoted section
 
589
                    self._state = nextchar
 
590
                # escape?
 
591
                elif (self._word_match(nextchar)
 
592
                      or nextchar in self._quote_chars
 
593
                      # or whitespace_split?
 
594
                      ):
 
595
                    self._token.append(nextchar)
 
596
                else:
 
597
                    raise AssertionError('state == "a", char: %r'
 
598
                                         % (nextchar,))
 
599
            else:
 
600
                raise AssertionError('unknown state: %r' % (self._state,))
 
601
        result = ''.join(self._token)
 
602
        self._token = []
 
603
        if not quoted and result == '':
 
604
            result = None
 
605
        return quoted, result
 
606
 
 
607
    def __iter__(self):
 
608
        return self
 
609
 
 
610
    def next(self):
 
611
        quoted, token = self._get_token()
 
612
        if token is None:
 
613
            raise StopIteration
 
614
        return quoted, token
 
615
 
 
616
 
 
617
def _command_line_to_argv(command_line):
 
618
    """Convert a Unicode command line into a set of argv arguments.
 
619
 
 
620
    This does wildcard expansion, etc. It is intended to make wildcards act
 
621
    closer to how they work in posix shells, versus how they work by default on
 
622
    Windows.
 
623
    """
 
624
    s = UnicodeShlex(command_line)
 
625
    # Now that we've split the content, expand globs
 
626
    # TODO: Use 'globbing' instead of 'glob.glob', this gives us stuff like
 
627
    #       '**/' style globs
 
628
    args = []
 
629
    for is_quoted, arg in s:
 
630
        if is_quoted or not glob.has_magic(arg):
 
631
            args.append(arg)
 
632
        else:
 
633
            args.extend(glob_one(arg))
 
634
    return args
 
635
 
 
636
 
 
637
if has_ctypes and winver != 'Windows 98':
 
638
    def get_unicode_argv():
 
639
        LPCWSTR = ctypes.c_wchar_p
 
640
        INT = ctypes.c_int
 
641
        POINTER = ctypes.POINTER
 
642
        prototype = ctypes.WINFUNCTYPE(LPCWSTR)
 
643
        GetCommandLine = prototype(("GetCommandLineW",
 
644
                                    ctypes.windll.kernel32))
 
645
        prototype = ctypes.WINFUNCTYPE(POINTER(LPCWSTR), LPCWSTR, POINTER(INT))
 
646
        command_line = GetCommandLine()
 
647
        # Skip the first argument, since we only care about parameters
 
648
        argv = _command_line_to_argv(command_line)[1:]
 
649
        if getattr(sys, 'frozen', None) is None:
 
650
            # Invoked via 'python.exe' which takes the form:
 
651
            #   python.exe [PYTHON_OPTIONS] C:\Path\bzr [BZR_OPTIONS]
 
652
            # we need to get only BZR_OPTIONS part,
 
653
            # We already removed 'python.exe' so we remove everything up to and
 
654
            # including the first non-option ('-') argument.
 
655
            for idx in xrange(len(argv)):
 
656
                if argv[idx][:1] != '-':
 
657
                    break
 
658
            argv = argv[idx+1:]
 
659
        return argv
 
660
else:
 
661
    get_unicode_argv = None