-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconfirmeddir.go
54 lines (46 loc) · 1.47 KB
/
confirmeddir.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
// SPDX-FileCopyrightText: 2024-Present Datadog, Inc
// SPDX-License-Identifier: Apache-2.0
package vfs
import (
"fmt"
"os"
"path/filepath"
"strings"
)
// ConfirmedDir is a clean, absolute, delinkified path
// that was confirmed to point to an existing directory.
type ConfirmedDir string
// NewTmpConfirmedDir returns a temporary dir, else error.
// The directory is cleaned, no symlinks, etc. so it's
// returned as a ConfirmedDir.
func NewTmpConfirmedDir() (ConfirmedDir, error) {
n, err := os.MkdirTemp("", "dd-vfs-")
if err != nil {
return "", fmt.Errorf("unable to create temporary directory: %w", err)
}
// In MacOs `os.MkdirTemp` creates a directory
// with root in the `/var` folder, which is in turn
// a symlinked path to `/private/var`.
// Function `filepath.EvalSymlinks`is used to
// resolve the real absolute path.
deLinked, err := filepath.EvalSymlinks(n)
return ConfirmedDir(deLinked), err
}
// HasPrefix ensure that the given path has the confirmed directory as prefix.
func (d ConfirmedDir) HasPrefix(path ConfirmedDir) bool {
upath := ConfirmedDir(filepath.ToSlash(path.String()))
ud := ConfirmedDir(filepath.ToSlash(d.String()))
if upath.String() == FakeRoot || upath == ud {
return true
}
return strings.HasPrefix(
string(ud),
string(upath)+"/")
}
// Join the given path to the confirmed directory.
func (d ConfirmedDir) Join(path string) string {
return filepath.Join(string(d), path)
}
func (d ConfirmedDir) String() string {
return string(d)
}