gh-126390: Support for preserving order of options and nonoption argu… · ebonnal/cpython@31a0795

@@ -24,9 +24,6 @@

2424

# TODO for gnu_getopt():

2525

#

2626

# - GNU getopt_long_only mechanism

27-

# - allow the caller to specify ordering

28-

# - RETURN_IN_ORDER option

29-

# - GNU extension with '-' as first character of option string

3027

# - an option string with a W followed by semicolon should

3128

# treat "-W foo" as "--foo"

3229

@@ -63,7 +60,7 @@ def getopt(args, shortopts, longopts = []):

6360

long options which should be supported. The leading '--'

6461

characters should not be included in the option name. Options

6562

which require an argument should be followed by an equal sign

66-

('='). Options which acept an optional argument should be

63+

('='). Options which accept an optional argument should be

6764

followed by an equal sign and question mark ('=?').

68656966

The return value consists of two elements: the first is a list of

@@ -116,8 +113,13 @@ def gnu_getopt(args, shortopts, longopts = []):

116113

else:

117114

longopts = list(longopts)

118115116+

return_in_order = False

117+

if shortopts.startswith('-'):

118+

shortopts = shortopts[1:]

119+

all_options_first = False

120+

return_in_order = True

119121

# Allow options after non-option arguments?

120-

if shortopts.startswith('+'):

122+

elif shortopts.startswith('+'):

121123

shortopts = shortopts[1:]

122124

all_options_first = True

123125

elif os.environ.get("POSIXLY_CORRECT"):

@@ -131,8 +133,14 @@ def gnu_getopt(args, shortopts, longopts = []):

131133

break

132134133135

if args[0][:2] == '--':

136+

if return_in_order and prog_args:

137+

opts.append((None, prog_args))

138+

prog_args = []

134139

opts, args = do_longs(opts, args[0][2:], longopts, args[1:])

135140

elif args[0][:1] == '-' and args[0] != '-':

141+

if return_in_order and prog_args:

142+

opts.append((None, prog_args))

143+

prog_args = []

136144

opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])

137145

else:

138146

if all_options_first: