Skip to content

Commit

Permalink
pass context to own commands and profile runnner
Browse files Browse the repository at this point in the history
  • Loading branch information
creativeprojects committed Nov 1, 2023
1 parent f346571 commit 4144642
Show file tree
Hide file tree
Showing 18 changed files with 897 additions and 366 deletions.
54 changes: 27 additions & 27 deletions commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,12 @@ func getOwnCommands() []ownCommand {
}
}

func panicCommand(_ io.Writer, _ commandRequest) error {
func panicCommand(_ io.Writer, _ commandContext) error {
panic("you asked for it")
}

func completeCommand(output io.Writer, request commandRequest) error {
args := request.args
func completeCommand(output io.Writer, request commandContext) error {
args := request.context.arguments
requester := "unknown"
requesterVersion := 0

Expand Down Expand Up @@ -193,8 +193,8 @@ var bashCompletionScript string
//go:embed contrib/completion/zsh-completion.sh
var zshCompletionScript string

func generateCommand(output io.Writer, request commandRequest) (err error) {
args := request.args
func generateCommand(output io.Writer, request commandContext) (err error) {
args := request.context.arguments
// enforce no-log
logger := clog.GetDefaultLogger()
handler := logger.GetHandler()
Expand All @@ -207,7 +207,7 @@ func generateCommand(output io.Writer, request commandRequest) (err error) {
} else if slices.Contains(args, "--json-schema") {
err = generateJsonSchema(output, args[slices.Index(args, "--json-schema")+1:])
} else if slices.Contains(args, "--random-key") {
request.flags.resticArgs = args[slices.Index(args, "--random-key"):]
request.context.flags.resticArgs = args[slices.Index(args, "--random-key"):]
err = randomKey(output, request)
} else if slices.Contains(args, "--zsh-completion") {
_, err = fmt.Fprintln(output, zshCompletionScript)
Expand Down Expand Up @@ -278,9 +278,9 @@ func sortedProfileKeys(data map[string]*config.Profile) []string {
return keys
}

func showProfile(output io.Writer, request commandRequest) error {
c := request.config
flags := request.flags
func showProfile(output io.Writer, request commandContext) error {
c := request.context.config
flags := request.context.flags

Check warning on line 283 in commands.go

View check run for this annotation

Codecov / codecov/patch

commands.go#L281-L283

Added lines #L281 - L283 were not covered by tests

// Load global section
global, err := c.GetGlobalSection()
Expand Down Expand Up @@ -340,9 +340,9 @@ func showSchedules(output io.Writer, schedulesConfig []*config.ScheduleConfig) {
}

// randomKey simply display a base64'd random key to the console
func randomKey(output io.Writer, request commandRequest) error {
func randomKey(output io.Writer, request commandContext) error {
var err error
flags := request.flags
flags := request.context.flags
size := uint64(1024)
// flags.resticArgs contain the command and the rest of the command line
if len(flags.resticArgs) > 1 {
Expand Down Expand Up @@ -398,10 +398,10 @@ func flagsForProfile(flags commandLineFlags, profileName string) commandLineFlag
}

// createSchedule accepts one argument from the commandline: --no-start
func createSchedule(_ io.Writer, request commandRequest) error {
c := request.config
flags := request.flags
args := request.args
func createSchedule(_ io.Writer, request commandContext) error {
c := request.context.config
flags := request.context.flags
args := request.context.arguments

Check warning on line 404 in commands.go

View check run for this annotation

Codecov / codecov/patch

commands.go#L401-L404

Added lines #L401 - L404 were not covered by tests

defer c.DisplayConfigurationIssues()

Expand Down Expand Up @@ -453,10 +453,10 @@ func createSchedule(_ io.Writer, request commandRequest) error {
return nil
}

func removeSchedule(_ io.Writer, request commandRequest) error {
c := request.config
flags := request.flags
args := request.args
func removeSchedule(_ io.Writer, request commandContext) error {
c := request.context.config
flags := request.context.flags
args := request.context.arguments

Check warning on line 459 in commands.go

View check run for this annotation

Codecov / codecov/patch

commands.go#L456-L459

Added lines #L456 - L459 were not covered by tests

// Unschedule all jobs of all selected profiles
for _, profileName := range selectProfiles(c, flags, args) {
Expand All @@ -476,10 +476,10 @@ func removeSchedule(_ io.Writer, request commandRequest) error {
return nil
}

func statusSchedule(w io.Writer, request commandRequest) error {
c := request.config
flags := request.flags
args := request.args
func statusSchedule(w io.Writer, request commandContext) error {
c := request.context.config
flags := request.context.flags
args := request.context.arguments

Check warning on line 482 in commands.go

View check run for this annotation

Codecov / codecov/patch

commands.go#L479-L482

Added lines #L479 - L482 were not covered by tests

defer c.DisplayConfigurationIssues()

Expand Down Expand Up @@ -572,9 +572,9 @@ func getRemovableScheduleJobs(c *config.Config, flags commandLineFlags) (schedul
return scheduler, profile, schedules, nil
}

func testElevationCommand(_ io.Writer, request commandRequest) error {
if request.flags.isChild {
client := remote.NewClient(request.flags.parentPort)
func testElevationCommand(_ io.Writer, request commandContext) error {
if request.context.flags.isChild {
client := remote.NewClient(request.context.flags.parentPort)

Check warning on line 577 in commands.go

View check run for this annotation

Codecov / codecov/patch

commands.go#L575-L577

Added lines #L575 - L577 were not covered by tests
term.Print("first line", "\n")
term.Println("second", "one")
term.Printf("value = %d\n", 11)
Expand All @@ -585,7 +585,7 @@ func testElevationCommand(_ io.Writer, request commandRequest) error {
return nil
}

return elevated(request.flags)
return elevated(request.context.flags)

Check warning on line 588 in commands.go

View check run for this annotation

Codecov / codecov/patch

commands.go#L588

Added line #L588 was not covered by tests
}

func retryElevated(err error, flags commandLineFlags) error {
Expand Down
34 changes: 17 additions & 17 deletions commands_display.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ func getCommonUsageHelpLine(commandName string, withProfile bool) string {
)
}

func displayOwnCommands(output io.Writer, request commandRequest) {
out, closer := displayWriter(output, request.flags)
func displayOwnCommands(output io.Writer, request commandContext) {
out, closer := displayWriter(output, request.context.flags)
defer closer()

for _, command := range request.ownCommands.commands {
Expand All @@ -86,8 +86,8 @@ func displayOwnCommands(output io.Writer, request commandRequest) {
}
}

func displayOwnCommandHelp(output io.Writer, commandName string, request commandRequest) {
out, closer := displayWriter(output, request.flags)
func displayOwnCommandHelp(output io.Writer, commandName string, request commandContext) {
out, closer := displayWriter(output, request.context.flags)
defer closer()

var command *ownCommand
Expand Down Expand Up @@ -130,8 +130,8 @@ func displayOwnCommandHelp(output io.Writer, commandName string, request command
}
}

func displayCommonUsageHelp(output io.Writer, request commandRequest) {
out, closer := displayWriter(output, request.flags)
func displayCommonUsageHelp(output io.Writer, request commandContext) {
out, closer := displayWriter(output, request.context.flags)

Check warning on line 134 in commands_display.go

View check run for this annotation

Codecov / codecov/patch

commands_display.go#L133-L134

Added lines #L133 - L134 were not covered by tests
defer closer()

out("resticprofile is a configuration profiles manager for backup profiles and ")
Expand All @@ -142,7 +142,7 @@ func displayCommonUsageHelp(output io.Writer, request commandRequest) {
out("\t%s [command specific flags]\n", getCommonUsageHelpLine("resticprofile-command", true))
out("\n")
out(ansiBold("resticprofile flags:\n"))
out(request.flags.usagesHelp)
out(request.context.flags.usagesHelp)

Check warning on line 145 in commands_display.go

View check run for this annotation

Codecov / codecov/patch

commands_display.go#L145

Added line #L145 was not covered by tests
out("\n\n")
out(ansiBold("resticprofile own commands:\n"))
displayOwnCommands(out(), request)
Expand Down Expand Up @@ -218,10 +218,10 @@ func displayResticHelp(output io.Writer, configuration *config.Config, flags com
}
}

func displayHelpCommand(output io.Writer, request commandRequest) error {
flags := request.flags
func displayHelpCommand(output io.Writer, request commandContext) error {
flags := request.context.flags

Check warning on line 222 in commands_display.go

View check run for this annotation

Codecov / codecov/patch

commands_display.go#L221-L222

Added lines #L221 - L222 were not covered by tests

out, closer := displayWriter(output, request.flags)
out, closer := displayWriter(output, request.context.flags)

Check warning on line 224 in commands_display.go

View check run for this annotation

Codecov / codecov/patch

commands_display.go#L224

Added line #L224 was not covered by tests
defer closer()

if flags.log == "" {
Expand All @@ -243,20 +243,20 @@ func displayHelpCommand(output io.Writer, request commandRequest) error {
displayOwnCommandHelp(out("\n"), *helpForCommand, request)

} else {
displayResticHelp(out(), request.config, flags, *helpForCommand)
displayResticHelp(out(), request.context.config, flags, *helpForCommand)

Check warning on line 246 in commands_display.go

View check run for this annotation

Codecov / codecov/patch

commands_display.go#L246

Added line #L246 was not covered by tests
}

return nil
}

func displayVersion(output io.Writer, request commandRequest) error {
out, closer := displayWriter(output, request.flags)
func displayVersion(output io.Writer, request commandContext) error {
out, closer := displayWriter(output, request.context.flags)

Check warning on line 253 in commands_display.go

View check run for this annotation

Codecov / codecov/patch

commands_display.go#L252-L253

Added lines #L252 - L253 were not covered by tests
defer closer()

out("resticprofile version %s commit %s\n", ansiBold(version), ansiYellow(commit))

// allow for the general verbose flag, or specified after the command
if request.flags.verbose || (len(request.args) > 0 && (request.args[0] == "-v" || request.args[0] == "--verbose")) {
if request.context.flags.verbose || (len(request.context.arguments) > 0 && (request.context.arguments[0] == "-v" || request.context.arguments[0] == "--verbose")) {

Check warning on line 259 in commands_display.go

View check run for this annotation

Codecov / codecov/patch

commands_display.go#L259

Added line #L259 was not covered by tests
out("\n")
out("\t%s:\t%s\n", "home", "https://github.com/creativeprojects/resticprofile")
out("\t%s:\t%s\n", "os", runtime.GOOS)
Expand All @@ -280,9 +280,9 @@ func displayVersion(output io.Writer, request commandRequest) error {
return nil
}

func displayProfilesCommand(output io.Writer, request commandRequest) error {
displayProfiles(output, request.config, request.flags)
displayGroups(output, request.config, request.flags)
func displayProfilesCommand(output io.Writer, request commandContext) error {
displayProfiles(output, request.context.config, request.context.flags)
displayGroups(output, request.context.config, request.context.flags)

Check warning on line 285 in commands_display.go

View check run for this annotation

Codecov / codecov/patch

commands_display.go#L283-L285

Added lines #L283 - L285 were not covered by tests
return nil
}

Expand Down
52 changes: 30 additions & 22 deletions commands_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,27 +46,27 @@ func fakeCommands() *OwnCommands {
return ownCommands
}

func firstCommand(_ io.Writer, _ commandRequest) error {
func firstCommand(_ io.Writer, _ commandContext) error {
return errors.New("first")
}

func secondCommand(_ io.Writer, _ commandRequest) error {
func secondCommand(_ io.Writer, _ commandContext) error {
return errors.New("second")
}

func thirdCommand(_ io.Writer, _ commandRequest) error {
func thirdCommand(_ io.Writer, _ commandContext) error {
return errors.New("third")
}

func TestDisplayOwnCommands(t *testing.T) {
buffer := &strings.Builder{}
displayOwnCommands(buffer, commandRequest{ownCommands: fakeCommands()})
displayOwnCommands(buffer, commandContext{ownCommands: fakeCommands(), context: &Context{}})
assert.Equal(t, " first first first\n second second second\n", buffer.String())
}

func TestDisplayOwnCommand(t *testing.T) {
buffer := &strings.Builder{}
displayOwnCommandHelp(buffer, "second", commandRequest{ownCommands: fakeCommands()})
displayOwnCommandHelp(buffer, "second", commandContext{ownCommands: fakeCommands(), context: &Context{}})
assert.Equal(t, `Purpose: second second
Usage:
Expand All @@ -87,29 +87,37 @@ func TestIsOwnCommand(t *testing.T) {
}

func TestRunOwnCommand(t *testing.T) {
assert.EqualError(t, fakeCommands().Run(nil, "first", commandLineFlags{}, nil), "first")
assert.EqualError(t, fakeCommands().Run(nil, "second", commandLineFlags{}, nil), "second")
assert.EqualError(t, fakeCommands().Run(nil, "third", commandLineFlags{}, nil), "third")
assert.EqualError(t, fakeCommands().Run(nil, "another one", commandLineFlags{}, nil), "command not found: another one")
assert.EqualError(t, fakeCommands().Run(&Context{resticCommand: "first"}), "first")
assert.EqualError(t, fakeCommands().Run(&Context{resticCommand: "second"}), "second")
assert.EqualError(t, fakeCommands().Run(&Context{resticCommand: "third"}), "third")
assert.EqualError(t, fakeCommands().Run(&Context{resticCommand: "another one"}), "command not found: another one")
}

func TestPanicCommand(t *testing.T) {
assert.Panics(t, func() {
_ = panicCommand(nil, commandRequest{})
_ = panicCommand(nil, commandContext{})
})
}

func TestRandomKeyOfInvalidSize(t *testing.T) {
assert.Error(t, randomKey(os.Stdout, commandRequest{flags: commandLineFlags{resticArgs: []string{"restic", "size"}}}))
assert.Error(t, randomKey(os.Stdout, commandContext{
context: &Context{
flags: commandLineFlags{resticArgs: []string{"restic", "size"}},
},
}))
}

func TestRandomKeyOfZeroSize(t *testing.T) {
assert.Error(t, randomKey(os.Stdout, commandRequest{flags: commandLineFlags{resticArgs: []string{"restic", "0"}}}))
assert.Error(t, randomKey(os.Stdout, commandContext{
context: &Context{
flags: commandLineFlags{resticArgs: []string{"restic", "0"}},
},
}))
}

func TestRandomKey(t *testing.T) {
// doesn't look like much, but it's testing the random generator is not throwing an error
assert.NoError(t, randomKey(os.Stdout, commandRequest{}))
assert.NoError(t, randomKey(os.Stdout, commandContext{context: &Context{}}))
}

func TestRemovableSchedules(t *testing.T) {
Expand Down Expand Up @@ -263,7 +271,7 @@ func TestCompleteCall(t *testing.T) {
for _, test := range testTable {
t.Run(strings.Join(test.args, " "), func(t *testing.T) {
buffer := &strings.Builder{}
assert.Nil(t, completeCommand(buffer, commandRequest{ownCommands: ownCommands, args: test.args}))
assert.Nil(t, completeCommand(buffer, commandContext{ownCommands: ownCommands, context: &Context{arguments: test.args}}))
assert.Equal(t, test.expected, buffer.String())
})
}
Expand All @@ -274,21 +282,21 @@ func TestGenerateCommand(t *testing.T) {

t.Run("--bash-completion", func(t *testing.T) {
buffer.Reset()
assert.Nil(t, generateCommand(buffer, commandRequest{args: []string{"--bash-completion"}}))
assert.Nil(t, generateCommand(buffer, commandContext{context: &Context{arguments: []string{"--bash-completion"}}}))
assert.Equal(t, strings.TrimSpace(bashCompletionScript), strings.TrimSpace(buffer.String()))
assert.Contains(t, bashCompletionScript, "#!/usr/bin/env bash")
})

t.Run("--zsh-completion", func(t *testing.T) {
buffer.Reset()
assert.Nil(t, generateCommand(buffer, commandRequest{args: []string{"--zsh-completion"}}))
assert.Nil(t, generateCommand(buffer, commandContext{context: &Context{arguments: []string{"--zsh-completion"}}}))
assert.Equal(t, strings.TrimSpace(zshCompletionScript), strings.TrimSpace(buffer.String()))
assert.Contains(t, zshCompletionScript, "#!/usr/bin/env zsh")
})

t.Run("--config-reference", func(t *testing.T) {
buffer.Reset()
assert.NoError(t, generateCommand(buffer, commandRequest{args: []string{"--config-reference"}}))
assert.NoError(t, generateCommand(buffer, commandContext{context: &Context{arguments: []string{"--config-reference"}}}))
ref := buffer.String()
assert.Contains(t, ref, "| **ionice-class** |")
assert.Contains(t, ref, "| **check-after** |")
Expand All @@ -297,29 +305,29 @@ func TestGenerateCommand(t *testing.T) {

t.Run("--json-schema", func(t *testing.T) {
buffer.Reset()
assert.NoError(t, generateCommand(buffer, commandRequest{args: []string{"--json-schema"}}))
assert.NoError(t, generateCommand(buffer, commandContext{context: &Context{arguments: []string{"--json-schema"}}}))
ref := buffer.String()
assert.Contains(t, ref, "\"profiles\":")
assert.Contains(t, ref, "/jsonschema/config-2.json")
})

t.Run("--json-schema v1", func(t *testing.T) {
buffer.Reset()
assert.NoError(t, generateCommand(buffer, commandRequest{args: []string{"--json-schema", "v1"}}))
assert.NoError(t, generateCommand(buffer, commandContext{context: &Context{arguments: []string{"--json-schema", "v1"}}}))
ref := buffer.String()
assert.Contains(t, ref, "/jsonschema/config-1.json")
})

t.Run("--json-schema --version 0.13 v1", func(t *testing.T) {
buffer.Reset()
assert.NoError(t, generateCommand(buffer, commandRequest{args: []string{"--json-schema", "--version", "0.13", "v1"}}))
assert.NoError(t, generateCommand(buffer, commandContext{context: &Context{arguments: []string{"--json-schema", "--version", "0.13", "v1"}}}))
ref := buffer.String()
assert.Contains(t, ref, "/jsonschema/config-1-restic-0-13.json")
})

t.Run("--random-key", func(t *testing.T) {
buffer.Reset()
assert.Nil(t, generateCommand(buffer, commandRequest{args: []string{"--random-key", "512"}}))
assert.Nil(t, generateCommand(buffer, commandContext{context: &Context{arguments: []string{"--random-key", "512"}}}))
assert.Equal(t, 684, len(strings.TrimSpace(buffer.String())))
})

Expand All @@ -328,7 +336,7 @@ func TestGenerateCommand(t *testing.T) {
opts := []string{"", "invalid", "--unknown"}
for _, option := range opts {
buffer.Reset()
err := generateCommand(buffer, commandRequest{args: []string{option}})
err := generateCommand(buffer, commandContext{context: &Context{arguments: []string{option}}})
assert.EqualError(t, err, fmt.Sprintf("nothing to generate for: %s", option))
assert.Equal(t, 0, buffer.Len())
}
Expand Down
Loading

0 comments on commit 4144642

Please sign in to comment.