Repository navigation
Expand file tree
/
Copy pathbinary.go
More file actions
103 lines (92 loc) · 1.95 KB
/
Copy pathbinary.go
File metadata and controls
103 lines (92 loc) · 1.95 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Package binary provides a binary manager
package binary
import (
"os"
"path/filepath"
"github.com/fentas/b/pkg/path"
)
func (b *Binary) LocalBinary(remote bool) *LocalBinary {
var latest string
if b.VersionF != nil && remote {
latest, _ = b.VersionF(b)
}
version := b.Version
if b.VersionLocalF != nil {
version, _ = b.VersionLocalF(b)
}
file := b.BinaryPath()
if !b.BinaryExists() {
file = ""
}
return &LocalBinary{
Name: b.Name,
Alias: b.Alias,
File: file,
Version: version,
Latest: latest,
Enforced: b.Version,
}
}
// BinaryPath is the path of the binary's file (FilePath). It sets File to
// it when File is empty.
func (b *Binary) BinaryPath() string {
if b.File == "" {
b.File = b.FilePath()
}
return b.File
}
// FilePath is the path of the binary's file: File, else the alias or the
// name in the binary directory. Unlike BinaryPath, it does not set File.
func (b *Binary) FilePath() string {
if b.File != "" {
return b.File
}
name := b.Alias
if name == "" {
name = b.Name
}
return filepath.Join(path.GetBinaryPath(), name)
}
func (b *Binary) BinaryExists() bool {
path := b.BinaryPath()
if path == "" {
return false
}
_, err := os.Stat(path)
return err == nil
}
func (b *Binary) EnsureBinary(update bool) error {
if b.BinaryExists() {
if !update {
return nil
}
local := b.LocalBinary(true)
if local.Version == local.Enforced || local.Enforced == "" && local.Latest == local.Version {
return nil
}
}
return b.DownloadBinary()
}
func (b *Binary) DownloadBinary() error {
err := os.MkdirAll(filepath.Dir(b.File), 0755)
if err != nil {
return err
}
path := b.BinaryPath()
if ex, err := os.Executable(); err != nil || ex != path {
return b.downloadBinary()
}
// Self update
old := path + ".old"
err = os.Rename(path, old)
if err != nil {
return err
}
defer os.Remove(old)
err = b.downloadBinary()
if err != nil {
// Rollback
_ = os.Rename(old, path)
}
return err
}