1
1
package hubtest
2
2
3
3
import (
4
+ "errors"
4
5
"fmt"
6
+ "io/fs"
5
7
"os"
6
8
"os/exec"
7
9
"path/filepath"
10
+ "strings"
8
11
9
12
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
10
13
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
58
61
`
59
62
)
60
63
64
+ // resolveBinaryPath returns the absolute path to an executable.
65
+ // - If the `binary` argument is relative, it is resolved as absolute.
66
+ // - If it's not a path, it's looked up in $PATH.
67
+ // In all cases it returns an error if the file doesn’t exist (after following links) or is a directory.
68
+ func resolveBinaryPath (binary string ) (string , error ) {
69
+ var resolved string
70
+
71
+ switch {
72
+ case filepath .IsAbs (binary ):
73
+ resolved = binary
74
+ case strings .Contains (binary , string (os .PathSeparator )):
75
+ absPath , err := filepath .Abs (binary )
76
+ if err != nil {
77
+ return "" , err
78
+ }
79
+ resolved = absPath
80
+ default :
81
+ p , err := exec .LookPath (binary )
82
+ if err != nil {
83
+ return "" , err
84
+ }
85
+ resolved = p
86
+ }
87
+
88
+ f , err := os .Stat (resolved )
89
+ switch {
90
+ case errors .Is (err , fs .ErrNotExist ):
91
+ return "" , err
92
+ case err != nil :
93
+ return "" , err
94
+ }
95
+
96
+ if f .IsDir () {
97
+ return "" , fmt .Errorf ("%q is a directory, not a file" , resolved )
98
+ }
99
+
100
+ return resolved , nil
101
+ }
102
+
61
103
func NewHubTest (hubPath string , crowdsecPath string , cscliPath string , isAppsecTest bool ) (HubTest , error ) {
62
104
hubPath , err := filepath .Abs (hubPath )
63
105
if err != nil {
@@ -74,17 +116,13 @@ func NewHubTest(hubPath string, crowdsecPath string, cscliPath string, isAppsecT
74
116
return HubTest {}, fmt .Errorf ("path to hub '%s' doesn't exist, can't run" , hubPath )
75
117
}
76
118
// we can't use hubtest without crowdsec binary
77
- if _ , err = exec .LookPath (crowdsecPath ); err != nil {
78
- if _ , err = os .Stat (crowdsecPath ); os .IsNotExist (err ) {
79
- return HubTest {}, fmt .Errorf ("path to crowdsec binary '%s' doesn't exist or is not in $PATH, can't run" , crowdsecPath )
80
- }
119
+ if crowdsecPath , err = resolveBinaryPath (crowdsecPath ); err != nil {
120
+ return HubTest {}, fmt .Errorf ("can't find crowdsec binary: %w" , err )
81
121
}
82
122
83
123
// we can't use hubtest without cscli binary
84
- if _ , err = exec .LookPath (cscliPath ); err != nil {
85
- if _ , err = os .Stat (cscliPath ); os .IsNotExist (err ) {
86
- return HubTest {}, fmt .Errorf ("path to cscli binary '%s' doesn't exist or is not in $PATH, can't run" , cscliPath )
87
- }
124
+ if cscliPath , err = resolveBinaryPath (cscliPath ); err != nil {
125
+ return HubTest {}, fmt .Errorf ("can't find cscli binary: %w" , err )
88
126
}
89
127
90
128
if isAppsecTest {
0 commit comments