|
| 1 | +package plan |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "text/tabwriter" |
| 9 | + |
| 10 | + "cuelang.org/go/cue" |
| 11 | + "cuelang.org/go/pkg/encoding/yaml" |
| 12 | + "github.com/rs/zerolog/log" |
| 13 | + "go.dagger.io/dagger/cmd/dagger/cmd/common" |
| 14 | + "go.dagger.io/dagger/compiler" |
| 15 | +) |
| 16 | + |
| 17 | +func ListOutputs(ctx context.Context, p *Plan, computed *compiler.Value, format, file string) error { |
| 18 | + lg := log.Ctx(ctx) |
| 19 | + path := cue.ParsePath("outputs.values") |
| 20 | + |
| 21 | + if !p.Source().LookupPath(path).Exists() { |
| 22 | + return nil |
| 23 | + } |
| 24 | + |
| 25 | + out := compiler.NewValue() |
| 26 | + |
| 27 | + if err := out.FillPath(cue.MakePath(), p.Source()); err != nil { |
| 28 | + return err |
| 29 | + } |
| 30 | + |
| 31 | + if err := out.FillPath(cue.MakePath(), computed); err != nil { |
| 32 | + return err |
| 33 | + } |
| 34 | + |
| 35 | + vals := out.LookupPath(path) |
| 36 | + |
| 37 | + // Avoid confusion on missing values by forcing concreteness |
| 38 | + if err := vals.IsConcreteR(); err != nil { |
| 39 | + return err |
| 40 | + } |
| 41 | + |
| 42 | + s, err := decodeOutput(vals, format) |
| 43 | + if err != nil { |
| 44 | + return err |
| 45 | + } |
| 46 | + |
| 47 | + if file == "" { |
| 48 | + lg.Info().Msg(fmt.Sprintf("Output:\n%v", s)) |
| 49 | + return nil |
| 50 | + } |
| 51 | + |
| 52 | + return os.WriteFile(file, []byte(s), 0600) |
| 53 | +} |
| 54 | + |
| 55 | +func decodeOutput(vals *compiler.Value, format string) (string, error) { |
| 56 | + switch format { |
| 57 | + case "json": |
| 58 | + s := vals.JSON().PrettyString() |
| 59 | + return s, nil |
| 60 | + |
| 61 | + case "yaml": |
| 62 | + s, err := yaml.Marshal(vals.Cue()) |
| 63 | + if err != nil { |
| 64 | + return "", err |
| 65 | + } |
| 66 | + return s, nil |
| 67 | + |
| 68 | + // The simplest and default case is to have outputs as |
| 69 | + // a struct of strings and print it as a table. |
| 70 | + case "plain", "": |
| 71 | + buf := new(bytes.Buffer) |
| 72 | + w := tabwriter.NewWriter(buf, 0, 4, 2, ' ', 0) |
| 73 | + fmt.Fprintln(w, "Field\tValue") |
| 74 | + |
| 75 | + if fields, err := vals.Fields(); err == nil { |
| 76 | + for _, out := range fields { |
| 77 | + fmt.Fprintf(w, "%s\t%s\n", out.Label(), common.FormatValue(out.Value)) |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + w.Flush() |
| 82 | + return buf.String(), nil |
| 83 | + } |
| 84 | + |
| 85 | + return "", fmt.Errorf("invalid --output-format %q", format) |
| 86 | +} |
0 commit comments