-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
2189 lines (2042 loc) · 81.8 KB
/
Copy pathmain.go
File metadata and controls
2189 lines (2042 loc) · 81.8 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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
// Copyright © 2026 container-compose project authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//===----------------------------------------------------------------------===//
package main
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/compose-spec/compose-go/v2/cli"
"github.com/compose-spec/compose-go/v2/dotenv"
"github.com/compose-spec/compose-go/v2/template"
"github.com/compose-spec/compose-go/v2/types"
composeRemote "github.com/stephenlclarke/container-compose/Tools/compose-normalizer/remote"
"go.yaml.in/yaml/v4"
)
func init() {
dotenv.RegisterFormat("raw", parseRawEnvFile)
}
func parseRawEnvFile(r io.Reader, filename string, vars map[string]string, lookup func(key string) (string, bool)) error {
content, err := io.ReadAll(r)
if err != nil {
return fmt.Errorf("failed to read %s: %w", filename, err)
}
for _, rawLine := range strings.Split(string(content), "\n") {
line := strings.TrimSuffix(rawLine, "\r")
trimmed := strings.TrimSpace(line)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
continue
}
key, value, ok := strings.Cut(line, "=")
key = strings.TrimSpace(key)
if key == "" {
return fmt.Errorf("failed to read %s: missing environment variable name", filename)
}
if ok {
vars[key] = value
continue
}
if lookup == nil {
continue
}
if resolved, found := lookup(key); found {
vars[key] = resolved
}
}
return nil
}
// stringList records repeatable flag values while preserving input order.
type stringList []string
// String returns the flag display value for repeated string options.
func (s *stringList) String() string {
if s == nil {
return ""
}
return strings.Join(*s, ",")
}
// Set records one occurrence of a repeatable CLI option.
func (s *stringList) Set(value string) error {
*s = append(*s, value)
return nil
}
// normalizedProject is the stable JSON envelope consumed by Swift.
type normalizedProject struct {
Name string `json:"name"`
WorkingDirectory string `json:"workingDirectory"`
ComposeFiles []string `json:"composeFiles"`
Environment map[string]string `json:"environment,omitempty"`
Profiles []string `json:"profiles,omitempty"`
Services map[string]normalizedService `json:"services"`
Networks map[string]normalizedNetwork `json:"networks"`
Volumes map[string]normalizedVolume `json:"volumes"`
Configs map[string]any `json:"configs,omitempty"`
Secrets map[string]any `json:"secrets,omitempty"`
Models map[string]any `json:"models,omitempty"`
Extensions map[string]any `json:"extensions,omitempty"`
}
// bridgeProject carries the runtime projection and compose-go's public model
// from one parse so Bridge templates retain Compose attribute names and shapes.
type bridgeProject struct {
Project *normalizedProject `json:"project"`
Model any `json:"model"`
}
type normalizedVariable struct {
Name string `json:"name"`
Required bool `json:"required"`
DefaultValue string `json:"defaultValue,omitempty"`
AlternateValue string `json:"alternateValue,omitempty"`
}
type normalizedEnvFile struct {
Path string `json:"path"`
Required bool `json:"required"`
Format string `json:"format,omitempty"`
}
// normalizedService contains the Compose service fields Swift can either
// orchestrate directly or preserve for config output and runtime gap checks.
type normalizedService struct {
Name string `json:"name"`
Image string `json:"image,omitempty"`
Profiles []string `json:"profiles,omitempty"`
PullPolicy string `json:"pullPolicy,omitempty"`
Platform string `json:"platform,omitempty"`
Annotations map[string]string `json:"annotations,omitempty"`
Attach *bool `json:"attach,omitempty"`
BlkioConfig *normalizedBlkioConfig `json:"blkioConfig,omitempty"`
MacAddress string `json:"macAddress,omitempty"`
Runtime string `json:"runtime,omitempty"`
Cgroup string `json:"cgroup,omitempty"`
CgroupParent string `json:"cgroupParent,omitempty"`
CPUCount int64 `json:"cpuCount,omitempty"`
CPUPercent float32 `json:"cpuPercent,omitempty"`
CPUPeriod int64 `json:"cpuPeriod,omitempty"`
CPUQuota int64 `json:"cpuQuota,omitempty"`
CPURealtimePeriod int64 `json:"cpuRealtimePeriod,omitempty"`
CPURealtimeRuntime int64 `json:"cpuRealtimeRuntime,omitempty"`
CPUSet string `json:"cpuset,omitempty"`
CPUShares int64 `json:"cpuShares,omitempty"`
Develop *normalizedDevelop `json:"develop,omitempty"`
Deploy *types.DeployConfig `json:"deploy,omitempty"`
DeployGPURequests []types.DeviceRequest `json:"deployGPURequests,omitempty"`
UnsupportedDeployFields []string `json:"unsupportedDeployFields,omitempty"`
DeployMode string `json:"deployMode,omitempty"`
DeployLabels map[string]string `json:"deployLabels,omitempty"`
DeployRestartPolicy *normalizedDeployRestartPolicy `json:"deployRestartPolicy,omitempty"`
Build *normalizedBuild `json:"build,omitempty"`
Command *[]string `json:"command,omitempty"`
Entrypoint *[]string `json:"entrypoint,omitempty"`
Provider *normalizedProvider `json:"provider,omitempty"`
CredentialSpec *types.CredentialSpecConfig `json:"credentialSpec,omitempty"`
DeviceCgroupRules []string `json:"deviceCgroupRules,omitempty"`
Devices []types.DeviceMapping `json:"devices,omitempty"`
Environment map[string]*string `json:"environment,omitempty"`
EnvFiles []normalizedEnvFile `json:"envFiles,omitempty"`
Expose []string `json:"expose,omitempty"`
Gpus []types.DeviceRequest `json:"gpus,omitempty"`
Ports []string `json:"ports,omitempty"`
Volumes []normalizedMount `json:"volumes,omitempty"`
VolumeDriver string `json:"volumeDriver,omitempty"`
VolumesFrom []string `json:"volumesFrom,omitempty"`
Networks []string `json:"networks,omitempty"`
NetworkAliases map[string][]string `json:"networkAliases,omitempty"`
NetworkOptions map[string]normalizedNetworkOptions `json:"networkOptions,omitempty"`
NetworkMode string `json:"networkMode,omitempty"`
DependsOn map[string]normalizedDependency `json:"dependsOn,omitempty"`
Links []string `json:"links,omitempty"`
ExternalLinks []string `json:"externalLinks,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
LabelFiles []string `json:"labelFiles,omitempty"`
ContainerName string `json:"containerName,omitempty"`
Hostname string `json:"hostname,omitempty"`
DomainName string `json:"domainName,omitempty"`
WorkingDir string `json:"workingDir,omitempty"`
User string `json:"user,omitempty"`
GroupAdd []string `json:"groupAdd,omitempty"`
TTY bool `json:"tty,omitempty"`
StdinOpen bool `json:"stdinOpen,omitempty"`
ReadOnly bool `json:"readOnly,omitempty"`
Privileged bool `json:"privileged,omitempty"`
Restart string `json:"restart,omitempty"`
Init *bool `json:"init,omitempty"`
Scale *int `json:"scale,omitempty"`
Logging *normalizedLoggingConfig `json:"logging,omitempty"`
LogDriver string `json:"logDriver,omitempty"`
LogOptions map[string]string `json:"logOptions,omitempty"`
StorageOptions map[string]string `json:"storageOptions,omitempty"`
UseAPISocket bool `json:"useAPISocket,omitempty"`
Ipc string `json:"ipc,omitempty"`
Isolation string `json:"isolation,omitempty"`
Tmpfs []string `json:"tmpfs,omitempty"`
DNS []string `json:"dns,omitempty"`
DNSSearch []string `json:"dnsSearch,omitempty"`
DNSOptions []string `json:"dnsOptions,omitempty"`
ExtraHosts []string `json:"extraHosts,omitempty"`
CapAdd []string `json:"capAdd,omitempty"`
CapDrop []string `json:"capDrop,omitempty"`
SecurityOpt []string `json:"securityOpt,omitempty"`
MemLimit string `json:"memLimit,omitempty"`
MemReservation string `json:"memReservation,omitempty"`
MemSwapLimit string `json:"memSwapLimit,omitempty"`
MemSwappiness string `json:"memSwappiness,omitempty"`
Models map[string]normalizedServiceModel `json:"models,omitempty"`
OomKillDisable bool `json:"oomKillDisable,omitempty"`
OomScoreAdj int64 `json:"oomScoreAdj,omitempty"`
PidsLimit int64 `json:"pidsLimit,omitempty"`
CPUS string `json:"cpus,omitempty"`
ShmSize string `json:"shmSize,omitempty"`
Ulimits []string `json:"ulimits,omitempty"`
Pid string `json:"pid,omitempty"`
Sysctls map[string]string `json:"sysctls,omitempty"`
StopSignal string `json:"stopSignal,omitempty"`
StopGracePeriodSeconds *int64 `json:"stopGracePeriodSeconds,omitempty"`
PreStart []normalizedServiceHook `json:"preStart,omitempty"`
PostStart []normalizedServiceHook `json:"postStart,omitempty"`
PreStop []normalizedServiceHook `json:"preStop,omitempty"`
UserNSMode string `json:"userns_mode,omitempty"`
Uts string `json:"uts,omitempty"`
Healthcheck any `json:"healthcheck,omitempty"`
Configs any `json:"configs,omitempty"`
Secrets any `json:"secrets,omitempty"`
Extensions map[string]any `json:"extensions,omitempty"`
}
// normalizedLoggingConfig is the lossless, runtime-neutral logging request.
// Driver is deliberately not omitempty so an explicit empty driver remains
// distinguishable from an omitted logging object.
type normalizedLoggingConfig struct {
Driver string `json:"driver"`
Options map[string]string `json:"options,omitempty"`
}
// normalizedBlkioConfig preserves Compose block I/O controls for the runtime
// CLI shape proposed in apple/container#1595.
type normalizedBlkioConfig struct {
Weight *uint16 `json:"weight,omitempty"`
WeightDevice []normalizedWeightDevice `json:"weightDevice,omitempty"`
DeviceReadBps []normalizedThrottleDevice `json:"deviceReadBps,omitempty"`
DeviceReadIOps []normalizedThrottleDevice `json:"deviceReadIOps,omitempty"`
DeviceWriteBps []normalizedThrottleDevice `json:"deviceWriteBps,omitempty"`
DeviceWriteIOps []normalizedThrottleDevice `json:"deviceWriteIOps,omitempty"`
}
// normalizedWeightDevice stores one per-device block I/O weight.
type normalizedWeightDevice struct {
Path string `json:"path"`
Weight uint16 `json:"weight"`
}
// normalizedThrottleDevice stores one per-device block I/O throttle.
type normalizedThrottleDevice struct {
Path string `json:"path"`
Rate string `json:"rate"`
}
// normalizedDeployRestartPolicy preserves the Compose Deploy restart policy
// fields that Swift maps or rejects against apple/container runtime support.
type normalizedDeployRestartPolicy struct {
Condition string `json:"condition,omitempty"`
DelayNanos int64 `json:"delayNanoseconds,omitempty"`
MaxAttempts *uint64 `json:"maxAttempts,omitempty"`
WindowNanos int64 `json:"windowNanoseconds,omitempty"`
}
// normalizedProvider records the provider executable and options used by a
// non-container service lifecycle.
type normalizedProvider struct {
Type string `json:"type"`
Options map[string][]string `json:"options,omitempty"`
}
// normalizedServiceModel records the environment-variable binding requested by
// a service for one top-level Compose model.
type normalizedServiceModel struct {
EndpointVariable string `json:"endpointVariable,omitempty"`
ModelVariable string `json:"modelVariable,omitempty"`
}
// normalizedBuild keeps the build fields needed to call `container build`.
type normalizedBuild struct {
Context string `json:"context,omitempty"`
Dockerfile string `json:"dockerfile,omitempty"`
DockerfileInline string `json:"dockerfileInline,omitempty"`
AdditionalContexts map[string]string `json:"additionalContexts,omitempty"`
Args map[string]string `json:"args,omitempty"`
CacheFrom []string `json:"cacheFrom,omitempty"`
CacheTo []string `json:"cacheTo,omitempty"`
Entitlements []string `json:"entitlements,omitempty"`
ExtraHosts []string `json:"extraHosts,omitempty"`
Isolation string `json:"isolation,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
Network string `json:"network,omitempty"`
Privileged bool `json:"privileged,omitempty"`
Secrets []normalizedBuildSecret `json:"secrets,omitempty"`
ShmSize string `json:"shmSize,omitempty"`
SSH []string `json:"ssh,omitempty"`
Target string `json:"target,omitempty"`
NoCache bool `json:"noCache,omitempty"`
NoCacheFilter []string `json:"noCacheFilter,omitempty"`
Pull bool `json:"pull,omitempty"`
Platforms []string `json:"platforms,omitempty"`
Tags []string `json:"tags,omitempty"`
Ulimits []string `json:"ulimits,omitempty"`
Provenance string `json:"provenance,omitempty"`
SBOM string `json:"sbom,omitempty"`
UnsupportedFields []string `json:"unsupportedFields,omitempty"`
}
// normalizedBuildSecret contains the apple/container `container build --secret` fields
// that can be safely derived from a Compose top-level secret definition.
type normalizedBuildSecret struct {
ID string `json:"id"`
File string `json:"file,omitempty"`
Environment string `json:"environment,omitempty"`
ExternalName string `json:"externalName,omitempty"`
}
// normalizedDevelop preserves Compose Develop Specification data needed by
// Swift validation and watch orchestration.
type normalizedDevelop struct {
Watch []normalizedWatchTrigger `json:"watch,omitempty"`
}
// normalizedWatchTrigger records one compose-go develop.watch trigger.
type normalizedWatchTrigger struct {
Path string `json:"path"`
Action string `json:"action"`
Target string `json:"target,omitempty"`
Ignore []string `json:"ignore,omitempty"`
Include []string `json:"include,omitempty"`
InitialSync bool `json:"initialSync,omitempty"`
Exec *normalizedWatchExecHook `json:"exec,omitempty"`
}
// normalizedWatchExecHook records sync+exec metadata without executing it.
type normalizedWatchExecHook struct {
Command []string `json:"command,omitempty"`
User string `json:"user,omitempty"`
Privileged bool `json:"privileged,omitempty"`
WorkingDir string `json:"workingDir,omitempty"`
Environment map[string]*string `json:"environment,omitempty"`
}
// normalizedServiceHook records lifecycle hook metadata for Swift execution.
type normalizedServiceHook struct {
Command []string `json:"command,omitempty"`
Image string `json:"image,omitempty"`
User string `json:"user,omitempty"`
Privileged bool `json:"privileged,omitempty"`
WorkingDir string `json:"workingDir,omitempty"`
Environment map[string]*string `json:"environment,omitempty"`
PerReplica bool `json:"perReplica,omitempty"`
}
// normalizedMount keeps mount data in a compact runtime-oriented shape.
type normalizedMount struct {
Type string `json:"type,omitempty"`
Source string `json:"source,omitempty"`
Target string `json:"target,omitempty"`
ReadOnly bool `json:"readOnly,omitempty"`
BindCreateHostPath *bool `json:"bindCreateHostPath,omitempty"`
BindPropagation string `json:"bindPropagation,omitempty"`
VolumeNoCopy bool `json:"volumeNoCopy,omitempty"`
VolumeSubpath string `json:"volumeSubpath,omitempty"`
ImageSubpath string `json:"imageSubpath,omitempty"`
VolumeLabels map[string]string `json:"volumeLabels,omitempty"`
TmpfsSize string `json:"tmpfsSize,omitempty"`
TmpfsMode string `json:"tmpfsMode,omitempty"`
Raw string `json:"raw,omitempty"`
UnsupportedFields []string `json:"unsupportedFields,omitempty"`
}
// normalizedIPAMPool preserves one ordered Compose IPAM configuration pool.
//
// The values remain source-shaped strings because Docker validates several of
// them only when it creates a network. Auxiliary address names are significant
// and therefore remain a map instead of being flattened to sorted values.
type normalizedIPAMPool struct {
Subnet string `json:"subnet,omitempty"`
AllocationRange string `json:"allocationRange,omitempty"`
Gateway string `json:"gateway,omitempty"`
AuxiliaryAddresses map[string]string `json:"auxiliaryAddresses,omitempty"`
}
// normalizedIPAM preserves the complete source-facing Compose IPAM model.
//
// Existing singular fields on normalizedNetwork remain as legacy runtime
// adapters. They must not be used to reconstruct this requested-state model.
type normalizedIPAM struct {
Driver string `json:"driver,omitempty"`
Options map[string]string `json:"options,omitempty"`
Config []normalizedIPAMPool `json:"config,omitempty"`
}
// normalizedNetwork contains project-level network metadata.
type normalizedNetwork struct {
Name string `json:"name"`
External bool `json:"external,omitempty"`
Driver string `json:"driver,omitempty"`
DriverOpts map[string]string `json:"driverOpts,omitempty"`
IPAMOptions map[string]string `json:"ipamOptions,omitempty"`
IPAM *normalizedIPAM `json:"ipam,omitempty"`
Internal bool `json:"internal,omitempty"`
Attachable bool `json:"attachable,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
EnableIPv4 *bool `json:"enableIPv4,omitempty"`
IPv4Subnet string `json:"ipv4Subnet,omitempty"`
IPv4Gateway string `json:"ipv4Gateway,omitempty"`
IPv4AllocationRange string `json:"ipv4AllocationRange,omitempty"`
IPv4ReservedAddresses []string `json:"ipv4ReservedAddresses,omitempty"`
IPv6Subnet string `json:"ipv6Subnet,omitempty"`
IPv6Gateway string `json:"ipv6Gateway,omitempty"`
EnableIPv6 *bool `json:"enableIPv6,omitempty"`
UnsupportedFields []string `json:"unsupportedFields,omitempty"`
}
// normalizedNetworkOptions preserves per-service network attachment settings.
type normalizedNetworkOptions struct {
DriverOpts map[string]string `json:"driverOpts,omitempty"`
GatewayPriority int `json:"gatewayPriority,omitempty"`
InterfaceName string `json:"interfaceName,omitempty"`
IPv4Address string `json:"ipv4Address,omitempty"`
IPv6Address string `json:"ipv6Address,omitempty"`
LinkLocalIPs []string `json:"linkLocalIPs,omitempty"`
MacAddress string `json:"macAddress,omitempty"`
Priority int `json:"priority,omitempty"`
}
// normalizedDependency preserves Compose dependency behavior that affects
// startup ordering or requires explicit unsupported-feature checks.
type normalizedDependency struct {
Condition string `json:"condition,omitempty"`
Restart bool `json:"restart,omitempty"`
Required *bool `json:"required,omitempty"`
}
// normalizedVolume contains project-level volume metadata.
type normalizedVolume struct {
Name string `json:"name"`
External bool `json:"external,omitempty"`
Driver string `json:"driver,omitempty"`
DriverOpts map[string]string `json:"driverOpts,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
}
// main exits with the helper status code returned by run.
func main() {
os.Exit(run(os.Args[1:], os.Stdout, os.Stderr))
}
// run parses helper flags and writes canonical Compose project JSON.
func run(args []string, stdout io.Writer, stderr io.Writer) int {
var files stringList
var profiles stringList
var envFiles stringList
var projectName string
var projectDirectory string
var noConsistency bool
var noEnvResolution bool
var noInterpolate bool
var noNormalize bool
var noPathResolution bool
var variables bool
var bridgeModel bool
var publish bool
var publishRepository string
var publishApp bool
var publishOCIVersion string
var publishResolveImageDigests bool
var publishWithEnv bool
var publishYes bool
var publishDryRun bool
flags := flag.NewFlagSet("compose-normalizer", flag.ContinueOnError)
flags.SetOutput(stderr)
flags.Var(&files, "file", "Compose file path. May be repeated.")
flags.Var(&profiles, "profile", "Compose profile. May be repeated.")
flags.Var(&envFiles, "env-file", "Environment file. May be repeated.")
flags.StringVar(&projectName, "project-name", "", "Compose project name.")
flags.StringVar(&projectDirectory, "project-directory", "", "Project directory.")
flags.BoolVar(&noConsistency, "no-consistency", false, "Skip model consistency checks.")
flags.BoolVar(&noEnvResolution, "no-env-resolution", false, "Do not resolve service env files.")
flags.BoolVar(&noInterpolate, "no-interpolate", false, "Do not interpolate environment variables.")
flags.BoolVar(&noNormalize, "no-normalize", false, "Do not normalize the compose model.")
flags.BoolVar(&noPathResolution, "no-path-resolution", false, "Do not resolve relative file paths.")
flags.BoolVar(&variables, "variables", false, "Print model variables as JSON.")
flags.BoolVar(&bridgeModel, "bridge-model", false, "Print the runtime project and Compose Bridge model as JSON.")
flags.BoolVar(&publish, "publish", false, "Publish the Compose project as an OCI artifact.")
flags.StringVar(&publishRepository, "publish-repository", "", "OCI repository reference for publish.")
flags.BoolVar(&publishApp, "publish-app", false, "Publish application image index.")
flags.StringVar(&publishOCIVersion, "publish-oci-version", "", "OCI image/artifact specification version.")
flags.BoolVar(&publishResolveImageDigests, "publish-resolve-image-digests", false, "Pin image tags to digests before publishing.")
flags.BoolVar(&publishWithEnv, "publish-with-env", false, "Include env files in the published OCI artifact.")
flags.BoolVar(&publishYes, "publish-yes", false, "Assume yes for publish preflight confirmations.")
flags.BoolVar(&publishDryRun, "publish-dry-run", false, "Plan publish without pushing to a registry.")
if err := flags.Parse(args); err != nil {
return 2
}
loadOptions := projectLoadOptions{
noConsistency: noConsistency,
noEnvResolution: noEnvResolution,
noInterpolate: noInterpolate,
noNormalize: noNormalize,
noPathResolution: noPathResolution,
}
var result any
var err error
modeCount := 0
for _, enabled := range []bool{variables, bridgeModel, publish} {
if enabled {
modeCount++
}
}
if modeCount > 1 {
fmt.Fprintln(stderr, "compose-normalizer: --variables, --bridge-model, and --publish are mutually exclusive")
return 2
}
if variables {
result, err = loadVariables(files, profiles, envFiles, projectName, projectDirectory, loadOptions)
} else if bridgeModel {
result, err = loadBridgeProject(files, profiles, envFiles, projectName, projectDirectory, loadOptions)
} else if publish {
result, err = publishComposeProject(publishRequest{
files: files,
profiles: profiles,
envFiles: envFiles,
projectName: projectName,
projectDirectory: projectDirectory,
loadOptions: loadOptions,
}, publishOptions{
repository: publishRepository,
app: publishApp,
ociVersion: publishOCIVersion,
resolveImageDigests: publishResolveImageDigests,
withEnv: publishWithEnv,
assumeYes: publishYes,
dryRun: publishDryRun,
}, stderr)
} else {
result, err = loadProject(files, profiles, envFiles, projectName, projectDirectory, loadOptions)
}
if err != nil {
fmt.Fprintf(stderr, "compose-normalizer: %v\n", err)
return 1
}
encoder := json.NewEncoder(stdout)
encoder.SetIndent("", " ")
if err := encoder.Encode(result); err != nil {
fmt.Fprintf(stderr, "compose-normalizer: encode: %v\n", err)
return 1
}
return 0
}
type projectLoadOptions struct {
noConsistency bool
noEnvResolution bool
noInterpolate bool
noNormalize bool
noPathResolution bool
}
// loadProject delegates Compose parsing, merging, interpolation, and profile
// handling to compose-go.
func loadProject(files, profiles, envFiles []string, projectName, projectDirectory string, optionalLoadOptions ...projectLoadOptions) (*normalizedProject, error) {
loadOptions := firstProjectLoadOptions(optionalLoadOptions)
project, resolvedProjectDirectory, err := loadComposeProject(files, profiles, envFiles, projectName, projectDirectory, loadOptions)
if err != nil {
return nil, err
}
return normalize(project, resolvedProjectDirectory), nil
}
// loadBridgeProject returns both orchestration data and compose-go's canonical
// public model without parsing or normalizing the Compose inputs twice.
func loadBridgeProject(files, profiles, envFiles []string, projectName, projectDirectory string, optionalLoadOptions ...projectLoadOptions) (*bridgeProject, error) {
loadOptions := firstProjectLoadOptions(optionalLoadOptions)
project, resolvedProjectDirectory, err := loadComposeProject(files, profiles, envFiles, projectName, projectDirectory, loadOptions)
if err != nil {
return nil, err
}
rawModel, err := project.MarshalYAML(types.WithSecretContent)
if err != nil {
return nil, fmt.Errorf("marshal bridge model: %w", err)
}
var model any
if err := yaml.Unmarshal(rawModel, &model); err != nil {
return nil, fmt.Errorf("decode bridge model: %w", err)
}
return &bridgeProject{
Project: normalize(project, resolvedProjectDirectory),
Model: model,
}, nil
}
// loadComposeProject applies Compose input options and returns compose-go's
// canonical project plus the resolved project directory.
func loadComposeProject(files, profiles, envFiles []string, projectName, projectDirectory string, loadOptions projectLoadOptions) (*types.Project, string, error) {
if projectDirectory == "" {
var err error
projectDirectory, err = os.Getwd()
if err != nil {
return nil, "", err
}
}
usesDefaultFiles := len(files) == 0
var options []cli.ProjectOptionsFn
options = append(options, cli.WithWorkingDirectory(projectDirectory))
options = append(options, cli.WithOsEnv)
envFiles = configuredEnvFiles(envFiles)
if len(envFiles) > 0 {
options = append(options, cli.WithEnvFiles(envFiles...))
} else {
options = append(options, cli.WithEnvFiles())
}
options = append(options, cli.WithDotEnv)
options = append(options, cli.WithResourceLoader(composeRemote.NewGitRemoteLoader(false)))
options = append(options, cli.WithResourceLoader(composeRemote.NewOCIRemoteLoader(false)))
if usesDefaultFiles {
options = append(options, cli.WithConfigFileEnv)
options = append(options, cli.WithDefaultConfigPath)
}
if projectName != "" {
options = append(options, cli.WithName(projectName))
}
if len(profiles) > 0 {
options = append(options, cli.WithProfiles(profiles))
} else {
options = append(options, cli.WithDefaultProfiles())
}
options = appendProjectLoadOptions(options, loadOptions)
projectOptions, err := newProjectOptions(files, projectDirectory, usesDefaultFiles, options...)
if err != nil {
return nil, "", err
}
if len(projectOptions.ConfigPaths) == 0 {
return nil, "", errors.New("no compose file found")
}
project, err := cli.ProjectFromOptions(context.Background(), projectOptions)
if err != nil {
return nil, "", err
}
if project.WorkingDir != "" {
projectDirectory = project.WorkingDir
}
return project, projectDirectory, nil
}
func loadVariables(files, profiles, envFiles []string, projectName, projectDirectory string, optionalLoadOptions ...projectLoadOptions) ([]normalizedVariable, error) {
loadOptions := firstProjectLoadOptions(optionalLoadOptions)
if projectDirectory == "" {
var err error
projectDirectory, err = os.Getwd()
if err != nil {
return nil, err
}
}
usesDefaultFiles := len(files) == 0
options := []cli.ProjectOptionsFn{cli.WithWorkingDirectory(projectDirectory), cli.WithOsEnv}
envFiles = configuredEnvFiles(envFiles)
if len(envFiles) > 0 {
options = append(options, cli.WithEnvFiles(envFiles...))
} else {
options = append(options, cli.WithEnvFiles())
}
options = append(options, cli.WithDotEnv)
options = append(options, cli.WithResourceLoader(composeRemote.NewGitRemoteLoader(false)))
options = append(options, cli.WithResourceLoader(composeRemote.NewOCIRemoteLoader(false)))
if usesDefaultFiles {
options = append(options, cli.WithConfigFileEnv, cli.WithDefaultConfigPath)
}
if projectName != "" {
options = append(options, cli.WithName(projectName))
}
if len(profiles) > 0 {
options = append(options, cli.WithProfiles(profiles))
} else {
options = append(options, cli.WithDefaultProfiles())
}
options = appendProjectLoadOptions(options, loadOptions)
options = append(options, cli.WithInterpolation(false))
projectOptions, err := newProjectOptions(files, projectDirectory, usesDefaultFiles, options...)
if err != nil {
return nil, err
}
if len(projectOptions.ConfigPaths) == 0 {
return nil, errors.New("no compose file found")
}
model, err := projectOptions.LoadModel(context.Background())
if err != nil {
return nil, err
}
extracted := template.ExtractVariables(model, template.DefaultPattern)
names := make([]string, 0, len(extracted))
for name := range extracted {
names = append(names, name)
}
sort.Strings(names)
variables := make([]normalizedVariable, 0, len(names))
for _, name := range names {
variable := extracted[name]
variables = append(variables, normalizedVariable{
Name: variable.Name,
Required: variable.Required,
DefaultValue: variable.DefaultValue,
AlternateValue: variable.PresenceValue,
})
}
return variables, nil
}
// configuredEnvFiles gives explicit --env-file values precedence over Docker
// Compose's comma-separated COMPOSE_ENV_FILES fallback. Source-checkout
// invocations receive the original Compose process directory because the Go
// helper itself runs from Tools/compose-normalizer.
func configuredEnvFiles(envFiles []string) []string {
if len(envFiles) > 0 {
return envFiles
}
configured := strings.TrimSpace(os.Getenv("COMPOSE_ENV_FILES"))
if configured == "" {
return nil
}
workingDirectory := strings.TrimSpace(os.Getenv("CONTAINER_COMPOSE_NORMALIZER_CALLER_WORKING_DIRECTORY"))
if workingDirectory == "" {
var err error
workingDirectory, err = os.Getwd()
if err != nil {
workingDirectory = ""
}
}
values := make([]string, 0)
for _, value := range strings.Split(configured, ",") {
if value = strings.TrimSpace(value); value != "" {
if workingDirectory != "" && !filepath.IsAbs(value) {
value = filepath.Join(workingDirectory, value)
}
values = append(values, value)
}
}
return values
}
func firstProjectLoadOptions(options []projectLoadOptions) projectLoadOptions {
if len(options) == 0 {
return projectLoadOptions{}
}
return options[0]
}
func appendProjectLoadOptions(options []cli.ProjectOptionsFn, loadOptions projectLoadOptions) []cli.ProjectOptionsFn {
options = append(options,
cli.WithConsistency(!loadOptions.noConsistency),
cli.WithInterpolation(!loadOptions.noInterpolate),
cli.WithNormalization(!loadOptions.noNormalize),
cli.WithResolvedPaths(!loadOptions.noPathResolution),
)
if loadOptions.noEnvResolution {
options = append(options, cli.WithoutEnvironmentResolution)
}
return options
}
// newProjectOptions applies compose-go options from the Compose project
// directory when default file discovery is active. That keeps COMPOSE_FILE
// paths from .env aligned between installed helpers and source-checkout go run.
func newProjectOptions(files []string, projectDirectory string, usesDefaultFiles bool, options ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) {
if !usesDefaultFiles {
return cli.NewProjectOptions(files, options...)
}
previousDirectory, err := os.Getwd()
if err != nil {
return nil, err
}
if err := os.Chdir(projectDirectory); err != nil {
return nil, err
}
defer func() {
_ = os.Chdir(previousDirectory)
}()
return cli.NewProjectOptions(files, options...)
}
// normalize copies the compose-go project into the stable JSON shape consumed
// by Swift orchestration.
func normalize(project *types.Project, projectDirectory string) *normalizedProject {
profiles := project.AllServices().GetProfiles()
sort.Strings(profiles)
result := &normalizedProject{
Name: project.Name,
WorkingDirectory: projectDirectory,
ComposeFiles: append([]string(nil), project.ComposeFiles...),
Environment: mapStringValues(project.Environment),
Profiles: profiles,
Services: map[string]normalizedService{},
Networks: map[string]normalizedNetwork{},
Volumes: map[string]normalizedVolume{},
}
for _, service := range project.Services {
result.Services[service.Name] = normalizeService(service, project.Secrets)
}
for name, network := range project.Networks {
ipv4Subnet, ipv4Gateway, ipv4AllocationRange, ipv4ReservedAddresses, ipv6Subnet, ipv6Gateway, enableIPv4, enableIPv6, unsupportedFields := projectNetworkValues(network)
result.Networks[name] = normalizedNetwork{
Name: firstNonEmpty(network.Name, name),
External: bool(network.External),
Driver: network.Driver,
DriverOpts: mapOptions(network.DriverOpts),
IPAMOptions: mapOptions(network.Ipam.Options),
IPAM: normalizeIPAM(network.Ipam),
Internal: network.Internal,
Attachable: network.Attachable,
Labels: mapLabels(network.Labels),
EnableIPv4: enableIPv4,
IPv4Subnet: ipv4Subnet,
IPv4Gateway: ipv4Gateway,
IPv4AllocationRange: ipv4AllocationRange,
IPv4ReservedAddresses: ipv4ReservedAddresses,
IPv6Subnet: ipv6Subnet,
IPv6Gateway: ipv6Gateway,
EnableIPv6: enableIPv6,
UnsupportedFields: unsupportedFields,
}
}
for name, volume := range project.Volumes {
result.Volumes[name] = normalizedVolume{
Name: firstNonEmpty(volume.Name, name),
External: bool(volume.External),
Driver: volume.Driver,
DriverOpts: mapOptions(volume.DriverOpts),
Labels: mapLabels(volume.Labels),
}
}
if len(project.Configs) > 0 {
result.Configs = jsonMap(project.Configs)
}
if len(project.Secrets) > 0 {
result.Secrets = jsonMap(project.Secrets)
}
if len(project.Models) > 0 {
result.Models = jsonMap(project.Models)
}
if len(project.Extensions) > 0 {
result.Extensions = project.Extensions
}
return result
}
// normalizeIPAM copies every compose-go IPAM pool in source order.
func normalizeIPAM(ipam types.IPAMConfig) *normalizedIPAM {
result := &normalizedIPAM{
Driver: ipam.Driver,
Options: mapOptions(ipam.Options),
}
for _, pool := range ipam.Config {
if pool == nil {
continue
}
result.Config = append(result.Config, normalizedIPAMPool{
Subnet: pool.Subnet,
AllocationRange: pool.IPRange,
Gateway: pool.Gateway,
AuxiliaryAddresses: mapMapping(pool.AuxiliaryAddresses),
})
}
if result.Driver == "" && len(result.Options) == 0 && len(result.Config) == 0 {
return nil
}
return result
}
// projectNetworkValues returns mapped IPAM values and project network fields that
// need runtime behavior beyond apple/container's current network API.
func projectNetworkValues(network types.NetworkConfig) (string, string, string, []string, string, string, *bool, *bool, []string) {
ipv4Subnet, ipv4Gateway, ipv4AllocationRange, ipv4ReservedAddresses, ipv6Subnet, ipv6Gateway, ipamFields := networkIPAMValues(network.Ipam)
enableIPv4 := network.EnableIPv4
enableIPv6 := network.EnableIPv6
fields := []string{}
driver := strings.TrimSpace(network.Driver)
appendUnsupportedNetworkField(&fields, "driver", driver != "" && driver != "bridge")
fields = append(fields, ipamFields...)
if len(fields) == 0 {
return ipv4Subnet, ipv4Gateway, ipv4AllocationRange, ipv4ReservedAddresses, ipv6Subnet, ipv6Gateway, enableIPv4, enableIPv6, nil
}
return ipv4Subnet, ipv4Gateway, ipv4AllocationRange, ipv4ReservedAddresses, ipv6Subnet, ipv6Gateway, enableIPv4, enableIPv6, fields
}
// normalizeService copies a compose-go service into the stable Swift model.
func normalizeService(service types.ServiceConfig, secrets map[string]types.SecretConfig) normalizedService {
result := normalizedService{
Name: service.Name,
Image: service.Image,
Profiles: append([]string(nil), service.Profiles...),
PullPolicy: service.PullPolicy,
Platform: service.Platform,
Annotations: mapMapping(service.Annotations),
Attach: service.Attach,
BlkioConfig: blkioConfigValue(service.BlkioConfig),
MacAddress: service.MacAddress,
Runtime: service.Runtime,
Cgroup: service.Cgroup,
CgroupParent: service.CgroupParent,
CPUCount: service.CPUCount,
CPUPercent: service.CPUPercent,
CPUPeriod: service.CPUPeriod,
CPUQuota: service.CPUQuota,
CPURealtimePeriod: service.CPURTPeriod,
CPURealtimeRuntime: service.CPURTRuntime,
CPUSet: service.CPUSet,
CPUShares: service.CPUShares,
Develop: developValues(service.Develop),
Deploy: service.Deploy,
DeployGPURequests: deployGPURequests(service.Deploy),
UnsupportedDeployFields: unsupportedDeployFields(service.Deploy),
DeployMode: deployMode(service.Deploy),
DeployLabels: deployLabels(service.Deploy),
DeployRestartPolicy: deployRestartPolicyValue(service.Deploy),
Command: shellCommandValue(service.Command),
Entrypoint: shellCommandValue(service.Entrypoint),
Provider: providerValue(service.Provider),
CredentialSpec: service.CredentialSpec,
DeviceCgroupRules: append([]string(nil), service.DeviceCgroupRules...),
Devices: append([]types.DeviceMapping(nil), service.Devices...),
Environment: mapEnvironment(service.Environment),
EnvFiles: envFileValues(service.EnvFiles),
Expose: append([]string(nil), service.Expose...),
Gpus: append([]types.DeviceRequest(nil), service.Gpus...),
Ports: portValues(service.Ports),
Volumes: mountValues(service.Volumes),
VolumeDriver: service.VolumeDriver,
VolumesFrom: append([]string(nil), service.VolumesFrom...),
Networks: networkValues(service.Networks),
NetworkAliases: networkAliasValues(service.Name, service.Networks),
NetworkOptions: networkOptionValues(service.Networks),
NetworkMode: service.NetworkMode,
DependsOn: dependsOnValues(service.DependsOn),
Links: append([]string(nil), service.Links...),
ExternalLinks: append([]string(nil), service.ExternalLinks...),
Labels: mapLabels(service.Labels),
LabelFiles: append([]string(nil), service.LabelFiles...),
ContainerName: service.ContainerName,
Hostname: service.Hostname,
DomainName: service.DomainName,
WorkingDir: service.WorkingDir,
User: service.User,
GroupAdd: append([]string(nil), service.GroupAdd...),
TTY: service.Tty,
StdinOpen: service.StdinOpen,
ReadOnly: service.ReadOnly,
Privileged: service.Privileged,
Restart: service.Restart,
Init: service.Init,
Scale: serviceScale(service),
Logging: loggingConfigValue(service.Logging),
LogDriver: service.LogDriver,
LogOptions: mapStringMap(service.LogOpt),
StorageOptions: mapStringMap(service.StorageOpt),
UseAPISocket: service.UseAPISocket,
Ipc: service.Ipc,
Isolation: service.Isolation,
Tmpfs: append([]string(nil), service.Tmpfs...),
DNS: append([]string(nil), service.DNS...),
DNSSearch: append([]string(nil), service.DNSSearch...),
DNSOptions: append([]string(nil), service.DNSOpts...),
ExtraHosts: service.ExtraHosts.AsList(":"),
CapAdd: append([]string(nil), service.CapAdd...),
CapDrop: append([]string(nil), service.CapDrop...),
SecurityOpt: append([]string(nil), service.SecurityOpt...),
MemLimit: firstNonEmpty(unitBytesValue(service.MemLimit), deployLimitMemory(service.Deploy)),
// Docker Compose local mode projects deploy reservation memory to the
// Engine soft-memory reservation. compose-go rejects distinct service and
// Deploy values, so this selects the Deploy form when it is present while
// retaining the existing service-level mapping as the fallback.
MemReservation: firstNonEmpty(deployReservationMemory(service.Deploy), unitBytesValue(service.MemReservation)),