-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcli.go
More file actions
830 lines (711 loc) · 22 KB
/
Copy pathcli.go
File metadata and controls
830 lines (711 loc) · 22 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
package dewy
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/fatih/color"
flags "github.com/jessevdk/go-flags"
"github.com/linyows/dewy/container"
"github.com/linyows/dewy/telemetry"
)
const (
// ExitOK for exit code.
ExitOK int = 0
// ExitErr for exit code.
ExitErr int = 1
// deployTimeFormat is the time format used for displaying container deployment times.
deployTimeFormat = "2006-01-02 15:04:05"
)
type cli struct {
env Env
command string
args []string
Name string `long:"name" short:"n" description:"Application name for container deployment"`
LogLevel string `long:"log-level" short:"l" arg:"(debug|info|warn|error)" description:"Set log level for output (default: error)"`
LogFormat string `long:"log-format" short:"f" arg:"(text|json)" description:"Set log format for output (default: text)"`
Interval int `long:"interval" arg:"seconds" short:"i" description:"Polling interval in seconds for checking registry updates (default: 10)"`
Ports []string `long:"port" short:"p" description:"For server: TCP ports to listen on. For container: port mappings in format 'proxy' or 'proxy:container' (multiple flags supported)"`
Registry string `long:"registry" description:"Registry URL (e.g., ghr://owner/repo, s3://region/bucket/prefix, docker://registry/repo)"`
Cache string `long:"cache" short:"c" description:"Cache backend URL (e.g., file:///path, s3://region/bucket/prefix, gs://bucket/prefix). Defaults to local file."`
Notifier string `long:"notifier" description:"Notifier URL for deployment notifications (e.g., slack://channel, mail://smtp:port/recipient)"`
BeforeDeployHook string `long:"before-deploy-hook" description:"Shell command to execute before deployment begins"`
AfterDeployHook string `long:"after-deploy-hook" description:"Shell command to execute after successful deployment"`
// Container-specific options
Replicas int `long:"replicas" description:"Number of container replicas to run (default: 1)"`
HealthPath string `long:"health-path" description:"Health check path (optional, e.g., /health)"`
HealthTimeout int `long:"health-timeout" description:"Health check timeout in seconds (default: 30)"`
DrainTime int `long:"drain-time" description:"Drain time in seconds after traffic switch (default: 30 for container command)"`
ContainerRuntime string `long:"runtime" description:"Container runtime (docker or podman, default: docker)"`
ProxyIdleTimeout int `long:"proxy-idle-timeout" description:"Proxy idle timeout in seconds (default: 300, 0 to disable)"`
Cmd []string `long:"cmd" description:"Command and arguments to pass to container (can be specified multiple times)"`
AdminPort int `long:"admin-port" description:"Admin API port for container command (default: 17539, auto-increments if in use)"`
Slot string `long:"slot" short:"s" description:"Deployment slot for blue/green deployment (e.g., blue, green). Only deploys if tag's build metadata matches."`
CalVer string `long:"calver" description:"CalVer format for version identification (e.g., YYYY.0M.0D.MICRO)"`
Telemetry bool `long:"telemetry" description:"Enable telemetry (Prometheus metrics on admin API /metrics endpoint)"`
OTLPEndpoint string `long:"otlp-endpoint" description:"OTLP gRPC endpoint for exporting metrics (e.g., localhost:4317)"`
OTLPInsecure bool `long:"otlp-insecure" description:"Use insecure (plaintext) gRPC for OTLP export (default: TLS)"`
Help bool `long:"help" short:"h" description:"show this help message and exit"`
Version bool `long:"version" short:"v" description:"prints the version number"`
}
// Env struct.
type Env struct {
Out, Err io.Writer
Args []string
*Info
}
type Info struct {
Version string
Commit string
Date string
}
func (i *Info) ShortCommit() string {
if len(i.Commit) > 7 {
return i.Commit[:7]
}
return i.Commit
}
// RunCLI runs as cli.
func RunCLI(env Env) int {
cli := &cli{env: env, Interval: -1, ProxyIdleTimeout: -1}
return cli.run()
}
func (c *cli) buildHelp(names []string) []string {
var help []string
t := reflect.TypeFor[cli]()
for _, name := range names {
f, ok := t.FieldByName(name)
if !ok {
continue
}
tag := f.Tag
if tag == "" {
continue
}
var o, a string
if a = tag.Get("arg"); a != "" {
a = fmt.Sprintf("=%s", a)
}
if s := tag.Get("short"); s != "" {
o = fmt.Sprintf("-%s, --%s%s", tag.Get("short"), tag.Get("long"), a)
} else {
o = fmt.Sprintf("--%s%s", tag.Get("long"), a)
}
desc := tag.Get("description")
if i := strings.Index(desc, "\n"); i >= 0 {
var buf bytes.Buffer
buf.WriteString(desc[:i+1])
desc = desc[i+1:]
const indent = " "
for {
if i = strings.Index(desc, "\n"); i >= 0 {
buf.WriteString(indent)
buf.WriteString(desc[:i+1])
desc = desc[i+1:]
continue
}
break
}
if len(desc) > 0 {
buf.WriteString(indent)
buf.WriteString(desc)
}
desc = buf.String()
}
help = append(help, fmt.Sprintf(" %-40s %s", o, desc))
}
return help
}
func (c *cli) showHelp() {
generalOpts := strings.Join(c.buildHelp([]string{
"Interval",
"Registry",
"Cache",
"Slot",
"CalVer",
"Notifier",
"LogLevel",
"LogFormat",
"BeforeDeployHook",
"AfterDeployHook",
"Telemetry",
"OTLPEndpoint",
"OTLPInsecure",
}), "\n")
serverOpts := strings.Join(c.buildHelp([]string{
"Ports",
}), "\n")
containerOpts := strings.Join(c.buildHelp([]string{
"Replicas",
"Cmd",
"HealthPath",
"HealthTimeout",
"DrainTime",
"ContainerRuntime",
"ProxyIdleTimeout",
}), "\n")
help := `Usage: dewy [--version] [--help] command <options>
Commands:
server Keep the app server up to date
assets Keep assets up to date
image Keep container images up to date with zero-downtime deployment
General Options:
%s
Server Command Options:
%s
Container Command Options:
%s
`
Banner(c.env.Out)
fmt.Fprintf(c.env.Out, help, generalOpts, serverOpts, containerOpts)
}
func (c *cli) run() int {
p := flags.NewParser(c, flags.PassDoubleDash)
args, err := p.ParseArgs(c.env.Args)
if err != nil || c.Help {
c.showHelp()
return ExitErr
}
if c.Version {
if c.LogFormat == "" {
c.LogFormat = "text"
}
if c.LogFormat == "json" {
slogger := SetupLogger("INFO", c.LogFormat, c.env.Err)
slogger.Info("Dewy version",
"version", c.env.Version,
"commit", c.env.ShortCommit(),
"date", c.env.Date)
} else {
fmt.Fprintf(c.env.Out, "dewy version: %s [%s, %s]\n", c.env.Version, c.env.ShortCommit(), c.env.Date)
}
return ExitOK
}
if len(args) == 0 || (args[0] != "server" && args[0] != "assets" && args[0] != "container") {
fmt.Fprintf(c.env.Err, "Error: command is not available\n")
c.showHelp()
return ExitErr
}
// Handle container subcommands (e.g., "dewy container list")
if args[0] == "container" && len(args) > 1 {
switch args[1] {
case "list":
return c.runContainerList()
default:
// Unknown subcommand, continue with normal container command
}
}
if c.Interval < 0 {
c.Interval = 10
}
c.command = args[0]
if len(args) > 1 {
c.args = args[1:]
}
if c.LogLevel != "" {
c.LogLevel = strings.ToUpper(c.LogLevel)
} else {
c.LogLevel = "ERROR"
}
if c.LogFormat == "" {
c.LogFormat = "text"
}
conf := DefaultConfig()
conf.Info = c.env.Info
if c.Registry == "" {
fmt.Fprintf(c.env.Err, "Error: --registry is not set\n")
c.showHelp()
return ExitErr
}
conf.Registry = c.Registry
conf.Cache.URL = c.Cache
conf.Notifier = c.Notifier
conf.BeforeDeployHook = c.BeforeDeployHook
conf.AfterDeployHook = c.AfterDeployHook
conf.AdminPort = c.AdminPort
conf.Slot = c.Slot
conf.CalVer = c.CalVer
switch c.command {
case "server":
if err := c.configureServerCommand(&conf); err != nil {
return ExitErr
}
case "container":
if err := c.configureContainerCommand(&conf); err != nil {
return ExitErr
}
default:
conf.Command = ASSETS
}
// Set up structured logger
slogger := SetupLogger(c.LogLevel, c.LogFormat, c.env.Err)
d, err := New(conf, slogger)
if err != nil {
fmt.Fprintf(c.env.Err, "Error: %s\n", err)
return ExitErr
}
// Initialize telemetry if enabled
if c.Telemetry || c.OTLPEndpoint != "" {
tp, err := telemetry.New(context.Background(), telemetry.Config{
Enabled: true,
OTLPEndpoint: c.OTLPEndpoint,
OTLPInsecure: c.OTLPInsecure,
ServiceName: "dewy",
Version: c.env.Version,
})
if err != nil {
fmt.Fprintf(c.env.Err, "Error: failed to initialize telemetry: %s\n", err)
return ExitErr
}
d.SetTelemetry(tp)
slogger.Info("Telemetry enabled",
slog.Bool("prometheus", true),
slog.String("otlp_endpoint", c.OTLPEndpoint))
}
d.Start(c.Interval)
return ExitOK
}
// configureServerCommand configures the server command settings.
func (c *cli) configureServerCommand(conf *Config) error {
conf.Command = SERVER
// Port is optional for server command (can run as job worker without port)
var parsedPorts []string
var err error
if len(c.Ports) > 0 {
parsedPorts, err = parsePorts(c.Ports)
if err != nil {
fmt.Fprintf(c.env.Err, "Error: invalid port specification: %s\n", err)
return err
}
}
var command string
var cmdArgs []string
if len(c.args) > 0 {
command = c.args[0]
if len(c.args) > 1 {
cmdArgs = c.args[1:]
}
}
conf.Starter = &StarterConfig{
ports: parsedPorts,
command: command,
args: cmdArgs,
logformat: c.LogFormat,
}
return nil
}
// configureContainerCommand configures the container command settings.
func (c *cli) configureContainerCommand(conf *Config) error {
conf.Command = CONTAINER
// Port is required for container command
if len(c.Ports) == 0 {
fmt.Fprintf(c.env.Err, "Error: --port option is required for container command\n")
return fmt.Errorf("port is required for container command")
}
// Parse port mappings
portMappings, err := parsePortMappings(c.Ports)
if err != nil {
fmt.Fprintf(c.env.Err, "Error: failed to parse port mappings: %v\n", err)
return err
}
if len(portMappings) == 0 {
fmt.Fprintf(c.env.Err, "Error: no valid port mappings specified\n")
return fmt.Errorf("no valid port mappings specified")
}
// Set defaults
// HealthPath is optional - if not specified, health check will be skipped
if c.HealthTimeout == 0 {
c.HealthTimeout = 30
}
if c.DrainTime == 0 {
c.DrainTime = 30
}
if c.ContainerRuntime == "" {
c.ContainerRuntime = "docker"
}
// Set default name if not specified
appName := c.Name
if appName == "" {
// Extract app name from registry URL (e.g., img://ghcr.io/owner/myapp:latest -> myapp)
appName = extractAppNameFromRegistry(c.Registry)
if appName == "" {
appName = "app" // Fallback if extraction fails
}
}
// ProxyIdleTimeout: -1 means not specified (use default 5min), 0 means disabled, >0 means custom
proxyIdleTimeout := 5 * time.Minute
if c.ProxyIdleTimeout == 0 {
proxyIdleTimeout = 0 // Explicitly disabled
} else if c.ProxyIdleTimeout > 0 {
proxyIdleTimeout = time.Duration(c.ProxyIdleTimeout) * time.Second
}
conf.Container = &ContainerConfig{
Name: appName,
PortMappings: portMappings,
Replicas: c.Replicas,
Command: c.Cmd,
ExtraArgs: c.args, // Arguments after -- separator (docker run options)
HealthPath: c.HealthPath,
HealthTimeout: time.Duration(c.HealthTimeout) * time.Second,
DrainTime: time.Duration(c.DrainTime) * time.Second,
Runtime: c.ContainerRuntime,
ProxyIdleTimeout: proxyIdleTimeout,
}
return nil
}
// parsePorts parses port specifications from CLI arguments.
func parsePorts(portSpecs []string) ([]string, error) {
if len(portSpecs) == 0 {
return nil, nil
}
var allPorts []string
for _, spec := range portSpecs {
ports, err := parsePortSpec(spec)
if err != nil {
return nil, err
}
allPorts = append(allPorts, ports...)
}
// Remove duplicates and validate
return validateAndDeduplicatePorts(allPorts)
}
// parsePortSpec parses a single port specification (supports comma-separated and ranges).
func parsePortSpec(spec string) ([]string, error) {
if spec == "" {
return nil, nil
}
var ports []string
parts := strings.SplitSeq(spec, ",")
for part := range parts {
part = strings.TrimSpace(part)
if part == "" {
continue
}
if strings.Contains(part, "-") {
// Range specification (e.g., "8000-8005")
rangePorts, err := parsePortRange(part)
if err != nil {
return nil, err
}
ports = append(ports, rangePorts...)
} else {
// Single port
if err := validatePort(part); err != nil {
return nil, err
}
ports = append(ports, part)
}
}
return ports, nil
}
// parsePortRange parses a port range like "8000-8005".
func parsePortRange(rangeSpec string) ([]string, error) {
parts := strings.Split(rangeSpec, "-")
if len(parts) != 2 {
return nil, fmt.Errorf("invalid port range format: %s", rangeSpec)
}
startStr := strings.TrimSpace(parts[0])
endStr := strings.TrimSpace(parts[1])
start, err := strconv.Atoi(startStr)
if err != nil {
return nil, fmt.Errorf("invalid start port in range %s: %w", rangeSpec, err)
}
end, err := strconv.Atoi(endStr)
if err != nil {
return nil, fmt.Errorf("invalid end port in range %s: %w", rangeSpec, err)
}
if start > end {
return nil, fmt.Errorf("start port (%d) cannot be greater than end port (%d)", start, end)
}
if end-start > 100 {
return nil, fmt.Errorf("port range too large (%d ports), maximum allowed is 100", end-start+1)
}
var ports []string
for i := start; i <= end; i++ {
if err := validatePortNumber(i); err != nil {
return nil, fmt.Errorf("invalid port %d in range %s: %w", i, rangeSpec, err)
}
ports = append(ports, strconv.Itoa(i))
}
return ports, nil
}
// validatePort validates a port string.
func validatePort(port string) error {
portNum, err := strconv.Atoi(port)
if err != nil {
return fmt.Errorf("invalid port number: %s", port)
}
return validatePortNumber(portNum)
}
// validatePortNumber validates a port number.
func validatePortNumber(port int) error {
if port < 1 || port > 65535 {
return fmt.Errorf("port number must be between 1 and 65535, got %d", port)
}
if port < 1024 {
slog.Warn("Using privileged port may require root privileges", slog.Int("port", port))
}
return nil
}
// validateAndDeduplicatePorts removes duplicates and sorts ports.
func validateAndDeduplicatePorts(ports []string) ([]string, error) {
if len(ports) == 0 {
return ports, nil
}
// Use map to track unique ports
uniquePorts := make(map[string]bool)
for _, port := range ports {
uniquePorts[port] = true
}
// Convert back to slice and sort
var result []string
for port := range uniquePorts {
result = append(result, port)
}
// Sort numerically
sort.Slice(result, func(i, j int) bool {
a, _ := strconv.Atoi(result[i])
b, _ := strconv.Atoi(result[j])
return a < b
})
return result, nil
}
// parsePortMappings parses port mapping specifications for container command.
// Supports formats:
// - "8080" -> proxy=8080, container=auto-detect (ContainerPort==0)
// - "8080:80" -> proxy=8080, container=80
func parsePortMappings(portSpecs []string) ([]container.PortMapping, error) {
if len(portSpecs) == 0 {
return nil, nil
}
mappings := make([]container.PortMapping, 0, len(portSpecs))
proxyPorts := make(map[int]bool) // Track duplicate proxy ports
for _, spec := range portSpecs {
spec = strings.TrimSpace(spec)
if spec == "" {
continue
}
var mapping container.PortMapping
// Check if it contains ":"
if strings.Contains(spec, ":") {
// Format: "proxy:container"
parts := strings.Split(spec, ":")
if len(parts) != 2 {
return nil, fmt.Errorf("invalid port mapping format: %s (expected proxy:container)", spec)
}
proxyPort, err := strconv.Atoi(strings.TrimSpace(parts[0]))
if err != nil {
return nil, fmt.Errorf("invalid proxy port in %s: %w", spec, err)
}
if err := validatePortNumber(proxyPort); err != nil {
return nil, fmt.Errorf("invalid proxy port in %s: %w", spec, err)
}
containerPort, err := strconv.Atoi(strings.TrimSpace(parts[1]))
if err != nil {
return nil, fmt.Errorf("invalid container port in %s: %w", spec, err)
}
if err := validatePortNumber(containerPort); err != nil {
return nil, fmt.Errorf("invalid container port in %s: %w", spec, err)
}
mapping = container.PortMapping{
ProxyPort: proxyPort,
ContainerPort: containerPort,
}
} else {
// Format: "proxy" (container port will be auto-detected)
proxyPort, err := strconv.Atoi(spec)
if err != nil {
return nil, fmt.Errorf("invalid port: %s", spec)
}
if err := validatePortNumber(proxyPort); err != nil {
return nil, fmt.Errorf("invalid port: %w", err)
}
mapping = container.PortMapping{
ProxyPort: proxyPort,
ContainerPort: 0, // Auto-detect
}
}
// Check for duplicate proxy ports
if proxyPorts[mapping.ProxyPort] {
return nil, fmt.Errorf("duplicate proxy port: %d", mapping.ProxyPort)
}
proxyPorts[mapping.ProxyPort] = true
mappings = append(mappings, mapping)
}
return mappings, nil
}
// Banner displays the Dewy ASCII art logo.
func Banner(w io.Writer) {
green := color.RGB(194, 73, 85)
grey := color.New(color.FgHiBlack)
green.Fprint(w, strings.TrimLeft(`
___ ___ _____ __ __
| \ | __| \ / /\ \/ /
| | | __| \ / / \ /
|___/ |___| \_/_/ |__|
`, "\n"))
grey.Fprint(w, `
Dewy - A declarative deployment tool of apps in non-K8s environments.
https://github.com/linyows/dewy
`)
}
// runContainerList runs the "dewy container list" command.
func (c *cli) runContainerList() int {
// Default admin port
adminPort := c.AdminPort
if adminPort == 0 {
adminPort = 17539
}
// Try to connect to admin API, scanning through possible ports
maxAttempts := 10
client := &http.Client{
Timeout: 2 * time.Second,
}
var resp *http.Response
var err error
var successPort int
for i := range maxAttempts {
currentPort := adminPort + i
url := fmt.Sprintf("http://localhost:%d/api/containers", currentPort)
resp, err = client.Get(url)
if err == nil {
// Successfully connected
successPort = currentPort
break
}
}
if resp == nil {
fmt.Fprintf(c.env.Err, "Error: no running dewy instances found (tried ports %d-%d)\n",
adminPort, adminPort+maxAttempts-1)
return ExitErr
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Fprintf(c.env.Err, "Error: admin API returned status %d\n", resp.StatusCode)
return ExitErr
}
// Parse response
var result struct {
Containers []*container.Info `json:"containers"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
fmt.Fprintf(c.env.Err, "Error: failed to parse response: %v\n", err)
return ExitErr
}
// Display results
c.displayContainerList(result.Containers)
// Show which port was used (helpful for debugging)
if successPort != adminPort {
fmt.Fprintf(c.env.Out, "\n(Connected to admin API on port %d)\n", successPort)
}
return ExitOK
}
// displayContainerList displays container information in table format.
func (c *cli) displayContainerList(containers []*container.Info) {
if len(containers) == 0 {
fmt.Fprintf(c.env.Out, "No containers found.\n")
return
}
// Sort by name
sort.Slice(containers, func(i, j int) bool {
return containers[i].Name < containers[j].Name
})
// Calculate max widths for each column
upstreamWidth := len("UPSTREAM")
deployTimeWidth := len("DEPLOY TIME")
deployTimeDataWidth := len(deployTimeFormat)
for _, info := range containers {
if len(info.IPPort) > upstreamWidth {
upstreamWidth = len(info.IPPort)
}
}
// Use the larger of header or data width for deploy time
if deployTimeDataWidth > deployTimeWidth {
deployTimeWidth = deployTimeDataWidth
}
// Add 4 spaces padding to each column
upstreamWidth += 4
deployTimeWidth += 4
// Print header
fmt.Fprintf(c.env.Out, "%-*s%-*s%s\n",
upstreamWidth, "UPSTREAM",
deployTimeWidth, "DEPLOY TIME",
"NAME")
// Print container rows
for _, info := range containers {
// Format deploy time
deployTime := info.DeployedAt.Format(deployTimeFormat)
fmt.Fprintf(c.env.Out, "%-*s%-*s%s\n",
upstreamWidth, info.IPPort,
deployTimeWidth, deployTime,
info.Name)
}
}
// extractAppNameFromRegistry extracts application name from registry URL.
// For container command (img:// scheme):
// - img://ghcr.io/owner/myapp:latest -> myapp
// - img://docker.io/library/nginx:1.21 -> nginx
// - img://gcr.io/project/myapp -> myapp
// - img://myapp:latest -> myapp
//
// For other commands:
// - ghr://owner/myrepo -> myrepo
// - s3://region/bucket/path/to/app -> app
func extractAppNameFromRegistry(registryURL string) string {
// Remove scheme (img://, ghr://, s3://, etc.)
parts := strings.SplitN(registryURL, "://", 2)
if len(parts) != 2 {
return ""
}
scheme := parts[0]
path := parts[1]
// For img:// (OCI registry): extract image name
// Examples:
// ghcr.io/owner/myapp:latest -> myapp
// docker.io/library/nginx:1.21 -> nginx
// gcr.io/project/myapp -> myapp
// myapp:latest -> myapp
if scheme == "img" {
// Remove query parameters if present (e.g., ?pre-release=true)
if idx := strings.Index(path, "?"); idx != -1 {
path = path[:idx]
}
// Split by / to get path components
pathParts := strings.Split(path, "/")
// Get the last component (image name with possible tag)
imageName := pathParts[len(pathParts)-1]
// Remove tag (everything after :)
if idx := strings.Index(imageName, ":"); idx != -1 {
imageName = imageName[:idx]
}
return imageName
}
// For ghr (GitHub Releases): owner/repo -> repo
if scheme == "ghr" {
pathParts := strings.Split(path, "/")
if len(pathParts) >= 2 {
return pathParts[1]
}
}
// For s3: region/bucket/path/to/app -> app
if scheme == "s3" {
pathParts := strings.Split(path, "/")
if len(pathParts) > 0 {
// Get last non-empty component
for i := len(pathParts) - 1; i >= 0; i-- {
if pathParts[i] != "" {
return pathParts[i]
}
}
}
}
return ""
}