-
Notifications
You must be signed in to change notification settings - Fork 9
/
printcomputed.go
81 lines (69 loc) · 2.11 KB
/
printcomputed.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package debug
import (
"context"
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/encoding/prototext"
"google.golang.org/protobuf/proto"
"namespacelabs.dev/foundation/internal/cli/fncobra"
"namespacelabs.dev/foundation/internal/codegen/protos/resolver"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/parsing"
"namespacelabs.dev/foundation/std/cfg"
"namespacelabs.dev/foundation/std/pkggraph"
)
func newPrintComputedCmd() *cobra.Command {
var (
env cfg.Context
locs fncobra.Locations
outputType string
)
return fncobra.
Cmd(&cobra.Command{
Use: "print-computed",
Short: "Load a service or server definition and print it's computed contents as JSON.",
}).
WithFlags(func(flags *pflag.FlagSet) {
flags.StringVar(&outputType, "output", "json", "One of json, textproto.")
}).
With(
fncobra.ParseEnv(&env),
fncobra.ParseLocations(&locs, &env, fncobra.ParseLocationsOpts{RequireSingle: true})).
Do(func(ctx context.Context) error {
pl := parsing.NewPackageLoader(env)
sealed, err := parsing.Seal(ctx, pl, locs.Locations[0].AsPackageName(), nil)
if err != nil {
return err
}
return output(ctx, pl, sealed.Proto, outputType)
})
}
func output(ctx context.Context, pl pkggraph.PackageLoader, msg proto.Message, outputType string) error {
switch outputType {
case "json":
body, err := (protojson.MarshalOptions{
UseProtoNames: true,
Multiline: true,
Resolver: resolver.NewResolver(ctx, pl),
}).Marshal(msg)
if err != nil {
return err
}
fmt.Fprintf(console.Stdout(ctx), "%s\n", body)
case "textproto":
out, err := prototext.MarshalOptions{
Multiline: true,
Resolver: resolver.NewResolver(ctx, pl),
}.Marshal(msg)
if err != nil {
return err
}
fmt.Fprintf(console.Stdout(ctx), "%s\n", out)
}
return nil
}