Skip to content

Commit b09d39c

Browse files
refactor(alpine): remove manual [ERROR]/[WARN]/[HINT] prefixes, use log library levels
Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent a544177 commit b09d39c

4 files changed

Lines changed: 66 additions & 71 deletions

File tree

artifactory/commands/alpine/apkcommand.go

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
buildUtils "github.com/jfrog/jfrog-cli-core/v2/common/build"
1212
"github.com/jfrog/jfrog-cli-core/v2/utils/config"
1313
"github.com/jfrog/gofrog/io"
14+
"github.com/jfrog/jfrog-client-go/utils/errorutils"
1415
"github.com/jfrog/jfrog-client-go/utils/log"
1516
)
1617

@@ -98,7 +99,7 @@ func (apkCmd *ApkCommand) ServerDetails() (*config.ServerDetails, error) {
9899
func (apkCmd *ApkCommand) Run() error {
99100
apkPath, err := exec.LookPath("apk")
100101
if err != nil {
101-
return fmt.Errorf("[ERROR] 'apk' binary not found. Is this an Alpine Linux environment?")
102+
return errorutils.CheckErrorf("'apk' binary not found. Is this an Alpine Linux environment?")
102103
}
103104

104105
needsAuth := buildInfoSubcmds[apkCmd.commandName] || authOnlySubcmds[apkCmd.commandName]
@@ -113,7 +114,7 @@ func (apkCmd *ApkCommand) Run() error {
113114
if needsBuildInfo {
114115
preSnapshot, err = biUtils.ListInstalledPackages()
115116
if err != nil {
116-
log.Warn("[WARN] Cannot list installed packages — Build Info not captured:", err)
117+
log.Warn("Cannot list installed packages — Build Info not captured:", err)
117118
needsBuildInfo = false
118119
}
119120
}
@@ -127,7 +128,7 @@ func (apkCmd *ApkCommand) Run() error {
127128
if needsBuildInfo {
128129
cacheDir, err = io.CreateTempDir()
129130
if err != nil {
130-
log.Warn("[WARN] Could not create temp cache dir — checksums may be incomplete:", err)
131+
log.Warn("Could not create temp cache dir — checksums may be incomplete:", err)
131132
} else {
132133
defer func() { _ = os.RemoveAll(cacheDir) }()
133134
}
@@ -161,16 +162,15 @@ func (apkCmd *ApkCommand) buildSubprocessEnv(injectAuth bool) ([]string, error)
161162

162163
if apkCmd.serverDetails == nil {
163164
if apkCmd.username != "" || apkCmd.password != "" {
164-
log.Warn("[WARN] --user/--password provided but no server URL is known. " +
165-
"Use --server-id to select a configured server so HTTP_AUTH can be injected.")
165+
log.Warn("--user/--password provided but no server URL is known. Use --server-id to select a configured server so HTTP_AUTH can be injected.")
166166
} else {
167-
log.Warn("[WARN] No JFrog server configured — skipping HTTP_AUTH injection. Run: jf c add")
167+
log.Warn("No JFrog server configured — skipping HTTP_AUTH injection. Run: jf c add")
168168
}
169169
return env, nil
170170
}
171171

172-
creds := resolveHTTPAuthCredentials(apkCmd.serverDetails, apkCmd.username, apkCmd.password)
173-
httpAuth, err := buildHTTPAuth(apkCmd.serverDetails.GetArtifactoryUrl(), creds)
172+
username, password := resolveHTTPAuthCredentials(apkCmd.serverDetails, apkCmd.username, apkCmd.password)
173+
httpAuth, err := buildHTTPAuth(apkCmd.serverDetails.GetArtifactoryUrl(), username, password)
174174
if err != nil {
175175
return nil, err
176176
}
@@ -181,13 +181,13 @@ func (apkCmd *ApkCommand) buildSubprocessEnv(injectAuth bool) ([]string, error)
181181
}
182182

183183
// buildHTTPAuth constructs the HTTP_AUTH=basic:<host>:<user>:<password> string for apk-tools.
184-
func buildHTTPAuth(rtURL string, creds resolvedCredentials) (string, error) {
184+
func buildHTTPAuth(rtURL, username, password string) (string, error) {
185185
parsed, err := url.Parse(rtURL)
186186
if err != nil {
187-
return "", fmt.Errorf("invalid Artifactory URL %q: %w", rtURL, err)
187+
return "", errorutils.CheckErrorf("invalid Artifactory URL %q: %w", rtURL, err)
188188
}
189189
host := parsed.Hostname()
190-
return fmt.Sprintf("basic:%s:%s:%s", host, creds.Username, creds.Password), nil
190+
return fmt.Sprintf("basic:%s:%s:%s", host, username, password), nil
191191
}
192192

193193
// runNativeApk spawns the native apk binary, streaming stdout/stderr in real time.
@@ -218,7 +218,7 @@ func emitSignatureHint(exitErr *exec.ExitError) {
218218
}
219219
for _, pattern := range sigPatterns {
220220
if strings.Contains(stderr, pattern) {
221-
log.Warn("[HINT] Signature verification failed. Fix: jf apk config --server-id <id> --repo <repo> --apply")
221+
log.Warn("Signature verification failed. Fix: jf apk config --server-id <id> --repo <repo> --apply")
222222
return
223223
}
224224
}
@@ -239,7 +239,7 @@ func (apkCmd *ApkCommand) collectBuildInfo(preSnapshot []biUtils.AlpinePackage,
239239

240240
buildObj, err := buildUtils.PrepareBuildPrerequisites(apkCmd.buildConfiguration)
241241
if err != nil {
242-
log.Warn("[WARN] Build Info publish failed:", err)
242+
log.Warn("Build Info publish failed:", err)
243243
return nil
244244
}
245245

@@ -252,7 +252,7 @@ func (apkCmd *ApkCommand) collectBuildInfo(preSnapshot []biUtils.AlpinePackage,
252252
alpineModule.SetCacheDir(cacheDir)
253253

254254
if err := alpineModule.CollectBuildInfo(); err != nil {
255-
log.Warn("[WARN] Build Info publish failed:", err)
255+
log.Warn("Build Info collection failed:", err)
256256
}
257257
return nil
258258
}

artifactory/commands/alpine/apkconfig.go

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"strings"
1010

1111
"github.com/jfrog/jfrog-cli-core/v2/utils/config"
12+
"github.com/jfrog/jfrog-client-go/utils/errorutils"
1213
"github.com/jfrog/jfrog-client-go/utils/log"
1314
)
1415

@@ -92,12 +93,12 @@ func (apkCmd *ApkConfigCommand) Run() error {
9293
apkCmd.branch = "main"
9394
}
9495

95-
creds := resolveCredentials(apkCmd.serverDetails, apkCmd.username, apkCmd.password)
96+
username, password := resolveCredentials(apkCmd.serverDetails, apkCmd.username, apkCmd.password)
9697

9798
rtURL := strings.TrimRight(apkCmd.serverDetails.GetArtifactoryUrl(), "/")
9899
keyEndpoint := fmt.Sprintf("%s/api/security/keypair/public/repositories/%s", rtURL, apkCmd.repoKey)
99100

100-
pemKey, err := downloadRSAKey(keyEndpoint, creds)
101+
pemKey, err := downloadRSAKey(keyEndpoint, username, password)
101102
if err != nil {
102103
return err
103104
}
@@ -113,43 +114,43 @@ func (apkCmd *ApkConfigCommand) Run() error {
113114
}
114115

115116
// downloadRSAKey fetches the RSA public key from the Artifactory keypair API.
116-
func downloadRSAKey(endpoint string, creds resolvedCredentials) (string, error) {
117-
if creds.Username == "" && creds.Password == "" {
118-
return "", fmt.Errorf("[ERROR] No credentials found for this server. Run: jf c add")
117+
func downloadRSAKey(endpoint, username, password string) (string, error) {
118+
if username == "" && password == "" {
119+
return "", errorutils.CheckErrorf("no credentials found for this server. Run: jf c add")
119120
}
120121

121122
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
122123
if err != nil {
123-
return "", fmt.Errorf("failed to build RSA key request: %w", err)
124+
return "", errorutils.CheckErrorf("failed to build RSA key request: %w", err)
124125
}
125-
req.SetBasicAuth(creds.Username, creds.Password)
126+
req.SetBasicAuth(username, password)
126127

127128
resp, err := http.DefaultClient.Do(req)
128129
if err != nil {
129-
return "", fmt.Errorf("failed to download RSA key from Artifactory: %w", err)
130+
return "", errorutils.CheckErrorf("failed to download RSA key from Artifactory: %w", err)
130131
}
131132
defer resp.Body.Close()
132133

133134
switch resp.StatusCode {
134135
case http.StatusOK:
135136
case http.StatusNotFound:
136-
return "", fmt.Errorf("[WARN] No RSA key configured for %q. Use --allow-untrusted or configure a signing key in Artifactory", endpoint)
137+
return "", errorutils.CheckErrorf("no RSA key configured for %q. Use --allow-untrusted or configure a signing key in Artifactory", endpoint)
137138
case http.StatusUnauthorized:
138-
return "", fmt.Errorf("[ERROR] Access token expired or invalid. Run: jf c add")
139+
return "", errorutils.CheckErrorf("access token expired or invalid. Run: jf c add")
139140
case http.StatusForbidden:
140-
return "", fmt.Errorf("[ERROR] Access token lacks read permission on the repository")
141+
return "", errorutils.CheckErrorf("access token lacks read permission on the repository")
141142
default:
142-
return "", fmt.Errorf("unexpected HTTP %d from Artifactory RSA key endpoint", resp.StatusCode)
143+
return "", errorutils.CheckErrorf("unexpected HTTP %d from Artifactory RSA key endpoint", resp.StatusCode)
143144
}
144145

145146
body, err := io.ReadAll(resp.Body)
146147
if err != nil {
147-
return "", fmt.Errorf("failed to read RSA key response body: %w", err)
148+
return "", errorutils.CheckErrorf("failed to read RSA key response body: %w", err)
148149
}
149150

150151
pem := string(body)
151152
if !strings.Contains(pem, "BEGIN PUBLIC KEY") {
152-
return "", fmt.Errorf("Artifactory returned an unexpected response for the RSA key endpoint (does the repo have a signing keypair configured?)")
153+
return "", errorutils.CheckErrorf("Artifactory returned an unexpected response for the RSA key endpoint (does the repo have a signing keypair configured?)")
153154
}
154155
return pem, nil
155156
}
@@ -171,16 +172,16 @@ func (apkCmd *ApkConfigCommand) printSetupScript(pemKey, keyFilePath, repoURL st
171172
// applyConfig writes the RSA key to disk and appends the repo URL to /etc/apk/repositories.
172173
func (apkCmd *ApkConfigCommand) applyConfig(pemKey, keyFilePath, repoURL string) error {
173174
if err := os.MkdirAll(apkKeysDir, 0755); err != nil {
174-
return fmt.Errorf("failed to create %s: %w", apkKeysDir, err)
175+
return errorutils.CheckErrorf("failed to create %s: %w", apkKeysDir, err)
175176
}
176177
if err := os.WriteFile(keyFilePath, []byte(pemKey), 0644); err != nil {
177-
return fmt.Errorf("failed to write RSA key to %s: %w", keyFilePath, err)
178+
return errorutils.CheckErrorf("failed to write RSA key to %s: %w", keyFilePath, err)
178179
}
179180
log.Info("RSA key written to", keyFilePath)
180181

181182
existing, err := os.ReadFile(apkRepositoriesFile)
182183
if err != nil && !os.IsNotExist(err) {
183-
return fmt.Errorf("failed to read %s: %w", apkRepositoriesFile, err)
184+
return errorutils.CheckErrorf("failed to read %s: %w", apkRepositoriesFile, err)
184185
}
185186
for _, line := range strings.Split(string(existing), "\n") {
186187
if strings.TrimSpace(line) == repoURL {
@@ -191,12 +192,12 @@ func (apkCmd *ApkConfigCommand) applyConfig(pemKey, keyFilePath, repoURL string)
191192

192193
f, err := os.OpenFile(apkRepositoriesFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
193194
if err != nil {
194-
return fmt.Errorf("failed to open %s for writing: %w", apkRepositoriesFile, err)
195+
return errorutils.CheckErrorf("failed to open %s for writing: %w", apkRepositoriesFile, err)
195196
}
196197
defer f.Close()
197198

198199
if _, err := fmt.Fprintln(f, repoURL); err != nil {
199-
return fmt.Errorf("failed to write repo URL to %s: %w", apkRepositoriesFile, err)
200+
return errorutils.CheckErrorf("failed to write repo URL to %s: %w", apkRepositoriesFile, err)
200201
}
201202
log.Info("Repository URL added to", apkRepositoriesFile)
202203
return nil

artifactory/commands/alpine/apkupload.go

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
"github.com/jfrog/gofrog/crypto"
1616
"github.com/jfrog/jfrog-client-go/artifactory/services"
1717
specutils "github.com/jfrog/jfrog-client-go/artifactory/services/utils"
18+
"github.com/jfrog/jfrog-client-go/utils/errorutils"
1819
"github.com/jfrog/jfrog-client-go/utils/log"
1920
)
2021

@@ -112,24 +113,24 @@ func (apkCmd *ApkUploadCommand) Run() error {
112113

113114
fileDetails, err := crypto.GetFileDetails(apkCmd.filePath, true)
114115
if err != nil {
115-
return fmt.Errorf("failed to compute checksums for %s: %w", apkCmd.filePath, err)
116+
return errorutils.CheckErrorf("failed to compute checksums for %s: %w", apkCmd.filePath, err)
116117
}
117118

118-
creds := resolveCredentials(apkCmd.serverDetails, apkCmd.username, apkCmd.password)
119+
username, password := resolveCredentials(apkCmd.serverDetails, apkCmd.username, apkCmd.password)
119120

120121
rtURL := apkCmd.serverDetails.GetArtifactoryUrl()
121122
target := fmt.Sprintf("%s/%s/%s/%s/%s", apkCmd.repoKey, apkCmd.alpineVersion, apkCmd.branch, arch, filename)
122123
uploadURL := rtURL + target
123124

124125
log.Info(fmt.Sprintf("Uploading %s → %s", filename, target))
125126

126-
if err := apkCmd.uploadFile(uploadURL, creds, fileDetails); err != nil {
127+
if err := apkCmd.uploadFile(uploadURL, username, password, fileDetails); err != nil {
127128
return err
128129
}
129130
log.Info("Upload successful.")
130131

131132
if err := apkCmd.setProperties(target, pkgName, pkgVersion, arch); err != nil {
132-
log.Warn("[WARN] Failed to set artifact properties:", err)
133+
log.Warn("Failed to set artifact properties:", err)
133134
}
134135

135136
collectBuildInfo, err := apkCmd.buildConfiguration.IsCollectBuildInfo()
@@ -138,57 +139,57 @@ func (apkCmd *ApkUploadCommand) Run() error {
138139
}
139140
if collectBuildInfo {
140141
if err := apkCmd.recordBuildInfoArtifact(filename, pkgName, pkgVersion, arch, fileDetails.Checksum); err != nil {
141-
log.Warn("[WARN] Build Info artifact recording failed:", err)
142+
log.Warn("Build Info artifact recording failed:", err)
142143
}
143144
}
144145
return nil
145146
}
146147

147148
// uploadFile PUTs the .apk file to Artifactory with checksum headers.
148-
func (apkCmd *ApkUploadCommand) uploadFile(uploadURL string, creds resolvedCredentials, fileDetails *crypto.FileDetails) error {
149+
func (apkCmd *ApkUploadCommand) uploadFile(uploadURL, username, password string, fileDetails *crypto.FileDetails) error {
149150
f, err := os.Open(apkCmd.filePath)
150151
if err != nil {
151-
return fmt.Errorf("failed to open %s: %w", apkCmd.filePath, err)
152+
return errorutils.CheckErrorf("failed to open %s: %w", apkCmd.filePath, err)
152153
}
153154
defer f.Close()
154155

155156
req, err := http.NewRequest(http.MethodPut, uploadURL, f)
156157
if err != nil {
157-
return fmt.Errorf("failed to build upload request: %w", err)
158+
return errorutils.CheckErrorf("failed to build upload request: %w", err)
158159
}
159160
req.ContentLength = fileDetails.Size
160-
req.SetBasicAuth(creds.Username, creds.Password)
161+
req.SetBasicAuth(username, password)
161162
req.Header.Set("X-Checksum-Sha1", fileDetails.Checksum.Sha1)
162163
req.Header.Set("X-Checksum-Md5", fileDetails.Checksum.Md5)
163164
req.Header.Set("X-Checksum", fileDetails.Checksum.Sha256)
164165
req.Header.Set("Content-Type", "application/octet-stream")
165166

166167
resp, err := http.DefaultClient.Do(req)
167168
if err != nil {
168-
return fmt.Errorf("upload request failed: %w", err)
169+
return errorutils.CheckErrorf("upload request failed: %w", err)
169170
}
170171
defer func() { _ = resp.Body.Close() }()
171172

172173
switch resp.StatusCode {
173174
case http.StatusCreated, http.StatusOK:
174175
return nil
175176
case http.StatusUnauthorized:
176-
return fmt.Errorf("[ERROR] Access token expired or invalid. Run: jf c add")
177+
return errorutils.CheckErrorf("access token expired or invalid. Run: jf c add")
177178
case http.StatusForbidden:
178-
return fmt.Errorf("[ERROR] Insufficient permissions to deploy to repository %q", apkCmd.repoKey)
179+
return errorutils.CheckErrorf("insufficient permissions to deploy to repository %q", apkCmd.repoKey)
179180
case http.StatusConflict:
180-
return fmt.Errorf("[ERROR] Artifact already exists at the target path (repo policy blocks overwrite)")
181+
return errorutils.CheckErrorf("artifact already exists at the target path (repo policy blocks overwrite)")
181182
default:
182183
body, _ := io.ReadAll(resp.Body)
183-
return fmt.Errorf("upload failed with HTTP %d: %s", resp.StatusCode, string(body))
184+
return errorutils.CheckErrorf("upload failed with HTTP %d: %s", resp.StatusCode, string(body))
184185
}
185186
}
186187

187188
// setProperties sets Alpine package properties on the uploaded artifact via a single SetProps call.
188189
func (apkCmd *ApkUploadCommand) setProperties(target, pkgName, pkgVersion, arch string) error {
189190
servicesManager, err := artutils.CreateServiceManager(apkCmd.serverDetails, -1, 0, false)
190191
if err != nil {
191-
return fmt.Errorf("failed to create Artifactory service manager: %w", err)
192+
return errorutils.CheckErrorf("failed to create Artifactory service manager: %w", err)
192193
}
193194

194195
propsStr := fmt.Sprintf("os.name=alpine;os.version=%s;os.arch=%s;apk.name=%s;apk.version=%s",
@@ -202,7 +203,7 @@ func (apkCmd *ApkUploadCommand) setProperties(target, pkgName, pkgVersion, arch
202203
CommonParams: &specutils.CommonParams{Pattern: target},
203204
})
204205
if err != nil {
205-
return fmt.Errorf("failed to search for uploaded artifact: %w", err)
206+
return errorutils.CheckErrorf("failed to search for uploaded artifact: %w", err)
206207
}
207208

208209
_, err = servicesManager.SetProps(services.PropsParams{
@@ -261,7 +262,7 @@ func (apkCmd *ApkUploadCommand) recordBuildInfoArtifact(filename, pkgName, pkgVe
261262
func parseApkFilename(filename string) (name, version, arch string, err error) {
262263
m := apkFilenamePattern.FindStringSubmatch(filename)
263264
if m == nil {
264-
return "", "", "", fmt.Errorf("cannot parse Alpine package filename %q — expected <name>-<ver>-<rel>.<arch>.apk", filename)
265+
return "", "", "", errorutils.CheckErrorf("cannot parse Alpine package filename %q — expected <name>-<ver>-<rel>.<arch>.apk", filename)
265266
}
266267
return m[1], m[2], m[3], nil
267268
}

0 commit comments

Comments
 (0)