...

Source file src/github.com/Microsoft/hcsshim/internal/appargs/appargs.go

Documentation: github.com/Microsoft/hcsshim/internal/appargs

     1  // Package appargs provides argument validation routines for use with
     2  // github.com/urfave/cli.
     3  package appargs
     4  
     5  import (
     6  	"errors"
     7  	"strconv"
     8  
     9  	"github.com/urfave/cli"
    10  )
    11  
    12  // Validator is an argument validator function. It returns the number of
    13  // arguments consumed or -1 on error.
    14  type Validator = func([]string) int
    15  
    16  // String is a validator for strings.
    17  func String(args []string) int {
    18  	if len(args) == 0 {
    19  		return -1
    20  	}
    21  	return 1
    22  }
    23  
    24  // NonEmptyString is a validator for non-empty strings.
    25  func NonEmptyString(args []string) int {
    26  	if len(args) == 0 || args[0] == "" {
    27  		return -1
    28  	}
    29  	return 1
    30  }
    31  
    32  // Int returns a validator for integers.
    33  func Int(base int, min int, max int) Validator {
    34  	return func(args []string) int {
    35  		if len(args) == 0 {
    36  			return -1
    37  		}
    38  		i, err := strconv.ParseInt(args[0], base, 0)
    39  		if err != nil || int(i) < min || int(i) > max {
    40  			return -1
    41  		}
    42  		return 1
    43  	}
    44  }
    45  
    46  // Optional returns a validator that treats an argument as optional.
    47  func Optional(v Validator) Validator {
    48  	return func(args []string) int {
    49  		if len(args) == 0 {
    50  			return 0
    51  		}
    52  		return v(args)
    53  	}
    54  }
    55  
    56  // Rest returns a validator that validates each of the remaining arguments.
    57  func Rest(v Validator) Validator {
    58  	return func(args []string) int {
    59  		count := len(args)
    60  		for len(args) != 0 {
    61  			n := v(args)
    62  			if n < 0 {
    63  				return n
    64  			}
    65  			args = args[n:]
    66  		}
    67  		return count
    68  	}
    69  }
    70  
    71  // ErrInvalidUsage is returned when there is a validation error.
    72  var ErrInvalidUsage = errors.New("invalid command usage")
    73  
    74  // Validate can be used as a command's Before function to validate the arguments
    75  // to the command.
    76  func Validate(vs ...Validator) cli.BeforeFunc {
    77  	return func(context *cli.Context) error {
    78  		remaining := context.Args()
    79  		for _, v := range vs {
    80  			consumed := v(remaining)
    81  			if consumed < 0 {
    82  				return ErrInvalidUsage
    83  			}
    84  			remaining = remaining[consumed:]
    85  		}
    86  
    87  		if len(remaining) > 0 {
    88  			return ErrInvalidUsage
    89  		}
    90  
    91  		return nil
    92  	}
    93  }
    94  

View as plain text