diff --git a/CHANGELOG.md b/CHANGELOG.md index 861521fad..8d2590d6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## 0.48.1 - Unreleased +- Calendar: give recurring `calendar create` and `calendar focus-time` events the calendar's time zone when `--from`/`--to` carry only an offset that matches it, so a weekly `-08:00` series stays at its local time after daylight saving starts instead of following a fixed `Etc/GMT+8` zone, and a `+05:30` series is accepted instead of failing with "Missing time zone definition". Offsets that match no zone the calendar uses keep their previous handling; an unmatched half-hour offset in `calendar create` now asks for `--timezone` (or `--start-timezone`/`--end-timezone` when one endpoint already has its own zone) before the event is created. (#1310) — thanks @saariuslystoned. + ## 0.48.0 - 2026-11-05 **Highlights:** New backups stay local until you configure a remote; existing configurations keep working. Store service-account keys in the keyring, search Gmail IDs efficiently, and use environment-backed watch tokens, with Calendar fixes and security dependency updates. diff --git a/docs/dates.md b/docs/dates.md index 921832214..8f8008887 100644 --- a/docs/dates.md +++ b/docs/dates.md @@ -47,3 +47,9 @@ Tracking `--since` also accepts `time.ParseDuration` values such as: - Generate RFC3339 for all datetime fields by default. - Use date-only for fields explicitly documented as dates. - For local scheduling, pass an explicit offset (or timezone-aware RFC3339) to avoid ambiguity. +- Recurring Calendar events repeat in one IANA time zone. When `calendar create` + or `calendar focus-time` gets `--rrule` with times that carry only an offset, + gog uses the calendar's time zone if it has that offset at the given time, so + the series keeps its local time across daylight saving changes. Other offsets + keep a fixed `Etc/GMT` zone, and UTC times stay in UTC. Pass `--timezone` to + choose the zone yourself. diff --git a/internal/cmd/calendar_build.go b/internal/cmd/calendar_build.go index dc79b82c2..549720521 100644 --- a/internal/cmd/calendar_build.go +++ b/internal/cmd/calendar_build.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "fmt" "regexp" "strconv" @@ -103,6 +104,104 @@ func extractTimezone(value string) string { return "" } +// applyRecurringCalendarTimezone sets the zone Google expands a recurring +// series in when --from or --to carries only a UTC offset. An offset alone maps +// to a fixed Etc/GMT zone, which keeps the series on that offset across +// daylight saving changes, and half-hour offsets have no Etc/GMT zone at all. +// The calendar's own zone is used when it has the same offset at that time. +// Explicit timezones, UTC times and all-day dates are kept as given. When +// timezoneFlag is set, an offset that still has no zone is a usage error that +// names the flag, instead of a request Google rejects. +func applyRecurringCalendarTimezone(ctx context.Context, mutation *calendarMutationContext, event *calendar.Event, startTimezone, endTimezone, timezoneFlag string) error { + if event == nil || len(event.Recurrence) == 0 { + return nil + } + start := recurringZoneFromOffset(event.Start, startTimezone) + end := recurringZoneFromOffset(event.End, endTimezone) + if !start && !end { + return nil + } + calendarTimezone, calendarLoc := mutation.calendarLocation(ctx) + // --timezone cannot be combined with the per-endpoint flags, so once one + // endpoint has its own zone, point the other at its own flag. + startFlag, endFlag := timezoneFlag, timezoneFlag + if timezoneFlag != "" && (strings.TrimSpace(startTimezone) != "" || strings.TrimSpace(endTimezone) != "") { + startFlag, endFlag = "--start-timezone", "--end-timezone" + } + if start { + if err := applyCalendarZoneForOffset(event.Start, calendarTimezone, calendarLoc, "--from", startFlag); err != nil { + return err + } + } + if end { + if err := applyCalendarZoneForOffset(event.End, calendarTimezone, calendarLoc, "--to", endFlag); err != nil { + return err + } + } + return nil +} + +// recurringTimezoneLookupPlan describes, for --dry-run, the calendar time zone +// lookup applyRecurringCalendarTimezone makes when the command runs. Dry runs +// stay offline, so the event they show carries the fallback zone. +func recurringTimezoneLookupPlan(event *calendar.Event, startTimezone, endTimezone, unmatched string) map[string]any { + if event == nil || len(event.Recurrence) == 0 { + return nil + } + out := map[string]any{} + for _, side := range []struct { + key string + dt *calendar.EventDateTime + explicit string + }{{"start", event.Start, startTimezone}, {"end", event.End, endTimezone}} { + if !recurringZoneFromOffset(side.dt, side.explicit) { + continue + } + t, err := time.Parse(time.RFC3339, strings.TrimSpace(side.dt.DateTime)) + if err != nil { + continue + } + entry := map[string]any{ + "offset": t.Format("-07:00"), + "rule": "use the calendar's time zone if it has this offset at dateTime", + } + if side.dt.TimeZone != "" { + entry["fallback_timezone"] = side.dt.TimeZone + } else { + entry["fallback"] = unmatched + } + out[side.key] = entry + } + if len(out) == 0 { + return nil + } + return out +} + +func recurringZoneFromOffset(dt *calendar.EventDateTime, explicitTimezone string) bool { + return dt != nil && strings.TrimSpace(explicitTimezone) == "" && + strings.TrimSpace(dt.DateTime) != "" && dt.TimeZone != tzUTC +} + +func applyCalendarZoneForOffset(dt *calendar.EventDateTime, calendarTimezone string, calendarLoc *time.Location, flagName, timezoneFlag string) error { + t, parseErr := time.Parse(time.RFC3339, strings.TrimSpace(dt.DateTime)) + if parseErr != nil { + // Not an RFC3339 instant: leave the zone to the existing handling. + return nil //nolint:nilerr // an unparsable time is not this helper's error to report + } + _, offset := t.Zone() + if calendarLoc != nil { + if _, calendarOffset := t.In(calendarLoc).Zone(); calendarOffset == offset { + dt.TimeZone = calendarTimezone + return nil + } + } + if dt.TimeZone == "" && timezoneFlag != "" { + return usagef("recurring events need an IANA time zone: %s offset %s has no fixed-offset zone and does not match the calendar's time zone; pass %s with an IANA zone name", flagName, t.Format("-07:00"), timezoneFlag) + } + return nil +} + type conferenceChoice struct { provider string } diff --git a/internal/cmd/calendar_edit.go b/internal/cmd/calendar_edit.go index 38dcb3a5e..f863b38b9 100644 --- a/internal/cmd/calendar_edit.go +++ b/internal/cmd/calendar_edit.go @@ -153,6 +153,9 @@ func (c *CalendarCreateCmd) Run(ctx context.Context, flags *RootFlags, kctx *kon if err != nil { return err } + if tzErr := applyRecurringCalendarTimezone(ctx, mutation, plan.Event, plan.StartTimezone, plan.EndTimezone, flagTimezone); tzErr != nil { + return tzErr + } var zoomMeeting *zoom.Meeting if plan.WithZoom { diff --git a/internal/cmd/calendar_event_plan.go b/internal/cmd/calendar_event_plan.go index 81dc4c452..82b952c5b 100644 --- a/internal/cmd/calendar_event_plan.go +++ b/internal/cmd/calendar_event_plan.go @@ -83,6 +83,10 @@ type calendarCreatePlan struct { WithZoom bool PlaceLookup *calendarPlaceLookupRequest Event *calendar.Event + // StartTimezone and EndTimezone are the explicit timezone flags in effect + // (--timezone applies to both); empty means the zone came from the offset. + StartTimezone string + EndTimezone string } type calendarUpdateFields struct { @@ -415,12 +419,14 @@ func buildCalendarCreatePlan(store *config.ConfigStore, input calendarCreateInpu } return &calendarCreatePlan{ - CalendarID: calendarID, - SendUpdates: sendUpdates, - WithMeet: input.WithMeet, - WithZoom: input.WithZoom, - PlaceLookup: placeLookup, - Event: event, + CalendarID: calendarID, + SendUpdates: sendUpdates, + WithMeet: input.WithMeet, + WithZoom: input.WithZoom, + PlaceLookup: placeLookup, + Event: event, + StartTimezone: startTZ, + EndTimezone: endTZ, }, nil } @@ -438,6 +444,13 @@ func (p *calendarCreatePlan) dryRunRequest() map[string]any { if p.PlaceLookup != nil { request["place_lookup"] = p.PlaceLookup.dryRunPayload() } + unmatched := "usage error asking for --timezone" + if strings.TrimSpace(p.StartTimezone) != "" || strings.TrimSpace(p.EndTimezone) != "" { + unmatched = "usage error asking for --start-timezone or --end-timezone" + } + if lookup := recurringTimezoneLookupPlan(p.Event, p.StartTimezone, p.EndTimezone, unmatched); lookup != nil { + request["recurring_timezone_lookup"] = lookup + } return request } diff --git a/internal/cmd/calendar_focus_time.go b/internal/cmd/calendar_focus_time.go index 2085676b6..e09311ee6 100644 --- a/internal/cmd/calendar_focus_time.go +++ b/internal/cmd/calendar_focus_time.go @@ -57,10 +57,14 @@ func (c *CalendarFocusTimeCmd) Run(ctx context.Context, flags *RootFlags) error Recurrence: buildRecurrence(c.Recurrence), } - if dryRunErr := dryRunExit(ctx, flags, "calendar.focus-time", map[string]any{ + dryRun := map[string]any{ "calendar_id": calendarID, "event": event, - }); dryRunErr != nil { + } + if lookup := recurringTimezoneLookupPlan(event, "", "", "no time zone is sent"); lookup != nil { + dryRun["recurring_timezone_lookup"] = lookup + } + if dryRunErr := dryRunExit(ctx, flags, "calendar.focus-time", dryRun); dryRunErr != nil { return dryRunErr } @@ -68,6 +72,9 @@ func (c *CalendarFocusTimeCmd) Run(ctx context.Context, flags *RootFlags) error if err != nil { return err } + if tzErr := applyRecurringCalendarTimezone(ctx, mutation, event, "", "", ""); tzErr != nil { + return tzErr + } created, err := mutation.insertEvent(ctx, event, calendarInsertOptions{}) if err != nil { diff --git a/internal/cmd/calendar_mutation_helpers.go b/internal/cmd/calendar_mutation_helpers.go index f238a32e4..d24d0b9c1 100644 --- a/internal/cmd/calendar_mutation_helpers.go +++ b/internal/cmd/calendar_mutation_helpers.go @@ -2,6 +2,7 @@ package cmd import ( "context" + "time" "google.golang.org/api/calendar/v3" @@ -13,6 +14,20 @@ type calendarMutationContext struct { u *ui.UI svc *calendar.Service calendarID string + + timezoneLoaded bool + timezone string + location *time.Location +} + +// calendarLocation returns the calendar's time zone, fetched once per command. +// An empty zone and nil location mean the lookup failed. +func (m *calendarMutationContext) calendarLocation(ctx context.Context) (string, *time.Location) { + if !m.timezoneLoaded { + m.timezone, m.location, _ = getCalendarLocation(ctx, m.svc, m.calendarID) + m.timezoneLoaded = true + } + return m.timezone, m.location } type calendarInsertOptions struct { @@ -98,7 +113,7 @@ func (m *calendarMutationContext) moveEvent(ctx context.Context, eventID, destin func (m *calendarMutationContext) writeEvent(ctx context.Context, event *calendar.Event) error { redactCalendarEventForOutput(ctx, event) - tz, loc, _ := getCalendarLocation(ctx, m.svc, m.calendarID) + tz, loc := m.calendarLocation(ctx) if outfmt.IsJSON(ctx) { return outfmt.WriteJSON(ctx, stdoutWriter(ctx), map[string]any{"event": wrapEventWithDaysWithTimezone(event, tz, loc)}) } diff --git a/internal/cmd/calendar_recurring_timezone_test.go b/internal/cmd/calendar_recurring_timezone_test.go new file mode 100644 index 000000000..89719f974 --- /dev/null +++ b/internal/cmd/calendar_recurring_timezone_test.go @@ -0,0 +1,225 @@ +package cmd + +import ( + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "google.golang.org/api/calendar/v3" +) + +type recurringCreateResult struct { + event calendar.Event + inserts int + err error +} + +func runRecurringCalendarCreate(t *testing.T, calendarTimezone string, args ...string) recurringCreateResult { + t.Helper() + return runRecurringCalendarCommand(t, &CalendarCreateCmd{}, calendarTimezone, append([]string{"primary", "--summary", "Standup"}, args...)...) +} + +func runRecurringCalendarCommand(t *testing.T, cmd any, calendarTimezone string, args ...string) recurringCreateResult { + t.Helper() + var result recurringCreateResult + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/calendars/primary/events"): + result.inserts++ + _ = json.NewDecoder(r.Body).Decode(&result.event) + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"id": "ev1"}) + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/calendars/primary"): + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"id": "primary", "timeZone": calendarTimezone}) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + + ctx := withCalendarTestService(newCmdRuntimeJSONOutputContext(t, io.Discard, io.Discard), newCalendarServiceFromServer(t, srv)) + result.err = runKong(t, cmd, args, ctx, &RootFlags{Account: "a@b.com"}) + return result +} + +func assertRecurringZones(t *testing.T, got calendar.Event, wantStart, wantEnd string) { + t.Helper() + if got.Start == nil || got.Start.TimeZone != wantStart { + t.Fatalf("start = %#v, want timeZone %q", got.Start, wantStart) + } + if got.End == nil || got.End.TimeZone != wantEnd { + t.Fatalf("end = %#v, want timeZone %q", got.End, wantEnd) + } +} + +func TestCalendarCreateCmd_RecurringOffsetUsesMatchingCalendarTimezone(t *testing.T) { + // -08:00 is Pacific standard time in November. A fixed Etc/GMT+8 zone would + // expand the series an hour later in local time once daylight saving starts. + result := runRecurringCalendarCreate(t, "America/Los_Angeles", + "--from", "2026-11-10T09:00:00-08:00", + "--to", "2026-11-10T09:30:00-08:00", + "--rrule", "RRULE:FREQ=WEEKLY;BYDAY=TU") + if result.err != nil { + t.Fatalf("create: %v", result.err) + } + assertRecurringZones(t, result.event, "America/Los_Angeles", "America/Los_Angeles") + if result.event.Start.DateTime != "2026-11-10T09:00:00-08:00" { + t.Fatalf("start dateTime changed: %q", result.event.Start.DateTime) + } +} + +func TestCalendarCreateCmd_RecurringHalfHourOffsetUsesCalendarTimezone(t *testing.T) { + // No Etc/GMT zone exists for +05:30, so the request used to carry no + // timeZone and Google rejected it ("Missing time zone definition"). + result := runRecurringCalendarCreate(t, "Asia/Kolkata", + "--from", "2026-11-10T09:00:00+05:30", + "--to", "2026-11-10T09:30:00+05:30", + "--rrule", "RRULE:FREQ=DAILY") + if result.err != nil { + t.Fatalf("create: %v", result.err) + } + assertRecurringZones(t, result.event, "Asia/Kolkata", "Asia/Kolkata") +} + +func TestCalendarCreateCmd_RecurringUnresolvableOffsetIsUsageError(t *testing.T) { + result := runRecurringCalendarCreate(t, "UTC", + "--from", "2026-11-10T09:00:00+05:30", + "--to", "2026-11-10T09:30:00+05:30", + "--rrule", "RRULE:FREQ=DAILY") + var exitErr *ExitError + if !errors.As(result.err, &exitErr) || exitErr.Code != 2 { + t.Fatalf("err = %v, want usage error", result.err) + } + if !strings.Contains(result.err.Error(), "--timezone") { + t.Fatalf("err = %v, want --timezone guidance", result.err) + } + if result.inserts != 0 { + t.Fatalf("inserted %d events before rejecting", result.inserts) + } +} + +// With one endpoint's zone given through --start-timezone, the guidance for +// the other endpoint must name a flag that can be combined with it: +// --timezone cannot be used together with --start-timezone or --end-timezone. +func TestCalendarCreateCmd_RecurringUnresolvedEndSuggestsGranularFlag(t *testing.T) { + result := runRecurringCalendarCreate(t, "UTC", + "--from", "2026-11-10T09:00:00+05:30", + "--to", "2026-11-10T09:30:00+05:30", + "--start-timezone", "Asia/Kolkata", + "--rrule", "RRULE:FREQ=DAILY") + var exitErr *ExitError + if !errors.As(result.err, &exitErr) || exitErr.Code != 2 { + t.Fatalf("err = %v, want usage error", result.err) + } + if msg := result.err.Error(); !strings.Contains(msg, "--to offset") || !strings.Contains(msg, "--end-timezone") || strings.Contains(msg, "pass --timezone") { + t.Fatalf("err = %v, want --end-timezone guidance for --to", result.err) + } + if result.inserts != 0 { + t.Fatalf("inserted %d events before rejecting", result.inserts) + } +} + +func TestCalendarCreateCmd_RecurringKeepsUTCAndExplicitTimezones(t *testing.T) { + utc := runRecurringCalendarCreate(t, "Europe/London", + "--from", "2026-11-10T09:00:00Z", + "--to", "2026-11-10T09:30:00Z", + "--rrule", "RRULE:FREQ=WEEKLY") + if utc.err != nil { + t.Fatalf("create: %v", utc.err) + } + assertRecurringZones(t, utc.event, "UTC", "UTC") + + explicit := runRecurringCalendarCreate(t, "America/Los_Angeles", + "--from", "2026-11-10T09:00:00-08:00", + "--to", "2026-11-10T09:30:00-08:00", + "--start-timezone", "America/Tijuana", + "--rrule", "RRULE:FREQ=WEEKLY") + if explicit.err != nil { + t.Fatalf("create: %v", explicit.err) + } + assertRecurringZones(t, explicit.event, "America/Tijuana", "America/Los_Angeles") +} + +func TestCalendarCreateCmd_SingleOffsetEventKeepsFixedZone(t *testing.T) { + result := runRecurringCalendarCreate(t, "America/Los_Angeles", + "--from", "2026-11-10T09:00:00-08:00", + "--to", "2026-11-10T09:30:00-08:00") + if result.err != nil { + t.Fatalf("create: %v", result.err) + } + assertRecurringZones(t, result.event, "Etc/GMT+8", "Etc/GMT+8") +} + +func TestCalendarFocusTimeCmd_RecurringOffsetUsesMatchingCalendarTimezone(t *testing.T) { + result := runRecurringCalendarCommand(t, &CalendarFocusTimeCmd{}, "America/Los_Angeles", + "primary", + "--from", "2026-11-10T09:00:00-08:00", + "--to", "2026-11-10T11:00:00-08:00", + "--rrule", "RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR") + if result.err != nil { + t.Fatalf("focus-time: %v", result.err) + } + assertRecurringZones(t, result.event, "America/Los_Angeles", "America/Los_Angeles") +} + +func TestCalendarCreateCmd_DryRunDeclaresRecurringTimezoneLookup(t *testing.T) { + result := executeWithTestRuntime(t, []string{ + "--json", "--dry-run", "calendar", "create", "primary", + "--summary", "Standup", + "--from", "2026-11-10T09:00:00-08:00", + "--to", "2026-11-10T09:30:00-08:00", + "--rrule", "RRULE:FREQ=WEEKLY", + }, nil) + if result.err != nil { + t.Fatalf("dry-run: %v", result.err) + } + var got struct { + Request map[string]any `json:"request"` + } + if err := json.Unmarshal([]byte(result.stdout), &got); err != nil { + t.Fatalf("json: %v (%q)", err, result.stdout) + } + lookup, ok := got.Request["recurring_timezone_lookup"].(map[string]any) + if !ok { + t.Fatalf("request = %#v, want recurring_timezone_lookup", got.Request) + } + start, _ := lookup["start"].(map[string]any) + if start["offset"] != "-08:00" || start["fallback_timezone"] != "Etc/GMT+8" { + t.Fatalf("start lookup = %#v", start) + } + + single := executeWithTestRuntime(t, []string{ + "--json", "--dry-run", "calendar", "create", "primary", + "--summary", "Standup", + "--from", "2026-11-10T09:00:00-08:00", + "--to", "2026-11-10T09:30:00-08:00", + "--timezone", "America/Los_Angeles", + "--rrule", "RRULE:FREQ=WEEKLY", + }, nil) + if single.err != nil { + t.Fatalf("dry-run: %v", single.err) + } + if strings.Contains(single.stdout, "recurring_timezone_lookup") { + t.Fatalf("explicit --timezone should need no lookup: %s", single.stdout) + } +} + +func TestCalendarFocusTimeCmd_DryRunDeclaresRecurringTimezoneLookup(t *testing.T) { + result := executeWithTestRuntime(t, []string{ + "--json", "--dry-run", "calendar", "focus-time", "primary", + "--from", "2026-11-10T09:00:00+05:30", + "--to", "2026-11-10T11:00:00+05:30", + "--rrule", "RRULE:FREQ=DAILY", + }, nil) + if result.err != nil { + t.Fatalf("dry-run: %v", result.err) + } + if !strings.Contains(result.stdout, `"recurring_timezone_lookup"`) || !strings.Contains(result.stdout, `"no time zone is sent"`) { + t.Fatalf("dry-run output lacks the timezone lookup: %s", result.stdout) + } +}