Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
lima-vm
GitHub Repository: lima-vm/lima
Path: blob/master/pkg/localpathutil/localpathutil.go
2610 views
1
// SPDX-FileCopyrightText: Copyright The Lima Authors
2
// SPDX-License-Identifier: Apache-2.0
3
4
package localpathutil
5
6
import (
7
"errors"
8
"fmt"
9
"os"
10
"path/filepath"
11
"strings"
12
)
13
14
// IsTildePath returns true if the path is "~" or starts with "~/".
15
// This means Expand() can expand it with the home directory.
16
func IsTildePath(path string) bool {
17
return path == "~" || strings.HasPrefix(path, "~/")
18
}
19
20
// Expand expands a path like "~", "~/", "~/foo".
21
// Paths like "~foo/bar" are unsupported.
22
//
23
// FIXME: is there an existing library for this?
24
func Expand(orig string) (string, error) {
25
s := orig
26
if s == "" {
27
return "", errors.New("empty path")
28
}
29
30
if strings.HasPrefix(s, "~") {
31
if IsTildePath(s) {
32
homeDir, err := os.UserHomeDir()
33
if err != nil {
34
return "", err
35
}
36
s = strings.Replace(s, "~", homeDir, 1)
37
} else {
38
// Paths like "~foo/bar" are unsupported.
39
return "", fmt.Errorf("unexpandable path %q", orig)
40
}
41
}
42
return filepath.Abs(s)
43
}
44
45