Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ run:
deadline: 5m
issues:
exclude-rules:
- path: fake_client\.go
# counterfeiter fakes are usually named 'fake_<something>.go'
# TODO: figure out why golangci-lint does not treat counterfeiter files as generated files
- path: fake_.*\.go
linters:
- gocritic
- dupl
Expand Down
2 changes: 2 additions & 0 deletions BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,15 @@ filegroup(
"//cmd/blocking-testgrid-tests:all-srcs",
"//cmd/krel:all-srcs",
"//cmd/kubepkg:all-srcs",
"//cmd/patch-announce:all-srcs",
"//cmd/release-notes:all-srcs",
"//lib:all-srcs",
"//pkg/command:all-srcs",
"//pkg/git:all-srcs",
"//pkg/kubepkg:all-srcs",
"//pkg/log:all-srcs",
"//pkg/notes:all-srcs",
"//pkg/patch:all-srcs",
"//pkg/release:all-srcs",
"//pkg/util:all-srcs",
"//pkg/version:all-srcs",
Expand Down
151 changes: 0 additions & 151 deletions announce-patch

This file was deleted.

22 changes: 12 additions & 10 deletions cmd/krel/cmd/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go_library(
srcs = [
"changelog.go",
"ff.go",
"patch-announce.go",
"push.go",
"root.go",
"version.go",
Expand All @@ -16,6 +17,7 @@ go_library(
"//pkg/log:go_default_library",
"//pkg/notes:go_default_library",
"//pkg/notes/options:go_default_library",
"//pkg/patch:go_default_library",
"//pkg/release:go_default_library",
"//pkg/util:go_default_library",
"//pkg/version:go_default_library",
Expand All @@ -28,6 +30,16 @@ go_library(
],
)

go_test(
name = "go_default_test",
srcs = [
"changelog_test.go",
"root_test.go",
],
embed = [":go_default_library"],
deps = ["@com_github_stretchr_testify//require:go_default_library"],
)

filegroup(
name = "package-srcs",
srcs = glob(["**"]),
Expand All @@ -41,13 +53,3 @@ filegroup(
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

go_test(
name = "go_default_test",
srcs = [
"changelog_test.go",
"root_test.go",
],
embed = [":go_default_library"],
deps = ["@com_github_stretchr_testify//require:go_default_library"],
)
2 changes: 0 additions & 2 deletions cmd/krel/cmd/changelog.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,6 @@ const (
)

func init() {
cobra.OnInitialize(initConfig)

const (
tagFlag = "tag"
tarsFlag = "tars"
Expand Down
2 changes: 0 additions & 2 deletions cmd/krel/cmd/ff.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,6 @@ var ffCmd = &cobra.Command{
}

func init() {
cobra.OnInitialize(initConfig)

ffCmd.PersistentFlags().StringVar(&ffOpts.branch, "branch", "", "branch")
ffCmd.PersistentFlags().StringVar(&ffOpts.masterRef, "ref", kgit.DefaultMasterRef, "ref on master")
ffCmd.PersistentFlags().StringVar(&ffOpts.org, "org", kgit.DefaultGithubOrg, "org to run tool against")
Expand Down
96 changes: 96 additions & 0 deletions cmd/krel/cmd/patch-announce.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
Copyright 2020 The Kubernetes 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 cmd

import (
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"k8s.io/release/pkg/log"
"k8s.io/release/pkg/patch"
"k8s.io/release/pkg/util"
)

// slap the subcommand onto the parent/root
func init() {
cmd := patchAnnounceCommand()
rootCmd.AddCommand(cmd)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

init() should be avoided.
the responsibility of the addition should be on the side of the root command.

pseudo-summary of the pattern:

parrentCmd := createParentCmd()
childCmd := createChildCmd()
parentCmd.AddCommand(childCmd)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I also don't like the use of init, but I also tried to be consistent with what we have right now. If you check my implementation, I did take care of encapsulating my command, not relying on global state or such, so that it could be moved around and the initialisation/registration of the commands could change as needed.

I could change to your proposed registration in this PR, but I lean towards be consistent with what we have right now, and change the registration for all commands in a separate PR.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's just a minor nit and for cobra related usage it should be fine.

}

func patchAnnounceCommand() *cobra.Command {
opts := patch.AnnounceOptions{}

cmd := &cobra.Command{
Use: "patch-announce",
Short: "Send out patch release announcement mails",
SilenceUsage: true,
SilenceErrors: true,
Args: cobra.MaximumNArgs(0), // no additional/positional args allowed
}

// setup local flags
cmd.PersistentFlags().StringVarP(&opts.SenderName, "sender-name", "n", "", "email sender's name")
cmd.PersistentFlags().StringVarP(&opts.SenderEmail, "sender-email", "e", "", "email sender's address")
cmd.PersistentFlags().StringVarP(&opts.FreezeDate, "freeze-date", "f", "", "date when no CPs are allowed anymore")
cmd.PersistentFlags().StringVarP(&opts.CutDate, "cut-date", "c", "", "date when the patch release is planned to be cut")
cmd.PersistentFlags().StringVarP(&opts.ReleaseRepoPath, "release-repo", "r", "./release", "local path of the k/release checkout")

// TODO: figure out, how we can read env vars and also be able to set the flags to required in a cobra-native way
cmd.PersistentFlags().StringVarP(&opts.SendgridAPIKey, "sendgrid-api-key", "s", util.EnvDefault("SENDGRID_API_KEY", ""), "API key for sendgrid")
cmd.PersistentFlags().StringVarP(&opts.GithubToken, "github-token", "g", util.EnvDefault("GITHUB_TOKEN", ""), "a GitHub token, used r/o for generating the release notes")

cmd.PreRunE = func(cmd *cobra.Command, _ []string) error {
// TODO: make github-token & sendgrid-api-key required too
if err := setFlagsRequired(cmd, "sender-name", "sender-email", "freeze-date", "cut-date"); err != nil {
return err
}

var err error
if opts.Nomock, err = cmd.Flags().GetBool("nomock"); err != nil {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nomock is already part of the rootOptions structure, so there is no need to add it twice.

Copy link
Contributor Author

@hoegaarden hoegaarden Jan 28, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • This is not "adding" the flag, this is asking the parent command to for a flag's value. Any parent command could have been responsible for adding/parsing that flag, this is a way to retrieve it's value from within a child.
  • I don't want to rely on any shared state between the parent (in our case, the root command) and this command. cobra gives me options to communicate with / query the parent command without this "external" shared state.
  • This decouples this command from any other / the root command. The only touch point with any other command is when we register it. Potentially we could move this command, change the parent, ... without really bothering this command.

return err
}
if opts.K8sRepoPath, err = cmd.Flags().GetString("repo"); err != nil {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

repoPath is already part of the rootOptions structure, so there is no need to add it twice.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return err
}
return nil
}

cmd.RunE = func(cmd *cobra.Command, args []string) error {
// Get the global logger, add the command's name as an initial tracing
// field and use that from here on
localLogger := logrus.NewEntry(logrus.StandardLogger())
logger := log.AddTracePath(localLogger, cmd.Name()).WithField("mock", !opts.Nomock)

announcer := &patch.Announcer{
Opts: opts,
}
announcer.SetLogger(logger, "announcer")

logger.Debug("run announcer")
return announcer.Run()
}

return cmd
}

func setFlagsRequired(cmd *cobra.Command, flags ...string) error {
for _, f := range flags {
if err := cmd.MarkPersistentFlagRequired(f); err != nil {
return err
}
}
return nil
}
22 changes: 4 additions & 18 deletions cmd/krel/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ import (

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "krel",
Short: "krel",
PreRunE: initLogging,
Use: "krel",
Short: "krel",
PersistentPreRunE: initLogging,
}

type rootOptions struct {
Expand All @@ -51,26 +51,12 @@ func Execute() {
}

func init() {
cobra.OnInitialize(initConfig)

rootCmd.PersistentFlags().BoolVar(&rootOpts.nomock, "nomock", false, "nomock flag")
rootCmd.PersistentFlags().BoolVar(&rootOpts.cleanup, "cleanup", false, "cleanup flag")
rootCmd.PersistentFlags().StringVar(&rootOpts.repoPath, "repo", filepath.Join(os.TempDir(), "k8s"), "the local path to the repository to be used")
rootCmd.PersistentFlags().StringVar(&rootOpts.logLevel, "log-level", "info", "the logging verbosity, either 'panic', 'fatal', 'error', 'warn', 'warning', 'info', 'debug' or 'trace'")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
}

func initLogging(*cobra.Command, []string) error {
logrus.SetFormatter(&logrus.TextFormatter{DisableTimestamp: true})
lvl, err := logrus.ParseLevel(rootOpts.logLevel)
if err != nil {
return err
}
logrus.SetLevel(lvl)
logrus.AddHook(log.NewFilenameHook())
logrus.Debugf("Using log level %q", lvl)
return nil
return log.SetupGlobalLogger(rootOpts.logLevel)
}
1 change: 0 additions & 1 deletion cmd/krel/cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ var versionCmd = &cobra.Command{
}

func init() {
cobra.OnInitialize(initConfig)
versionCmd.PersistentFlags().BoolVarP(&versionOpts.json, "json", "j", false,
"print JSON instead of text")
rootCmd.AddCommand(versionCmd)
Expand Down
Loading