comparison mercurial/pycompat.py @ 30583:c6ce11f2ee50

py3: make a bytes version of getopt.getopt() getopt.getopt() deals with unicodes on Python 3 internally and if bytes arguments are passed, then it will return TypeError. So we have now pycompat.getoptb() which takes bytes arguments, convert them to unicode, call getopt.getopt() and then convert the returned value back to bytes and then return those value. All the instances of getopt.getopt() are replaced with pycompat.getoptb().
author Pulkit Goyal <7895pulkit@gmail.com>
date Tue, 06 Dec 2016 06:36:36 +0530
parents fc0cfe6c87d7
children fbc3f73dc802
comparison
equal deleted inserted replaced
30582:6146d5acee69 30583:c6ce11f2ee50
8 This contains aliases to hide python version-specific details from the core. 8 This contains aliases to hide python version-specific details from the core.
9 """ 9 """
10 10
11 from __future__ import absolute_import 11 from __future__ import absolute_import
12 12
13 import getopt
13 import os 14 import os
14 import sys 15 import sys
15 16
16 ispy3 = (sys.version_info[0] >= 3) 17 ispy3 = (sys.version_info[0] >= 3)
17 18
85 getattr = _wrapattrfunc(builtins.getattr) 86 getattr = _wrapattrfunc(builtins.getattr)
86 hasattr = _wrapattrfunc(builtins.hasattr) 87 hasattr = _wrapattrfunc(builtins.hasattr)
87 setattr = _wrapattrfunc(builtins.setattr) 88 setattr = _wrapattrfunc(builtins.setattr)
88 xrange = builtins.range 89 xrange = builtins.range
89 90
91 # getopt.getopt() on Python 3 deals with unicodes internally so we cannot
92 # pass bytes there. Passing unicodes will result in unicodes as return
93 # values which we need to convert again to bytes.
94 def getoptb(args, shortlist, namelist):
95 args = [a.decode('latin-1') for a in args]
96 shortlist = shortlist.decode('latin-1')
97 namelist = [a.decode('latin-1') for a in namelist]
98 opts, args = getopt.getopt(args, shortlist, namelist)
99 opts = [(a[0].encode('latin-1'), a[1].encode('latin-1'))
100 for a in opts]
101 args = [a.encode('latin-1') for a in args]
102 return opts, args
103
90 else: 104 else:
91 def sysstr(s): 105 def sysstr(s):
92 return s 106 return s
93 107
94 # Partial backport from os.py in Python 3, which only accepts bytes. 108 # Partial backport from os.py in Python 3, which only accepts bytes.
103 117
104 # In Python 2, fsdecode() has a very chance to receive bytes. So it's 118 # In Python 2, fsdecode() has a very chance to receive bytes. So it's
105 # better not to touch Python 2 part as it's already working fine. 119 # better not to touch Python 2 part as it's already working fine.
106 def fsdecode(filename): 120 def fsdecode(filename):
107 return filename 121 return filename
122
123 def getoptb(args, shortlist, namelist):
124 return getopt.getopt(args, shortlist, namelist)
108 125
109 osname = os.name 126 osname = os.name
110 ospathsep = os.pathsep 127 ospathsep = os.pathsep
111 ossep = os.sep 128 ossep = os.sep
112 stdin = sys.stdin 129 stdin = sys.stdin