-
Notifications
You must be signed in to change notification settings - Fork 17
/
linker.go
58 lines (47 loc) · 1.12 KB
/
linker.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
package npminstall
import (
"crypto/sha256"
"fmt"
"os"
"path/filepath"
)
type Linker struct {
tmpDir string
path string
}
func NewLinker(tmpDir string) Linker {
return Linker{
tmpDir: tmpDir,
}
}
func (l Linker) WithPath(path string) Symlinker {
l.path = path
return l
}
func (l Linker) Link(source, target string) error {
indirection := filepath.Join(l.tmpDir, fmt.Sprintf("%x", sha256.Sum256([]byte(source+target))))
if l.path != "" {
indirection = filepath.Join(l.tmpDir, l.path)
}
err := os.RemoveAll(source)
if err != nil {
return fmt.Errorf("failed to remove link source: %w", err)
}
err = os.RemoveAll(indirection)
if err != nil {
return fmt.Errorf("failed to remove link indirection: %w", err)
}
err = os.MkdirAll(filepath.Dir(indirection), os.ModePerm)
if err != nil {
return fmt.Errorf("failed to create indirection path: %w", err)
}
err = os.Symlink(indirection, source)
if err != nil {
return fmt.Errorf("failed to create link source: %w", err)
}
err = os.Symlink(target, indirection)
if err != nil {
return fmt.Errorf("failed to create link indirection: %w", err)
}
return nil
}