-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathrun.go
More file actions
237 lines (212 loc) · 5.97 KB
/
run.go
File metadata and controls
237 lines (212 loc) · 5.97 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
// Copyright 2019 The kpt 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
//
// http://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 run
import (
"bytes"
"context"
"flag"
"fmt"
"os"
"os/exec"
"runtime/debug"
"strconv"
"strings"
kptcommands "github.com/kptdev/kpt/commands"
"github.com/kptdev/kpt/internal/docs/generated/overview"
"github.com/kptdev/kpt/pkg/lib/util/cmdutil"
"github.com/kptdev/kpt/pkg/printer"
"github.com/spf13/cobra"
"sigs.k8s.io/kustomize/kyaml/commandutil"
)
var pgr []string
func GetMain(ctx context.Context) *cobra.Command {
os.Setenv(commandutil.EnableAlphaCommmandsEnvName, "true")
// Initialize version info from build settings at startup.
initVersion()
cmd := &cobra.Command{
Use: "kpt",
Short: overview.CliShort,
Long: overview.CliLong,
SilenceUsage: true,
// We handle all errors in main after return from cobra so we can
// adjust the error message coming from libraries
SilenceErrors: true,
RunE: func(cmd *cobra.Command, _ []string) error {
h, err := cmd.Flags().GetBool("help")
if err != nil {
return err
}
if h {
return cmd.Help()
}
return cmd.Usage()
},
}
cmd.PersistentFlags().AddGoFlagSet(flag.CommandLine)
cmd.PersistentFlags().BoolVar(&printer.TruncateOutput, "truncate-output", true,
"Enable the truncation for output")
// wire the global printer
pr := printer.New(cmd.OutOrStdout(), cmd.ErrOrStderr())
// create context with associated printer
ctx = printer.WithContext(ctx, pr)
// find the pager if one exists
func() {
if val, found := os.LookupEnv("KPT_NO_PAGER_HELP"); !found || val != "1" {
// use a pager for printing tutorials
e, found := os.LookupEnv("PAGER")
var err error
if found {
pgr = []string{e}
return
}
e, err = exec.LookPath("pager")
if err == nil {
pgr = []string{e}
return
}
e, err = exec.LookPath("less")
if err == nil {
pgr = []string{e, "-R"}
return
}
}
}()
// help and documentation
cmd.InitDefaultHelpCmd()
cmd.AddCommand(kptcommands.GetKptCommands(ctx, "kpt", version)...)
// enable stack traces
cmd.PersistentFlags().BoolVar(&cmdutil.StackOnError, "stack-trace", false,
"Print a stack-trace on failure")
if _, err := exec.LookPath("git"); err != nil {
fmt.Fprintf(os.Stderr, "kpt requires that `git` is installed and on the PATH")
os.Exit(1)
}
replace(cmd)
cmd.AddCommand(versionCmd)
hideFlags(cmd)
return cmd
}
func replace(c *cobra.Command) {
for i := range c.Commands() {
replace(c.Commands()[i])
}
c.SetHelpFunc(newHelp(pgr, c))
}
func newHelp(e []string, c *cobra.Command) func(command *cobra.Command, strings []string) {
if len(pgr) == 0 {
return c.HelpFunc()
}
fn := c.HelpFunc()
return func(command *cobra.Command, args []string) {
stty := exec.Command("stty", "size")
stty.Stdin = os.Stdin
out, err := stty.Output()
if err == nil {
terminalHeight, err := strconv.Atoi(strings.Split(string(out), " ")[0])
helpHeight := strings.Count(command.Long, "\n") +
strings.Count(command.UsageString(), "\n")
if err == nil && terminalHeight > helpHeight {
// don't use a pager if the help is shorter than the console
fn(command, args)
return
}
}
b := &bytes.Buffer{}
pager := exec.Command(e[0])
if len(e) > 1 {
pager.Args = append(pager.Args, e[1:]...)
}
pager.Stdin = b
pager.Stdout = c.OutOrStdout()
c.SetOut(b)
fn(command, args)
if err := pager.Run(); err != nil {
fmt.Fprintf(c.ErrOrStderr(), "%v", err)
os.Exit(1)
}
}
}
var version = "unknown"
// initVersion enriches the version string with runtime build information.
// It reads VCS revision from Go's build info when available (i.e., when
// built with module mode). This provides the commit hash for development builds.
//
// For release builds, goreleaser injects the proper version tag (e.g., v1.0.0-beta.62)
// via ldflags. In that case, version will already be set to a proper semver string
// and this function will not override it.
func initVersion() {
// If version is already set to a proper release version (starts with 'v'),
// don't override it. Goreleaser sets the version at build time for releases.
if strings.HasPrefix(version, "v") && !strings.Contains(version, "-dev+") {
return
}
if info, ok := debug.ReadBuildInfo(); ok {
for _, setting := range info.Settings {
if setting.Key == "vcs.revision" {
shortCommit := setting.Value
if len(shortCommit) >= 12 {
shortCommit = shortCommit[:12]
}
version = "v0.0.0-dev+" + shortCommit
return
}
}
}
}
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version number of kpt",
Run: func(_ *cobra.Command, _ []string) {
fmt.Printf("%s\n", version)
},
}
// hideFlags hides any cobra flags that are unlikely to be used by
// customers.
func hideFlags(cmd *cobra.Command) {
flags := []string{
// Flags related to logging
"add_dir_header",
"alsologtostderr",
"log_backtrace_at",
"log_dir",
"log_file",
"log_file_max_size",
"logtostderr",
"one_output",
"skip_headers",
"skip_log_headers",
"stack-trace",
"stderrthreshold",
"vmodule",
// Flags related to apiserver
"as",
"as-group",
"cache-dir",
"certificate-authority",
"client-certificate",
"client-key",
"insecure-skip-tls-verify",
"match-server-version",
"password",
"token",
"username",
}
for _, f := range flags {
_ = cmd.PersistentFlags().MarkHidden(f)
}
// We need to recurse into subcommands otherwise flags aren't hidden on leaf commands
for _, child := range cmd.Commands() {
hideFlags(child)
}
}