-
-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathvendor_utils.go
More file actions
714 lines (638 loc) · 26.4 KB
/
Copy pathvendor_utils.go
File metadata and controls
714 lines (638 loc) · 26.4 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
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
package exec
import (
"fmt"
"net/url"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"github.com/bmatcuk/doublestar/v4"
"github.com/pkg/errors"
"github.com/samber/lo"
"go.yaml.in/yaml/v3"
log "github.com/cloudposse/atmos/pkg/logger"
"github.com/cloudposse/atmos/pkg/perf"
"github.com/cloudposse/atmos/pkg/schema"
"github.com/cloudposse/atmos/pkg/ui"
u "github.com/cloudposse/atmos/pkg/utils"
"github.com/cloudposse/atmos/pkg/vendor"
"github.com/cloudposse/atmos/pkg/vendoring/install"
"github.com/cloudposse/atmos/pkg/vendoring/version"
)
// Dedicated logger for stderr to keep stdout clean of detailed messaging, e.g. for files vendoring.
var StderrLogger = func() *log.AtmosLogger {
l := log.New()
l.SetOutput(os.Stderr)
return l
}()
var (
ErrVendorComponents = errors.New("failed to vendor components")
ErrSourceMissing = errors.New("'source' must be specified in 'sources' in the vendor config file")
ErrTargetsMissing = errors.New("'targets' must be specified for the source in the vendor config file")
ErrVendorConfigSelfImport = errors.New("vendor config file imports itself in 'spec.imports'")
ErrMissingVendorConfigDefinition = errors.New("either 'spec.sources' or 'spec.imports' (or both) must be defined in the vendor config file")
ErrVendoringNotConfigured = errors.New("Vendoring is not configured. To set up vendoring, please see https://atmos.tools/core-concepts/vendor/")
ErrPermissionDenied = errors.New("Permission denied when accessing")
ErrEmptySources = errors.New("'spec.sources' is empty in the vendor config file and the imports")
ErrNoComponentsWithTags = errors.New("there are no components in the vendor config file")
ErrNoYAMLConfigFiles = errors.New("no YAML configuration files found in directory")
ErrDuplicateComponents = errors.New("duplicate component names")
ErrDuplicateImport = errors.New("Duplicate import")
ErrDuplicateComponentsFound = errors.New("duplicate component")
ErrComponentNotDefined = errors.New("the flag '--component' is passed, but the component is not defined in any of the 'sources' in the vendor config file and the imports")
)
type processTargetsParams struct {
AtmosConfig *schema.AtmosConfiguration
IndexSource int
Source *schema.AtmosVendorSource
TemplateData struct{ Component, Version string }
VendorConfigFilePath string
URI string
SourceTemplate string // Raw un-templated source URL for per-target version re-resolution.
PkgType install.PkgType
SourceIsLocalFile bool
// RawVersion is the source-level declared version, populated only when it was a semver range
// (TemplateData.Version already carries its resolved concrete value) -- see
// install.VendorPackage.RawVersion.
RawVersion string
// RefreshLock forces fresh semver-range resolution for any per-target version override --
// see resolveEffectiveVersion.
RefreshLock bool
// Lister overrides the remote Git tag lister for any per-target version override -- see
// vendorSourceParams.lister's doc comment.
Lister version.RemoteLister
}
type executeVendorOptions struct {
atmosConfig *schema.AtmosConfiguration
vendorConfigFileName string
atmosVendorSpec schema.AtmosVendorSpec
component string
tags []string
dryRun bool
refreshLock bool
// lockEnforcement is one of install.LockEnforcementSilent/Warn/Strict; see VendorFlags.LockEnforcement.
lockEnforcement string
}
type vendorSourceParams struct {
atmosConfig *schema.AtmosConfiguration
sources []schema.AtmosVendorSource
component string
tags []string
vendorConfigFileName string
vendorConfigFilePath string
// refreshLock forces fresh semver-range version resolution (bypassing any matching
// vendor.lock.yaml receipt) for range-declared `version:` sources -- see resolveEffectiveVersion.
refreshLock bool
// lister overrides the remote Git tag lister used to resolve a semver-range `version:`. Nil in
// every production call path (install.ResolveDeclaredVersion defaults to version.DefaultLister);
// only ever set by tests, so a range's resolution can be verified without real network access.
lister version.RemoteLister
}
// ReadAndProcessVendorConfigFile reads and processes the Atmos vendoring config file `vendor.yaml`.
func ReadAndProcessVendorConfigFile(
atmosConfig *schema.AtmosConfiguration,
vendorConfigFile string,
checkGlobalConfig bool,
) (schema.AtmosVendorConfig, bool, string, error) {
defer perf.Track(atmosConfig, "exec.ReadAndProcessVendorConfigFile")()
var vendorConfig schema.AtmosVendorConfig
vendorConfig.Spec.Sources = []schema.AtmosVendorSource{} // Initialize empty sources slice
// Determine the vendor config file path
foundVendorConfigFile := resolveVendorConfigFilePath(atmosConfig, vendorConfigFile, checkGlobalConfig)
if foundVendorConfigFile == "" {
log.Debug("Vendor config file not found", "file", vendorConfigFile)
return vendorConfig, false, "", nil
}
// Validate and process the vendor config file or directory
configFiles, err := getConfigFiles(foundVendorConfigFile)
if err != nil {
return vendorConfig, false, "", err
}
// Merge all config files into a single vendor configuration
vendorConfig, err = mergeVendorConfigFiles(configFiles)
if err != nil {
return vendorConfig, false, "", err
}
return vendorConfig, true, foundVendorConfigFile, nil
}
// getVendorDirToUse returns the appropriate vendor directory for file resolution. It prefers
// the precomputed VendorDirAbsolutePath (set by AtmosConfigAbsolutePaths, the same mechanism
// cloudposse/atmos#2864 uses for the top-level base_path), falling back to joining the raw
// BasePath/Vendor.BasePath for callers that construct an AtmosConfiguration by hand without
// running it through AtmosConfigAbsolutePaths first (e.g. tests). Mirrors getWorkflowsDirToUse
// and getBasePathToUse (validate_component.go).
func getVendorDirToUse(atmosConfig *schema.AtmosConfiguration) string {
if atmosConfig.VendorDirAbsolutePath != "" {
return atmosConfig.VendorDirAbsolutePath
}
// u.JoinPath (unlike filepath.Join) returns an already-absolute Vendor.BasePath as-is
// instead of nesting it under BasePath.
return u.JoinPath(atmosConfig.BasePath, atmosConfig.Vendor.BasePath)
}
// Helper function to resolve the vendor config file path.
func resolveVendorConfigFilePath(atmosConfig *schema.AtmosConfiguration, vendorConfigFile string, checkGlobalConfig bool) string {
if checkGlobalConfig && atmosConfig.Vendor.BasePath != "" {
if !filepath.IsAbs(atmosConfig.Vendor.BasePath) {
return getVendorDirToUse(atmosConfig)
}
return atmosConfig.Vendor.BasePath
}
// Search for the vendor config file
foundVendorConfigFile, fileExists := u.SearchConfigFile(vendorConfigFile)
if !fileExists {
pathToVendorConfig := filepath.Join(getBasePathToUse(atmosConfig), vendorConfigFile)
foundVendorConfigFile, fileExists = u.SearchConfigFile(pathToVendorConfig)
if !fileExists {
return "" // File does not exist, but this is not an error
}
}
return foundVendorConfigFile
}
// Helper function to get config files from a path (file or directory).
func getConfigFiles(path string) ([]string, error) {
fileInfo, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return nil, ErrVendoringNotConfigured
}
if os.IsPermission(err) {
return nil, fmt.Errorf("%w '%s'. Please check the file permissions", ErrPermissionDenied, path)
}
return nil, fmt.Errorf("An error occurred while accessing the vendoring configuration: %w", err)
}
if fileInfo.IsDir() {
matches, err := doublestar.Glob(os.DirFS(path), "*.{yaml,yml}")
if err != nil {
return nil, err
}
if len(matches) == 0 {
return nil, fmt.Errorf("%w '%s'", ErrNoYAMLConfigFiles, path)
}
for i, match := range matches {
matches[i] = filepath.Join(path, match)
}
sort.Strings(matches)
return matches, nil
}
return []string{path}, nil
}
// Helper function to merge multiple config files into a single vendor configuration.
func mergeVendorConfigFiles(configFiles []string) (schema.AtmosVendorConfig, error) {
var vendorConfig schema.AtmosVendorConfig
sourceMap := make(map[string]bool) // Track unique sources by component name
importMap := make(map[string]bool) // Track unique imports
for _, configFile := range configFiles {
var currentConfig schema.AtmosVendorConfig
yamlFile, err := os.ReadFile(configFile)
if err != nil {
return vendorConfig, err
}
if err := yaml.Unmarshal(yamlFile, ¤tConfig); err != nil {
return vendorConfig, err
}
// Merge sources, checking for duplicates
for i := range currentConfig.Spec.Sources {
source := currentConfig.Spec.Sources[i]
if source.Component != "" {
if sourceMap[source.Component] {
return vendorConfig, fmt.Errorf("%w '%s' found in config file '%s'", ErrDuplicateComponentsFound, source.Component, configFile)
}
sourceMap[source.Component] = true
}
vendorConfig.Spec.Sources = append(vendorConfig.Spec.Sources, source)
}
// Merge imports, checking for duplicates
for _, imp := range currentConfig.Spec.Imports {
if !importMap[imp] {
importMap[imp] = true
vendorConfig.Spec.Imports = append(vendorConfig.Spec.Imports, imp)
}
}
}
return vendorConfig, nil
}
// ExecuteAtmosVendorInternal downloads the artifacts from the sources and writes them to the targets.
func ExecuteAtmosVendorInternal(params *executeVendorOptions) error {
defer perf.Track(nil, "exec.ExecuteAtmosVendorInternal")()
var err error
vendorConfigFilePath := filepath.Dir(params.vendorConfigFileName)
// displayPath keeps the log message short and machine-independent; params.vendorConfigFileName
// itself stays untouched (and possibly absolute) for the actual file/source resolution below.
logInitialMessage(displayPath(params.vendorConfigFileName), params.tags)
if len(params.atmosVendorSpec.Sources) == 0 && len(params.atmosVendorSpec.Imports) == 0 {
return fmt.Errorf("%w '%s'", ErrMissingVendorConfigDefinition, params.vendorConfigFileName)
}
// Process imports and return all sources from all the imports and from `vendor.yaml`.
sources, _, err := processVendorImports(
params.atmosConfig,
params.vendorConfigFileName,
params.atmosVendorSpec.Imports,
params.atmosVendorSpec.Sources,
[]string{params.vendorConfigFileName},
)
if err != nil {
return err
}
if len(sources) == 0 {
return fmt.Errorf("%w %s", ErrEmptySources, params.vendorConfigFileName)
}
if err := validateTagsAndComponents(sources, params.vendorConfigFileName, params.component, params.tags); err != nil {
return err
}
sourceParams := &vendorSourceParams{
atmosConfig: params.atmosConfig,
sources: sources,
component: params.component,
tags: params.tags,
vendorConfigFileName: params.vendorConfigFileName,
vendorConfigFilePath: vendorConfigFilePath,
refreshLock: params.refreshLock,
}
packages, err := processAtmosVendorSource(sourceParams)
if err != nil {
return err
}
opts := install.InstallOptions{DryRun: params.dryRun, RefreshLock: params.refreshLock, LockEnforcement: params.lockEnforcement}
packages, err = install.FilterPending(params.atmosConfig, packages, opts)
if err != nil {
return err
}
if len(packages) > 0 {
return executeVendorModel(packages, opts, params.atmosConfig)
}
return nil
}
func validateTagsAndComponents(
sources []schema.AtmosVendorSource,
vendorConfigFileName string,
component string,
tags []string,
) error {
if len(tags) > 0 {
componentTags := lo.FlatMap(sources, func(s schema.AtmosVendorSource, _ int) []string {
return s.Tags
})
if len(lo.Intersect(tags, componentTags)) == 0 {
return fmt.Errorf("%w '%s' tagged with the tags %v",
ErrNoComponentsWithTags, vendorConfigFileName, tags)
}
}
components := lo.FilterMap(sources, func(s schema.AtmosVendorSource, _ int) (string, bool) {
return s.Component, s.Component != ""
})
if duplicates := lo.FindDuplicates(components); len(duplicates) > 0 {
return fmt.Errorf("%w %v in the vendor config file '%s' and the imports",
ErrDuplicateComponents, duplicates, vendorConfigFileName)
}
if component != "" && !slices.Contains(components, component) {
return fmt.Errorf("%w component '%s', file '%s'",
ErrComponentNotDefined, component, vendorConfigFileName)
}
return nil
}
func processAtmosVendorSource(params *vendorSourceParams) ([]install.VendorPackage, error) {
var packages []install.VendorPackage
for indexSource := range params.sources {
pkgs, skip, err := processAtmosVendorSourceEntry(params, indexSource)
if err != nil {
return nil, err
}
if skip {
continue
}
packages = append(packages, pkgs...)
}
return packages, nil
}
// processAtmosVendorSourceEntry resolves and installs the packages for the single vendor.yaml
// source at params.sources[indexSource]. Skip is true when shouldSkipSource excludes this source
// based on the requested component/tags filter, in which case pkgs and err are both zero-valued.
func processAtmosVendorSourceEntry(params *vendorSourceParams, indexSource int) (pkgs []install.VendorPackage, skip bool, err error) {
if shouldSkipSource(¶ms.sources[indexSource], params.component, params.tags) {
return nil, true, nil
}
if err := validateSourceFields(¶ms.sources[indexSource], params.vendorConfigFileName); err != nil {
return nil, false, err
}
resolution, err := resolveAtmosVendorSource(params, indexSource)
if err != nil {
return nil, false, err
}
// Process each target within the source.
pkgs, err = processTargets(&processTargetsParams{
AtmosConfig: params.atmosConfig,
IndexSource: indexSource,
Source: ¶ms.sources[indexSource],
TemplateData: resolution.TemplateData,
VendorConfigFilePath: params.vendorConfigFilePath,
URI: resolution.URI,
SourceTemplate: params.sources[indexSource].Source,
PkgType: resolution.PkgType,
SourceIsLocalFile: resolution.SourceIsLocalFile,
RawVersion: resolution.RawVersion,
RefreshLock: params.refreshLock,
Lister: params.lister,
})
if err != nil {
return nil, false, err
}
return pkgs, false, nil
}
// atmosVendorSourceResolution is resolveAtmosVendorSource's result: the templated source URI (with
// a range-declared `version:` already resolved to a concrete version -- see resolveEffectiveVersion),
// its classification, and the template data used to produce it (reused unchanged for every target
// that doesn't declare its own version override).
type atmosVendorSourceResolution struct {
URI string
TemplateData struct{ Component, Version string }
PkgType install.PkgType
SourceIsLocalFile bool
// RawVersion is the source-level declared version, populated only when it was a semver range --
// see install.VendorPackage.RawVersion.
RawVersion string
}
// resolveAtmosVendorSource resolves params.sources[indexSource]'s declared version, templates it
// into the source URI, and classifies the result (OCI/local/remote) -- the shared preamble
// processAtmosVendorSourceEntry needs before it can process each of the source's targets.
func resolveAtmosVendorSource(params *vendorSourceParams, indexSource int) (*atmosVendorSourceResolution, error) {
src := ¶ms.sources[indexSource]
resolvedVersion, rawVersion, err := install.ResolveEffectiveVersion(&install.ResolveEffectiveVersionInputs{
AtmosConfig: params.atmosConfig,
Name: src.Component,
Source: src.Source,
RawVersion: src.Version,
Constraints: src.Constraints,
RefreshLock: params.refreshLock,
Lister: params.lister,
})
if err != nil {
return nil, fmt.Errorf("resolve version for component %q: %w", src.Component, err)
}
tmplData := struct {
Component string
Version string
}{src.Component, resolvedVersion}
// Parse 'source' template
uri, err := ProcessTmpl(params.atmosConfig, fmt.Sprintf("source-%d", indexSource), src.Source, tmplData, false)
if err != nil {
return nil, err
}
// Normalize the URI to handle triple-slash pattern (///), which indicates cloning from
// the root of the repository. This pattern broke in go-getter v1.7.9 due to CVE-2025-8959
// security fixes.
uri = normalizeVendorURI(uri)
useOciScheme, useLocalFileSystem, sourceIsLocalFile, err := determineSourceType(&uri, params.vendorConfigFilePath)
if err != nil {
return nil, err
}
if !useLocalFileSystem {
if err := u.ValidateURI(uri); err != nil {
if strings.Contains(uri, "..") {
return nil, fmt.Errorf("invalid URI for component %s: %w: Please ensure the source is a valid local path", src.Component, err)
}
return nil, fmt.Errorf("invalid URI for component %s: %w", src.Component, err)
}
}
return &atmosVendorSourceResolution{
URI: uri,
TemplateData: tmplData,
PkgType: install.DeterminePackageType(useOciScheme, useLocalFileSystem),
SourceIsLocalFile: sourceIsLocalFile,
RawVersion: rawVersion,
}, nil
}
// resolvedTarget holds the resolved URI, version, template data, and source classification for a single target.
type resolvedTarget struct {
uri string
version string
rawVersion string
tmplData struct{ Component, Version string }
pkgType install.PkgType
sourceIsLocalFile bool
}
// resolveTargetOverride re-resolves the source URI and classification when a target has a version override.
func resolveTargetOverride(params *processTargetsParams, indexTarget int, tgt schema.AtmosVendorTarget) (*resolvedTarget, error) {
resolvedVersion, rawVersion, err := install.ResolveEffectiveVersion(&install.ResolveEffectiveVersionInputs{
AtmosConfig: params.AtmosConfig,
Name: params.Source.Component,
Source: params.SourceTemplate,
RawVersion: tgt.Version,
Constraints: params.Source.Constraints,
Discriminator: fmt.Sprintf("target-%d", indexTarget),
RefreshLock: params.RefreshLock,
Lister: params.Lister,
})
if err != nil {
return nil, fmt.Errorf("resolve version for component %q target %d: %w", params.Source.Component, indexTarget, err)
}
tmplData := struct{ Component, Version string }{
Component: params.TemplateData.Component,
Version: resolvedVersion,
}
// Re-template the source URL with the target-specific version.
effectiveURI, err := ProcessTmpl(
params.AtmosConfig,
fmt.Sprintf("source-%d-target-%d", params.IndexSource, indexTarget),
params.SourceTemplate,
tmplData,
false,
)
if err != nil {
return nil, err
}
effectiveURI = normalizeVendorURI(effectiveURI)
// Recompute source classification from the re-resolved URI, since per-target version
// overrides may produce a URI with a different scheme or locality than the source-level URI.
useOciScheme, useLocalFileSystem, sourceIsLocalFile, err := determineSourceType(&effectiveURI, params.VendorConfigFilePath)
if err != nil {
return nil, err
}
if !useLocalFileSystem {
if err := u.ValidateURI(effectiveURI); err != nil {
return nil, fmt.Errorf("invalid URI for component %s: %w", params.Source.Component, err)
}
}
return &resolvedTarget{
uri: effectiveURI,
version: resolvedVersion,
rawVersion: rawVersion,
tmplData: tmplData,
pkgType: install.DeterminePackageType(useOciScheme, useLocalFileSystem),
sourceIsLocalFile: sourceIsLocalFile,
}, nil
}
func processTargets(params *processTargetsParams) ([]install.VendorPackage, error) {
var packages []install.VendorPackage
for indexTarget, tgt := range params.Source.Targets {
// Determine the effective template data and URI for this target.
tmplData := params.TemplateData
effectiveURI := params.URI
// Default to the source-level resolved version/raw-range (TemplateData.Version is already
// the resolved concrete version; RawVersion is empty unless it was a range).
effectiveVersion := params.TemplateData.Version
effectiveRawVersion := params.RawVersion
// Default to source-level classification.
pType := params.PkgType
sourceIsLocalFile := params.SourceIsLocalFile
// If the target has its own version, override template data and re-resolve the source URI.
if tgt.Version != "" {
resolved, err := resolveTargetOverride(params, indexTarget, tgt)
if err != nil {
return nil, err
}
effectiveURI = resolved.uri
effectiveVersion = resolved.version
effectiveRawVersion = resolved.rawVersion
tmplData = resolved.tmplData
pType = resolved.pkgType
sourceIsLocalFile = resolved.sourceIsLocalFile
}
// Template-expand the target path.
target, err := ProcessTmpl(params.AtmosConfig, fmt.Sprintf("target-%d-%d", params.IndexSource, indexTarget), tgt.Path, tmplData, false)
if err != nil {
return nil, err
}
targetPath := filepath.Join(params.VendorConfigFilePath, target)
// Resolve to absolute so the vendor lock's target-containment check (pkg/vendoring/lockfile)
// compares two absolute paths; a relative VendorConfigFilePath otherwise makes targetPath
// relative to CWD, which the lock validation cannot reliably relate back to BasePath.
targetPath, err = filepath.Abs(targetPath)
if err != nil {
return nil, fmt.Errorf("resolve target path: %w", err)
}
pkgName := params.Source.Component
if pkgName == "" {
pkgName = effectiveURI
}
// Create package.
p := install.NewAtmosVendorPackage(&install.AtmosPackageParams{
Name: pkgName,
URI: effectiveURI,
TargetPath: targetPath,
Version: effectiveVersion,
RawVersion: effectiveRawVersion,
PkgType: pType,
SourceIsLocalFile: sourceIsLocalFile,
Source: *params.Source,
})
packages = append(packages, p)
}
return packages, nil
}
// processVendorImports processes all imports recursively and returns a list of sources.
func processVendorImports(
atmosConfig *schema.AtmosConfiguration,
vendorConfigFile string,
imports []string,
sources []schema.AtmosVendorSource,
allImports []string,
) ([]schema.AtmosVendorSource, []string, error) {
var mergedSources []schema.AtmosVendorSource
for _, imp := range imports {
if slices.Contains(allImports, imp) {
return nil, nil, fmt.Errorf(
"%w '%s' in the vendor config file '%s'. It was already imported in the import chain",
ErrDuplicateImport,
imp,
vendorConfigFile,
)
}
allImports = append(allImports, imp)
vendorConfig, _, _, err := ReadAndProcessVendorConfigFile(atmosConfig, imp, false)
if err != nil {
return nil, nil, err
}
if slices.Contains(vendorConfig.Spec.Imports, imp) {
return nil, nil, fmt.Errorf("%w file '%s'", ErrVendorConfigSelfImport, imp)
}
if len(vendorConfig.Spec.Sources) == 0 && len(vendorConfig.Spec.Imports) == 0 {
return nil, nil, fmt.Errorf("%w '%s'", ErrMissingVendorConfigDefinition, imp)
}
mergedSources, allImports, err = processVendorImports(atmosConfig, imp, vendorConfig.Spec.Imports, mergedSources, allImports)
if err != nil {
return nil, nil, err
}
for i := range vendorConfig.Spec.Sources {
vendorConfig.Spec.Sources[i].File = imp
}
mergedSources = append(mergedSources, vendorConfig.Spec.Sources...)
}
return append(mergedSources, sources...), allImports, nil
}
func logInitialMessage(vendorConfigFileName string, tags []string) {
logMessage := fmt.Sprintf("Vendoring from '%s'", vendorConfigFileName)
if len(tags) > 0 {
logMessage = fmt.Sprintf("%s for tags {%s}", logMessage, strings.Join(tags, ", "))
}
ui.Info(logMessage)
}
func validateSourceFields(s *schema.AtmosVendorSource, vendorConfigFileName string) error {
// Ensure necessary fields are present
if s.File == "" {
s.File = vendorConfigFileName
}
if s.Source == "" {
return fmt.Errorf("%w `%s`", ErrSourceMissing, s.File)
}
if len(s.Targets) == 0 {
return fmt.Errorf("%w for source '%s' in file '%s'", ErrTargetsMissing, s.Source, s.File)
}
if err := version.ValidateVersionRangeConstraints(s.Version, s.Constraints); err != nil {
return err
}
return nil
}
func shouldSkipSource(s *schema.AtmosVendorSource, component string, tags []string) bool {
// Skip if component or tags do not match
// If `--component` is specified, and it's not equal to this component, skip this component
// If `--tags` list is specified, and it does not contain any tags defined in this component, skip this component.
return (component != "" && s.Component != component) || (len(tags) > 0 && len(lo.Intersect(tags, s.Tags)) == 0)
}
// normalizeVendorURI normalizes vendor source URIs to handle all patterns consistently.
// Delegates to pkg/vendor for the shared implementation.
func normalizeVendorURI(uri string) string {
return vendor.NormalizeURI(uri)
}
func determineSourceType(uri *string, vendorConfigFilePath string) (bool, bool, bool, error) {
// Determine if the URI is an OCI scheme, a local file, or remote
useLocalFileSystem := false
sourceIsLocalFile := false
useOciScheme := strings.HasPrefix(*uri, "oci://")
if useOciScheme {
*uri = strings.TrimPrefix(*uri, "oci://")
return useOciScheme, useLocalFileSystem, sourceIsLocalFile, nil
}
absPath, err := u.JoinPathAndValidate(vendorConfigFilePath, *uri)
// if URI contain path traversal is path should be resolved
if err != nil && strings.Contains(*uri, "..") && !strings.HasPrefix(*uri, "file://") {
return useOciScheme, useLocalFileSystem, sourceIsLocalFile, fmt.Errorf("invalid source path '%s': %w", *uri, err)
}
if err == nil {
uri = &absPath
useLocalFileSystem = true
sourceIsLocalFile = u.FileExists(*uri)
}
parsedURL, err := url.Parse(*uri)
if err != nil {
return useOciScheme, useLocalFileSystem, sourceIsLocalFile, err
}
if parsedURL.Scheme != "" {
if parsedURL.Scheme == "file" {
trimmedPath := strings.TrimPrefix(filepath.ToSlash(parsedURL.Path), "/")
*uri = filepath.Clean(trimmedPath)
useLocalFileSystem = true
}
}
return useOciScheme, useLocalFileSystem, sourceIsLocalFile, nil
}
// generateSkipFunction creates a function that determines whether to skip files during copying.
// Delegates to pkg/vendor for the shared implementation.
func generateSkipFunction(tempDir string, s *schema.AtmosVendorSource) func(os.FileInfo, string, string) (bool, error) {
return vendor.CreateSkipFunc(tempDir, s.IncludedPaths, s.ExcludedPaths)
}
// shouldExcludeFile checks if the file matches any of the excluded patterns.
// Delegates to pkg/vendor for the shared implementation.
func shouldExcludeFile(src string, excludedPaths []string, trimmedSrc string) (bool, error) {
return vendor.ShouldExcludeFile(excludedPaths, trimmedSrc)
}