Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

schedule: added unified schedule config struct #333

Merged
merged 5 commits into from
Mar 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 22 additions & 26 deletions commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/creativeprojects/resticprofile/term"
"github.com/creativeprojects/resticprofile/util/templates"
"github.com/creativeprojects/resticprofile/win"
"golang.org/x/exp/maps"
)

var (
Expand Down Expand Up @@ -330,7 +331,7 @@ func showProfile(output io.Writer, ctx commandContext) error {
_, _ = fmt.Fprintln(output)

// Show schedules
showSchedules(output, profile.Schedules())
showSchedules(output, maps.Values(profile.Schedules()))

// Show deprecation notice
displayProfileDeprecationNotices(profile)
Expand All @@ -342,12 +343,13 @@ func showProfile(output io.Writer, ctx commandContext) error {
}

func showSchedules(output io.Writer, schedules []*config.Schedule) {
slices.SortFunc(schedules, config.CompareSchedules)
for _, schedule := range schedules {
err := config.ShowStruct(output, schedule, "schedule "+schedule.CommandName+"@"+schedule.Profiles[0])
err := config.ShowStruct(output, schedule.ScheduleConfig, fmt.Sprintf("schedule %s", schedule.ScheduleOrigin()))
if err != nil {
fmt.Fprintln(output, err)
_, _ = fmt.Fprintln(output, err)
}
fmt.Fprintln(output, "")
_, _ = fmt.Fprintln(output, "")
}
}

Expand Down Expand Up @@ -552,7 +554,7 @@ func getScheduleJobs(c *config.Config, flags commandLineFlags) (schedule.Schedul
return nil, nil, nil, fmt.Errorf("cannot load profile '%s': %w", flags.name, err)
}

return schedule.NewSchedulerConfig(global), profile, profile.Schedules(), nil
return schedule.NewSchedulerConfig(global), profile, maps.Values(profile.Schedules()), nil
}

func requireScheduleJobs(schedules []*config.Schedule, flags commandLineFlags) error {
Expand All @@ -572,12 +574,13 @@ func getRemovableScheduleJobs(c *config.Config, flags commandLineFlags) (schedul
for _, command := range profile.SchedulableCommands() {
declared := false
for _, s := range schedules {
if declared = s.CommandName == command; declared {
if declared = s.ScheduleOrigin().Command == command; declared {
break
}
}
if !declared {
schedules = append(schedules, config.NewEmptySchedule(profile.Name, command))
origin := config.ScheduleOrigin(profile.Name, command)
schedules = append(schedules, config.NewDefaultSchedule(c, origin))
}
}

Expand Down Expand Up @@ -609,39 +612,32 @@ func preRunSchedule(ctx *Context) error {
return fmt.Errorf("cannot load profile '%s': %w", profileName, err)
}
// get the list of all scheduled commands to find the current command
schedules := profile.Schedules()
for _, schedule := range schedules {
if schedule.CommandName == ctx.command {
ctx.schedule = schedule
prepareScheduledProfile(ctx)
break
}
if ctx.schedule, ok = profile.Schedules()[ctx.command]; ok {
prepareScheduledProfile(ctx)
}
}
return nil
}

func prepareScheduledProfile(ctx *Context) {
clog.Debugf("preparing scheduled profile %q", ctx.request.schedule)
s := ctx.schedule
// log file
if len(ctx.schedule.Log) > 0 {
ctx.logTarget = ctx.schedule.Log
if len(s.Log) > 0 {
ctx.logTarget = s.Log
}
// battery
if ctx.schedule.IgnoreOnBatteryLessThan > 0 {
ctx.stopOnBattery = ctx.schedule.IgnoreOnBatteryLessThan
} else if ctx.schedule.IgnoreOnBattery {
if s.IgnoreOnBatteryLessThan > 0 && !s.IgnoreOnBattery.IsStrictlyFalse() {
ctx.stopOnBattery = s.IgnoreOnBatteryLessThan
} else if s.IgnoreOnBattery.IsTrue() {
ctx.stopOnBattery = 100
}
// lock
if ctx.schedule.GetLockWait() > 0 {
ctx.lockWait = ctx.schedule.LockWait
}
if ctx.schedule.GetLockMode() == config.ScheduleLockModeDefault {
if ctx.schedule.GetLockWait() > 0 {
ctx.lockWait = ctx.schedule.GetLockWait()
if s.GetLockMode() == config.ScheduleLockModeDefault {
if duration := s.GetLockWait(); duration > 0 {
ctx.lockWait = duration
}
} else if ctx.schedule.GetLockMode() == config.ScheduleLockModeIgnore {
} else if s.GetLockMode() == config.ScheduleLockModeIgnore {
ctx.noLock = true
}
}
Expand Down
43 changes: 22 additions & 21 deletions commands_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"testing"

"github.com/creativeprojects/resticprofile/config"
"github.com/creativeprojects/resticprofile/constants"
"github.com/creativeprojects/resticprofile/schedule"
"github.com/creativeprojects/resticprofile/util/collect"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -64,10 +65,11 @@ schedule = "daily"
declaredCount := 0

for _, jobConfig := range schedules {
scheduler := schedule.NewScheduler(schedule.NewHandler(schedule.SchedulerDefaultOS{}), jobConfig.Profiles[0])
configOrigin := jobConfig.ScheduleOrigin()
scheduler := schedule.NewScheduler(schedule.NewHandler(schedule.SchedulerDefaultOS{}), configOrigin.Name)
defer func(s *schedule.Scheduler) { s.Close() }(scheduler) // Capture current ref to scheduler to be able to close it when function returns.

if jobConfig.CommandName == "check" {
if configOrigin.Command == constants.CommandCheck {
assert.False(t, scheduler.NewJob(scheduleToConfig(jobConfig)).RemoveOnly())
declaredCount++
} else {
Expand Down Expand Up @@ -114,7 +116,7 @@ schedule = "daily"
assert.NotNil(t, profile)
assert.NotEmpty(t, schedules)
assert.Len(t, schedules, 1)
assert.Equal(t, "check", schedules[0].CommandName)
assert.Equal(t, "check", schedules[0].ScheduleOrigin().Command)
}
}

Expand Down Expand Up @@ -274,29 +276,28 @@ func TestGenerateCommand(t *testing.T) {

func TestShowSchedules(t *testing.T) {
buffer := &bytes.Buffer{}
create := func(command string, at ...string) *config.Schedule {
origin := config.ScheduleOrigin("default", command)
return config.NewDefaultSchedule(nil, origin, at...)
}
schedules := []*config.Schedule{
{
Profiles: []string{"default"},
CommandName: "check",
Schedules: []string{"weekly"},
},
{
Profiles: []string{"default"},
CommandName: "backup",
Schedules: []string{"daily"},
},
create("check", "weekly"),
create("backup", "daily"),
}
expected := strings.TrimSpace(`
schedule check@default:
run: check
profiles: default
schedule: weekly

schedule backup@default:
run: backup
profiles: default
schedule: daily
at: daily
permission: auto
priority: background
lock-mode: default
capture-environment: RESTIC_*

schedule check@default:
at: weekly
permission: auto
priority: background
lock-mode: default
capture-environment: RESTIC_*
`)
showSchedules(buffer, schedules)
assert.Equal(t, expected, strings.TrimSpace(buffer.String()))
Expand Down
11 changes: 11 additions & 0 deletions config/confidential.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config

import (
"encoding/json"
"reflect"
"regexp"

Expand All @@ -25,6 +26,16 @@ func (c ConfidentialValue) String() string {
return c.public
}

func (c *ConfidentialValue) UnmarshalJSON(data []byte) (err error) {
err = json.Unmarshal(data, &c.confidential)
c.public = c.confidential
return
}

func (c ConfidentialValue) MarshalJSON() ([]byte, error) {
return json.Marshal(c.Value())
}

func (c *ConfidentialValue) IsConfidential() bool {
return c.public != c.confidential
}
Expand Down
30 changes: 30 additions & 0 deletions config/confidential_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package config

import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"regexp"
Expand Down Expand Up @@ -276,3 +277,32 @@ profile:
assert.Equal(t, []string{"--repo=" + expectedSecret}, args.GetAll())
assert.Equal(t, []string{"--repo=" + expectedPublic}, result.GetAll())
}

func TestConfidentialToJSON(t *testing.T) {
t.Run("marshal", func(t *testing.T) {
value := NewConfidentialValue("plain")
assert.False(t, value.IsConfidential())

binary, _ := json.Marshal(value)
assert.Equal(t, `"plain"`, string(binary))

value.hideValue()
assert.True(t, value.IsConfidential())

binary, _ = json.Marshal(value)
assert.Equal(t, `"plain"`, string(binary))
})

t.Run("unmarshal", func(t *testing.T) {
value := NewConfidentialValue("")
value.hideValue()
assert.True(t, value.IsConfidential())

assert.NoError(t, json.Unmarshal([]byte(`"plain"`), &value))

// the confidential state is not marshalled for now
assert.False(t, value.IsConfidential())
assert.Equal(t, "plain", value.Value())
assert.Equal(t, "plain", value.String())
})
}
Loading
Loading