-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
known.go
99 lines (86 loc) · 1.93 KB
/
known.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// package main contains the logic for the "known" command
package main
import (
"errors"
"fmt"
"log"
"regexp"
"runtime"
"strings"
"github.com/oalders/is/attr"
"github.com/oalders/is/os"
"github.com/oalders/is/parser"
"github.com/oalders/is/types"
"github.com/oalders/is/version"
)
// Run "is known ...".
//
//nolint:gocritic
func (r *KnownCmd) Run(ctx *types.Context) error {
result := ""
var err error
isVersion, segment, err := isVersion(r)
if err != nil {
return err
}
if r.OS.Attr != "" {
result, err = os.Info(ctx, r.OS.Attr)
} else if r.CLI.Attr != "" {
result, err = runCLI(ctx, r.CLI.Name)
} else if r.Arch.Attr != "" {
result = runtime.GOARCH
}
if err != nil {
return err
}
if len(result) > 0 && isVersion {
got, err := version.NewVersion(result)
if err != nil {
return errors.Join(errors.New("parse version from output"), err)
}
segments := got.Segments()
result = fmt.Sprintf("%d", segments[segment])
}
if len(result) > 0 {
ctx.Success = true
}
//nolint:forbidigo
fmt.Println(result)
return err
}
func isVersion(r *KnownCmd) (bool, uint, error) { //nolint:varnamelen
if r.OS.Attr == attr.Version || r.CLI.Attr == attr.Version {
switch {
case r.Major:
return true, 0, nil
case r.Minor:
return true, 1, nil
case r.Patch:
return true, 2, nil
}
}
if r.Major || r.Minor || r.Patch {
return false, 0, errors.New("--major, --minor and --patch can only be used with version")
}
return false, 0, nil
}
func runCLI(ctx *types.Context, cliName string) (string, error) {
result, err := parser.CLIOutput(ctx, cliName)
if err != nil {
re := regexp.MustCompile(`executable file not found`)
if re.MatchString(err.Error()) {
if ctx.Debug {
log.Printf("executable file \"%s\" not found", cliName)
}
ctx.Success = false
return "", nil
}
return "", err
}
if len(result) > 0 {
if err != nil {
result = strings.TrimRight(result, "\n")
}
}
return result, err
}