Debian Codegraph @

cmd/humanlog/versions.go

raw symbols SCIP
1 package main
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "log"
8 "net/http"
9 "os"
10 "runtime"
11 "time"
12
13 "github.com/blang/semver"
14 "github.com/bufbuild/connect-go"
15 "github.com/fatih/color"
16 cliupdatepb "github.com/humanlogio/api/go/svc/cliupdate/v1"
17 "github.com/humanlogio/api/go/svc/cliupdate/v1/cliupdatev1connect"
18 types "github.com/humanlogio/api/go/types/v1"
19 "github.com/humanlogio/humanlog/internal/pkg/config"
20 "github.com/humanlogio/humanlog/internal/pkg/selfupdate"
21 "github.com/humanlogio/humanlog/internal/pkg/state"
22 "github.com/mattn/go-isatty"
23 "github.com/urfave/cli"
24 )
25
26 func isTerminal(f *os.File) bool {
27 return isatty.IsTerminal(f.Fd()) || isatty.IsCygwinTerminal(f.Fd())
28 }
29
30 func shouldCheckForUpdate(cctx *cli.Context, cfg *config.Config, state *state.State) bool {
31 if cctx.Args().First() == versionCmdName {
32 return false // check is done already
33 }
34 if cfg.SkipCheckForUpdates != nil && *cfg.SkipCheckForUpdates {
35 return false
36 }
37 return true
38 }
39
40 func shouldPromptAboutUpdate() bool {
41 if !isTerminal(os.Stderr) || !isTerminal(os.Stdout) {
42 // not in interactive mode
43 return false
44 }
45 return true
46 }
47
48 var httpClient = &http.Client{
49 Transport: &http.Transport{},
50 }
51
52 func reqMeta(st *state.State) *types.ReqMeta {
53 req := new(types.ReqMeta)
54 if st == nil {
55 return req
56 }
57 if st.AccountID != nil {
58 req.AccountId = *st.AccountID
59 }
60 if st.MachineID != nil {
61 req.MachineId = *st.MachineID
62 }
63 return req
64 }
65
66 func updateFromResMeta(st *state.State, res *types.ResMeta, latestKnownVersion *semver.Version, latestKnownVersionUpdatedAt *time.Time) error {
67 changed := false
68 if st.AccountID == nil || res.AccountId != *st.AccountID {
69 st.AccountID = &res.AccountId
70 changed = true
71 }
72 if st.MachineID == nil || res.MachineId != *st.MachineID {
73 st.MachineID = &res.MachineId
74 changed = true
75 }
76 if st.LatestKnownVersion == nil && latestKnownVersion != nil {
77 st.LatestKnownVersion = latestKnownVersion
78 changed = true
79 } else if st.LatestKnownVersion != nil && latestKnownVersion != nil && !st.LatestKnownVersion.EQ(*latestKnownVersion) {
80 st.LatestKnownVersion = latestKnownVersion
81 changed = true
82 }
83 if st.LastestKnownVersionUpdatedAt == nil && latestKnownVersionUpdatedAt != nil {
84 st.LastestKnownVersionUpdatedAt = latestKnownVersionUpdatedAt
85 changed = true
86 } else if st.LastestKnownVersionUpdatedAt != nil && latestKnownVersionUpdatedAt != nil && !st.LastestKnownVersionUpdatedAt.Equal(*latestKnownVersionUpdatedAt) {
87 st.LastestKnownVersionUpdatedAt = latestKnownVersionUpdatedAt
88 changed = true
89 }
90 if !changed {
91 return nil
92 }
93 return st.WriteBack()
94 }
95
96 const versionCmdName = "version"
97
98 func versionCmd(
99 getCtx func(cctx *cli.Context) context.Context,
100 getCfg func(cctx *cli.Context) *config.Config,
101 getState func(cctx *cli.Context) *state.State,
102 ) cli.Command {
103 return cli.Command{
104 Name: versionCmdName,
105 Usage: "Interact with humanlog versions",
106 Subcommands: cli.Commands{
107 {
108 Name: "check",
109 Usage: "checks whether a newer version is available",
110 Action: func(cctx *cli.Context) error {
111 ctx := getCtx(cctx)
112 cfg := getCfg(cctx)
113 state := getState(cctx)
114 nextVersion, nextArtifact, hasUpdate, err := checkForUpdate(ctx, cfg, state)
115 if err != nil {
116 return err
117 }
118 if !hasUpdate {
119 log.Printf("you're already running the latest version: v%v", semverVersion.String())
120 return nil
121 }
122 nextSV, err := nextVersion.AsSemver()
123 if err != nil {
124 return fmt.Errorf("invalid semver received: %w", err)
125 }
126 promptToUpdate(semverVersion, nextSV)
127 log.Printf("- url: %s", nextArtifact.Url)
128 log.Printf("- sha256: %s", nextArtifact.Sha256)
129 log.Printf("- sig: %s", nextArtifact.Signature)
130 return nil
131 },
132 },
133 {
134 Name: "update",
135 Usage: "self-update to the latest version",
136 Action: func(cctx *cli.Context) error {
137 ctx := getCtx(cctx)
138 cfg := getCfg(cctx)
139 state := getState(cctx)
140 _, _, hasUpdate, err := checkForUpdate(ctx, cfg, state)
141 if err != nil {
142 return err
143 }
144 if !hasUpdate {
145 log.Printf("you're already running the latest version: v%v", semverVersion.String())
146 return nil
147 }
148 return selfupdate.UpgradeInPlace(ctx, os.Stdout, os.Stderr, os.Stdin)
149 },
150 },
151 },
152 }
153 }
154
155 const apiURL = "https://api.humanlog.io"
156
157 type checkForUpdateReq struct {
158 arch string
159 os string
160 current *types.Version
161 }
162 type checkForUpdateRes struct {
163 pb *types.Version
164 sem semver.Version
165 hasUpdate bool
166 }
167
168 func checkForUpdate(ctx context.Context, cfg *config.Config, state *state.State) (v *types.Version, a *types.VersionArtifact, hasUpdate bool, err error) {
169 currentSV, err := version.AsSemver()
170 if err != nil {
171 return nil, nil, false, err
172 }
173
174 updateClient := cliupdatev1connect.NewUpdateServiceClient(httpClient, apiURL)
175 res, err := updateClient.GetNextUpdate(ctx, connect.NewRequest(&cliupdatepb.GetNextUpdateRequest{
176 ProjectName: "humanlog",
177 CurrentVersion: version,
178 MachineArchitecture: runtime.GOARCH,
179 MachineOperatingSystem: runtime.GOOS,
180 Meta: reqMeta(state),
181 }))
182 if err != nil {
183 return nil, nil, false, err
184 }
185 msg := res.Msg
186
187 lastCheckAt := time.Now()
188 nextSV, err := msg.NextVersion.AsSemver()
189 if err != nil {
190 return nil, nil, false, err
191 }
192 if err := updateFromResMeta(state, msg.Meta, &nextSV, &lastCheckAt); err != nil {
193 logwarn("failed to persist internal state: %v", err)
194 }
195
196 return msg.NextVersion, msg.NextArtifact, currentSV.LT(nextSV), nil
197 }
198
199 func asyncCheckForUpdate(ctx context.Context, req *checkForUpdateReq, cfg *config.Config, state *state.State) <-chan *checkForUpdateRes {
200 out := make(chan *checkForUpdateRes, 1)
201 go func() {
202 defer close(out)
203 nextVersion, _, hasUpdate, err := checkForUpdate(ctx, cfg, state)
204 if err != nil {
205 if errors.Is(errors.Unwrap(err), context.Canceled) {
206 return
207 }
208 // TODO: log to diagnostic file?
209 logwarn("failed to check for update: %v", err)
210 return
211 }
212 nexVersion, err := nextVersion.AsSemver()
213 if err != nil {
214 logwarn("next version is not a valid semver: %v", err)
215 return
216 }
217 out <- &checkForUpdateRes{
218 pb: nextVersion,
219 sem: nexVersion,
220 hasUpdate: hasUpdate,
221 }
222 }()
223 return out
224 }
225
226 func promptToUpdate(from, to semver.Version) {
227 log.Print(
228 color.YellowString("Update available %s -> %s.", from, to),
229 )
230 log.Print(
231 color.YellowString("Run `%s` to upgrade.", color.New(color.Bold).Sprint("humanlog version update")),
232 )
233 }