~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/win32utils.py

  • Committer: John Arbash Meinel
  • Date: 2009-11-10 19:45:43 UTC
  • mto: (4807.2.5 2.1.0b4-win32-accepted)
  • mto: This revision was merged to the branch mainline in revision 4810.
  • Revision ID: john@arbash-meinel.com-20091110194543-49bm5wv5y2x0up1v
Remove the TODO, since it works now.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
21
21
 
22
22
import glob
23
23
import os
 
24
import re
 
25
import shlex
24
26
import struct
 
27
import StringIO
25
28
import sys
26
29
 
27
 
from bzrlib import cmdline
28
30
 
29
31
# Windows version
30
32
if sys.platform == 'win32':
135
137
                'WorkingSetSize': mem_struct.WorkingSetSize,
136
138
                'QuotaPeakPagedPoolUsage': mem_struct.QuotaPeakPagedPoolUsage,
137
139
                'QuotaPagedPoolUsage': mem_struct.QuotaPagedPoolUsage,
138
 
                'QuotaPeakNonPagedPoolUsage':
139
 
                    mem_struct.QuotaPeakNonPagedPoolUsage,
 
140
                'QuotaPeakNonPagedPoolUsage': mem_struct.QuotaPeakNonPagedPoolUsage,
140
141
                'QuotaNonPagedPoolUsage': mem_struct.QuotaNonPagedPoolUsage,
141
142
                'PagefileUsage': mem_struct.PagefileUsage,
142
143
                'PeakPagefileUsage': mem_struct.PeakPagefileUsage,
153
154
                   ' or win32process')
154
155
        return
155
156
    if short:
156
 
        # using base-2 units (see HACKING.txt).
157
 
        trace.note('WorkingSize %7dKiB'
158
 
                   '\tPeakWorking %7dKiB\t%s',
 
157
        trace.note('WorkingSize %7dKB'
 
158
                   '\tPeakWorking %7dKB\t%s',
159
159
                   info['WorkingSetSize'] / 1024,
160
160
                   info['PeakWorkingSetSize'] / 1024,
161
161
                   message)
162
162
        return
163
163
    if message:
164
164
        trace.note('%s', message)
165
 
    trace.note('WorkingSize       %8d KiB', info['WorkingSetSize'] / 1024)
166
 
    trace.note('PeakWorking       %8d KiB', info['PeakWorkingSetSize'] / 1024)
167
 
    trace.note('PagefileUsage     %8d KiB', info.get('PagefileUsage', 0) / 1024)
168
 
    trace.note('PeakPagefileUsage %8d KiB',
169
 
               info.get('PeakPagefileUsage', 0) / 1024)
170
 
    trace.note('PrivateUsage      %8d KiB', info.get('PrivateUsage', 0) / 1024)
 
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)
171
170
    trace.note('PageFaultCount    %8d', info.get('PageFaultCount', 0))
172
171
 
173
172
 
183
182
        return (defaultx, defaulty)
184
183
 
185
184
    # To avoid problem with redirecting output via pipe
186
 
    # we need to use stderr instead of stdout
 
185
    # need to use stderr instead of stdout
187
186
    h = ctypes.windll.kernel32.GetStdHandle(WIN32_STDERR_HANDLE)
188
187
    csbi = ctypes.create_string_buffer(22)
189
188
    res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
190
189
 
191
190
    if res:
192
191
        (bufx, bufy, curx, cury, wattr,
193
 
        left, top, right, bottom, maxx, maxy) = struct.unpack(
194
 
            "hhhhHhhhhhh", csbi.raw)
 
192
        left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
195
193
        sizex = right - left + 1
196
194
        sizey = bottom - top + 1
197
195
        return (sizex, sizey)
394
392
 
395
393
 
396
394
def _ensure_unicode(s):
 
395
    from bzrlib import osutils
397
396
    if s and type(s) != unicode:
398
397
        from bzrlib import osutils
399
398
        s = s.decode(osutils.get_user_encoding())
414
413
 
415
414
 
416
415
def _ensure_with_dir(path):
417
 
    if (not os.path.split(path)[0] or path.startswith(u'*')
418
 
        or path.startswith(u'?')):
 
416
    if not os.path.split(path)[0] or path.startswith(u'*') or path.startswith(u'?'):
419
417
        return u'./' + path, True
420
418
    else:
421
419
        return path, False
522
520
            trace.mutter('Unable to set hidden attribute on %r: %s', path, e)
523
521
 
524
522
 
525
 
def _command_line_to_argv(command_line, single_quotes_allowed=False):
526
 
    """Convert a Unicode command line into a list of argv arguments.
527
 
 
528
 
    It performs wildcard expansion to make wildcards act closer to how they
529
 
    work in posix shells, versus how they work by default on Windows. Quoted
530
 
    arguments are left untouched.
531
 
 
532
 
    :param command_line: The unicode string to split into an arg list.
533
 
    :param single_quotes_allowed: Whether single quotes are accepted as quoting
534
 
                                  characters like double quotes. False by
535
 
                                  default.
536
 
    :return: A list of unicode strings.
537
 
    """
538
 
    s = cmdline.Splitter(command_line, single_quotes_allowed=single_quotes_allowed)
539
 
    # Now that we've split the content, expand globs if necessary
 
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
 
538
        self._quote_chars = u'\'"'
 
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 ', currently in a '-delimited quotod section
 
547
        #   "\" - after '\', checking the next char
 
548
        self._state = ' '
 
549
        self._token = [] # Current token being parsed
 
550
 
 
551
    def _get_token(self):
 
552
        # Were there quote chars as part of this token?
 
553
        quoted = False
 
554
        quoted_state = None
 
555
        for nextchar in self._input_iter:
 
556
            if self._state == ' ':
 
557
                if self._whitespace_match(nextchar):
 
558
                    # if self._token: return token
 
559
                    continue
 
560
                elif nextchar in self._quote_chars:
 
561
                    self._state = nextchar # quoted state
 
562
                elif self._word_match(nextchar):
 
563
                    self._token.append(nextchar)
 
564
                    self._state = 'a'
 
565
                else:
 
566
                    raise AssertionError('wtttf?')
 
567
            elif self._state in self._quote_chars:
 
568
                quoted = True
 
569
                if nextchar == self._state: # End of quote
 
570
                    self._state = 'a' # posix allows 'foo'bar to translate to
 
571
                                      # foobar
 
572
                elif self._state == '"' and nextchar == self._escape:
 
573
                    quoted_state = self._state
 
574
                    self._state = nextchar
 
575
                else:
 
576
                    self._token.append(nextchar)
 
577
            elif self._state == self._escape:
 
578
                if nextchar == '\\':
 
579
                    self._token.append('\\')
 
580
                elif nextchar == '"':
 
581
                    self._token.append(nextchar)
 
582
                else:
 
583
                    self._token.append('\\' + nextchar)
 
584
                self._state = quoted_state
 
585
            elif self._state == 'a':
 
586
                if self._whitespace_match(nextchar):
 
587
                    if self._token:
 
588
                        break # emit this token
 
589
                    else:
 
590
                        continue # no token to emit
 
591
                elif nextchar in self._quote_chars:
 
592
                    # Start a new quoted section
 
593
                    self._state = nextchar
 
594
                # escape?
 
595
                elif (self._word_match(nextchar)
 
596
                      or nextchar in self._quote_chars
 
597
                      # or whitespace_split?
 
598
                      ):
 
599
                    self._token.append(nextchar)
 
600
                else:
 
601
                    raise AssertionError('state == "a", char: %r'
 
602
                                         % (nextchar,))
 
603
            else:
 
604
                raise AssertionError('unknown state: %r' % (self._state,))
 
605
        result = ''.join(self._token)
 
606
        self._token = []
 
607
        if not quoted and result == '':
 
608
            result = None
 
609
        return quoted, result
 
610
 
 
611
    def __iter__(self):
 
612
        return self
 
613
 
 
614
    def next(self):
 
615
        quoted, token = self._get_token()
 
616
        if token is None:
 
617
            raise StopIteration
 
618
        return quoted, token
 
619
 
 
620
 
 
621
def _command_line_to_argv(command_line):
 
622
    """Convert a Unicode command line into a set of argv arguments.
 
623
 
 
624
    This does wildcard expansion, etc. It is intended to make wildcards act
 
625
    closer to how they work in posix shells, versus how they work by default on
 
626
    Windows.
 
627
    """
 
628
    s = UnicodeShlex(command_line)
 
629
    # Now that we've split the content, expand globs
540
630
    # TODO: Use 'globbing' instead of 'glob.glob', this gives us stuff like
541
631
    #       '**/' style globs
542
632
    args = []
543
633
    for is_quoted, arg in s:
544
634
        if is_quoted or not glob.has_magic(arg):
545
 
            args.append(arg)
 
635
            args.append(arg.replace(u'\\', u'/'))
546
636
        else:
547
637
            args.extend(glob_one(arg))
548
638
    return args
550
640
 
551
641
if has_ctypes and winver != 'Windows 98':
552
642
    def get_unicode_argv():
553
 
        prototype = ctypes.WINFUNCTYPE(ctypes.c_wchar_p)
554
 
        GetCommandLineW = prototype(("GetCommandLineW",
555
 
                                     ctypes.windll.kernel32))
556
 
        command_line = GetCommandLineW()
557
 
        if command_line is None:
558
 
            raise ctypes.WinError()
 
643
        LPCWSTR = ctypes.c_wchar_p
 
644
        INT = ctypes.c_int
 
645
        POINTER = ctypes.POINTER
 
646
        prototype = ctypes.WINFUNCTYPE(LPCWSTR)
 
647
        GetCommandLine = prototype(("GetCommandLineW",
 
648
                                    ctypes.windll.kernel32))
 
649
        prototype = ctypes.WINFUNCTYPE(POINTER(LPCWSTR), LPCWSTR, POINTER(INT))
 
650
        command_line = GetCommandLine()
559
651
        # Skip the first argument, since we only care about parameters
560
 
        argv = _command_line_to_argv(command_line)[1:]
 
652
        argv = _command_line_to_argv(GetCommandLine())[1:]
561
653
        if getattr(sys, 'frozen', None) is None:
562
654
            # Invoked via 'python.exe' which takes the form:
563
655
            #   python.exe [PYTHON_OPTIONS] C:\Path\bzr [BZR_OPTIONS]