go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/flag/fixflagpos/fix.go (about)

     1  // Copyright 2017 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package fixflagpos
    16  
    17  import (
    18  	"strings"
    19  )
    20  
    21  // Fix rearranges an `args []string` command line to enable positional arguments
    22  // to be allowed before flag arguments, which makes some invocations look more
    23  // natural.
    24  //
    25  // Converts [pos1 pos2 -flag value pos3] into [-flag value pos3 pos1 pos2].
    26  func Fix(args []string) []string {
    27  	// Find the first flag argument or '--'.
    28  	flagIdx := -1
    29  	for i, arg := range args {
    30  		if strings.HasPrefix(arg, "-") {
    31  			flagIdx = i
    32  			break
    33  		}
    34  	}
    35  
    36  	if flagIdx == -1 {
    37  		return args // no arguments at all or only positional arguments
    38  	}
    39  
    40  	// Move positional arguments after the flags.
    41  	buf := make([]string, 0, len(args))
    42  	return append(append(buf, args[flagIdx:]...), args[:flagIdx]...)
    43  }
    44  
    45  // FixSubcommands is like Fix, except the first positional argument is
    46  // understood as a subcommand name and it is not moved.
    47  //
    48  // Converts [pos1 pos2 -flag value pos3] into [pos1 -flag value pos3 pos2].
    49  //
    50  // Taking cipd as an example, compare:
    51  //   - Default: cipd set-ref -ref=abc -version=def package/name
    52  //   - Improved: cipd set-ref package/name -ref=abc -version=def
    53  //
    54  // Much better.
    55  func FixSubcommands(args []string) []string {
    56  	// Nothing do it if the first argument is a flag.
    57  	if len(args) == 0 || strings.HasPrefix(args[0], "-") {
    58  		return args
    59  	}
    60  	buf := make([]string, 0, len(args))
    61  	return append(append(buf, args[0]), Fix(args[1:])...)
    62  }