gstat/args/args.go

90 lines
2 KiB
Go
Raw Permalink Normal View History

2020-05-01 16:15:50 +02:00
package args
2020-05-03 16:24:05 +02:00
import (
"errors"
2020-11-10 14:50:31 +01:00
"fmt"
"os"
2020-05-09 14:30:54 +02:00
"strings"
2020-05-03 16:24:05 +02:00
"github.com/jessevdk/go-flags"
)
// Arguments represent the flags given at program start.
2020-05-01 16:15:50 +02:00
type Arguments struct {
2020-11-15 20:25:31 +01:00
CPU bool `short:"c" long:"cpu" description:"Include the total CPU consumption."`
Mem bool `short:"m" long:"mem" description:"Include the RAM usage."`
Disk bool `short:"d" long:"disk" description:"Include the Disk usage."`
Processes bool `short:"p" long:"proc" description:"Include the top 10 running processes with the highest CPU consumption."`
Health string `long:"health" description:"Make a healthcheck call against the URI."`
2020-05-03 16:24:05 +02:00
rest []string
}
2020-05-09 14:30:54 +02:00
// Validate the arguments.
2020-05-28 22:17:38 +02:00
func (a *Arguments) Validate() []ValidationError {
var validationErrors = make([]ValidationError, 0, 10)
if a.Equals(Arguments{}) {
return append(validationErrors, newValidationError(*a, "Arguments are empty"))
}
err := uriValidate(a.Health)
if err != nil {
validationErrors = append(validationErrors, newValidationError(*a, err.Error()))
}
2020-05-28 22:17:38 +02:00
return validationErrors
2020-05-03 16:24:05 +02:00
}
// Equals checks for field equality
func (a Arguments) Equals(other Arguments) bool {
if a.CPU != other.CPU {
return false
}
if a.Mem != other.Mem {
return false
}
if a.Disk != other.Disk {
return false
}
if a.Processes != other.Processes {
return false
}
if a.Health != other.Health {
return false
}
return true
}
// Parse the flags to the Arguments struct.
2020-05-03 16:24:05 +02:00
func Parse() Arguments {
args := Arguments{}
2020-05-29 13:44:48 +02:00
_, err := flags.Parse(&args)
2020-05-03 16:24:05 +02:00
if err != nil {
2020-11-10 14:50:31 +01:00
if _, ok := err.(*flags.Error); ok {
os.Exit(1)
} else {
fmt.Println(err)
os.Exit(1)
}
2020-05-03 16:24:05 +02:00
}
return args
2020-05-01 16:15:50 +02:00
}
2020-05-09 14:30:54 +02:00
func uriValidate(uri string) error {
scheme := strings.Split(uri, "://")
if len(scheme) < 2 {
return errors.New("The URI does not looks like schema://provider")
}
if len(strings.Split(scheme[1], ".")) < 2 {
return errors.New("The URI provider does not has a top and second level domain like example.com")
}
return nil
}