|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + "time" |
| 8 | +) |
| 9 | + |
| 10 | +const updateCheckURL = "https://open.devicelab.dev/api/maestro-runner/updates" |
| 11 | + |
| 12 | +// updateNotice receives the update message from the background check. |
| 13 | +var updateNotice = make(chan string, 1) |
| 14 | + |
| 15 | +type updateResponse struct { |
| 16 | + LatestVersion string `json:"latest_version"` |
| 17 | +} |
| 18 | + |
| 19 | +// startUpdateCheck kicks off a background update check. |
| 20 | +// Call printUpdateNotice() later to print the result. |
| 21 | +func startUpdateCheck() { |
| 22 | + ch := updateNotice |
| 23 | + go func() { |
| 24 | + client := &http.Client{Timeout: 3 * time.Second} |
| 25 | + |
| 26 | + req, err := http.NewRequest("GET", updateCheckURL, nil) |
| 27 | + if err != nil { |
| 28 | + ch <- "" |
| 29 | + return |
| 30 | + } |
| 31 | + |
| 32 | + req.Header.Set("User-Agent", "maestro-runner") |
| 33 | + |
| 34 | + resp, err := client.Do(req) |
| 35 | + if err != nil { |
| 36 | + ch <- "" |
| 37 | + return |
| 38 | + } |
| 39 | + defer resp.Body.Close() |
| 40 | + |
| 41 | + if resp.StatusCode != http.StatusOK { |
| 42 | + ch <- "" |
| 43 | + return |
| 44 | + } |
| 45 | + |
| 46 | + var result updateResponse |
| 47 | + if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { |
| 48 | + ch <- "" |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + if result.LatestVersion != "" && result.LatestVersion != Version { |
| 53 | + ch <- fmt.Sprintf("\n Update available: %s → %s\n Run: curl -fsSL https://open.devicelab.dev/install/maestro-runner.sh | bash\n", Version, result.LatestVersion) |
| 54 | + } else { |
| 55 | + ch <- "" |
| 56 | + } |
| 57 | + }() |
| 58 | +} |
| 59 | + |
| 60 | +// printUpdateNotice prints the update message if one is available. |
| 61 | +func printUpdateNotice() { |
| 62 | + select { |
| 63 | + case msg := <-updateNotice: |
| 64 | + if msg != "" { |
| 65 | + fmt.Print(msg) |
| 66 | + } |
| 67 | + default: |
| 68 | + // Check not finished yet, don't block |
| 69 | + } |
| 70 | +} |
0 commit comments