-
-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathsha_artifact.go
More file actions
257 lines (213 loc) · 8.1 KB
/
sha_artifact.go
File metadata and controls
257 lines (213 loc) · 8.1 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package toolchain
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"time"
errUtils "github.com/cloudposse/atmos/errors"
"github.com/cloudposse/atmos/pkg/github"
log "github.com/cloudposse/atmos/pkg/logger"
"github.com/cloudposse/atmos/pkg/perf"
"github.com/cloudposse/atmos/pkg/ui"
)
const (
// shaVersionDirFormat is the format for SHA version directory names.
shaVersionDirFormat = "sha-%s"
)
// SHACacheMetadata stores info about a cached SHA binary.
type SHACacheMetadata struct {
SHA string `json:"sha"` // Full SHA of the commit.
CheckedAt time.Time `json:"checked_at"` // Last time we installed/verified.
RunID int64 `json:"run_id"` // Workflow run ID.
}
// CheckSHACacheStatus determines if a SHA binary needs installation.
// Returns true if binary exists and is valid, along with the binary path.
func CheckSHACacheStatus(sha string) (exists bool, binaryPath string) {
defer perf.Track(nil, "toolchain.CheckSHACacheStatus")()
shortSHA := sha
if len(shortSHA) > shortSHALength {
shortSHA = shortSHA[:shortSHALength]
}
shaVersionDir := fmt.Sprintf(shaVersionDirFormat, shortSHA)
installDir := filepath.Join(GetInstallPath(), "bin", atmosOwner, atmosRepo, shaVersionDir)
// Check if binary exists.
binaryName := atmosBinaryName
if runtime.GOOS == "windows" {
binaryName = atmosBinaryNameExe
}
binaryPath = filepath.Join(installDir, binaryName)
if _, err := os.Stat(binaryPath); os.IsNotExist(err) {
return false, ""
}
// Binary exists - SHAs are immutable, so no need to check for updates.
log.Debug("Found cached SHA binary", "sha", shortSHA, "path", binaryPath)
return true, binaryPath
}
// saveSHACacheMetadata saves cache metadata for a SHA.
func saveSHACacheMetadata(sha string, meta *SHACacheMetadata) error {
shortSHA := sha
if len(shortSHA) > shortSHALength {
shortSHA = shortSHA[:shortSHALength]
}
shaVersionDir := fmt.Sprintf(shaVersionDirFormat, shortSHA)
metaPath := filepath.Join(GetInstallPath(), "bin", atmosOwner, atmosRepo, shaVersionDir, cacheMetadataFile)
data, err := json.MarshalIndent(meta, "", " ")
if err != nil {
return err
}
return os.WriteFile(metaPath, data, cacheFilePermissions)
}
// SaveSHACacheMetadataAfterInstall saves cache metadata after a successful installation.
func SaveSHACacheMetadataAfterInstall(sha string, info *github.SHAArtifactInfo) {
defer perf.Track(nil, "toolchain.SaveSHACacheMetadataAfterInstall")()
meta := &SHACacheMetadata{
SHA: info.HeadSHA,
CheckedAt: time.Now(),
RunID: info.RunID,
}
if err := saveSHACacheMetadata(sha, meta); err != nil {
log.Debug("Failed to save cache metadata after install", "error", err)
}
}
// InstallFromSHA downloads and installs Atmos from a commit SHA's build artifact.
// Returns the installed binary path.
func InstallFromSHA(sha string, showProgress bool) (string, error) {
defer perf.Track(nil, "toolchain.InstallFromSHA")()
ctx := context.Background()
// Get GitHub token if available (not required for public repos).
token := github.GetGitHubToken()
shortSHA := sha
if len(shortSHA) > shortSHALength {
shortSHA = shortSHA[:shortSHALength]
}
// Show progress if requested.
if showProgress {
ui.Infof("Installing Atmos from SHA `%s`...", shortSHA)
}
// Get artifact info.
artifactInfo, err := github.GetSHAArtifactInfo(ctx, atmosOwner, atmosRepo, sha)
if err != nil {
return "", handleSHAArtifactError(err, sha)
}
if showProgress {
// Format timestamp and short SHA for enriched message.
timeStr := artifactInfo.RunStartedAt.Local().Format("Jan 2, 2006 at 3:04 PM")
displaySHA := artifactInfo.HeadSHA
if len(displaySHA) > shortSHALength {
displaySHA = displaySHA[:shortSHALength]
}
ui.Successf("Found workflow run #%d (sha: `%s`) from %s", artifactInfo.RunID, displaySHA, timeStr)
}
// Download and install the artifact.
shaVersionDir := fmt.Sprintf(shaVersionDirFormat, shortSHA)
// Convert SHAArtifactInfo to PRArtifactInfo for the shared download function.
prInfo := &github.PRArtifactInfo{
PRNumber: 0, // Not a PR.
HeadSHA: artifactInfo.HeadSHA,
RunID: artifactInfo.RunID,
ArtifactID: artifactInfo.ArtifactID,
ArtifactName: artifactInfo.ArtifactName,
SizeInBytes: artifactInfo.SizeInBytes,
DownloadURL: artifactInfo.DownloadURL,
RunStartedAt: artifactInfo.RunStartedAt,
}
binaryPath, err := downloadAndInstallArtifactToDir(ctx, token, shaVersionDir, prInfo, showProgress)
if err != nil {
return "", err
}
// Save cache metadata for future lookups.
SaveSHACacheMetadataAfterInstall(sha, artifactInfo)
return binaryPath, nil
}
// handleSHAArtifactError converts GitHub errors to user-friendly errors.
func handleSHAArtifactError(err error, sha string) error {
shortSHA := sha
if len(shortSHA) > shortSHALength {
shortSHA = shortSHA[:shortSHALength]
}
commitURL := fmt.Sprintf("https://github.com/%s/%s/commit/%s", atmosOwner, atmosRepo, sha)
// Check for specific error types.
if isNotFoundError(err) {
return buildSHANotFoundError(shortSHA, commitURL)
}
if isNoWorkflowError(err) {
return buildNoWorkflowForSHAError(shortSHA, commitURL)
}
if isNoArtifactError(err) {
return buildNoArtifactForSHAError(shortSHA, commitURL)
}
if isPlatformError(err) {
return buildPlatformNotSupportedError()
}
// Generic error.
return buildGenericSHAError(shortSHA, commitURL, err)
}
// isNotFoundError checks if the error is a "not found" type error.
func isNotFoundError(err error) bool {
return github.IsNotFoundError(err)
}
// isNoWorkflowError checks if the error is a "no workflow run" error.
func isNoWorkflowError(err error) bool {
return github.IsNoWorkflowError(err)
}
// isNoArtifactError checks if the error is a "no artifact" error.
func isNoArtifactError(err error) bool {
return github.IsNoArtifactError(err)
}
// isPlatformError checks if the error is a platform-related error.
func isPlatformError(err error) bool {
return github.IsPlatformError(err)
}
// buildSHANotFoundError builds a user-friendly error for SHA not found.
func buildSHANotFoundError(shortSHA, commitURL string) error {
return errUtils.Build(errUtils.ErrToolNotFound).
WithExplanationf("Commit %s not found", shortSHA).
WithHintf("Check commit: %s", commitURL).
WithExitCode(1).
Err()
}
// buildNoWorkflowForSHAError builds a user-friendly error for no workflow run.
func buildNoWorkflowForSHAError(shortSHA, commitURL string) error {
return errUtils.Build(errUtils.ErrToolNotFound).
WithExplanationf("No completed CI run found for commit %s", shortSHA).
WithHint("CI workflow may not have completed yet").
WithHint("CI build may be failing for this commit").
WithHint("Artifacts from fork commits are not accessible").
WithHintf("Check commit: %s", commitURL).
WithExitCode(1).
Err()
}
// buildNoArtifactForSHAError builds a user-friendly error for no artifact found.
func buildNoArtifactForSHAError(shortSHA, commitURL string) error {
return errUtils.Build(errUtils.ErrToolNotFound).
WithExplanationf("Build artifact not found for commit %s", shortSHA).
WithHint("Artifacts may have expired (90-day retention)").
WithHint("Build job may have been skipped").
WithHintf("Check commit: %s", commitURL).
WithExitCode(1).
Err()
}
// buildPlatformNotSupportedError builds a user-friendly error for unsupported platform.
func buildPlatformNotSupportedError() error {
platforms := github.SupportedPRPlatforms()
return errUtils.Build(errUtils.ErrToolPlatformNotSupported).
WithExplanationf("No artifact available for %s/%s", runtime.GOOS, runtime.GOARCH).
WithHintf("Artifacts currently only support: %s", strings.Join(platforms, ", ")).
WithHint("Use a release version instead: atmos --use-version <version>").
WithHint("Or build from source: go install github.com/cloudposse/atmos@<branch>").
WithExitCode(1).
Err()
}
// buildGenericSHAError builds a generic error with the underlying cause.
func buildGenericSHAError(shortSHA, commitURL string, err error) error {
return errUtils.Build(errUtils.ErrToolInstall).
WithExplanationf("Failed to get artifact info for commit %s", shortSHA).
WithCause(err).
WithHintf("Check commit: %s", commitURL).
WithExitCode(1).
Err()
}