cli: fix lint errors

PR-URL: https://github.com/hasura/graphql-engine-mono/pull/1749
Co-authored-by: Aravind K P <8335904+scriptonist@users.noreply.github.com>
GitOrigin-RevId: 4515f7f2c58b7f28645b2c5a5d9842aa7a844eae
This commit is contained in:
Kali Vara Purushotham Santhati 2021-10-13 20:08:07 +05:30 committed by hasura-bot
parent eb90c236ea
commit 94a3be3e6e
70 changed files with 353 additions and 254 deletions

View File

@ -4,7 +4,8 @@ ARG upx_version="3.96"
# install go dependencies
RUN go get github.com/mitchellh/gox \
&& go get github.com/tcnksm/ghr
&& go get github.com/tcnksm/ghr \
&& go get github.com/golangci/golangci-lint/cmd/golangci-lint@v1.41.1
# install UPX, netcat and gcloud cli
RUN apt-get update && apt-get install -y \
@ -17,7 +18,7 @@ RUN apt-get update && apt-get install -y \
&& ACCEPT_EULA=Y apt-get install -y ca-certificates libkrb5-3 libpq5 libnuma1 unixodbc-dev msodbcsql17 apt-transport-https gnupg google-cloud-sdk hub \
&& curl -Lo /tmp/upx-${upx_version}.tar.xz https://github.com/upx/upx/releases/download/v${upx_version}/upx-${upx_version}-amd64_linux.tar.xz \
&& xz -d -c /tmp/upx-${upx_version}.tar.xz \
| tar -xOf - upx-${upx_version}-amd64_linux/upx > /bin/upx \
| tar -xOf - upx-${upx_version}-amd64_linux/upx > /bin/upx \
&& chmod a+x /bin/upx \
&& apt-get -y auto-remove \
&& rm -rf /var/lib/apt/lists/*

View File

@ -232,7 +232,7 @@ jobs:
# changes only contains files in .ciignore
check_build_worthiness:
docker:
- image: hasura/graphql-engine-cli-builder:20210310
- image: hasura/graphql-engine-cli-builder:9657e5303218c015a20cd0d7e252d5600537e6384b172003273b6ebd38c451d8
working_directory: ~/graphql-engine
steps:
- attach_workspace:
@ -622,7 +622,7 @@ jobs:
build_cli:
docker:
- image: hasura/graphql-engine-cli-builder:20210310
- image: hasura/graphql-engine-cli-builder:9657e5303218c015a20cd0d7e252d5600537e6384b172003273b6ebd38c451d8
working_directory: ~/graphql-engine
steps:
- attach_workspace:
@ -636,6 +636,7 @@ jobs:
name: build cli
working_directory: cli
command: |
make lint
make build
make compress
make ci-copy-binary

View File

@ -18,6 +18,10 @@ endif
deps:
go mod download
.PHONY: lint
lint:
golangci-lint run
# build cli locally, for all given platform/arch
.PHONY: build
build: export CGO_ENABLED=0

View File

@ -27,7 +27,6 @@ import (
"github.com/hasura/graphql-engine/cli/v2/internal/hasura/pgdump"
"github.com/hasura/graphql-engine/cli/v2/internal/hasura/v1graphql"
"github.com/hasura/graphql-engine/cli/v2/migrate/database/hasuradb"
"golang.org/x/term"
"github.com/hasura/graphql-engine/cli/v2/internal/hasura/v1metadata"
"github.com/hasura/graphql-engine/cli/v2/internal/hasura/v1query"
@ -58,6 +57,7 @@ import (
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"github.com/subosito/gotenv"
"golang.org/x/term"
"gopkg.in/yaml.v2"
)

View File

@ -51,7 +51,9 @@ func NewActionsCmd(ec *cli.ExecutionContext) *cobra.Command {
f.String("endpoint", "", "http(s) endpoint for Hasura GraphQL engine")
f.String("admin-secret", "", "admin secret for Hasura GraphQL engine")
f.String("access-key", "", "access key for Hasura GraphQL engine")
f.MarkDeprecated("access-key", "use --admin-secret instead")
if err := f.MarkDeprecated("access-key", "use --admin-secret instead"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
f.Bool("insecure-skip-tls-verify", false, "skip TLS verification and disable cert checking (default: false)")
f.String("certificate-authority", "", "path to a cert file for the certificate authority")

View File

@ -61,7 +61,7 @@ func (o *actionsCodegenOptions) run() (err error) {
}
if o.EC.Config.ActionConfig.Codegen.Framework == "" {
return fmt.Errorf(`Could not find codegen config. For adding codegen config, run:
return fmt.Errorf(`could not find codegen config. For adding codegen config, run:
hasura actions use-codegen`)
}

View File

@ -96,7 +96,7 @@ func (o *actionsCreateOptions) run() error {
// if codegen config not present, skip codegen
if o.EC.Config.ActionConfig.Codegen.Framework == "" {
if o.withCodegen {
return fmt.Errorf(`Could not find codegen config. For adding codegen config, run:
return fmt.Errorf(`could not find codegen config. For adding codegen config, run:
hasura actions use-codegen`)
}

View File

@ -48,9 +48,7 @@ var _ = Describe("actions_create", func() {
fmt.Println(err)
}
_, err = file.Write([]byte(data))
if err != nil {
fmt.Println(err)
}
Expect(err).To(BeNil())
file.Close()
session = testutil.Hasura(testutil.CmdOpts{
Args: []string{"actions", "create", "action1", "--file", filePath},

View File

@ -134,7 +134,6 @@ func (o *actionsUseCodegenOptions) run() error {
suffix++
err = util.FSCheckIfDirPathExists(starterKitDirname)
}
err = nil
// copy the starter kit
destinationDir := filepath.Join(o.EC.ExecutionDirectory, starterKitDirname)

View File

@ -63,7 +63,6 @@ func NewCompletionCmd(ec *cli.ExecutionContext) *cobra.Command {
}
completionCmd.Flags().StringVar(&opts.File, "file", "", "file to which output has to be written")
completionCmd.MarkFlagFilename("file")
return completionCmd
}
@ -91,7 +90,7 @@ func (o *completionOptions) run() error {
err = o.Cmd.Root().GenZshCompletion(os.Stdout)
}
default:
err = fmt.Errorf("Unknown shell: %s. Use bash or zsh", o.Shell)
err = fmt.Errorf("unknown shell: %s. Use bash or zsh", o.Shell)
}
if err != nil {
return err

View File

@ -67,7 +67,9 @@ func NewConsoleCmd(ec *cli.ExecutionContext) *cobra.Command {
f.String("endpoint", "", "http(s) endpoint for Hasura GraphQL engine")
f.String("admin-secret", "", "admin secret for Hasura GraphQL engine")
f.String("access-key", "", "access key for Hasura GraphQL engine")
f.MarkDeprecated("access-key", "use --admin-secret instead")
if err := f.MarkDeprecated("access-key", "use --admin-secret instead"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
f.Bool("insecure-skip-tls-verify", false, "skip TLS verification and disable cert checking (default: false)")
f.String("certificate-authority", "", "path to a cert file for the certificate authority")

View File

@ -50,7 +50,9 @@ func NewDeployCmd(ec *cli.ExecutionContext) *cobra.Command {
f.String("endpoint", "", "http(s) endpoint for Hasura GraphQL engine")
f.String("admin-secret", "", "admin secret for Hasura GraphQL engine")
f.String("access-key", "", "access key for Hasura GraphQL engine")
f.MarkDeprecated("access-key", "use --admin-secret instead")
if err := f.MarkDeprecated("access-key", "use --admin-secret instead"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
f.Bool("insecure-skip-tls-verify", false, "skip TLS verification and disable cert checking (default: false)")
f.String("certificate-authority", "", "path to a cert file for the certificate authority")
f.Bool("disable-interactive", false, "disables interactive prompts (default: false)")
@ -63,7 +65,9 @@ func NewDeployCmd(ec *cli.ExecutionContext) *cobra.Command {
util.BindPFlag(v, "disable_interactive", f.Lookup("disable-interactive"))
f.BoolVar(&ec.DisableAutoStateMigration, "disable-auto-state-migration", false, "after a config v3 update, disable automatically moving state from hdb_catalog.schema_migrations to catalog state")
f.MarkHidden("disable-auto-state-migration")
if err := f.MarkHidden("disable-auto-state-migration"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
return deployCmd
}

View File

@ -68,7 +68,10 @@ func (o *helpOptions) run() {
cmd, _, e := c.Root().Find(args)
if cmd == nil || e != nil {
c.Printf("Unknown help topic %#q\n", args)
c.Root().Usage()
err := c.Root().Usage()
if err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
} else {
if cmd.Name() == "hasura" {
// root command
@ -85,7 +88,10 @@ func (o *helpOptions) run() {
fmt.Println(`Use "hasura [command] --help" for more information about a command.`)
} else {
cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
cmd.Help()
err := cmd.Help()
if err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
}
}

View File

@ -87,12 +87,18 @@ func NewInitCmd(ec *cli.ExecutionContext) *cobra.Command {
f.StringVar(&opts.AdminSecret, "admin-secret", "", "admin secret for Hasura GraphQL engine")
f.StringVar(&opts.AdminSecret, "access-key", "", "access key for Hasura GraphQL engine")
f.StringVar(&opts.Template, "install-manifest", "", "install manifest to be cloned")
f.MarkDeprecated("access-key", "use --admin-secret instead")
f.MarkDeprecated("directory", "use directory-name argument instead")
if err := f.MarkDeprecated("access-key", "use --admin-secret instead"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
if err := f.MarkDeprecated("directory", "use directory-name argument instead"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
// only used in tests
f.BoolVar(&opts.GetMetadataMigrations, "fetch", false, "It fetches the metadata and migrations from server without prompt")
f.MarkHidden("fetch")
if err := f.MarkHidden("fetch"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
return initCmd
}
@ -201,25 +207,16 @@ func (o *InitOptions) createFiles() error {
return errors.Wrap(err, "error creating setup directories")
}
// set config object
var config *cli.Config
if o.Version == cli.V1 {
config = &cli.Config{
ServerConfig: cli.ServerConfig{
Endpoint: "http://localhost:8080",
},
}
} else {
config = &cli.Config{
Version: o.Version,
ServerConfig: cli.ServerConfig{
Endpoint: "http://localhost:8080",
},
MetadataDirectory: "metadata",
ActionConfig: &actionMetadataFileTypes.ActionExecutionConfig{
Kind: "synchronous",
HandlerWebhookBaseURL: "http://localhost:3000",
},
}
var config = &cli.Config{
Version: o.Version,
ServerConfig: cli.ServerConfig{
Endpoint: defaultEndpoint,
},
MetadataDirectory: "metadata",
ActionConfig: &actionMetadataFileTypes.ActionExecutionConfig{
Kind: "synchronous",
HandlerWebhookBaseURL: "http://localhost:3000",
},
}
if o.Endpoint != "" {
if _, err := url.ParseRequestURI(o.Endpoint); err != nil {
@ -253,7 +250,10 @@ func (o *InitOptions) createFiles() error {
if err != nil {
return errors.Wrap(err, "cannot write metadata directory")
}
o.EC.Version.GetServerFeatureFlags()
err = o.EC.Version.GetServerFeatureFlags()
if err != nil {
o.EC.Logger.Warnf("error determining server feature flags: %v", err)
}
// create metadata files
plugins := make(metadataobject.Objects, 0)

View File

@ -55,7 +55,9 @@ func NewMetadataCmd(ec *cli.ExecutionContext) *cobra.Command {
f.String("endpoint", "", "http(s) endpoint for Hasura GraphQL engine")
f.String("admin-secret", "", "admin secret for Hasura GraphQL engine")
f.String("access-key", "", "access key for Hasura GraphQL engine")
f.MarkDeprecated("access-key", "use --admin-secret instead")
if err := f.MarkDeprecated("access-key", "use --admin-secret instead"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
f.Bool("insecure-skip-tls-verify", false, "skip TLS verification and disable cert checking (default: false)")
f.String("certificate-authority", "", "path to a cert file for the certificate authority")
@ -76,13 +78,19 @@ func writeByOutputFormat(w io.Writer, b []byte, format rawOutputFormat) error {
if err != nil {
return err
}
io.Copy(w, out)
_, err = io.Copy(w, out)
if err != nil {
return fmt.Errorf("writing output failed: %w", err)
}
case rawOutputFormatYAML:
o, err := yaml.JSONToYAML(b)
if err != nil {
return err
}
io.Copy(w, bytes.NewReader(o))
_, err = io.Copy(w, bytes.NewReader(o))
if err != nil {
return fmt.Errorf("writing output failed: %w", err)
}
default:
return fmt.Errorf("output format '%v' is not supported. supported formats: %v, %v", format, rawOutputFormatJSON, rawOutputFormatYAML)
}

View File

@ -47,8 +47,9 @@ func newMetadataApplyCmd(ec *cli.ExecutionContext) *cobra.Command {
// deprecated flag
f.BoolVar(&opts.FromFile, "from-file", false, "apply metadata from migrations/metadata.[yaml|json]")
f.MarkDeprecated("from-file", "deprecation is a side effect of config v1 deprecation from v2.0.0")
if err := f.MarkDeprecated("from-file", "deprecation is a side effect of config v1 deprecation from v2.0.0"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
f.BoolVar(&opts.DryRun, "dry-run", false, "show metadata generated from project directory without applying to server. generated metadata will be printed as JSON by default, use -o flag for other display formats")
f.StringVarP(&opts.rawOutput, "output", "o", "", `specify an output format to show applied metadata. Allowed values: json, yaml (default "json")`)
return metadataApplyCmd

View File

@ -215,7 +215,7 @@ func (m *metadataModeYAMLHandler) Diff(o *MetadataDiffOptions) error {
func export(o *MetadataExportOptions, mode cli.MetadataMode) error {
metadata, err := ec.APIClient.V1Metadata.ExportMetadata()
if err != nil {
fmt.Errorf("exporting metadata from server: %w", err)
return fmt.Errorf("exporting metadata from server: %w", err)
}
var metadataBytes []byte
metadataBytes, err = ioutil.ReadAll(metadata)
@ -293,22 +293,22 @@ func diff(o *MetadataDiffOptions, mode cli.MetadataMode) error {
}
serverMetadata, err := cli.GetCommonMetadataOps(o.EC).ExportMetadata()
if err != nil {
fmt.Errorf("exporting metadata from server: %w", err)
return fmt.Errorf("exporting metadata from server: %w", err)
}
var serverMetadataBytes []byte
serverMetadataBytes, err = ioutil.ReadAll(serverMetadata)
if err != nil {
fmt.Errorf("reading server metadata: %w", err)
return fmt.Errorf("reading server metadata: %w", err)
}
if mode == cli.MetadataModeYAML {
serverMetadataBytes, err = goyaml.JSONToYAML(serverMetadataBytes)
if err != nil {
fmt.Errorf("parsing server metadata as yaml: %w", err)
return fmt.Errorf("parsing server metadata as yaml: %w", err)
}
}
localMetadataBytes, err := ioutil.ReadFile(o.EC.MetadataFile)
if err != nil {
fmt.Errorf("reading local metadata: %w", err)
return fmt.Errorf("reading local metadata: %w", err)
}
return printDiff(string(serverMetadataBytes), string(localMetadataBytes), "server", "project", o.Output, o.DiffType, !o.EC.IsTerminal)
}

View File

@ -49,7 +49,9 @@ func NewMigrateCmd(ec *cli.ExecutionContext) *cobra.Command {
f.String("endpoint", "", "http(s) endpoint for Hasura GraphQL engine")
f.String("admin-secret", "", "admin secret for Hasura GraphQL engine")
f.String("access-key", "", "access key for Hasura GraphQL engine")
f.MarkDeprecated("access-key", "use --admin-secret instead")
if err := f.MarkDeprecated("access-key", "use --admin-secret instead"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
f.Bool("insecure-skip-tls-verify", false, "skip TLS verification and disable cert checking (default: false)")
f.String("certificate-authority", "", "path to a cert file for the certificate authority")
f.Bool("disable-interactive", false, "disables interactive prompts (default: false)")
@ -62,7 +64,9 @@ func NewMigrateCmd(ec *cli.ExecutionContext) *cobra.Command {
util.BindPFlag(v, "disable_interactive", f.Lookup("disable-interactive"))
f.BoolVar(&ec.DisableAutoStateMigration, "disable-auto-state-migration", false, "after a config v3 update, disable automatically moving state from hdb_catalog.schema_migrations to catalog state")
f.MarkHidden("disable-auto-state-migration")
if err := f.MarkHidden("disable-auto-state-migration"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
migrateCmd.AddCommand(
newMigrateApplyCmd(ec),

View File

@ -87,7 +87,9 @@ func newMigrateApplyCmd(ec *cli.ExecutionContext) *cobra.Command {
f.BoolVar(&opts.DryRun, "dry-run", false, "print the names of migrations which are going to be applied")
f.BoolVar(&opts.AllDatabases, "all-databases", false, "set this flag to attempt to apply migrations on all databases present on server")
f.BoolVar(&opts.ProgressBarLogs, "progressbar-logs", false, "print the logs of progressbar")
f.MarkHidden("progressbar-logs")
if err := f.MarkHidden("progressbar-logs"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
return migrateApplyCmd
}

View File

@ -116,8 +116,12 @@ func newMigrateCreateCmd(ec *cli.ExecutionContext) *cobra.Command {
f.StringVar(&opts.upSQL, "up-sql", "", "sql string/query that is to be used to create an up migration")
f.StringVar(&opts.downSQL, "down-sql", "", "sql string/query that is to be used to create a down migration")
migrateCreateCmd.MarkFlagFilename("sql-from-file")
migrateCreateCmd.MarkFlagFilename("metadata-from-file")
if err := migrateCreateCmd.MarkFlagFilename("sql-from-file", "sql"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
if err := migrateCreateCmd.MarkFlagFilename("metadata-from-file", "json"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
return migrateCreateCmd
}
@ -156,7 +160,7 @@ func (o *migrateCreateOptions) run() (version int64, err error) {
if o.sqlServer || o.upSQLChanged || o.downSQLChanged {
migrateDrv, err = migrate.NewMigrate(o.EC, true, o.Source.Name, o.Source.Kind)
if err != nil {
return 0, errors.Wrap(err, "cannot create migrate instance")
return 0, fmt.Errorf("cannot create migrate instance: %w", err)
}
}
@ -164,29 +168,32 @@ func (o *migrateCreateOptions) run() (version int64, err error) {
// sql-file flag is set
err := createOptions.SetSQLUpFromFile(o.sqlFile)
if err != nil {
return 0, errors.Wrap(err, "cannot set sql file")
return 0, fmt.Errorf("cannot set sql file: %w", err)
}
}
if o.sqlServer {
data, err := migrateDrv.ExportSchemaDump(o.schemaNames, o.Source.Name, o.Source.Kind)
if err != nil {
return 0, errors.Wrap(err, "cannot fetch schema dump")
return 0, fmt.Errorf("cannot fetch schema dump: %w", err)
}
err = createOptions.SetSQLUp(string(data))
if err != nil {
return 0, fmt.Errorf("while writing data from server into the up.sql file: %w", err)
}
createOptions.SetSQLUp(string(data))
}
// create pure sql based migrations here
if o.upSQLChanged {
err = createOptions.SetSQLUp(o.upSQL)
if err != nil {
return 0, errors.Wrap(err, "up migration with SQL string could not be created")
return 0, fmt.Errorf("up migration with SQL string could not be created: %w", err)
}
}
if o.downSQLChanged {
err = createOptions.SetSQLDown(o.downSQL)
if err != nil {
return 0, errors.Wrap(err, "down migration with SQL string could not be created")
return 0, fmt.Errorf("down migration with SQL string could not be created: %w", err)
}
}
@ -198,13 +205,16 @@ func (o *migrateCreateOptions) run() (version int64, err error) {
defer func() {
if err != nil {
createOptions.Delete()
if err := createOptions.Delete(); err != nil {
o.EC.Logger.Warnf("cannot delete dangling migrations: %v", err)
}
}
}()
err = createOptions.Create()
if err != nil {
return 0, errors.Wrap(err, "error creating migration files")
return 0, fmt.Errorf("error creating migration files: %w", err)
}
o.EC.Spinner.Stop()
o.EC.Logger.Infof("Created Migrations")
if o.fromServer {
opts := &MigrateApplyOptions{

View File

@ -42,7 +42,7 @@ func newMigrateDeleteCmd(ec *cli.ExecutionContext) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
// exit if user inputs n for clearing migrations
if cmd.Flags().Changed("all") && !opts.force {
if cmd.Flags().Changed("all") && !opts.force && opts.EC.IsTerminal {
confirmation, err := util.GetYesNoPrompt("clear all migrations of database and it's history on the server?")
if err != nil {
return fmt.Errorf("error getting user input: %w", err)
@ -94,7 +94,6 @@ type MigrateDeleteOptions struct {
func (o *MigrateDeleteOptions) Run() error {
o.EC.Spin("Deleting migration...")
defer o.EC.Spinner.Stop()
migrateDrv, err := migrate.NewMigrate(o.EC, true, o.Source.Name, o.Source.Kind)
if err != nil {
@ -140,7 +139,7 @@ func (o *MigrateDeleteOptions) Run() error {
return fmt.Errorf("error removing migrations from project: %w", err)
}
}
o.EC.Spinner.Stop()
o.EC.Logger.Infof("Deleted migrations")
return nil
}

View File

@ -56,7 +56,10 @@ func newMigrateSquashCmd(ec *cli.ExecutionContext) *cobra.Command {
f.BoolVar(&opts.deleteSource, "delete-source", false, "delete the source files after squashing without any confirmation")
// mark flag as required
migrateSquashCmd.MarkFlagRequired("from")
err := migrateSquashCmd.MarkFlagRequired("from")
if err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
return migrateSquashCmd
}
@ -134,7 +137,7 @@ func (o *migrateSquashOptions) run() error {
newPath := filepath.Join(o.EC.MigrationDir, o.Source.Name, fmt.Sprintf("%d_%s", toMigration.Version, o.name))
err = os.Rename(oldPath, newPath)
if err != nil {
fmt.Errorf("renaming squashed migrations: %w", err)
return fmt.Errorf("renaming squashed migrations: %w", err)
}
o.EC.Logger.Infof("Created '%d_%s' after squashing '%d' till '%d'", toMigration.Version, o.name, versions[0], versions[len(versions)-1])

View File

@ -79,7 +79,7 @@ var _ = Describe("hasura migrate squash", func() {
Eventually(session, timeout).Should(Exit(0))
for _, dir := range toSquash {
// get version from dir name "1588172670820_create_table_public_table50"
Expect(session.Out.Contents()).ToNot(ContainSubstring(fmt.Sprintf(dir)))
Expect(session.Out.Contents()).ToNot(ContainSubstring(dir))
}
// assert contents of squashed migration
@ -159,7 +159,7 @@ var _ = Describe("hasura migrate squash", func() {
Eventually(session, timeout).Should(Exit(0))
for _, dir := range toSquash {
// get version from dir name "1588172670820_create_table_public_table50"
Expect(session.Out.Contents()).ToNot(ContainSubstring(fmt.Sprintf(dir)))
Expect(session.Out.Contents()).ToNot(ContainSubstring(dir))
}
// assert contents of squashed migration

View File

@ -22,14 +22,11 @@ import (
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"syscall"
"unicode"
"github.com/hasura/graphql-engine/cli/v2"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
@ -165,23 +162,6 @@ func HandlePluginCommand(pluginHandler PluginHandler, cmdArgs []string) error {
return nil
}
func ensureDirs(paths ...string) error {
for _, p := range paths {
if err := os.MkdirAll(p, 0755); err != nil {
return errors.Wrapf(err, "failed to ensure create directory %q", p)
}
}
return nil
}
func indent(s string) string {
out := "\\\n"
s = strings.TrimRightFunc(s, unicode.IsSpace)
out += regexp.MustCompile("(?m)^").ReplaceAllString(s, " | ")
out += "\n/"
return out
}
func limitString(s string, length int) string {
if len(s) > length && length > 3 {
s = s[:length-3] + "..."

View File

@ -63,7 +63,9 @@ func newPluginsInstallCmd(ec *cli.ExecutionContext) *cobra.Command {
f.Var(&opts.Version, "version", "version to be installed")
f.StringVar(&opts.ManifestFile, "manifest-file", "", "(dev) speficy local manifest file")
f.MarkHidden("manifest-file")
if err := f.MarkHidden("manifest-file"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
return pluginsInstallCmd
}

View File

@ -94,7 +94,6 @@ func (p *pluginListOptions) run() error {
var version string
if _, ok := installed[name]; ok {
status = "yes"
version = installed[name]
} else if _, ok, err := plugins.MatchPlatform(plugin.Platforms); err != nil {
return errors.Wrapf(err, "failed to get the matching platform for plugin %s", name)
} else if ok {

View File

@ -83,7 +83,9 @@ func init() {
f.BoolVar(&ec.NoColor, "no-color", false, "do not colorize output (default: false)")
f.StringVar(&ec.Envfile, "envfile", ".env", ".env filename to load ENV vars from")
f.StringVar(&ec.CliExtSourceBinPath, "cli-ext-path", "", "path to cli-ext binary")
f.MarkHidden("cli-ext-path")
if err := f.MarkHidden("cli-ext-path"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
}
// NewDefaultHasuraCommand creates the `hasura` command with default arguments

View File

@ -305,10 +305,6 @@ func newScriptsUpdateConfigV2Cmd(ec *cli.ExecutionContext) *cobra.Command {
ec.Config.ActionConfig.Codegen = nil
// run metadata export
ec.Spin("Exporting metadata...")
migrateDrv, err = migrate.NewMigrate(ec, true, "", hasura.SourceKindPG)
if err != nil {
return errors.Wrap(err, "unable to initialize migrations driver")
}
var files map[string][]byte
mdHandler := projectmetadata.NewHandlerFromEC(ec)
files, err = mdHandler.ExportMetadata()
@ -361,7 +357,9 @@ func newScriptsUpdateConfigV2Cmd(ec *cli.ExecutionContext) *cobra.Command {
f.String("endpoint", "", "http(s) endpoint for Hasura GraphQL engine")
f.String("admin-secret", "", "admin secret for Hasura GraphQL engine")
f.String("access-key", "", "access key for Hasura GraphQL engine")
f.MarkDeprecated("access-key", "use --admin-secret instead")
if err := f.MarkDeprecated("access-key", "use --admin-secret instead"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
f.Bool("insecure-skip-tls-verify", false, "skip TLS verification and disable cert checking (default: false)")
f.String("certificate-authority", "", "path to a cert file for the certificate authority")

View File

@ -52,7 +52,9 @@ Note that this process is completely independent from your Hasura Graphql Engine
f.String("endpoint", "", "http(s) endpoint for Hasura GraphQL engine")
f.String("admin-secret", "", "admin secret for Hasura GraphQL engine")
f.String("access-key", "", "access key for Hasura GraphQL engine")
f.MarkDeprecated("access-key", "use --admin-secret instead")
if err := f.MarkDeprecated("access-key", "use --admin-secret instead"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
f.Bool("insecure-skip-tls-verify", false, "skip TLS verification and disable cert checking (default: false)")
f.String("certificate-authority", "", "path to a cert file for the certificate authority")

View File

@ -85,7 +85,9 @@ func NewSeedCmd(ec *cli.ExecutionContext) *cobra.Command {
f.String("endpoint", "", "http(s) endpoint for Hasura GraphQL engine")
f.String("admin-secret", "", "admin secret for Hasura GraphQL engine")
f.String("access-key", "", "access key for Hasura GraphQL engine")
f.MarkDeprecated("access-key", "use --admin-secret instead")
if err := f.MarkDeprecated("access-key", "use --admin-secret instead"); err != nil {
ec.Logger.WithError(err).Errorf("error while using a dependency library")
}
f.Bool("insecure-skip-tls-verify", false, "skip TLS verification and disable cert checking (default: false)")
f.String("certificate-authority", "", "path to a cert file for the certificate authority")
f.Bool("disable-interactive", false, "disables interactive prompts (default: false)")

View File

@ -63,6 +63,7 @@ var _ = Describe("seed apply (config v2)", func() {
editEndpointInConfig(filepath.Join(projectDirectoryConfigV2, defaultConfigFilename), hgeEndpoint)
err := os.MkdirAll(filepath.Join(filepath.Join(projectDirectoryConfigV2, "seeds")), 0755)
Expect(err).To(BeNil())
file, err := os.Create(filepath.Join(projectDirectoryConfigV2, "seeds", "table_seed.sql"))
Expect(err).To(BeNil())

View File

@ -2,12 +2,11 @@ package cli
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/sirupsen/logrus"
"github.com/gofrs/uuid"
homedir "github.com/mitchellh/go-homedir"
"github.com/pkg/errors"
@ -45,7 +44,6 @@ type rawGlobalConfig struct {
ShowUpdateNotification *bool `json:"show_update_notification"`
CLIEnvironment Environment `json:"cli_environment"`
logger *logrus.Logger
shoudlWrite bool
}
@ -66,7 +64,7 @@ func (c *rawGlobalConfig) validateKeys() error {
if c.UUID == nil {
u, err := uuid.NewV4()
if err != nil {
errors.Wrap(err, "failed generating uuid")
return fmt.Errorf("failed generating uuid : %w", err)
}
uid := u.String()
c.UUID = &uid

View File

@ -34,6 +34,8 @@ func TestCommands(t *testing.T) {
ec.Spinner = spinner.New(spinner.CharSets[7], 100*time.Millisecond)
ec.Spinner.Writer = ioutil.Discard
ec.Viper = viper.New()
ec.Stdout = os.Stdout
ec.Stderr = os.Stderr
initDir := filepath.Join(os.TempDir(), "hasura-cli-test-"+strconv.Itoa(rand.Intn(1000)))
defer os.RemoveAll(initDir)
@ -91,6 +93,8 @@ func TestCommands(t *testing.T) {
ec.Spinner = spinner.New(spinner.CharSets[7], 100*time.Millisecond)
ec.Spinner.Writer = ioutil.Discard
ec.Viper = viper.New()
ec.Stdout = os.Stdout
ec.Stderr = os.Stderr
initDir := filepath.Join(os.TempDir(), "hasura-cli-test-"+strconv.Itoa(rand.Intn(1000)))
defer os.RemoveAll(initDir)

View File

@ -88,7 +88,7 @@ func TestMetadataCmd(t *testing.T, ec *cli.ExecutionContext) {
&commands.MigrateApplyOptions{
EC: ec,
DownMigration: "all",
Source: cli.Source{"", hasura.SourceKindPG},
Source: cli.Source{Name: "", Kind: hasura.SourceKindPG},
},
nil,
"",

View File

@ -36,7 +36,7 @@ func TestMigrateCmd(t *testing.T, ec *cli.ExecutionContext) {
}{
{"apply-up-all-migrations", &commands.MigrateApplyOptions{
EC: ec,
Source: cli.Source{"", hasura.SourceKindPG},
Source: cli.Source{Name: "", Kind: hasura.SourceKindPG},
}, nil, migrate.Status{
Index: []uint64{1, 2},
Migrations: map[uint64]*migrate.MigrationStatus{
@ -53,7 +53,7 @@ func TestMigrateCmd(t *testing.T, ec *cli.ExecutionContext) {
{"apply-down-1-migration", &commands.MigrateApplyOptions{
EC: ec,
DownMigration: "1",
Source: cli.Source{"", hasura.SourceKindPG},
Source: cli.Source{Name: "", Kind: hasura.SourceKindPG},
}, nil, migrate.Status{
Index: []uint64{1, 2},
Migrations: map[uint64]*migrate.MigrationStatus{
@ -70,7 +70,7 @@ func TestMigrateCmd(t *testing.T, ec *cli.ExecutionContext) {
{"apply-down-all-migration", &commands.MigrateApplyOptions{
EC: ec,
DownMigration: "all",
Source: cli.Source{"", hasura.SourceKindPG},
Source: cli.Source{Name: "", Kind: hasura.SourceKindPG},
}, nil, migrate.Status{
Index: []uint64{1, 2},
Migrations: map[uint64]*migrate.MigrationStatus{
@ -87,7 +87,7 @@ func TestMigrateCmd(t *testing.T, ec *cli.ExecutionContext) {
{"apply-goto-2-migration", &commands.MigrateApplyOptions{
EC: ec,
GotoVersion: "2",
Source: cli.Source{"", hasura.SourceKindPG},
Source: cli.Source{Name: "", Kind: hasura.SourceKindPG},
}, nil, migrate.Status{
Index: []uint64{1, 2},
Migrations: map[uint64]*migrate.MigrationStatus{
@ -104,7 +104,7 @@ func TestMigrateCmd(t *testing.T, ec *cli.ExecutionContext) {
{"apply-goto-nil-migration", &commands.MigrateApplyOptions{
EC: ec,
GotoVersion: "-1",
Source: cli.Source{"", hasura.SourceKindPG},
Source: cli.Source{Name: "", Kind: hasura.SourceKindPG},
}, nil, migrate.Status{
Index: []uint64{1, 2},
Migrations: map[uint64]*migrate.MigrationStatus{
@ -121,7 +121,7 @@ func TestMigrateCmd(t *testing.T, ec *cli.ExecutionContext) {
{"apply-up-1-migration", &commands.MigrateApplyOptions{
EC: ec,
UpMigration: "1",
Source: cli.Source{"", hasura.SourceKindPG},
Source: cli.Source{Name: "", Kind: hasura.SourceKindPG},
}, nil, migrate.Status{
Index: []uint64{1, 2},
Migrations: map[uint64]*migrate.MigrationStatus{
@ -138,7 +138,7 @@ func TestMigrateCmd(t *testing.T, ec *cli.ExecutionContext) {
{"apply-version-2-up-migration", &commands.MigrateApplyOptions{
EC: ec,
VersionMigration: "2",
Source: cli.Source{"", hasura.SourceKindPG},
Source: cli.Source{Name: "", Kind: hasura.SourceKindPG},
}, nil, migrate.Status{
Index: []uint64{1, 2},
Migrations: map[uint64]*migrate.MigrationStatus{
@ -156,7 +156,7 @@ func TestMigrateCmd(t *testing.T, ec *cli.ExecutionContext) {
EC: ec,
VersionMigration: "2",
MigrationType: "down",
Source: cli.Source{"", hasura.SourceKindPG},
Source: cli.Source{Name: "", Kind: hasura.SourceKindPG},
}, nil, migrate.Status{
Index: []uint64{1, 2},
Migrations: map[uint64]*migrate.MigrationStatus{
@ -185,7 +185,7 @@ func TestMigrateCmd(t *testing.T, ec *cli.ExecutionContext) {
}
statusOpts := &commands.MigrateStatusOptions{
EC: ec,
Source: cli.Source{"", hasura.SourceKindPG},
Source: cli.Source{Name: "", Kind: hasura.SourceKindPG},
}
actualStatus, err := statusOpts.Run()
if err != nil {

View File

@ -79,7 +79,7 @@ func TestDeployCmd(t *testing.T, ec *cli.ExecutionContext) {
if tc.expectedMetadataFolder != "" {
assert.DirExists(t, ec.MetadataDir)
filepath.Walk(filepath.Join(tc.expectedMetadataFolder), func(path string, info os.FileInfo, err error) error {
err = filepath.Walk(filepath.Join(tc.expectedMetadataFolder), func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
name := info.Name()
expectedByt, err := ioutil.ReadFile(path)
@ -94,6 +94,9 @@ func TestDeployCmd(t *testing.T, ec *cli.ExecutionContext) {
}
return nil
})
if err != nil {
t.Fatalf("%s: unable to read metadata, got %v", tc.name, err)
}
}
expectedStatusByt, err := json.Marshal(tc.migrateStatus)

View File

@ -126,7 +126,7 @@ func TestMetadataCmd(t *testing.T, ec *cli.ExecutionContext) {
}
if tc.expectedMetadataFolder != "" {
assert.DirExists(t, ec.MetadataDir)
filepath.Walk(filepath.Join(tc.expectedMetadataFolder), func(path string, info os.FileInfo, err error) error {
err = filepath.Walk(filepath.Join(tc.expectedMetadataFolder), func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
name := info.Name()
expectedByt, err := ioutil.ReadFile(path)
@ -141,6 +141,9 @@ func TestMetadataCmd(t *testing.T, ec *cli.ExecutionContext) {
}
return nil
})
if err != nil {
t.Fatalf("%s: unable to read metadata, got %v", tc.name, err)
}
}
})
}

View File

@ -19,8 +19,7 @@ func TestHasuraDatabaseOperations_RunSQL(t *testing.T) {
path string
}
type args struct {
input hasura.MSSQLRunSQLInput
database string
input hasura.MSSQLRunSQLInput
}
tests := []struct {
name string

View File

@ -19,8 +19,7 @@ func TestHasuraDatabaseOperations_RunSQL(t *testing.T) {
path string
}
type args struct {
input hasura.PGRunSQLInput
database string
input hasura.PGRunSQLInput
}
tests := []struct {
name string

View File

@ -103,7 +103,3 @@ func resolveTags(ctx map[string]string, node *yaml.Node) (*yaml.Node, error) {
}
return node, nil
}
type IncludeTagVisitor struct {
baseDir string
}

View File

@ -33,7 +33,7 @@ func (t *V3MetadataTableConfig) Export(md yaml.MapSlice) (map[string][]byte, met
}
var metadata struct {
Sources []struct {
Name string `yaml:"name"'`
Name string `yaml:"name"`
Tables []yaml.MapSlice `yaml:"tables"`
} `yaml:"sources"`
}

View File

@ -24,7 +24,11 @@ func (a *V3MetadataV2ConfigVersion) Build(metadata *yaml.MapSlice) metadataobjec
}
func NewV3MetadataVersion(ec *cli.ExecutionContext, baseDir string) *V3MetadataV2ConfigVersion {
ec.Version.GetServerFeatureFlags()
err := ec.Version.GetServerFeatureFlags()
if err != nil {
ec.Logger.Errorf("got error while creating instance of V3MetadtaV2ConfigVersion: %v", err)
return nil
}
return &V3MetadataV2ConfigVersion{
&VersionConfig{
MetadataDir: baseDir,

View File

@ -19,7 +19,11 @@ type VersionConfig struct {
}
func New(ec *cli.ExecutionContext, baseDir string) *VersionConfig {
ec.Version.GetServerFeatureFlags()
err := ec.Version.GetServerFeatureFlags()
if err != nil {
ec.Logger.Errorf("got error while creating instance of VersionConfig: %v", err)
return nil
}
return &VersionConfig{
MetadataDir: baseDir,
}

View File

@ -42,7 +42,7 @@ func GetSourceKind(exportMetadata func() (io.Reader, error), sourceName string)
}
var sources []struct {
Name string `yaml:"name"`
Kind hasura.SourceKind `yaml: "kind"`
Kind hasura.SourceKind `yaml:"kind"`
}
path, err := yaml.PathString("$.sources[*]")
if err != nil {
@ -83,7 +83,7 @@ func GetSources(exportMetadata func() (io.Reader, error)) ([]string, error) {
}
type Source struct {
Name string `yaml: "name"`
Name string `yaml:"name"`
Kind hasura.SourceKind `yaml:"kind"`
}

View File

@ -166,7 +166,7 @@ func (h *Handler) GetInconsistentMetadata() (bool, []InconsistentMetadataObject,
}
var objects []InconsistentMetadataObject
err = mapstructure.Decode(inconsistentMetadata.InconsistentObjects, &objects)
return inconsistentMetadata.IsConsistent, objects, nil
return inconsistentMetadata.IsConsistent, objects, err
}
func (h *Handler) DropInconsistentMetadata() error {

View File

@ -26,7 +26,10 @@ func GetMetadataObjectsWithDir(ec *cli.ExecutionContext, dir ...string) metadata
} else {
metadataDir = dir[0]
}
ec.Version.GetServerFeatureFlags()
err := ec.Version.GetServerFeatureFlags()
if err != nil {
ec.Logger.Errorf("error determining server feature flags: %v", err)
}
objects := make(metadataobject.Objects, 0)
if ec.Config.Version >= cli.V2 && metadataDir != "" {
// hasura core metadata objects

View File

@ -19,7 +19,6 @@ import (
"fmt"
"github.com/hasura/graphql-engine/cli/v2/util"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/afero"
)
@ -72,7 +71,7 @@ func UpdateProjectV3(opts UpdateProjectV3Opts) error {
opts.Logger.Warn(`The update process replaces project metadata with metadata on the server`)
opts.Logger.Infof("Using %s server at %s for update", opts.EC.Version.GetServerVersion(), opts.EC.Config.ServerConfig.Endpoint)
if !opts.Force {
if !opts.Force && opts.EC.IsTerminal {
response, err := util.GetYesNoPrompt("continue?")
if err != nil {
return err
@ -125,34 +124,34 @@ func UpdateProjectV3(opts UpdateProjectV3Opts) error {
// get directory names to move
migrationDirectoriesToMove, err := getMigrationDirectoryNames(opts.Fs, opts.MigrationsAbsDirectoryPath)
if err != nil {
return errors.Wrap(err, "getting list of migrations to move")
return fmt.Errorf("getting list of migrations to move: %w", err)
}
// move seed child directories
// get directory names to move
seedFilesToMove, err := getSeedFiles(opts.Fs, opts.SeedsAbsDirectoryPath)
if err != nil {
return errors.Wrap(err, "getting list of seed files to move")
return fmt.Errorf("getting list of seed files to move: %w", err)
}
// create a new directory for TargetDatabase
targetMigrationsDirectoryName := filepath.Join(opts.MigrationsAbsDirectoryPath, targetDatabase)
if err = opts.Fs.Mkdir(targetMigrationsDirectoryName, 0755); err != nil {
errors.Wrap(err, "creating target migrations directory")
return fmt.Errorf("creating target migrations directory: %w", err)
}
// create a new directory for TargetDatabase
targetSeedsDirectoryName := filepath.Join(opts.SeedsAbsDirectoryPath, targetDatabase)
if err = opts.Fs.Mkdir(targetSeedsDirectoryName, 0755); err != nil {
errors.Wrap(err, "creating target seeds directory")
return fmt.Errorf("creating target seeds directory: %w", err)
}
// move migration directories to target database directory
if err := copyMigrations(opts.Fs, migrationDirectoriesToMove, opts.MigrationsAbsDirectoryPath, targetMigrationsDirectoryName); err != nil {
return errors.Wrap(err, "moving migrations to target database directory")
return fmt.Errorf("moving migrations to target database directory: %w", err)
}
// move seed directories to target database directory
if err := copyFiles(opts.Fs, seedFilesToMove, opts.SeedsAbsDirectoryPath, targetSeedsDirectoryName); err != nil {
return errors.Wrap(err, "moving seeds to target database directory")
return fmt.Errorf("moving seeds to target database directory: %w", err)
}
opts.EC.Logger.Debug("completed: copy old migrations to new directory structure")
@ -171,11 +170,11 @@ func UpdateProjectV3(opts UpdateProjectV3Opts) error {
opts.EC.Spin("Cleaning project directory ")
// delete original migrations
if err := removeDirectories(opts.Fs, opts.MigrationsAbsDirectoryPath, migrationDirectoriesToMove); err != nil {
return errors.Wrap(err, "removing up original migrations")
return fmt.Errorf("removing up original migrations: %w", err)
}
// delete original seeds
if err := removeDirectories(opts.Fs, opts.SeedsAbsDirectoryPath, seedFilesToMove); err != nil {
return errors.Wrap(err, "removing up original migrations")
return fmt.Errorf("removing up original migrations: %w", err)
}
// remove functions.yaml and tables.yaml files
metadataFiles := []string{"functions.yaml", "tables.yaml"}
@ -217,12 +216,12 @@ func copyMigrations(fs afero.Fs, dirs []string, parentDir, target string) error
if f.IsDir() {
err := util.CopyDirAfero(fs, filepath.Join(parentDir, dir), filepath.Join(target, dir))
if err != nil {
return errors.Wrapf(err, "moving %s to %s", dir, target)
return fmt.Errorf("moving %s to %s : %w", dir, target, err)
}
} else {
err := util.CopyFileAfero(fs, filepath.Join(parentDir, dir), filepath.Join(target, dir))
if err != nil {
return errors.Wrapf(err, "moving %s to %s", dir, target)
return fmt.Errorf("moving %s to %s : %w", dir, target, err)
}
}
}
@ -235,7 +234,7 @@ func copyFiles(fs afero.Fs, files []string, parentDir, target string) error {
for _, dir := range files {
err := util.CopyFileAfero(fs, filepath.Join(parentDir, dir), filepath.Join(target, dir))
if err != nil {
return errors.Wrapf(err, "moving %s to %s", dir, target)
return fmt.Errorf("moving %s to %s : %w", dir, target, err)
}
}
return nil
@ -315,11 +314,11 @@ func CopyState(ec *cli.ExecutionContext, sourceDatabase, destDatabase string) er
}
cliState, err := statestore.NewCLICatalogState(ec.APIClient.V1Metadata).Get()
if err != nil {
return fmt.Errorf("error while fetching catalog state: %v", err)
return fmt.Errorf("error while fetching catalog state: %w", err)
}
cliState.IsStateCopyCompleted = true
if _, err := statestore.NewCLICatalogState(ec.APIClient.V1Metadata).Set(*cliState); err != nil {
return fmt.Errorf("cannot set catalog state: %v", err)
return fmt.Errorf("cannot set catalog state: %w", err)
}
return nil
}
@ -328,7 +327,7 @@ func CheckIfUpdateToConfigV3IsRequired(ec *cli.ExecutionContext) error {
// see if an update to config V3 is necessary
if ec.Config.Version <= cli.V1 && ec.HasMetadataV3 {
ec.Logger.Info("config v1 is deprecated from v1.4")
return errors.New("please upgrade your project to a newer version.\nuse " + color.New(color.FgCyan).SprintFunc()("hasura scripts update-project-v2") + " to upgrade your project to config v2")
return fmt.Errorf("please upgrade your project to a newer version.\nuse " + color.New(color.FgCyan).SprintFunc()("hasura scripts update-project-v2") + " to upgrade your project to config v2")
}
if ec.Config.Version < cli.V3 && ec.HasMetadataV3 {
sources, err := metadatautil.GetSources(ec.APIClient.V1Metadata.ExportMetadata)
@ -338,7 +337,7 @@ func CheckIfUpdateToConfigV3IsRequired(ec *cli.ExecutionContext) error {
upgrade := func() error {
ec.Logger.Info("Looks like you are trying to use hasura with multiple databases, which requires some changes on your project directory\n")
ec.Logger.Info("please use " + color.New(color.FgCyan).SprintFunc()("hasura scripts update-project-v3") + " to make this change")
return errors.New("update to config V3")
return fmt.Errorf("update to config V3")
}
if len(sources) == 0 {
return fmt.Errorf("no connected databases found on hasura")

View File

@ -59,7 +59,7 @@ func TestMigrationStateStoreHdbTable_SetVersions(t *testing.T) {
},
args{
"default",
[]statestore.Version{{1, false}, {2, false}, {3, false}},
[]statestore.Version{{Version: 1, Dirty: false}, {Version: 2, Dirty: false}, {Version: 3, Dirty: false}},
},
false,
},

View File

@ -126,7 +126,7 @@ func (s *StateStoreHdbTable) PrepareSettingsDriver() error {
func (s *StateStoreHdbTable) setDefaults() error {
var sql string
for _, setting := range Settings {
sql += `INSERT INTO ` + fmt.Sprintf("%s.%s", s.schema, s.table) + ` (setting, value) VALUES ('` + fmt.Sprintf("%s", setting.GetName()) + `', '` + fmt.Sprintf("%s", setting.GetDefaultValue()) + `');`
sql += `INSERT INTO ` + fmt.Sprintf("%s.%s", s.schema, s.table) + ` (setting, value) VALUES ('` + setting.GetName() + `', '` + setting.GetDefaultValue() + `');`
}
query := hasura.PGRunSQLInput{

View File

@ -88,11 +88,9 @@ func (m *mockDriver) Query(data interface{}) error {
}
func (m *mockDriver) ResetQuery() {
return
}
func (m *mockDriver) Squash(list *CustomList, ret chan<- interface{}) {
return
}
func (m *mockDriver) EnableCheckMetadataConsistency(enabled bool) {

View File

@ -24,7 +24,7 @@ func (h *HasuraDB) PushToList(migration io.Reader, fileType string, l *database.
tt := &hasura.PGRunSQLInput{
SQL: body,
}
l.PushBack(tt)
l.List.PushBack(tt)
default:
return fmt.Errorf("invalid migration file type")
}
@ -32,10 +32,7 @@ func (h *HasuraDB) PushToList(migration io.Reader, fileType string, l *database.
}
func (h *HasuraDB) Squash(l *database.CustomList, ret chan<- interface{}) {
for e := l.Front(); e != nil; e = e.Next() {
q := HasuraInterfaceQuery{
Args: e.Value,
}
for e := l.List.Front(); e != nil; e = e.Next() {
switch args := e.Value.(type) {
case *hasura.PGRunSQLInput:
ret <- []byte(args.SQL)
@ -45,6 +42,5 @@ func (h *HasuraDB) Squash(l *database.CustomList, ret chan<- interface{}) {
ret <- fmt.Errorf("invalid metadata action")
return
}
ret <- q
}
}

View File

@ -86,7 +86,7 @@ func (h HasuraError) Error() string {
errorStrings = append(errorStrings, fmt.Sprintf("File: '%s'", h.migrationFile))
}
if h.migrationQuery != "" {
errorStrings = append(errorStrings, fmt.Sprintf("%s", h.migrationQuery))
errorStrings = append(errorStrings, h.migrationQuery)
}
var internalError SQLInternalError
var internalErrors []SQLInternalError
@ -148,4 +148,4 @@ func NewHasuraError(data []byte, isCmd bool) error {
default:
return fmt.Errorf("Data Error: %s", string(data))
}
}
}

View File

@ -31,7 +31,9 @@ func TestHasuraError_Error(t *testing.T) {
}
}`)
var v interface{}
json.Unmarshal(d, &v)
if err := json.Unmarshal(d, &v); err != nil {
t.Fatal(err)
}
return v
}(),
},
@ -48,7 +50,9 @@ func TestHasuraError_Error(t *testing.T) {
}
}]`)
var v interface{}
json.Unmarshal(d, &v)
if err := json.Unmarshal(d, &v); err != nil {
t.Fatal(err)
}
return v
}(),
},

View File

@ -65,10 +65,7 @@ func (m *Migrations) Next(version uint64) (migrationVersion *MigrationVersion, o
func (m *Migrations) Read(version uint64) (ok bool) {
pos := m.findPos(version)
if pos >= 0 {
return true
}
return false
return pos >= 0
}
func (m *Migrations) findPos(version uint64) int {

View File

@ -7,11 +7,11 @@ import (
)
type CustomList struct {
*list.List
List *list.List
}
func (c *CustomList) Iterate() linq.Iterator {
length := c.Len()
length := c.List.Len()
var prevElem *list.Element
i := 0
return func() (item interface{}, ok bool) {
@ -20,7 +20,7 @@ func (c *CustomList) Iterate() linq.Iterator {
}
if i == 0 {
prevElem = c.Front()
prevElem = c.List.Front()
i++
} else {
prevElem = prevElem.Next()

View File

@ -415,7 +415,10 @@ func (m *Migrate) RemoveVersions(versions []uint64) error {
}
for _, version := range versions {
m.databaseDrv.RemoveVersion(int64(version))
err = m.databaseDrv.RemoveVersion(int64(version))
if err != nil {
return err
}
}
return m.unlockErr(nil)
}
@ -467,7 +470,11 @@ func (m *Migrate) Squash(v1 uint64, v2 int64) (vs []int64, us []byte, ds []byte,
dataUp := make(chan interface{}, m.PrefetchMigrations)
dataDown := make(chan interface{}, m.PrefetchMigrations)
retVersions := make(chan int64, m.PrefetchMigrations)
go m.squashMigrations(retUp, retDown, dataUp, dataDown, retVersions)
go func() {
if err := m.squashMigrations(retUp, retDown, dataUp, dataDown, retVersions); err != nil {
m.Logger.Error(err)
}
}()
// make a chan for errors
errChn := make(chan error, 2)
@ -752,7 +759,11 @@ func (m *Migrate) squashUp(from uint64, to int64, ret chan<- interface{}) {
// write the body of the migration to reader
// the migr instance sent via the channel will then start reading
// from it
go migr.Buffer()
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
count++
}
@ -791,7 +802,11 @@ func (m *Migrate) squashUp(from uint64, to int64, ret chan<- interface{}) {
}
ret <- migr
go migr.Buffer()
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
if int64(next) == to {
return
}
@ -832,7 +847,11 @@ func (m *Migrate) squashDown(v1 uint64, v2 int64, ret chan<- interface{}) {
return
}
ret <- migr
go migr.Buffer()
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
return
} else if err != nil {
ret <- err
@ -848,7 +867,11 @@ func (m *Migrate) squashDown(v1 uint64, v2 int64, ret chan<- interface{}) {
}
ret <- migr
go migr.Buffer()
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
} else {
m.Logger.Warnf("%v", err)
}
@ -891,7 +914,12 @@ func (m *Migrate) read(version uint64, direction string, ret chan<- interface{},
}
ret <- migr
go migr.Buffer()
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
} else {
// it's going down
if m.stop() {
@ -918,7 +946,11 @@ func (m *Migrate) read(version uint64, direction string, ret chan<- interface{},
return
}
ret <- migr
go migr.Buffer()
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
return
} else if err != nil {
ret <- err
@ -932,7 +964,11 @@ func (m *Migrate) read(version uint64, direction string, ret chan<- interface{},
}
ret <- migr
go migr.Buffer()
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
}
}
@ -1000,7 +1036,11 @@ func (m *Migrate) readUp(limit int64, ret chan<- interface{}, bar *pb.ProgressBa
return
}
ret <- migr
go migr.Buffer()
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
from = int64(firstVersion)
count++
@ -1059,7 +1099,11 @@ func (m *Migrate) readUp(limit int64, ret chan<- interface{}, bar *pb.ProgressBa
}
ret <- migr
go migr.Buffer()
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
from = int64(next)
count++
@ -1131,7 +1175,11 @@ func (m *Migrate) readDown(limit int64, ret chan<- interface{}, bar *pb.Progress
return
}
ret <- migr
go migr.Buffer()
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
count++
}
@ -1148,7 +1196,11 @@ func (m *Migrate) readDown(limit int64, ret chan<- interface{}, bar *pb.Progress
}
ret <- migr
go migr.Buffer()
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
from = int64(prev.Version)
count++
}
@ -1169,27 +1221,26 @@ func (m *Migrate) runMigrations(ret <-chan interface{}, bar *pb.ProgressBar) err
return nil
}
switch r.(type) {
switch r := r.(type) {
case error:
// Clear Migration query
m.databaseDrv.ResetQuery()
return r.(error)
return r
case *Migration:
migr := r.(*Migration)
if migr.Body != nil {
if r.Body != nil {
if !m.SkipExecution {
m.Logger.Debugf("applying migration: %s", migr.FileName)
if err := m.databaseDrv.Run(migr.BufferedBody, migr.FileType, migr.FileName); err != nil {
m.Logger.Debugf("applying migration: %s", r.FileName)
if err := m.databaseDrv.Run(r.BufferedBody, r.FileType, r.FileName); err != nil {
return err
}
}
incrementProgressBar(bar)
version := int64(migr.Version)
version := int64(r.Version)
// Insert Version number into the table
if err := m.databaseDrv.SetVersion(version, false); err != nil {
return err
}
if version != migr.TargetVersion {
if version != r.TargetVersion {
// Delete Version number from the table
if err := m.databaseDrv.RemoveVersion(version); err != nil {
return err
@ -1209,15 +1260,14 @@ func (m *Migrate) runDryRun(ret <-chan interface{}) error {
return nil
}
switch r.(type) {
switch r := r.(type) {
case error:
return r.(error)
return r
case *Migration:
migr := r.(*Migration)
if migr.Body != nil {
version := int64(migr.Version)
if r.Body != nil {
version := int64(r.Version)
if version != lastInsertVersion {
migrations = append(migrations, migr)
migrations = append(migrations, r)
lastInsertVersion = version
}
}
@ -1236,7 +1286,7 @@ func (m *Migrate) squashMigrations(retUp <-chan interface{}, retDown <-chan inte
var err error
squashList := database.CustomList{
list.New(),
List: list.New(),
}
defer func() {
@ -1249,21 +1299,20 @@ func (m *Migrate) squashMigrations(retUp <-chan interface{}, retDown <-chan inte
if m.stop() {
return
}
switch r.(type) {
switch r := r.(type) {
case error:
dataUp <- r.(error)
dataUp <- r
case *Migration:
migr := r.(*Migration)
if migr.Body != nil {
if r.Body != nil {
// read migration body and push it to squash list
if err = m.databaseDrv.PushToList(migr.BufferedBody, migr.FileType, &squashList); err != nil {
if err = m.databaseDrv.PushToList(r.BufferedBody, r.FileType, &squashList); err != nil {
dataUp <- err
return
}
}
version := int64(migr.Version)
if version == migr.TargetVersion && version != latestVersion {
version := int64(r.Version)
if version == r.TargetVersion && version != latestVersion {
versions <- version
latestVersion = version
}
@ -1276,7 +1325,7 @@ func (m *Migrate) squashMigrations(retUp <-chan interface{}, retDown <-chan inte
var err error
squashList := database.CustomList{
list.New(),
List: list.New(),
}
defer func() {
@ -1289,13 +1338,12 @@ func (m *Migrate) squashMigrations(retUp <-chan interface{}, retDown <-chan inte
if m.stop() {
return
}
switch r.(type) {
switch r := r.(type) {
case error:
dataDown <- r.(error)
dataDown <- r
case *Migration:
migr := r.(*Migration)
if migr.Body != nil {
if err = m.databaseDrv.PushToList(migr.BufferedBody, migr.FileType, &squashList); err != nil {
if r.Body != nil {
if err = m.databaseDrv.PushToList(r.BufferedBody, r.FileType, &squashList); err != nil {
dataDown <- err
return
}
@ -1428,13 +1476,6 @@ func (m *Migrate) newMigration(version uint64, targetVersion int64) (*Migration,
}
}
}
if m.PrefetchMigrations > 0 && migr.Body != nil {
//m.logVerbosePrintf("Start buffering %v\n", migr.LogString())
} else {
//m.logVerbosePrintf("Scheduled %v\n", migr.LogString())
}
return migr, nil
}
@ -1496,7 +1537,6 @@ func (m *Migrate) lock() error {
} else {
errchan <- nil
}
return
}()
// wait until we either recieve ErrLockTimeout or error from Lock operation
@ -1637,7 +1677,11 @@ func (m *Migrate) readUpFromVersion(from int64, to int64, ret chan<- interface{}
return
}
ret <- migr
go migr.Buffer()
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
from = int64(firstVersion)
continue
@ -1670,7 +1714,11 @@ func (m *Migrate) readUpFromVersion(from int64, to int64, ret chan<- interface{}
}
ret <- migr
go migr.Buffer()
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
from = int64(next)
}
@ -1735,7 +1783,11 @@ func (m *Migrate) readDownFromVersion(from int64, to int64, ret chan<- interface
}
ret <- migr
go migr.Buffer()
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
from = database.NilVersion
continue
@ -1754,7 +1806,11 @@ func (m *Migrate) readDownFromVersion(from int64, to int64, ret chan<- interface
}
ret <- migr
go migr.Buffer()
go func(migr *Migration, m *Migrate) {
if err := migr.Buffer(); err != nil {
m.Logger.Error(err)
}
}(migr, m)
from = int64(prev.Version)
}
}

View File

@ -121,7 +121,9 @@ func (m *Migration) Buffer() error {
// start reading from body, peek won't move the read pointer though
// poor man's solution?
b.Peek(int(m.BufferSize))
if _, err := b.Peek(int(m.BufferSize)); err != nil && err != io.EOF {
return err
}
m.FinishedBuffering = time.Now()

View File

@ -93,7 +93,12 @@ func TestOpenWithRelativePath(t *testing.T) {
if err != nil {
t.Fatal(err)
}
defer os.Chdir(wd) // rescue working dir after we are done
defer func() {
err = os.Chdir(wd) // rescue working dir after we are done
if err != nil {
t.Fatal(err)
}
}()
if err := os.Chdir(tmpDir); err != nil {
t.Fatal(err)

View File

@ -120,8 +120,7 @@ func (i *Migrations) Next(version uint64) (nextVersion uint64, ok bool) {
}
func (i *Migrations) GetDirections(version uint64) map[Direction]bool {
var directions map[Direction]bool
directions = map[Direction]bool{
var directions = map[Direction]bool{
Down: false,
Up: false,
MetaDown: false,

View File

@ -46,7 +46,6 @@ func (s *Stub) Scan() error {
}
func (s *Stub) DefaultParser(p source.Parser) {
return
}
func (s *Stub) First() (version uint64, err error) {

View File

@ -63,16 +63,6 @@ func (i *Status) Read(version uint64) (m *MigrationStatus, ok bool) {
return nil, false
}
func (i *Status) findPos(version uint64) int {
if len(i.Index) > 0 {
ix := i.Index.Search(version)
if ix < len(i.Index) && i.Index[ix] == version {
return ix
}
}
return -1
}
type uint64Slice []uint64
func (s uint64Slice) Len() int {

View File

@ -25,7 +25,6 @@ type ServeOpts struct {
SignalChanAPIServer chan os.Signal
SignalChanConsoleServer chan os.Signal
WG sync.WaitGroup
}
// Server console and API Server
@ -52,7 +51,7 @@ func Serve(opts *ServeOpts) error {
}()
// Create WaitGroup for running 2 servers
wg := opts.WG
wg := new(sync.WaitGroup)
wg.Add(1)
go func() {
if err := apiHTTPServer.ListenAndServe(); err != nil {

View File

@ -112,8 +112,6 @@ func TestProjectMetadataOps_Parse(t *testing.T) {
defer teardown()
type fields struct {
projectDirectory string
adminSecret string
endpointString string
}
tests := []struct {
name string
@ -196,8 +194,6 @@ func TestProjectMetadataOps_Diff(t *testing.T) {
defer teardown()
type fields struct {
projectDirectory string
adminSecret string
endpointString string
}
tests := []struct {
name string
@ -245,7 +241,6 @@ func TestProjectMetadata_Reload(t *testing.T) {
defer teardown()
type fields struct {
projectDirectory string
adminSecret string
endpointString string
}
tests := []struct {

View File

@ -185,9 +185,9 @@ func detectMIMEType(at io.ReaderAt) (string, error) {
if err != nil && err != io.EOF {
return "", errors.Wrap(err, "failed to read first 512 bytes")
}
if n < 512 {
//klog.V(5).Infof("Did only read %d of 512 bytes to determine the file type", n)
}
// if n < 512 {
//klog.V(5).Infof("Did only read %d of 512 bytes to determine the file type", n)
// }
// Cut off mime extra info beginning with ';' i.e:
// "text/plain; charset=utf-8" should result in "text/plain".

View File

@ -24,7 +24,7 @@ func (c *Config) findPluginManifestFiles(indexDir string) ([]string, error) {
fs := afero.Afero{
Fs: afero.NewOsFs(),
}
fs.Walk(indexDir, func(path string, info os.FileInfo, err error) error {
err := fs.Walk(indexDir, func(path string, info os.FileInfo, err error) error {
if info == nil {
if err != nil {
return err
@ -36,6 +36,9 @@ func (c *Config) findPluginManifestFiles(indexDir string) ([]string, error) {
}
return nil
})
if err != nil {
return nil, err
}
return out, nil
}

View File

@ -47,7 +47,10 @@ func CreateSeedFile(fs afero.Fs, opts CreateSeedOpts) (*string, error) {
defer file.Close()
r := bufio.NewReader(opts.Data)
io.Copy(file, r)
_, err = io.Copy(file, r)
if err != nil {
return nil, err
}
return &fullFilePath, nil
}

View File

@ -74,6 +74,7 @@ SELECT pg_catalog.setval('public.authors_id_seq', 1, false);
_, err = q.PGRunSQL(hasura.PGRunSQLInput{
SQL: string(b),
})
require.NoError(t, err)
},
},
}

View File

@ -90,7 +90,11 @@ func downloadAsset(url, fileName, filePath string) (*os.File, error) {
// HasUpdate tells us if there is a new stable or prerelease update available.
func HasUpdate(currentVersion *semver.Version, timeFile string) (bool, *semver.Version, bool, *semver.Version, error) {
if timeFile != "" {
defer writeTimeToFile(timeFile, time.Now().UTC())
defer func() {
if err := writeTimeToFile(timeFile, time.Now().UTC()); err != nil {
fmt.Fprintln(os.Stderr, "failed writing last update check time: ", err)
}
}()
}
latestVersion, preReleaseVersion, err := getLatestVersion()

View File

@ -2,6 +2,7 @@ package util
import (
"fmt"
"os"
"strings"
"github.com/spf13/pflag"
@ -16,7 +17,10 @@ var ViperEnvReplacer = strings.NewReplacer(".", "_")
// BindPFlag - binds flag with viper along with env usage
func BindPFlag(v *viper.Viper, key string, f *pflag.Flag) {
v.BindPFlag(key, f)
err := v.BindPFlag(key, f)
if err != nil {
fmt.Fprintf(os.Stderr, "viper failed binding pflag: %v with error: %v \n", key, err)
}
key = ViperEnvReplacer.Replace(key)
key = strings.ToUpper(ViperEnvPrefix + "_" + key)
f.Usage = f.Usage + fmt.Sprintf(` (env "%s")`, key)

View File

@ -2,6 +2,7 @@ package util
import (
"archive/zip"
"fmt"
"io"
"os"
"path/filepath"
@ -24,7 +25,9 @@ func Unzip(archive, target string) error {
for _, file := range reader.File {
path := filepath.Join(target, file.Name)
if file.FileInfo().IsDir() {
os.MkdirAll(path, file.Mode())
if err = os.MkdirAll(path, file.Mode()); err != nil {
return fmt.Errorf("error while creating directory and it's parent directories: %w", err)
}
continue
}