From a0835d920f6b7a20a004fe0d5381c75161b66c9b Mon Sep 17 00:00:00 2001 From: Andrew Slotin Date: Fri, 18 Aug 2023 14:27:40 +0200 Subject: [PATCH 01/15] Add basic init command --- cmd/init.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 cmd/init.go diff --git a/cmd/init.go b/cmd/init.go new file mode 100644 index 00000000000..bdd934af91d --- /dev/null +++ b/cmd/init.go @@ -0,0 +1,33 @@ +package cmd + +import ( + "fmt" + + "github.com/spf13/cobra" + "go.k6.io/k6/cmd/state" +) + +func getCmdInit(gs *state.GlobalState) *cobra.Command { + exampleText := getExampleText(gs, ` + # Create a minimal k6 script in the current directory. By default, k6 creates script.js. + {{.}} init + + # Create a minimal k6 script in the current directory and store it in test.js + {{.}} init test.js`) + + return &cobra.Command{ + Use: "init", + Short: "Initialize a new k6 script.", + Long: `Initialize a new k6 script. + +This command will create a minimal k6 script in the current directory and +store it in the file specified by the first argument. If no argument is +provided, the script will be stored in script.js. + +This command will not overwrite existing files.`, + Example: exampleText, + Run: func(cmd *cobra.Command, args []string) { + fmt.Println("init called") + }, + } +} From 52cd7bbf5d07a49b92f1c8df546c59656eaaa47a Mon Sep 17 00:00:00 2001 From: Andrew Slotin Date: Fri, 18 Aug 2023 14:27:56 +0200 Subject: [PATCH 02/15] Include k6 init into the list of supported commands --- cmd/root.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/root.go b/cmd/root.go index c23605b9370..aa68577f410 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -59,7 +59,7 @@ func newRootCommand(gs *state.GlobalState) *rootCommand { subCommands := []func(*state.GlobalState) *cobra.Command{ getCmdArchive, getCmdCloud, getCmdInspect, getCmdLogin, getCmdPause, getCmdResume, getCmdScale, getCmdRun, - getCmdStats, getCmdStatus, getCmdVersion, + getCmdStats, getCmdStatus, getCmdVersion, getCmdInit, } for _, sc := range subCommands { From a6cd4eb1af39e6262b70c6ce992638b9d18b3e8e Mon Sep 17 00:00:00 2001 From: Andrew Slotin Date: Fri, 18 Aug 2023 14:40:48 +0200 Subject: [PATCH 03/15] Check whether file exists before initializing it --- cmd/init.go | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/cmd/init.go b/cmd/init.go index bdd934af91d..113709cdb9f 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -1,13 +1,40 @@ package cmd import ( - "fmt" - "github.com/spf13/cobra" "go.k6.io/k6/cmd/state" + "go.k6.io/k6/lib/fsext" ) +const defaultNewScriptName = "script.js" + +// initCmd represents the `k6 init` command +type initCmd struct { + gs *state.GlobalState +} + +func (c *initCmd) run(cmd *cobra.Command, args []string) error { + target := defaultNewScriptName + if len(args) > 0 { + target = args[0] + } + + fileExists, err := fsext.Exists(c.gs.FS, target) + if err != nil { + return err + } + + if fileExists { + c.gs.Logger.Errorf("%s already exists", target) + return err + } + + return nil +} + func getCmdInit(gs *state.GlobalState) *cobra.Command { + c := &initCmd{gs: gs} + exampleText := getExampleText(gs, ` # Create a minimal k6 script in the current directory. By default, k6 creates script.js. {{.}} init @@ -26,8 +53,6 @@ provided, the script will be stored in script.js. This command will not overwrite existing files.`, Example: exampleText, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("init called") - }, + RunE: c.run, } } From f4f4ac2821a2688919a70904a595700a2dd785ed Mon Sep 17 00:00:00 2001 From: Andrew Slotin Date: Fri, 18 Aug 2023 14:46:55 +0200 Subject: [PATCH 04/15] Create a simple test script when running k6 init --- .gitignore | 1 + cmd/init.go | 28 +++++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index da105bfff55..e9f51db1f84 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ *.syso .idea *.DS_Store +script.js /versioninfo.json diff --git a/cmd/init.go b/cmd/init.go index 113709cdb9f..60a2cc2e7b5 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -1,12 +1,24 @@ package cmd import ( + "fmt" + "github.com/spf13/cobra" "go.k6.io/k6/cmd/state" "go.k6.io/k6/lib/fsext" ) -const defaultNewScriptName = "script.js" +const ( + defaultNewScriptName = "script.js" + defaultNewScript = `import http from 'k6/http'; +import { sleep } from 'k6'; + +export default function () { + http.get('https://grafana.com'); + sleep(1); +} +` +) // initCmd represents the `k6 init` command type initCmd struct { @@ -29,6 +41,20 @@ func (c *initCmd) run(cmd *cobra.Command, args []string) error { return err } + fd, err := c.gs.FS.Create(target) + if err != nil { + return err + } + defer fd.Close() + + _, err = fd.Write([]byte(defaultNewScript)) + if err != nil { + return err + } + + printToStdout(c.gs, fmt.Sprintf("Initialized a new k6 test script in %s.\n", target)) + printToStdout(c.gs, fmt.Sprintf("You can now execute it by running `%s run %s`.\n", c.gs.BinaryName, target)) + return nil } From dc611bcc3efa512f8ae6b0514512d5d75b1c5df4 Mon Sep 17 00:00:00 2001 From: Andrew Slotin Date: Fri, 18 Aug 2023 15:16:52 +0200 Subject: [PATCH 05/15] Limit number of args accepted by k6 init --- cmd/init.go | 1 + 1 file changed, 1 insertion(+) diff --git a/cmd/init.go b/cmd/init.go index 60a2cc2e7b5..813c0cf3daf 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -79,6 +79,7 @@ provided, the script will be stored in script.js. This command will not overwrite existing files.`, Example: exampleText, + Args: cobra.MaximumNArgs(1), RunE: c.run, } } From 0d9893b6d85d4c08e6ea8b7692b72ff659dead79 Mon Sep 17 00:00:00 2001 From: Andrew Slotin Date: Fri, 18 Aug 2023 15:28:08 +0200 Subject: [PATCH 06/15] Add a flag to force overwrite existing files with k6 init --- cmd/init.go | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/cmd/init.go b/cmd/init.go index 813c0cf3daf..637bf0aff52 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/spf13/cobra" + "github.com/spf13/pflag" "go.k6.io/k6/cmd/state" "go.k6.io/k6/lib/fsext" ) @@ -22,7 +23,16 @@ export default function () { // initCmd represents the `k6 init` command type initCmd struct { - gs *state.GlobalState + gs *state.GlobalState + overwriteFiles bool +} + +func (c *initCmd) flagSet() *pflag.FlagSet { + flags := pflag.NewFlagSet("", pflag.ContinueOnError) + flags.SortFlags = false + flags.BoolVarP(&c.overwriteFiles, "force", "f", false, "Overwrite existing files") + + return flags } func (c *initCmd) run(cmd *cobra.Command, args []string) error { @@ -36,7 +46,7 @@ func (c *initCmd) run(cmd *cobra.Command, args []string) error { return err } - if fileExists { + if fileExists && !c.overwriteFiles { c.gs.Logger.Errorf("%s already exists", target) return err } @@ -66,9 +76,12 @@ func getCmdInit(gs *state.GlobalState) *cobra.Command { {{.}} init # Create a minimal k6 script in the current directory and store it in test.js - {{.}} init test.js`) + {{.}} init test.js - return &cobra.Command{ + # Overwrite existing test.js with a minimal k6 script + {{.}} init -f test.js`[1:]) + + initCmd := &cobra.Command{ Use: "init", Short: "Initialize a new k6 script.", Long: `Initialize a new k6 script. @@ -82,4 +95,7 @@ This command will not overwrite existing files.`, Args: cobra.MaximumNArgs(1), RunE: c.run, } + initCmd.Flags().AddFlagSet(c.flagSet()) + + return initCmd } From 80c0464a7340e9702367da971270a8d978a634d9 Mon Sep 17 00:00:00 2001 From: Andrew Slotin Date: Fri, 13 Oct 2023 15:01:50 +0200 Subject: [PATCH 07/15] Add sections with cloud and browser options to the k6 init script --- cmd/init.go | 72 ++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 63 insertions(+), 9 deletions(-) diff --git a/cmd/init.go b/cmd/init.go index 637bf0aff52..698a70105c8 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -2,6 +2,8 @@ package cmd import ( "fmt" + "path" + "text/template" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -9,17 +11,68 @@ import ( "go.k6.io/k6/lib/fsext" ) -const ( - defaultNewScriptName = "script.js" - defaultNewScript = `import http from 'k6/http'; +const defaultNewScriptName = "script.js" + +var defaultNewScriptTemplate = template.Must(template.New("init").Parse(`import http from 'k6/http'; import { sleep } from 'k6'; -export default function () { - http.get('https://grafana.com'); +export const options = { + // A number specifying the number of VUs to run concurrently. + vus: 10, + // A string specifying the total duration of the test run. + duration: '30s', + + // The following section contains configuration options for execution of this + // test script in Grafana Cloud. + // + // See https://grafana.com/docs/grafana-cloud/k6/get-started/run-cloud-tests-from-the-cli/ + // to learn about authoring and running k6 test scripts in Grafana Cloud. + // + // cloud: { + // // The ID of the project to which the test is assigned in the k6 Cloud UI. + // // By default tests are executed in default project. + // projectID: "", + // // The name of the test in the k6 Cloud UI. + // // Test runs with the same name will be grouped. + // name: "{{ .ScriptName }}" + // }, + + // Uncomment this section to enable the use of Browser API in your tests. + // + // See https://k6.io/docs/using-k6-browser/running-browser-tests/ to learn more + // about using Browser API in your test scripts. + // + // scenarios: { + // // The scenario name appears in the result summary, tags, and so on. + // SCENARIO NAME: { + // // Mandatory parameter for browser-based tests. + // executor: 'shared-iterations', + // options: { + // browser: { + // // This is a mandatory parameter that instructs k6 to launch and + // // connect to a chromium-based browser, and use it to run UI-based + // // tests. + // type: 'chromium', + // }, + // }, + // }, + // } +}; + +// The function that defines VU logic. +// +// See https://k6.io/docs/examples/tutorials/get-started-with-k6/ to learn more +// about authoring k6 scripts. +// +export default function() { + http.get('http://test.k6.io'); sleep(1); } -` -) +`)) + +type initScriptTemplateArgs struct { + ScriptName string +} // initCmd represents the `k6 init` command type initCmd struct { @@ -57,8 +110,9 @@ func (c *initCmd) run(cmd *cobra.Command, args []string) error { } defer fd.Close() - _, err = fd.Write([]byte(defaultNewScript)) - if err != nil { + if err := defaultNewScriptTemplate.Execute(fd, initScriptTemplateArgs{ + ScriptName: path.Base(target), + }); err != nil { return err } From 448641326020a26a9b7a4fad5919c2f6c5c025dd Mon Sep 17 00:00:00 2001 From: Andrew Slotin Date: Fri, 13 Oct 2023 15:52:39 +0200 Subject: [PATCH 08/15] Add tests for k6 init command --- cmd/init.go | 13 +++++-- cmd/init_test.go | 97 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 106 insertions(+), 4 deletions(-) create mode 100644 cmd/init_test.go diff --git a/cmd/init.go b/cmd/init.go index 698a70105c8..4cee0fe748a 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -1,6 +1,7 @@ package cmd import ( + "errors" "fmt" "path" "text/template" @@ -13,7 +14,10 @@ import ( const defaultNewScriptName = "script.js" -var defaultNewScriptTemplate = template.Must(template.New("init").Parse(`import http from 'k6/http'; +//nolint:gochecknoglobals +var ( + errFileExists = errors.New("file already exists") + defaultNewScriptTemplate = template.Must(template.New("init").Parse(`import http from 'k6/http'; import { sleep } from 'k6'; export const options = { @@ -69,6 +73,7 @@ export default function() { sleep(1); } `)) +) type initScriptTemplateArgs struct { ScriptName string @@ -88,7 +93,7 @@ func (c *initCmd) flagSet() *pflag.FlagSet { return flags } -func (c *initCmd) run(cmd *cobra.Command, args []string) error { +func (c *initCmd) run(cmd *cobra.Command, args []string) error { //nolint:revive target := defaultNewScriptName if len(args) > 0 { target = args[0] @@ -101,14 +106,14 @@ func (c *initCmd) run(cmd *cobra.Command, args []string) error { if fileExists && !c.overwriteFiles { c.gs.Logger.Errorf("%s already exists", target) - return err + return errFileExists } fd, err := c.gs.FS.Create(target) if err != nil { return err } - defer fd.Close() + defer fd.Close() //nolint:errcheck if err := defaultNewScriptTemplate.Execute(fd, initScriptTemplateArgs{ ScriptName: path.Base(target), diff --git a/cmd/init_test.go b/cmd/init_test.go new file mode 100644 index 00000000000..da34f6b26e0 --- /dev/null +++ b/cmd/init_test.go @@ -0,0 +1,97 @@ +package cmd + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.k6.io/k6/cmd/tests" + "go.k6.io/k6/lib/fsext" +) + +func TestInitScript(t *testing.T) { + t.Parallel() + + testCases := []struct { + name string + scriptNameArg string + expectedCloudName string + expectedFilePath string + }{ + { + name: "default script name", + expectedCloudName: "script.js", + expectedFilePath: defaultNewScriptName, + }, + { + name: "user-specified script name", + scriptNameArg: "mytest.js", + expectedCloudName: "mytest.js", + expectedFilePath: "mytest.js", + }, + { + name: "script outside of current working directory", + scriptNameArg: "../mytest.js", + expectedCloudName: "mytest.js", + expectedFilePath: "../mytest.js", + }, + } + + for _, testCase := range testCases { + testCase := testCase + t.Run(testCase.name, func(t *testing.T) { + t.Parallel() + + ts := tests.NewGlobalTestState(t) + ts.CmdArgs = []string{"k6", "init"} + if testCase.scriptNameArg != "" { + ts.CmdArgs = append(ts.CmdArgs, testCase.scriptNameArg) + } + + newRootCommand(ts.GlobalState).execute() + + data, err := fsext.ReadFile(ts.FS, testCase.expectedFilePath) + require.NoError(t, err) + + jsData := string(data) + assert.Contains(t, jsData, "export const options = {") + assert.Contains(t, jsData, fmt.Sprintf(`name: "%s"`, testCase.expectedCloudName)) + assert.Contains(t, jsData, "export default function() {") + }) + } +} + +func TestInitScript_FileExists_NoOverwrite(t *testing.T) { + t.Parallel() + + ts := tests.NewGlobalTestState(t) + require.NoError(t, fsext.WriteFile(ts.FS, defaultNewScriptName, []byte("untouched"), 0o644)) + + ts.CmdArgs = []string{"k6", "init"} + ts.ExpectedExitCode = -1 + + newRootCommand(ts.GlobalState).execute() + + data, err := fsext.ReadFile(ts.FS, defaultNewScriptName) + require.NoError(t, err) + + assert.Contains(t, string(data), "untouched") +} + +func TestInitScript_FileExists_Overwrite(t *testing.T) { + t.Parallel() + + ts := tests.NewGlobalTestState(t) + require.NoError(t, fsext.WriteFile(ts.FS, defaultNewScriptName, []byte("untouched"), 0o644)) + + ts.CmdArgs = []string{"k6", "init", "-f"} + + newRootCommand(ts.GlobalState).execute() + + data, err := fsext.ReadFile(ts.FS, defaultNewScriptName) + require.NoError(t, err) + + assert.Contains(t, string(data), "export const options = {") + assert.Contains(t, string(data), "export default function() {") +} From f864d0160598779a1e63e804fc34751f59939945 Mon Sep 17 00:00:00 2001 From: Andrey Slotin Date: Mon, 16 Oct 2023 18:05:49 +0200 Subject: [PATCH 09/15] Apply suggestions from code review Co-authored-by: Ivan <2103732+codebien@users.noreply.github.com> --- cmd/init.go | 22 +++++++++------------- cmd/root.go | 4 ++-- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/cmd/init.go b/cmd/init.go index 4cee0fe748a..e7bab7f5f42 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -1,7 +1,6 @@ package cmd import ( - "errors" "fmt" "path" "text/template" @@ -15,9 +14,7 @@ import ( const defaultNewScriptName = "script.js" //nolint:gochecknoglobals -var ( - errFileExists = errors.New("file already exists") - defaultNewScriptTemplate = template.Must(template.New("init").Parse(`import http from 'k6/http'; +var defaultNewScriptTemplate = template.Must(template.New("init").Parse(`import http from 'k6/http'; import { sleep } from 'k6'; export const options = { @@ -30,7 +27,7 @@ export const options = { // test script in Grafana Cloud. // // See https://grafana.com/docs/grafana-cloud/k6/get-started/run-cloud-tests-from-the-cli/ - // to learn about authoring and running k6 test scripts in Grafana Cloud. + // to learn about authoring and running k6 test scripts in Grafana k6 Cloud. // // cloud: { // // The ID of the project to which the test is assigned in the k6 Cloud UI. @@ -69,11 +66,10 @@ export const options = { // about authoring k6 scripts. // export default function() { - http.get('http://test.k6.io'); + http.get('https://test.k6.io'); sleep(1); } `)) -) type initScriptTemplateArgs struct { ScriptName string @@ -105,15 +101,16 @@ func (c *initCmd) run(cmd *cobra.Command, args []string) error { //nolint:revive } if fileExists && !c.overwriteFiles { - c.gs.Logger.Errorf("%s already exists", target) - return errFileExists + return fmt.Errorf("%s already exists, please use the `--force` flag if you want overwrite it", target) } fd, err := c.gs.FS.Create(target) if err != nil { return err } - defer fd.Close() //nolint:errcheck + defer func() { + _ = fd.Close() // we may think to check the error and log + }() if err := defaultNewScriptTemplate.Execute(fd, initScriptTemplateArgs{ ScriptName: path.Base(target), @@ -121,8 +118,7 @@ func (c *initCmd) run(cmd *cobra.Command, args []string) error { //nolint:revive return err } - printToStdout(c.gs, fmt.Sprintf("Initialized a new k6 test script in %s.\n", target)) - printToStdout(c.gs, fmt.Sprintf("You can now execute it by running `%s run %s`.\n", c.gs.BinaryName, target)) + printToStdout(c.gs, fmt.Sprintf("Initialized a new k6 test script in %s. You can now execute it by running `%s run %s`.\n", target, c.gs.BinaryName, target)) return nil } @@ -142,7 +138,7 @@ func getCmdInit(gs *state.GlobalState) *cobra.Command { initCmd := &cobra.Command{ Use: "init", - Short: "Initialize a new k6 script.", + Short: "Initialize a new k6 script", Long: `Initialize a new k6 script. This command will create a minimal k6 script in the current directory and diff --git a/cmd/root.go b/cmd/root.go index aa68577f410..365fd469b87 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -57,9 +57,9 @@ func newRootCommand(gs *state.GlobalState) *rootCommand { rootCmd.SetIn(gs.Stdin) subCommands := []func(*state.GlobalState) *cobra.Command{ - getCmdArchive, getCmdCloud, getCmdInspect, + getCmdArchive, getCmdCloud, getCmdInit, getCmdInspect, getCmdLogin, getCmdPause, getCmdResume, getCmdScale, getCmdRun, - getCmdStats, getCmdStatus, getCmdVersion, getCmdInit, + getCmdStats, getCmdStatus, getCmdVersion, } for _, sc := range subCommands { From 70018260edd612822e55ebc6dce9243919c3af0c Mon Sep 17 00:00:00 2001 From: Andrew Slotin Date: Mon, 16 Oct 2023 18:29:09 +0200 Subject: [PATCH 10/15] Highlight the path to the script created with `k6 init` --- cmd/init.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/cmd/init.go b/cmd/init.go index e7bab7f5f42..a74be18d057 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -5,6 +5,7 @@ import ( "path" "text/template" + "github.com/fatih/color" "github.com/spf13/cobra" "github.com/spf13/pflag" "go.k6.io/k6/cmd/state" @@ -118,7 +119,13 @@ func (c *initCmd) run(cmd *cobra.Command, args []string) error { //nolint:revive return err } - printToStdout(c.gs, fmt.Sprintf("Initialized a new k6 test script in %s. You can now execute it by running `%s run %s`.\n", target, c.gs.BinaryName, target)) + valueColor := getColor(c.gs.Flags.NoColor || !c.gs.Stdout.IsTTY, color.Bold) + printToStdout(c.gs, fmt.Sprintf( + "Initialized a new k6 test script in %s. You can now execute it by running `%s run %s`.\n", + valueColor.Sprint(target), + c.gs.BinaryName, + target, + )) return nil } From 97e03e2376fd282960055fe3f6af35599ced509d Mon Sep 17 00:00:00 2001 From: Andrey Slotin Date: Wed, 18 Oct 2023 14:58:27 +0200 Subject: [PATCH 11/15] Add a comment explaining script.js in the .gitignore Co-authored-by: Ivan <2103732+codebien@users.noreply.github.com> --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index e9f51db1f84..3daee534bd1 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ *.syso .idea *.DS_Store +# Excluding as it is the file generated by the k6 init command script.js /versioninfo.json From 54db5f986d644d4a32e45af2bba2c0bc7632dab5 Mon Sep 17 00:00:00 2001 From: Andrew Slotin Date: Wed, 18 Oct 2023 17:48:00 +0200 Subject: [PATCH 12/15] Ensure `k6 init` creates a valid JS script when all blocks are uncommented --- cmd/init.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/cmd/init.go b/cmd/init.go index a74be18d057..0b85337b8dd 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -46,8 +46,12 @@ export const options = { // // scenarios: { // // The scenario name appears in the result summary, tags, and so on. - // SCENARIO NAME: { - // // Mandatory parameter for browser-based tests. + // // You can give the scenario any name, as long as each name in the script is unique. + // ui: { + // // Executor is a mandatory parameter for browser-based tests. + // // Shared iterations in this case tells k6 to reuse VUs to execute iterations. + // // + // // See https://k6.io/docs/using-k6/scenarios/executors/ for other executor types. // executor: 'shared-iterations', // options: { // browser: { From 5c11c2903629180a1927c14f5e414ded3a88114c Mon Sep 17 00:00:00 2001 From: Andrew Slotin Date: Wed, 18 Oct 2023 18:08:47 +0200 Subject: [PATCH 13/15] Use options.ext.loadimpact to provide cloud config in a new script --- cmd/init.go | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/cmd/init.go b/cmd/init.go index 0b85337b8dd..175c2a2d6f0 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -30,13 +30,15 @@ export const options = { // See https://grafana.com/docs/grafana-cloud/k6/get-started/run-cloud-tests-from-the-cli/ // to learn about authoring and running k6 test scripts in Grafana k6 Cloud. // - // cloud: { - // // The ID of the project to which the test is assigned in the k6 Cloud UI. - // // By default tests are executed in default project. - // projectID: "", - // // The name of the test in the k6 Cloud UI. - // // Test runs with the same name will be grouped. - // name: "{{ .ScriptName }}" + // ext: { + // loadimpact: { + // // The ID of the project to which the test is assigned in the k6 Cloud UI. + // // By default tests are executed in default project. + // projectID: "", + // // The name of the test in the k6 Cloud UI. + // // Test runs with the same name will be grouped. + // name: "{{ .ScriptName }}" + // } // }, // Uncomment this section to enable the use of Browser API in your tests. From 6b91c914906f65c8e5239b8c9c2c1cf51a579cb7 Mon Sep 17 00:00:00 2001 From: Andrew Slotin Date: Fri, 3 Nov 2023 12:18:30 +0100 Subject: [PATCH 14/15] Rename `k6 init` to `k6 new` --- cmd/{init.go => new.go} | 26 +++++++++++++------------- cmd/{init_test.go => new_test.go} | 12 ++++++------ cmd/root.go | 2 +- 3 files changed, 20 insertions(+), 20 deletions(-) rename cmd/{init.go => new.go} (88%) rename cmd/{init_test.go => new_test.go} (88%) diff --git a/cmd/init.go b/cmd/new.go similarity index 88% rename from cmd/init.go rename to cmd/new.go index 175c2a2d6f0..19d95c9483c 100644 --- a/cmd/init.go +++ b/cmd/new.go @@ -15,7 +15,7 @@ import ( const defaultNewScriptName = "script.js" //nolint:gochecknoglobals -var defaultNewScriptTemplate = template.Must(template.New("init").Parse(`import http from 'k6/http'; +var defaultNewScriptTemplate = template.Must(template.New("new").Parse(`import http from 'k6/http'; import { sleep } from 'k6'; export const options = { @@ -82,13 +82,13 @@ type initScriptTemplateArgs struct { ScriptName string } -// initCmd represents the `k6 init` command -type initCmd struct { +// newScriptCmd represents the `k6 new` command +type newScriptCmd struct { gs *state.GlobalState overwriteFiles bool } -func (c *initCmd) flagSet() *pflag.FlagSet { +func (c *newScriptCmd) flagSet() *pflag.FlagSet { flags := pflag.NewFlagSet("", pflag.ContinueOnError) flags.SortFlags = false flags.BoolVarP(&c.overwriteFiles, "force", "f", false, "Overwrite existing files") @@ -96,7 +96,7 @@ func (c *initCmd) flagSet() *pflag.FlagSet { return flags } -func (c *initCmd) run(cmd *cobra.Command, args []string) error { //nolint:revive +func (c *newScriptCmd) run(cmd *cobra.Command, args []string) error { //nolint:revive target := defaultNewScriptName if len(args) > 0 { target = args[0] @@ -136,23 +136,23 @@ func (c *initCmd) run(cmd *cobra.Command, args []string) error { //nolint:revive return nil } -func getCmdInit(gs *state.GlobalState) *cobra.Command { - c := &initCmd{gs: gs} +func getCmdNewScript(gs *state.GlobalState) *cobra.Command { + c := &newScriptCmd{gs: gs} exampleText := getExampleText(gs, ` # Create a minimal k6 script in the current directory. By default, k6 creates script.js. - {{.}} init + {{.}} new # Create a minimal k6 script in the current directory and store it in test.js - {{.}} init test.js + {{.}} new test.js # Overwrite existing test.js with a minimal k6 script - {{.}} init -f test.js`[1:]) + {{.}} new -f test.js`[1:]) initCmd := &cobra.Command{ - Use: "init", - Short: "Initialize a new k6 script", - Long: `Initialize a new k6 script. + Use: "new", + Short: "Create and initialize a new k6 script", + Long: `Create and initialize a new k6 script. This command will create a minimal k6 script in the current directory and store it in the file specified by the first argument. If no argument is diff --git a/cmd/init_test.go b/cmd/new_test.go similarity index 88% rename from cmd/init_test.go rename to cmd/new_test.go index da34f6b26e0..1b97cf38718 100644 --- a/cmd/init_test.go +++ b/cmd/new_test.go @@ -10,7 +10,7 @@ import ( "go.k6.io/k6/lib/fsext" ) -func TestInitScript(t *testing.T) { +func TestNewScriptCmd(t *testing.T) { t.Parallel() testCases := []struct { @@ -44,7 +44,7 @@ func TestInitScript(t *testing.T) { t.Parallel() ts := tests.NewGlobalTestState(t) - ts.CmdArgs = []string{"k6", "init"} + ts.CmdArgs = []string{"k6", "new"} if testCase.scriptNameArg != "" { ts.CmdArgs = append(ts.CmdArgs, testCase.scriptNameArg) } @@ -62,13 +62,13 @@ func TestInitScript(t *testing.T) { } } -func TestInitScript_FileExists_NoOverwrite(t *testing.T) { +func TestNewScriptCmd_FileExists_NoOverwrite(t *testing.T) { t.Parallel() ts := tests.NewGlobalTestState(t) require.NoError(t, fsext.WriteFile(ts.FS, defaultNewScriptName, []byte("untouched"), 0o644)) - ts.CmdArgs = []string{"k6", "init"} + ts.CmdArgs = []string{"k6", "new"} ts.ExpectedExitCode = -1 newRootCommand(ts.GlobalState).execute() @@ -79,13 +79,13 @@ func TestInitScript_FileExists_NoOverwrite(t *testing.T) { assert.Contains(t, string(data), "untouched") } -func TestInitScript_FileExists_Overwrite(t *testing.T) { +func TestNewScriptCmd_FileExists_Overwrite(t *testing.T) { t.Parallel() ts := tests.NewGlobalTestState(t) require.NoError(t, fsext.WriteFile(ts.FS, defaultNewScriptName, []byte("untouched"), 0o644)) - ts.CmdArgs = []string{"k6", "init", "-f"} + ts.CmdArgs = []string{"k6", "new", "-f"} newRootCommand(ts.GlobalState).execute() diff --git a/cmd/root.go b/cmd/root.go index 365fd469b87..6bf12711d89 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -57,7 +57,7 @@ func newRootCommand(gs *state.GlobalState) *rootCommand { rootCmd.SetIn(gs.Stdin) subCommands := []func(*state.GlobalState) *cobra.Command{ - getCmdArchive, getCmdCloud, getCmdInit, getCmdInspect, + getCmdArchive, getCmdCloud, getCmdNewScript, getCmdInspect, getCmdLogin, getCmdPause, getCmdResume, getCmdScale, getCmdRun, getCmdStats, getCmdStatus, getCmdVersion, } From 28c340306a12ae9d1cdc53dcb31cebd95d773ce3 Mon Sep 17 00:00:00 2001 From: Andrew Slotin Date: Fri, 3 Nov 2023 12:42:52 +0100 Subject: [PATCH 15/15] Replace references to k6.io/docs with Grafana docs in the new k6 script --- cmd/new.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cmd/new.go b/cmd/new.go index 19d95c9483c..518cd618be4 100644 --- a/cmd/new.go +++ b/cmd/new.go @@ -43,7 +43,7 @@ export const options = { // Uncomment this section to enable the use of Browser API in your tests. // - // See https://k6.io/docs/using-k6-browser/running-browser-tests/ to learn more + // See https://grafana.com/docs/k6/latest/using-k6-browser/running-browser-tests/ to learn more // about using Browser API in your test scripts. // // scenarios: { @@ -53,7 +53,7 @@ export const options = { // // Executor is a mandatory parameter for browser-based tests. // // Shared iterations in this case tells k6 to reuse VUs to execute iterations. // // - // // See https://k6.io/docs/using-k6/scenarios/executors/ for other executor types. + // // See https://grafana.com/docs/k6/latest/using-k6/scenarios/executors/ for other executor types. // executor: 'shared-iterations', // options: { // browser: { @@ -69,7 +69,7 @@ export const options = { // The function that defines VU logic. // -// See https://k6.io/docs/examples/tutorials/get-started-with-k6/ to learn more +// See https://grafana.com/docs/k6/latest/examples/get-started-with-k6/ to learn more // about authoring k6 scripts. // export default function() {