Skip to content

Commit 12b0df8

Browse files
authored
refactor: improve TryGetFileAbsPath() panic message (#240)
Before ``` panic: file not found: /Users/steve/.local/bin/file_not_exist ``` After ``` panic: failed to absolutize path 'file_not_exist', tried ['/Users/steve/go/src/infini.sh/loadgen/bin/file_not_exist', '/Users/steve/.local/bin/file_not_exist'], but they do not exist ```
1 parent 65beef2 commit 12b0df8

File tree

1 file changed

+34
-22
lines changed

1 file changed

+34
-22
lines changed

core/util/fsutils.go

Lines changed: 34 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -302,38 +302,50 @@ func FileExtension(file string) string {
302302
return strings.ToLower(strings.TrimSpace(ext))
303303
}
304304

305-
// Smart get file abs path
305+
// Smart get file abs path.
306+
//
307+
// If all attempts fail, and `ignoreMissing` is set to `true`, this function
308+
// returns `filePath` as-is. Otherwise, it panics.
306309
func TryGetFileAbsPath(filePath string, ignoreMissing bool) string {
307-
filename, _ := filepath.Abs(filePath)
308-
if FileExists(filename) {
309-
return filename
310-
}
311-
312-
pwd, _ := os.Getwd()
313-
if pwd != "" {
314-
pwd = path.Join(pwd, filePath)
310+
if path.IsAbs(filePath) {
311+
return filePath
315312
}
316313

317-
if FileExists(filename) {
318-
return filename
314+
/*
315+
* Interpret it relative to process working directory
316+
*/
317+
absPathRelativeToWd, _ := filepath.Abs(filePath)
318+
if FileExists(absPathRelativeToWd) {
319+
return absPathRelativeToWd
319320
}
320321

321-
ex, err := os.Executable()
322-
var exPath string
322+
/*
323+
* Interpret it relative to the directory that contains this executable.
324+
*/
325+
absPathRelativeToExeDir := ""
326+
exePath, err := os.Executable()
323327
if err == nil {
324-
exPath = filepath.Dir(ex)
325-
}
328+
exeDir := filepath.Dir(exePath)
329+
absPathRelativeToExeDir = path.Join(exeDir, filePath)
326330

327-
if exPath != "" {
328-
filename = path.Join(exPath, filePath)
331+
if FileExists(absPathRelativeToExeDir) {
332+
return absPathRelativeToExeDir
333+
}
329334
}
330335

331-
if FileExists(filename) {
332-
return filename
333-
} else {
334-
if !ignoreMissing {
335-
panic(errors.New("file not found:" + filename))
336+
/*
337+
* All attempts failed. Panic if `ignoreMissing` is not set. Otherwise,
338+
* return `filePath` as-is.
339+
*/
340+
if !ignoreMissing {
341+
errorMsg := fmt.Sprintf("failed to absolutize path '%s', tried ['%s'", filePath, absPathRelativeToWd)
342+
if absPathRelativeToExeDir != "" {
343+
errorMsg += fmt.Sprintf(", '%s'", absPathRelativeToExeDir)
336344
}
345+
errorMsg += "], but they do not exist"
346+
347+
panic(errors.New(errorMsg))
348+
} else {
337349
return filePath
338350
}
339351
}

0 commit comments

Comments
 (0)