~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/win32utils.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-11-08 02:16:17 UTC
  • mfrom: (4780.1.6 419776-subunit)
  • Revision ID: pqm@pqm.ubuntu.com-20091108021617-uqg5jxt2xx7lm4fe
(vila) Make --parallel=fork compatible with --subunit,
        treat skips as success

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006, 2007 Canonical Ltd
 
2
#
 
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
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Win32-specific helper functions
 
18
 
 
19
Only one dependency: ctypes should be installed.
 
20
"""
 
21
 
 
22
import glob
 
23
import os
 
24
import re
 
25
import shlex
 
26
import struct
 
27
import StringIO
 
28
import sys
 
29
 
 
30
 
 
31
# Windows version
 
32
if sys.platform == 'win32':
 
33
    _major,_minor,_build,_platform,_text = sys.getwindowsversion()
 
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
 
53
        winver = 'Windows 98'
 
54
else:
 
55
    winver = None
 
56
 
 
57
 
 
58
# We can cope without it; use a separate variable to help pyflakes
 
59
try:
 
60
    import ctypes
 
61
    has_ctypes = True
 
62
except ImportError:
 
63
    has_ctypes = False
 
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'
 
71
try:
 
72
    import win32file
 
73
    import pywintypes
 
74
    has_win32file = True
 
75
except ImportError:
 
76
    has_win32file = False
 
77
try:
 
78
    import win32api
 
79
    has_win32api = True
 
80
except ImportError:
 
81
    has_win32api = False
 
82
 
 
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...
 
87
 
 
88
# Special Win32 API constants
 
89
# Handles of std streams
 
90
WIN32_STDIN_HANDLE = -10
 
91
WIN32_STDOUT_HANDLE = -11
 
92
WIN32_STDERR_HANDLE = -12
 
93
 
 
94
# CSIDL constants (from MSDN 2003)
 
95
CSIDL_APPDATA = 0x001A      # Application Data folder
 
96
CSIDL_LOCAL_APPDATA = 0x001c# <user name>\Local Settings\Application Data (non roaming)
 
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
 
 
104
# Registry data type ids
 
105
REG_SZ = 1
 
106
REG_EXPAND_SZ = 2
 
107
 
 
108
 
 
109
def debug_memory_win32api(message='', short=True):
 
110
    """Use trace.note() to dump the running memory info."""
 
111
    from bzrlib import trace
 
112
    if has_ctypes:
 
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
               }
 
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)
 
152
    else:
 
153
        trace.note('Cannot debug memory on win32 without ctypes'
 
154
                   ' or win32process')
 
155
        return
 
156
    if short:
 
157
        trace.note('WorkingSize %7dKB'
 
158
                   '\tPeakWorking %7dKB\t%s',
 
159
                   info['WorkingSetSize'] / 1024,
 
160
                   info['PeakWorkingSetSize'] / 1024,
 
161
                   message)
 
162
        return
 
163
    if message:
 
164
        trace.note('%s', message)
 
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)
 
170
    trace.note('PageFaultCount    %8d', info.get('PageFaultCount', 0))
 
171
 
 
172
 
 
173
def get_console_size(defaultx=80, defaulty=25):
 
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,
 
192
        left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
 
193
        sizex = right - left + 1
 
194
        sizey = bottom - top + 1
 
195
        return (sizex, sizey)
 
196
    else:
 
197
        return (defaultx, defaulty)
 
198
 
 
199
 
 
200
def _get_sh_special_folder_path(csidl):
 
201
    """Call SHGetSpecialFolderPathW if available, or return None.
 
202
 
 
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
 
 
235
def get_appdata_location():
 
236
    """Return Application Data location.
 
237
    Return None if we cannot obtain location.
 
238
 
 
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.
 
245
    To convert plain string to unicode use
 
246
    s.decode(osutils.get_user_encoding())
 
247
    (XXX - but see bug 262874, which asserts the correct encoding is 'mbcs')
 
248
    """
 
249
    appdata = _get_sh_special_folder_path(CSIDL_APPDATA)
 
250
    if appdata:
 
251
        return appdata
 
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
 
 
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
 
279
    s.decode(osutils.get_user_encoding())
 
280
    (XXX - but see bug 262874, which asserts the correct encoding is 'mbcs')
 
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
 
 
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
 
 
298
    Returned value can be unicode or plain string.
 
299
    To convert plain string to unicode use
 
300
    s.decode(osutils.get_user_encoding())
 
301
    """
 
302
    home = _get_sh_special_folder_path(CSIDL_PERSONAL)
 
303
    if home:
 
304
        return home
 
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:
 
312
        return os.path.splitdrive(windir)[0] + '/'
 
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
 
 
321
    Returned value can be unicode or plain string.
 
322
    To convert plain string to unicode use
 
323
    s.decode(osutils.get_user_encoding())
 
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
 
 
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
 
 
344
def get_host_name():
 
345
    """Return host machine name.
 
346
    If name cannot be obtained return None.
 
347
 
 
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.
 
350
    """
 
351
    if has_win32api:
 
352
        try:
 
353
            return win32api.GetComputerNameEx(_WIN32_ComputerNameDnsHostname)
 
354
        except (NotImplementedError, win32api.error):
 
355
            # NotImplemented will happen on win9x...
 
356
            pass
 
357
    if has_ctypes:
 
358
        try:
 
359
            kernel32 = ctypes.windll.kernel32
 
360
        except AttributeError:
 
361
            pass # Missing the module we need
 
362
        else:
 
363
            buf = create_buffer(MAX_COMPUTERNAME_LENGTH+1)
 
364
            n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH+1)
 
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))):
 
382
                return buf.value
 
383
    # otherwise try env variables, which will be 'mbcs' encoded
 
384
    # on Windows (Python doesn't expose the native win32 unicode environment)
 
385
    # According to this:
 
386
    # http://msdn.microsoft.com/en-us/library/aa246807.aspx
 
387
    # environment variables should always be encoded in 'mbcs'.
 
388
    try:
 
389
        return os.environ['COMPUTERNAME'].decode("mbcs")
 
390
    except KeyError:
 
391
        return None
 
392
 
 
393
 
 
394
def _ensure_unicode(s):
 
395
    from bzrlib import osutils
 
396
    if s and type(s) != unicode:
 
397
        from bzrlib import osutils
 
398
        s = s.decode(osutils.get_user_encoding())
 
399
    return s
 
400
 
 
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())
 
413
 
 
414
 
 
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
 
420
 
 
421
def _undo_ensure_with_dir(path, corrected):
 
422
    if corrected:
 
423
        return path[2:]
 
424
    else:
 
425
        return path
 
426
 
 
427
 
 
428
 
 
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
 
 
449
def glob_expand(file_list):
 
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:
 
464
        expanded_file_list.extend(glob_one(possible_glob))
 
465
    return expanded_file_list
 
466
 
 
467
 
 
468
def get_app_path(appname):
 
469
    """Look up in Windows registry for full path to application executable.
 
470
    Typically, applications create subkey with their basename
 
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
    """
 
478
    import _winreg
 
479
 
 
480
    basename = appname
 
481
    if not os.path.splitext(basename)[1]:
 
482
        basename = appname + '.exe'
 
483
 
 
484
    try:
 
485
        hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
 
486
            'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\' +
 
487
            basename)
 
488
    except EnvironmentError:
 
489
        return appname
 
490
 
 
491
    try:
 
492
        try:
 
493
            path, type_id = _winreg.QueryValueEx(hkey, '')
 
494
        except WindowsError:
 
495
            return appname
 
496
    finally:
 
497
        _winreg.CloseKey(hkey)
 
498
 
 
499
    if type_id == REG_SZ:
 
500
        return path
 
501
    if type_id == REG_EXPAND_SZ and has_win32api:
 
502
        fullpath = win32api.ExpandEnvironmentStrings(path)
 
503
        if len(fullpath) > 1 and fullpath[0] == '"' and fullpath[-1] == '"':
 
504
            fullpath = fullpath[1:-1]   # remove quotes around value
 
505
        return fullpath
 
506
    return appname
 
507
 
 
508
 
 
509
def set_file_attr_hidden(path):
 
510
    """Set file attributes to hidden if possible"""
 
511
    if has_win32file:
 
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:
 
519
            from bzrlib import trace
 
520
            trace.mutter('Unable to set hidden attribute on %r: %s', path, e)
 
521
 
 
522
 
 
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 '\', 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:
 
633
        if is_quoted or not glob.has_magic(arg):
 
634
            args.append(arg.replace(u'\\', u'/'))
 
635
        else:
 
636
            args.extend(glob_one(arg))
 
637
    return args
 
638
 
 
639
 
 
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))
 
649
        command_line = GetCommandLine()
 
650
        # Skip the first argument, since we only care about parameters
 
651
        argv = _command_line_to_argv(GetCommandLine())[1:]
 
652
        if getattr(sys, 'frozen', None) is None:
 
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,
 
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:]
 
662
        return argv
 
663
else:
 
664
    get_unicode_argv = None