(finalCmd *Command, args []string, lastArg string)
| 652 | } |
| 653 | |
| 654 | func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) { |
| 655 | if finalCmd.DisableFlagParsing { |
| 656 | // We only do flag completion if we are allowed to parse flags |
| 657 | // This is important for commands which have requested to do their own flag completion. |
| 658 | return nil, args, lastArg, nil |
| 659 | } |
| 660 | |
| 661 | var flagName string |
| 662 | trimmedArgs := args |
| 663 | flagWithEqual := false |
| 664 | orgLastArg := lastArg |
| 665 | |
| 666 | // When doing completion of a flag name, as soon as an argument starts with |
| 667 | // a '-' we know it is a flag. We cannot use isFlagArg() here as that function |
| 668 | // requires the flag name to be complete |
| 669 | if len(lastArg) > 0 && lastArg[0] == '-' { |
| 670 | if index := strings.Index(lastArg, "="); index >= 0 { |
| 671 | // Flag with an = |
| 672 | if strings.HasPrefix(lastArg[:index], "--") { |
| 673 | // Flag has full name |
| 674 | flagName = lastArg[2:index] |
| 675 | } else { |
| 676 | // Flag is shorthand |
| 677 | // We have to get the last shorthand flag name |
| 678 | // e.g. `-asd` => d to provide the correct completion |
| 679 | // https://github.com/spf13/cobra/issues/1257 |
| 680 | flagName = lastArg[index-1 : index] |
| 681 | } |
| 682 | lastArg = lastArg[index+1:] |
| 683 | flagWithEqual = true |
| 684 | } else { |
| 685 | // Normal flag completion |
| 686 | return nil, args, lastArg, nil |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | if len(flagName) == 0 { |
| 691 | if len(args) > 0 { |
| 692 | prevArg := args[len(args)-1] |
| 693 | if isFlagArg(prevArg) { |
| 694 | // Only consider the case where the flag does not contain an =. |
| 695 | // If the flag contains an = it means it has already been fully processed, |
| 696 | // so we don't need to deal with it here. |
| 697 | if index := strings.Index(prevArg, "="); index < 0 { |
| 698 | if strings.HasPrefix(prevArg, "--") { |
| 699 | // Flag has full name |
| 700 | flagName = prevArg[2:] |
| 701 | } else { |
| 702 | // Flag is shorthand |
| 703 | // We have to get the last shorthand flag name |
| 704 | // e.g. `-asd` => d to provide the correct completion |
| 705 | // https://github.com/spf13/cobra/issues/1257 |
| 706 | flagName = prevArg[len(prevArg)-1:] |
| 707 | } |
| 708 | // Remove the uncompleted flag or else there could be an error created |
| 709 | // for an invalid value for that flag |
| 710 | trimmedArgs = args[:len(args)-1] |
| 711 | } |
no test coverage detected