/
project.go
363 lines (330 loc) · 11 KB
/
project.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
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package project
import (
"archive/zip"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/jfrog/gocmd/cmd"
"github.com/jfrog/gocmd/executers"
executersutils "github.com/jfrog/gocmd/executers/utils"
"github.com/jfrog/jfrog-cli-core/artifactory/utils"
"github.com/jfrog/jfrog-client-go/artifactory"
"github.com/jfrog/jfrog-client-go/artifactory/buildinfo"
_go "github.com/jfrog/jfrog-client-go/artifactory/services/go"
servicesutils "github.com/jfrog/jfrog-client-go/artifactory/services/utils"
cliutils "github.com/jfrog/jfrog-client-go/utils"
"github.com/jfrog/jfrog-client-go/utils/errorutils"
"github.com/jfrog/jfrog-client-go/utils/io/fileutils"
"github.com/jfrog/jfrog-client-go/utils/io/fileutils/checksum"
"github.com/jfrog/jfrog-client-go/utils/log"
"github.com/jfrog/jfrog-client-go/utils/version"
)
// Represent go project
type Go interface {
Dependencies() []executers.Package
CreateBuildInfoDependencies(includeInfoFiles bool) error
PublishPackage(targetRepo, buildName, buildNumber, projectKey string, servicesManager artifactory.ArtifactoryServicesManager) (*servicesutils.OperationSummary, error)
PublishDependencies(targetRepo string, servicesManager artifactory.ArtifactoryServicesManager, includeDepSlice []string) (succeeded, failed int, err error)
BuildInfo(includeArtifacts bool, module, targetRepository string) *buildinfo.BuildInfo
LoadDependencies() error
}
type goProject struct {
dependencies []executers.Package
artifacts []buildinfo.Artifact
modContent []byte
moduleName string
version string
projectPath string
}
// Load go project.
func Load(version, projectPath string) (Go, error) {
goProject := &goProject{version: version, projectPath: projectPath}
err := goProject.readModFile()
return goProject, err
}
// Get the go project dependencies.
func (project *goProject) Dependencies() []executers.Package {
return project.dependencies
}
// Get the go project dependencies.
func (project *goProject) CreateBuildInfoDependencies(includeInfoFiles bool) error {
for i, dep := range project.dependencies {
err := dep.CreateBuildInfoDependencies(includeInfoFiles)
if err != nil {
return err
}
project.dependencies[i] = dep
}
return nil
}
// Get the project dependencies.
func (project *goProject) LoadDependencies() error {
var err error
project.dependencies, err = project.loadDependencies()
return err
}
func (project *goProject) loadDependencies() ([]executers.Package, error) {
cachePath, err := executersutils.GetCachePath()
if err != nil {
return nil, err
}
modulesMap, err := cmd.GetDependenciesList(project.projectPath)
if err != nil {
return nil, err
}
if modulesMap == nil {
return nil, nil
}
return executers.GetDependencies(cachePath, modulesMap)
}
// Publish go project to Artifactory.
func (project *goProject) PublishPackage(targetRepo, buildName, buildNumber, projectKey string, servicesManager artifactory.ArtifactoryServicesManager) (*servicesutils.OperationSummary, error) {
log.Info("Publishing", project.getId(), "to", targetRepo)
props, err := utils.CreateBuildProperties(buildName, buildNumber, projectKey)
if err != nil {
return nil, err
}
// Temp directory for the project archive.
// The directory will be deleted at the end.
tempDirPath, err := fileutils.CreateTempDir()
if err != nil {
return nil, err
}
defer fileutils.RemoveTempDir(tempDirPath)
params := _go.NewGoParams()
params.Version = project.version
params.Props = props
params.TargetRepo = targetRepo
params.ModuleId = project.getId()
params.ModContent = project.modContent
params.ModPath = filepath.Join(project.projectPath, "go.mod")
params.ZipPath, err = project.archiveProject(project.version, tempDirPath)
if err != nil {
return nil, err
}
// Create the info file if Artifactory version is 6.10.0 and above.
artifactoryVersion, err := servicesManager.GetConfig().GetServiceDetails().GetVersion()
if err != nil {
return nil, err
}
version := version.NewVersion(artifactoryVersion)
if version.AtLeast(_go.ArtifactoryMinSupportedVersionForInfoFile) {
pathToInfo, err := project.createInfoFile()
if err != nil {
return nil, err
}
defer os.Remove(pathToInfo)
if len(buildName) > 0 && len(buildNumber) > 0 {
err = project.addInfoFileToBuildInfo(pathToInfo)
if err != nil {
return nil, err
}
}
params.InfoPath = pathToInfo
}
return servicesManager.PublishGoProject(params)
}
// Creates the info file.
// Returns the path to that file.
func (project *goProject) createInfoFile() (string, error) {
log.Debug("Creating info file", project.projectPath)
currentTime := time.Now().Format("2006-01-02T15:04:05Z")
goInfoContent := goInfo{Version: project.version, Time: currentTime}
content, err := json.Marshal(&goInfoContent)
if err != nil {
return "", errorutils.CheckError(err)
}
file, err := os.Create(project.version + ".info")
if err != nil {
return "", errorutils.CheckError(err)
}
defer file.Close()
_, err = file.Write(content)
if err != nil {
return "", errorutils.CheckError(err)
}
path, err := filepath.Abs(file.Name())
if err != nil {
return "", errorutils.CheckError(err)
}
log.Debug("Info file was successfully created:", path)
return path, nil
}
func (project *goProject) PublishDependencies(targetRepo string, servicesManager artifactory.ArtifactoryServicesManager, includeDepSlice []string) (succeeded, failed int, err error) {
log.Info("Publishing package dependencies...")
includeDep := cliutils.ConvertSliceToMap(includeDepSlice)
skip := 0
_, includeAll := includeDep["ALL"]
dependencies := project.Dependencies()
for _, dependency := range dependencies {
includeDependency := includeAll
if !includeDependency {
if _, included := includeDep[dependency.GetId()]; included {
includeDependency = true
}
}
if includeDependency {
err = dependency.Publish("", targetRepo, servicesManager)
if err != nil {
err = errors.New("Failed to publish " + dependency.GetId() + " due to: " + err.Error())
log.Error("Failed to publish", dependency.GetId(), ":", err)
} else {
succeeded++
}
continue
}
skip++
}
failed = len(dependencies) - succeeded - skip
if failed > 0 {
err = errors.New("Publishing project dependencies finished with errors. Please review the logs.")
}
return succeeded, failed, err
}
// Get the build info of the go project
func (project *goProject) BuildInfo(includeArtifacts bool, module, targetRepository string) *buildinfo.BuildInfo {
buildInfoDependencies := []buildinfo.Dependency{}
for _, dep := range project.dependencies {
buildInfoDependencies = append(buildInfoDependencies, dep.Dependencies()...)
}
var artifacts []buildinfo.Artifact
if includeArtifacts {
artifacts = project.artifacts
// Add artifacts target-path.
moduleId := strings.Split(project.moduleName, ":")
for i := range artifacts {
artifact := &artifacts[i]
targetPath := targetRepository
_ = _go.CreateUrlPath(moduleId[0], project.version, "", "."+artifact.Type, &targetPath)
artifact.Path = targetPath
}
}
buildInfoModule := buildinfo.Module{Id: module, Type: buildinfo.Go, Artifacts: artifacts, Dependencies: buildInfoDependencies}
if module == "" {
buildInfoModule.Id = project.getId()
}
return &buildinfo.BuildInfo{Modules: []buildinfo.Module{buildInfoModule}}
}
// Get go project ID in the form of projectName:version
func (project *goProject) getId() string {
return project.moduleName
}
// Read go.mod file and add it as an artifact to the build info.
func (project *goProject) readModFile() error {
var err error
if project.projectPath == "" {
project.projectPath, err = cmd.GetProjectRoot()
if err != nil {
return errorutils.CheckError(err)
}
}
modFilePath := filepath.Join(project.projectPath, "go.mod")
modFileExists, _ := fileutils.IsFileExists(modFilePath, true)
if !modFileExists {
return errorutils.CheckError(errors.New("Could not find project's go.mod in " + project.projectPath))
}
modFile, err := os.Open(modFilePath)
if err != nil {
return err
}
defer modFile.Close()
content, err := io.ReadAll(modFile)
if err != nil {
return errorutils.CheckError(err)
}
// Read module name
project.moduleName, err = parseModuleName(string(content))
if err != nil {
return err
}
checksums, err := checksum.Calc(bytes.NewBuffer(content))
if err != nil {
return err
}
project.modContent = content
// Add mod file as artifact
artifact := buildinfo.Artifact{Name: project.version + ".mod", Type: "mod"}
artifact.Checksum = buildinfo.Checksum{Sha1: checksums[checksum.SHA1], Md5: checksums[checksum.MD5]}
project.artifacts = append(project.artifacts, artifact)
return nil
}
// Archive the go project.
// Returns the path of the temp archived project file.
func (project *goProject) archiveProject(version, tempDir string) (string, error) {
tempFile, err := os.CreateTemp(tempDir, "project.zip")
if err != nil {
return "", errorutils.CheckError(err)
}
defer tempFile.Close()
err = archiveProject(tempFile, project.projectPath, project.moduleName, version)
if err != nil {
return "", errorutils.CheckError(err)
}
// Double-check that the paths within the zip file are well-formed.
fi, err := tempFile.Stat()
if err != nil {
return "", err
}
z, err := zip.NewReader(tempFile, fi.Size())
if err != nil {
return "", err
}
prefix := project.moduleName + "@" + version + "/"
for _, f := range z.File {
if !strings.HasPrefix(f.Name, prefix) {
return "", fmt.Errorf("zip for %s has unexpected file %s", prefix[:len(prefix)-1], f.Name)
}
}
// Sync the file before renaming it
if err := tempFile.Sync(); err != nil {
return "", err
}
if err := tempFile.Close(); err != nil {
return "", err
}
fileDetails, err := fileutils.GetFileDetails(tempFile.Name())
if err != nil {
return "", err
}
artifact := buildinfo.Artifact{Name: version + ".zip", Type: "zip"}
artifact.Checksum = buildinfo.Checksum{Sha1: fileDetails.Checksum.Sha1, Md5: fileDetails.Checksum.Md5}
project.artifacts = append(project.artifacts, artifact)
return tempFile.Name(), nil
}
// Add the info file also as an artifact to be part of the build info.
func (project *goProject) addInfoFileToBuildInfo(infoFilePath string) error {
fileDetails, err := fileutils.GetFileDetails(infoFilePath)
if err != nil {
return err
}
artifact := buildinfo.Artifact{Name: project.version + ".info", Type: "info"}
artifact.Checksum = buildinfo.Checksum{Sha1: fileDetails.Checksum.Sha1, Md5: fileDetails.Checksum.Md5}
project.artifacts = append(project.artifacts, artifact)
return nil
}
// Parse module name from go.mod content.
func parseModuleName(modContent string) (string, error) {
r, err := regexp.Compile(`module "?([\w\.@:%_\+-.~#?&]+/?.+\w)`)
if err != nil {
return "", errorutils.CheckError(err)
}
lines := strings.Split(modContent, "\n")
for _, v := range lines {
matches := r.FindStringSubmatch(v)
if len(matches) == 2 {
return matches[1], nil
}
}
return "", errorutils.CheckError(errors.New("Module name missing in go.mod file"))
}
type goInfo struct {
Version string `json:"Version"`
Time string `json:"Time"`
}