-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #6 from johnbelamaric/porchctl
Add porchctl command
- Loading branch information
Showing
34 changed files
with
4,629 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
// Copyright 2023 The kpt and Nephio 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 main | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"os" | ||
|
||
"github.com/nephio-project/porch/cmd/porchctl/run" | ||
"github.com/nephio-project/porch/internal/kpt/errors" | ||
"github.com/nephio-project/porch/internal/kpt/errors/resolver" | ||
"github.com/nephio-project/porch/internal/kpt/util/cmdutil" | ||
"github.com/spf13/cobra" | ||
_ "k8s.io/client-go/plugin/pkg/client/auth" | ||
"k8s.io/component-base/cli" | ||
"k8s.io/klog/v2" | ||
k8scmdutil "k8s.io/kubectl/pkg/cmd/util" | ||
) | ||
|
||
func main() { | ||
// Handle all setup in the runMain function so os.Exit doesn't interfere | ||
// with defer. | ||
os.Exit(runMain()) | ||
} | ||
|
||
// runMain does the initial setup in order to run kpt. The return value from | ||
// this function will be the exit code when kpt terminates. | ||
func runMain() int { | ||
var err error | ||
|
||
ctx := context.Background() | ||
|
||
// Enable commandline flags for klog. | ||
// logging will help in collecting debugging information from users | ||
klog.InitFlags(nil) | ||
|
||
cmd := run.GetMain(ctx) | ||
|
||
err = cli.RunNoErrOutput(cmd) | ||
if err != nil { | ||
return handleErr(cmd, err) | ||
} | ||
return 0 | ||
} | ||
|
||
// handleErr takes care of printing an error message for a given error. | ||
func handleErr(cmd *cobra.Command, err error) int { | ||
// First attempt to see if we can resolve the error into a specific | ||
// error message. | ||
if re, resolved := resolver.ResolveError(err); resolved { | ||
if re.Message != "" { | ||
fmt.Fprintf(cmd.ErrOrStderr(), "%s \n", re.Message) | ||
} | ||
return re.ExitCode | ||
} | ||
|
||
// Then try to see if it is of type *errors.Error | ||
var kptErr *errors.Error | ||
if errors.As(err, &kptErr) { | ||
unwrapped, ok := errors.UnwrapErrors(kptErr) | ||
if ok && !cmdutil.PrintErrorStacktrace() { | ||
fmt.Fprintf(cmd.ErrOrStderr(), "Error: %s \n", unwrapped.Error()) | ||
return 1 | ||
} | ||
fmt.Fprintf(cmd.ErrOrStderr(), "%s \n", kptErr.Error()) | ||
return 1 | ||
} | ||
|
||
// Finally just let the error handler for kubectl handle it. This handles | ||
// printing of several error types used in kubectl | ||
// TODO: See if we can handle this in kpt and get a uniform experience | ||
// across all of kpt. | ||
k8scmdutil.CheckErr(err) | ||
return 1 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,210 @@ | ||
// Copyright 2023 The kpt and Nephio 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" | ||
"strconv" | ||
"strings" | ||
|
||
"github.com/nephio-project/porch/internal/kpt/util/cmdutil" | ||
"github.com/nephio-project/porch/pkg/cli/commands" | ||
"github.com/nephio-project/porch/pkg/kpt/printer" | ||
"github.com/spf13/cobra" | ||
) | ||
|
||
var pgr []string | ||
|
||
const description = ` | ||
porchctl interacts with a Kubernetes API server with the Porch | ||
server installed as an aggregated API server. It allows you to | ||
manage Porch repository registrations and the packages within | ||
those repositories. | ||
` | ||
|
||
func GetMain(ctx context.Context) *cobra.Command { | ||
cmd := &cobra.Command{ | ||
Use: "porchctl", | ||
Short: "Manage porch repositories and packages", | ||
Long: description, | ||
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, args []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("PORCHCTL_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(commands.GetCommands(ctx, "porchctl", 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, "porchctl 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" | ||
|
||
var versionCmd = &cobra.Command{ | ||
Use: "version", | ||
Short: "Print the version number of porchctl", | ||
Run: func(cmd *cobra.Command, args []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) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.