This repository has been archived by the owner on Oct 10, 2023. It is now read-only.
/
core.go
104 lines (89 loc) · 2.46 KB
/
core.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
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
104
// Copyright 2021 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package cli
import (
"bytes"
"io"
"os"
"path/filepath"
"github.com/pkg/errors"
"golang.org/x/mod/semver"
"github.com/vmware-tanzu/tanzu-framework/cli/core/pkg/buildinfo"
cliapi "github.com/vmware-tanzu/tanzu-framework/cli/runtime/apis/cli/v1alpha1"
)
// CoreName is the name of the core binary.
const CoreName = "core"
const coreDescription = "The core Tanzu CLI"
// CoreDescriptor is the core descriptor.
var CoreDescriptor = cliapi.PluginDescriptor{
Name: CoreName,
Description: coreDescription,
Version: buildinfo.Version,
BuildSHA: buildinfo.SHA,
}
// CorePlugin is the core plugin.
var CorePlugin = Plugin{
Name: CoreName,
Description: coreDescription,
}
// HasUpdate tells whether the core plugin has an update.
func HasUpdate(repo Repository) (update bool, version string, err error) {
plugin, err := repo.Describe(CoreName)
if err != nil {
return false, version, err
}
versionSelector := repo.VersionSelector()
version = plugin.FindVersion(versionSelector)
compared := semver.Compare(version, buildinfo.Version)
if compared == 1 {
return true, version, nil
}
return false, version, nil
}
// Update the core CLI.
func Update(repo Repository) error {
var executable string
update, version, err := HasUpdate(repo)
if err != nil {
return err
}
if !update {
return nil
}
b, err := repo.Fetch(CoreName, version, BuildArch())
if err != nil {
return err
}
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return errors.Wrap(err, "could not locate filepath of running binary")
}
newCliFile := filepath.Join(dir, "tanzu_new")
outFile, err := os.OpenFile(newCliFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
if err != nil {
return errors.Wrap(err, "could not create new binary file")
}
defer outFile.Close()
_, err = io.Copy(outFile, bytes.NewReader(b))
if err != nil {
return errors.Wrap(err, "could not copy new binary file")
}
outFile.Close()
if BuildArch().IsWindows() {
executable = outFile.Name() + ".exe"
err = os.Rename(outFile.Name(), executable)
if err != nil {
return errors.Wrap(err, "could not rename binary file")
}
} else {
executable, err = os.Executable()
if err != nil {
return errors.Wrap(err, "could not locate current executable")
}
err = os.Rename(outFile.Name(), executable)
if err != nil {
return errors.Wrap(err, "could not rename binary file")
}
}
return nil
}