diff --git a/COMPAT.md b/COMPAT.md index 367dfeb..c0b83e2 100644 --- a/COMPAT.md +++ b/COMPAT.md @@ -15,7 +15,7 @@ on the same invocations. | `eb` | `eb --last-log [--tmp-logdir=TMP_LOGDIR] --output-style=basic`, and the same without `--output-style` when that fails or prints nothing; the last line printed is the log | | stdout | `Failed build log: LOGDIR/NAME.failed.ebout.log`, `Failed command output: LOGDIR/NAME.failed.command-{out,err}.txt`, `Failed meson test log: LOGDIR/NAME.failed.meson-testlog.txt`, `Failed command output not kept: EASYBUILD_TMPDIR is not set.`, `Failed command output not kept: PATH is not under EASYBUILD_TMPDIR.`, `Failed command output not kept: PATH belongs to another user.`, `No EasyBuild log to keep for NAME.`, `No EasyBuild log to keep for NAME: eb is not on PATH.`, `No EasyBuild log to keep for NAME: eb --last-log exited N.`, `No EasyBuild log to keep for NAME: PATH is another build's log.`, `eb-keep-logs rotate: N files compressed, M runs deleted under ROOT`, with `1 file` and `1 run` for a count of one; LOGDIR in these lines without its trailing slashes | | files | kept files closed to others (command streams mode 0600), their resolved paths appended to `LOGDIR/.licensed-logs` unless already listed; on a failure, `NAME.stdout.log`, a TMP_LOGDIR below LOGDIR and the regular files directly in it closed to others, a symbolic link left as it is; `rotate` writes `FILE.gz` with the file's mode and updates `.licensed-logs` to the `.gz` path | -| run ages | days from the local midnight of the date in the run's name, as `date -d YYYYMMDD` computes it, including TZ rules, except in the two cases of `TZ` and `TZDIR` under unintended differences; a run whose local midnight does not exist is skipped | +| run ages | days from the local midnight of the date in the run's name, as `date -d YYYYMMDD` computes it, including TZ rules, except for the zones under unintended differences; a run whose local midnight does not exist is skipped | | the run in progress | `rotate` neither compresses nor deletes the run that holds its stdout or stderr, when either is a regular file, or `EB_PIPELINE_LOG_DIR` | ## Deliberate differences @@ -38,13 +38,17 @@ on the same invocations. | a log larger than 1 GiB | scanned | copied, not checked for another build and not scanned for the command output or meson paths, with a message on stderr | | a meson testlog larger than 1 GiB | kept unless its summary shows every test passing | kept without reading the summary, with a message on stderr | | a log with NUL bytes | `grep` reports a binary match and the scan finds nothing | scanned as text | +| `date` not GNU's, as on Ubuntu from 25.10, where `date` is uutils' and GNU's is `gnudate` | run ages follow that `date`; uutils' 0.10.0 reads as UTC some `TZ` rule strings that glibc reads, such as one after a `:` or one without an end rule: `TZ=CET-1CEST,M3.5.0 date -d 20261101 +%s` prints 1793491200 | run ages as GNU `date` gives them, whatever `date` is: 1793484000, as `gnudate` prints | ## Unintended differences -The Zig build differs here without meaning to; each is a bug in the Zig build. +The Zig build does not mean to differ from the shell script in these cases, +each shown by a command. Any other difference from the shell script that is +not listed above is a bug in the Zig build. | case | shell script | Zig build | |---|---|---| -| `EB_KEEP_LOGS_NOW` set but empty | the current time | refused, exit 2: `eb-keep-logs: EB_KEEP_LOGS_NOW must be seconds since the epoch, not ''` | -| `TZDIR` set but empty, `TZ` naming a zone file | the file under `/usr/share/zoneinfo`, as `date` reads it | the name is looked up relative to the working directory, so the zone is UTC unless a file of that name is there | -| `TZ` with a leading `:` that names no file, such as `:CET-1CEST,M3.5.0,M10.5.0/3` | the rule string after the `:`, as `date` reads it | UTC | +| `TZ` a rule string with daylight saving time but no rules, such as `NZST-12NZDT`, where `TZDIR` holds a `posixrules` file | glibc takes the changes from that file's transitions (New York's on most systems), moved by the difference between its offsets and the string's, and after the last of them uses the file's own rule and offsets: `TZ=NZST-12NZDT date -d 20260309 +%s` prints 1772971200, in standard time | the second Sunday in March to the first Sunday in November, at 02:00, in every year, as glibc has it without `posixrules`: 1772967600, in daylight time | +| `TZ` a rule string with an `Mm.w.d` rule whose month is not 1 to 12, or not given, such as `CET-1CEST,M13.1.0,M10.5.0/3` | glibc reads days from outside its table of months, which C leaves undefined: `TZ=CET-1CEST,M13.1.0,M10.5.0/3 date -d 20260701 +%s` prints 1782860400 | the rule falls on 1 January: 1782856800 | +| a zone file with leap seconds, as the `right/` zones and `zic -L` have | glibc counts them, 27 by 2026: `TZ=right/UTC date -d 20261101 +%s` prints 1793491227 | leap seconds are not counted: 1793491200 | +| a zone file whose first time type is daylight saving time, that has no transitions and a footer whose offsets are not those of its first standard time type, or whose footer glibc cannot read; no file of tzdata's is one, but `zic` writes the first kind for a zone that starts in daylight saving time | glibc uses the first standard time type before the first transition and when there are none, and UTC after the last transition when it cannot read the footer: `printf 'Zone X 1:00 1:00 CEST 2000\n\t1:00 - CET\n' > /tmp/x.zi && zic -d /tmp/z /tmp/x.zi && TZ=/tmp/z/X date -d 19990701 +%s` prints 930783600, in standard time | the first time type before the first transition, and the footer when there are no transitions, as RFC 8536 has it; after the last transition, its offset when the footer cannot be read: 930780000, in daylight time | diff --git a/build.zig b/build.zig index 7b1d6da..4cad483 100644 --- a/build.zig +++ b/build.zig @@ -42,15 +42,19 @@ pub fn build(b: *std.Build) void { // The shell suite of the old implementation, run against this binary. // It and the differential run below run in the build root: their script // paths are relative, and zig build may be started in a subdirectory. + // Both run every time, as the cache sees neither their scripts nor the + // date and tzdata of the host, which the suite compares with. const suite = b.addSystemCommand(&.{ "bash", "-c", "TOOL_BIN=\"$0\" exec bash tests/test_eb_keep_logs.sh" }); suite.addArtifactArg(exe); suite.setCwd(b.path(".")); suite.expectExitCode(0); + suite.has_side_effects = true; // The same invocations through the shell implementation and this one. const diff = b.addSystemCommand(&.{ "bash", "-c", "TOOL_BIN=\"$0\" exec bash tests/differential.sh" }); diff.addArtifactArg(exe); diff.setCwd(b.path(".")); diff.expectExitCode(0); + diff.has_side_effects = true; const test_step = b.step("test", "Run the unit tests, the command-line suite and the differential run"); test_step.dependOn(&b.addRunArtifact(unit).step); diff --git a/changelog.d/+compat-date.doc.md b/changelog.d/+compat-date.doc.md new file mode 100644 index 0000000..97f7d9f --- /dev/null +++ b/changelog.d/+compat-date.doc.md @@ -0,0 +1 @@ +COMPAT.md lists a `date` other than GNU's among the deliberate differences: the shell script's run ages follow that `date`, and uutils' `date`, Ubuntu's from 25.10, reads as UTC some `TZ` rule strings that glibc reads, where the Zig build's run ages are GNU `date`'s whatever `date` is. diff --git a/changelog.d/+compat-unintended.doc.md b/changelog.d/+compat-unintended.doc.md index ab54ae7..9ad74a3 100644 --- a/changelog.d/+compat-unintended.doc.md +++ b/changelog.d/+compat-unintended.doc.md @@ -1 +1 @@ -COMPAT.md lists three differences between the Zig build and the shell script that are bugs, not choices: an empty `EB_KEEP_LOGS_NOW` is refused instead of meaning the current time, an empty `TZDIR` leaves a zone name relative to the working directory, and a `TZ` with a leading `:` that names no file is UTC. Its rows on `EB_KEEP_LOGS_NOW` and on run ages no longer claim more than the Zig build does. +COMPAT.md has a section for differences between the Zig build and the shell script that are not choices, each with a command that shows it: a `TZ` rule string without rules where `TZDIR` holds a `posixrules` file, a rule month glibc reads out of bounds, zone files with leap seconds, and zone files unlike any of tzdata's. Its rows on `EB_KEEP_LOGS_NOW` and on run ages no longer claim more than the Zig build does. diff --git a/changelog.d/+doc-comments.doc.md b/changelog.d/+doc-comments.doc.md index 1d2e86c..4636ddf 100644 --- a/changelog.d/+doc-comments.doc.md +++ b/changelog.d/+doc-comments.doc.md @@ -1 +1 @@ -Every `pub` declaration has a doc comment, whose first sentence is the summary the API pages list, and the comment at the top of `src/localtime.zig` names the two cases in which the zone is read differently from glibc: an empty `TZDIR`, and a `TZ` with a leading `:` that names no file. +Every `pub` declaration has a doc comment, whose first sentence is the summary the API pages list. diff --git a/changelog.d/+mtime-comment.doc.md b/changelog.d/+mtime-comment.doc.md new file mode 100644 index 0000000..f54adf0 --- /dev/null +++ b/changelog.d/+mtime-comment.doc.md @@ -0,0 +1 @@ +The comments on `runAgeDays` in `src/main.zig` and on `_run_age_days` in the shell script give the right reason a run's age comes from its name, not its directory's mtime: compressing the run's logs moves the mtime, where a chmod changes only the ctime. diff --git a/changelog.d/+now-empty.bugfix.md b/changelog.d/+now-empty.bugfix.md new file mode 100644 index 0000000..9ef4b3e --- /dev/null +++ b/changelog.d/+now-empty.bugfix.md @@ -0,0 +1 @@ +`rotate` takes an empty `EB_KEEP_LOGS_NOW` as unset and dates runs against the current time, as the shell script does, instead of refusing it with exit 2. diff --git a/changelog.d/+suite-gnu-date.misc.md b/changelog.d/+suite-gnu-date.misc.md new file mode 100644 index 0000000..e053e01 --- /dev/null +++ b/changelog.d/+suite-gnu-date.misc.md @@ -0,0 +1 @@ +`zig build test` passes where `date` is not GNU's, as on Ubuntu from 25.10, where uutils' `date` failed three checks of the command-line suite: the suite takes a run's local midnight under `TZ` from GNU `date` (`gnudate` there) and runs the tool with that `date`, and where there is no GNU `date` it skips those checks, saying so on stderr. A failed check of the suite or a difference in the differential run is printed on stderr, which `zig build test` shows, instead of on stdout, which it drops, and both run on every `zig build test`, as its cache sees neither their scripts nor the host's `date` and tzdata. diff --git a/changelog.d/+tz-colon-rule.bugfix.md b/changelog.d/+tz-colon-rule.bugfix.md new file mode 100644 index 0000000..653b27f --- /dev/null +++ b/changelog.d/+tz-colon-rule.bugfix.md @@ -0,0 +1 @@ +When a `TZ` with a leading `:` names no zone file, as `:CET-1CEST,M3.5.0,M10.5.0/3` does, `rotate` reads the POSIX rule string after the `:`, as the shell script's `date` does, instead of dating runs in UTC. diff --git a/changelog.d/+tz-rule-glibc.bugfix.md b/changelog.d/+tz-rule-glibc.bugfix.md new file mode 100644 index 0000000..0544f7d --- /dev/null +++ b/changelog.d/+tz-rule-glibc.bugfix.md @@ -0,0 +1 @@ +`rotate` reads a malformed `TZ` rule string as far as the shell script's `date` reads it, instead of dating runs in UTC: text after the rules is ignored, a missing end rule is the first Sunday in November, and a rule cut short keeps what was read of it, as glibc keeps it. Rules also apply as glibc applies them, with the changes of the year in UTC, and up to 1970 with the changes of 1970. diff --git a/changelog.d/+tzdir-empty.bugfix.md b/changelog.d/+tzdir-empty.bugfix.md new file mode 100644 index 0000000..d82daaa --- /dev/null +++ b/changelog.d/+tzdir-empty.bugfix.md @@ -0,0 +1 @@ +`rotate` takes an empty `TZDIR` as unset and finds the zone `TZ` names under `/usr/share/zoneinfo`, as the shell script's `date` does, instead of looking it up relative to the working directory and dating runs in UTC when no file of that name is there. diff --git a/docs/orgmode/explanation/local-time.org b/docs/orgmode/explanation/local-time.org index 58dbde0..0e8d244 100644 --- a/docs/orgmode/explanation/local-time.org +++ b/docs/orgmode/explanation/local-time.org @@ -44,7 +44,7 @@ The Zig build has to give the same ages without =date=: it is one static binary - Days are 86,400 seconds long, as in the shell script, so for an hour around the midnight after a daylight saving change a run's age is a day off the calendar: just after midnight following the change to summer time, a run from two days before counts as one day old. - A run dated in the future is younger than 0 days and is left alone, except one dated less than a day ahead, which counts as 0 days old. - Only the date is checked: =HHMMSS= has to be six digits, not a time that exists. -- The zone is read as glibc reads it except in two cases, an empty =TZDIR= and a =TZ= with a leading =:= that names no file, which [[file:../reference/compatibility.org][Compatibility]] lists under unintended differences. +- A few zones give a midnight other than =date='s, as [[file:../reference/compatibility.org][Compatibility]] lists: among them a =TZ= rule string with daylight saving time but no rules, where the system has a =posixrules= file, and the =right/= zones, which count leap seconds. ** Further reading diff --git a/docs/orgmode/reference/cli.org b/docs/orgmode/reference/cli.org index d5079df..2504766 100644 --- a/docs/orgmode/reference/cli.org +++ b/docs/orgmode/reference/cli.org @@ -42,14 +42,14 @@ eb-keep-logs --help | --version ** Environment -| Variable | Command | Meaning | -|-----------------------+----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| =PATH= | =failed= | Where =eb= is looked up. =eb= runs with the environment =failed= got. | -| =EASYBUILD_TMPDIR= | =failed= | A failed command's output is copied only from below this directory, both paths resolved. Unset or empty, it is not copied. | -| =EB_KEEP_LOGS_NOW= | =rotate= | The time =rotate= takes as now, in seconds since the epoch. When set, it must be an integer; an empty value is refused too, where the shell script takes the current time. | -| =EB_PIPELINE_LOG_DIR= | =rotate= | The run that holds this path is left alone: it is the run eb-pipeline writes into. Unset, empty, or a path that does not exist, it changes nothing. | -| =TZ= | =rotate= | The time zone of the local midnight: unset, =/etc/localtime=; empty, UTC; otherwise a zone file, by name under =TZDIR= or by absolute path, or a POSIX rule string such as =CET-1CEST,M3.5.0,M10.5.0/3=. A value starting with =:= is a zone file only, where the shell script's =date= reads a rule string after the =:= too. A zone that cannot be read is UTC. | -| =TZDIR= | =rotate= | The directory of zone files, =/usr/share/zoneinfo= when unset. Set but empty, a zone name is looked up relative to the working directory, where the shell script's =date= uses =/usr/share/zoneinfo=. | +| Variable | Command | Meaning | +|-----------------------+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| =PATH= | =failed= | Where =eb= is looked up. =eb= runs with the environment =failed= got. | +| =EASYBUILD_TMPDIR= | =failed= | A failed command's output is copied only from below this directory, both paths resolved. Unset or empty, it is not copied. | +| =EB_KEEP_LOGS_NOW= | =rotate= | The time =rotate= takes as now, in seconds since the epoch: an integer. Unset or empty, it is the current time. | +| =EB_PIPELINE_LOG_DIR= | =rotate= | The run that holds this path is left alone: it is the run eb-pipeline writes into. Unset, empty, or a path that does not exist, it changes nothing. | +| =TZ= | =rotate= | The time zone of the local midnight: unset, =/etc/localtime=; empty, UTC; otherwise, with a leading =:= dropped, a zone file, by name under =TZDIR= or by absolute path, or else a POSIX rule string such as =CET-1CEST,M3.5.0,M10.5.0/3=, as the shell script's =date= reads it, a malformed one as far as glibc reads it. A zone that cannot be read is UTC; [[file:compatibility.org][Compatibility]] lists the zones =date= reads otherwise. | +| =TZDIR= | =rotate= | The directory of zone files, =/usr/share/zoneinfo= when unset or empty. | ** Exit status @@ -70,7 +70,7 @@ eb-keep-logs --help | --version | =ROOT ROOT is not a directory= | =ROOT= does not name a directory that can be opened. | | =OPTION needs a number of days= | =--compress-after= is missing, or a value is missing, empty, not decimal digits or too large. | | =--delete-after must be later than --compress-after= | =--delete-after= is not larger than =--compress-after=. | -| =EB_KEEP_LOGS_NOW must be seconds since the epoch, not 'VALUE'= | =EB_KEEP_LOGS_NOW= is set, and is not an integer. | +| =EB_KEEP_LOGS_NOW must be seconds since the epoch, not 'VALUE'= | =EB_KEEP_LOGS_NOW= is neither empty nor an integer. | | =cannot read ROOT ROOT=, =cannot read ROOT ROOT: ERROR= | =ROOT= could not be listed. | | =cannot read the arguments= | The arguments could not be read into memory. | diff --git a/eb-keep-logs b/eb-keep-logs index c2b1222..8f31d5d 100755 --- a/eb-keep-logs +++ b/eb-keep-logs @@ -207,7 +207,9 @@ cmd_failed() { } # Days since a run directory's name, YYYYMMDD_HHMMSS; empty when the name is -# not a run directory. The name, not the mtime: a later chmod moves the mtime. +# not a run directory. The name, not the mtime: compressing the run's logs +# moves the mtime of the directory they are in, where a chmod changes only +# the ctime. _run_age_days() { local base date now start base=$(basename "$1") diff --git a/src/localtime.zig b/src/localtime.zig index 145b539..9885901 100644 --- a/src/localtime.zig +++ b/src/localtime.zig @@ -3,16 +3,13 @@ //! //! The zone comes from TZ much as glibc reads it: unset means //! /etc/localtime; empty means UTC; otherwise the value, without a leading -//! ':', names a TZif file, under TZDIR (default /usr/share/zoneinfo) unless -//! it is an absolute path, and a value without a leading ':' that names no -//! file is a POSIX TZ rule string. A zone that cannot be read or parsed is -//! UTC. TZif files use their transitions, then the POSIX rule in their -//! footer for times after the last transition. -//! -//! Two cases differ from glibc, which takes an empty TZDIR as unset and -//! reads a rule string after a leading ':' too: here an empty TZDIR leaves a -//! zone name relative to the working directory, and a value with a leading -//! ':' that names no file is UTC. +//! ':', names a TZif file, under TZDIR (/usr/share/zoneinfo when TZDIR is +//! unset or empty) unless it is an absolute path, or, when it names no +//! file, is a POSIX TZ rule string, read and applied as glibc's tzset.c +//! reads and applies it where TZDIR has no posixrules file, a malformed one +//! included. A zone that cannot be read is UTC. TZif files use their +//! transitions, then the POSIX rule in their footer for times after the +//! last transition. const std = @import("std"); const common = @import("zig_common"); const fsx = common.fsx; @@ -21,14 +18,16 @@ const sys = common.sys; const Allocator = std.mem.Allocator; /// The day of the year on which a POSIX TZ rule starts or ends daylight -/// saving time: `Jn`, `n` or `Mm.w.d`. +/// saving time: `Jn`, `n` or `Mm.w.d`. It holds what glibc holds, so a rule +/// glibc stopped reading keeps what was read of it, a number not read being +/// 0, and a rule not read at all is `julian0` 0. pub const Rule = union(enum) { /// Day of year 1..365, February 29 never counted. julian1: u16, /// Day of year 0..365, February 29 counted. julian0: u16, - /// Month 1..12, week 1..5 (5 = last), weekday 0..6 (0 = Sunday). - mwd: struct { m: u8, w: u8, d: u8 }, + /// Weekday `d` (0 = Sunday) of week `w` (5 = the last) of month `m`. + mwd: struct { m: u16, w: u16, d: u16 }, }; /// A POSIX TZ rule string, such as `CET-1CEST,M3.5.0,M10.5.0/3`, as @@ -36,10 +35,10 @@ pub const Rule = union(enum) { pub const Posix = struct { /// Seconds east of UTC. std_off: i32, - /// Daylight saving time, null when the zone has none: `off` in seconds - /// east of UTC, and the days it starts and ends with their times in - /// seconds from that day's local midnight, `start_time` in standard time - /// and `end_time` in daylight time. + /// Daylight saving time, null when nothing follows standard time: `off` + /// in seconds east of UTC, and the days it starts and ends with their + /// times in seconds from that day's local midnight, `start_time` in + /// standard time and `end_time` in daylight time. dst: ?struct { off: i32, start: Rule, @@ -138,147 +137,233 @@ fn yearOf(days: i64) i64 { return yoe + era * 400 + @as(i64, if (m <= 2) 1 else 0); } -/// Day number (days since the epoch) on which `r` falls in year `y`. -fn ruleDay(r: Rule, y: i64) i64 { - const jan1 = daysFromCivil(y, 1, 1); +/// Days before each month and in the year, in a common and a leap year. +const mon_yday = [2][13]u16{ + .{ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, + .{ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }, +}; + +/// The UTC second at which rule `r`, `secs` after local midnight in a zone +/// `off` seconds east of UTC, falls in year `y`, worked out as glibc's +/// compute_change does: counted from 1970-01-01 in every year up to 1970, +/// with the weekday of a month's first day from Zeller's congruence in C's +/// truncating division. +fn change(r: Rule, secs: i32, off: i32, y: i64) i64 { + var t: i64 = if (y > 1970) daysFromCivil(y, 1, 1) * 86400 else 0; switch (r) { - .julian1 => |n| { - var d: i64 = n - 1; - if (isLeap(y) and n >= 60) d += 1; - return jan1 + d; + .julian1 => |d| { + t += (@as(i64, d) - 1) * 86400; + if (d >= 60 and isLeap(y)) t += 86400; }, - .julian0 => |n| return jan1 + n, - .mwd => |x| { - const first = daysFromCivil(y, x.m, 1); - const wd_first = @mod(first + 4, 7); // 1970-01-01 was a Thursday - var day = first + @mod(@as(i64, x.d) - wd_first, 7) + (@as(i64, x.w) - 1) * 7; - const last = first + daysInMonth(y, x.m) - 1; - while (day > last) day -= 7; - return day; + .julian0 => |d| t += @as(i64, d) * 86400, + // For a month outside 1..12 glibc reads past its month table, which + // C leaves undefined; here the rule falls on 1 January. + .mwd => |x| if (x.m >= 1 and x.m <= 12) { + const days = mon_yday[@intFromBool(isLeap(y))]; + const len: i64 = days[x.m] - days[x.m - 1]; + t += @as(i64, days[x.m - 1]) * 86400; + const m1: i64 = @rem(@as(i64, x.m) + 9, 12) + 1; + const yy0 = if (x.m <= 2) y - 1 else y; + const yy1 = @divTrunc(yy0, 100); + const yy2 = @rem(yy0, 100); + var dow = @rem(@divTrunc(26 * m1 - 2, 10) + 1 + yy2 + @divTrunc(yy2, 4) + @divTrunc(yy1, 4) - 2 * yy1, 7); + if (dow < 0) dow += 7; + var d = @as(i64, x.d) - dow; + if (d < 0) d += 7; + var i: u16 = 1; + while (i < x.w and d + 7 < len) : (i += 1) d += 7; + t += d * 86400; }, } + return t - off + secs; } -/// Seconds east of UTC that rule `p` puts in force at UTC time `t`: the -/// daylight offset from the year's start of daylight saving time to its end, -/// the standard offset otherwise. A start later in the year than the end, -/// as in the southern hemisphere, means daylight time spans the new year. +/// Seconds east of UTC that rule `p` puts in force at UTC time `t`, as +/// glibc's __tz_compute works it out from the changes in `t`'s year in UTC: +/// the daylight offset from the start of daylight saving time to its end, +/// or, when the end comes first, as in the southern hemisphere, until the +/// end and from the start; the standard offset otherwise, and always when +/// the two fall on the same second. pub fn posixOffset(p: Posix, t: i64) i32 { const dst = p.dst orelse return p.std_off; - const y = yearOf(@divFloor(t + p.std_off, 86400)); - // Start is given in standard time, end in daylight time. - const start = ruleDay(dst.start, y) * 86400 + dst.start_time - p.std_off; - const end = ruleDay(dst.end, y) * 86400 + dst.end_time - dst.off; - const in_dst = if (start < end) (t >= start and t < end) else !(t >= end and t < start); + const y = yearOf(@divFloor(t, 86400)); + const start = change(dst.start, dst.start_time, p.std_off, y); + const end = change(dst.end, dst.end_time, dst.off, y); + const in_dst = if (start > end) t < end or t >= start else t >= start and t < end; return if (in_dst) dst.off else p.std_off; } -const Parser = struct { - s: []const u8, - i: usize = 0, - - fn peek(p: *Parser) ?u8 { - return if (p.i < p.s.len) p.s[p.i] else null; +/// What C's `sscanf` stores for one `%hu` at `s[i.*..]`: white space, an +/// optional sign and decimal digits, the number read as `strtoul` reads it +/// and cut to 16 bits. Null, with `i` unmoved, when no digit follows. +fn scanHu(s: []const u8, i: *usize) ?u16 { + var j = i.*; + while (j < s.len and std.ascii.isWhitespace(s[j])) j += 1; + const neg = j < s.len and s[j] == '-'; + if (j < s.len and (s[j] == '+' or s[j] == '-')) j += 1; + const start = j; + var v: u64 = 0; + var over = false; + while (j < s.len and std.ascii.isDigit(s[j])) : (j += 1) { + const m = @mulWithOverflow(v, 10); + const a = @addWithOverflow(m[0], s[j] - '0'); + over = over or m[1] != 0 or a[1] != 0; + v = a[0]; } + if (j == start) return null; + i.* = j; + // strtoul gives ULONG_MAX for a number out of range, and negates the rest. + return if (over) std.math.maxInt(u16) else @truncate(if (neg) 0 -% v else v); +} + +/// What C's `sscanf(s, "%hu%n:%hu%n:%hu%n", ...)` reads from `s[i..]`: the +/// `n` numbers, up to three apart by `:`, it read with `scanHu`, and where +/// it stopped after the last of them. +const Hms = struct { + v: [3]u16 = .{ 0, 0, 0 }, + n: u2 = 0, + end: usize, - fn name(p: *Parser) !void { - if (p.peek() == '<') { - const close = std.mem.findScalarPos(u8, p.s, p.i, '>') orelse return error.Bad; - if (close - p.i - 1 < 3) return error.Bad; - p.i = close + 1; - return; + fn scan(s: []const u8, i: usize) Hms { + var h: Hms = .{ .end = i }; + var j = i; + while (h.n < 3) : (h.n += 1) { + if (h.n > 0) { + if (j >= s.len or s[j] != ':') break; + j += 1; + } + h.v[h.n] = scanHu(s, &j) orelse break; + h.end = j; } - const start = p.i; - while (p.peek()) |c| : (p.i += 1) if (!std.ascii.isAlphabetic(c)) break; - if (p.i - start < 3) return error.Bad; + return h; } +}; - fn num(p: *Parser, max: i64) !i64 { - const start = p.i; - while (p.peek()) |c| : (p.i += 1) if (!std.ascii.isDigit(c)) break; - if (p.i == start or p.i - start > 3) return error.Bad; - const v = std.fmt.parseInt(i64, p.s[start..p.i], 10) catch return error.Bad; - if (v > max) return error.Bad; - return v; +/// glibc 2.39's TZ parser, one method per function of its tzset.c. +const Parser = struct { + s: []const u8, + i: usize = 0, + + /// The byte at `k`, 0 past the end, where a C string has its NUL. + fn at(p: *const Parser, k: usize) u8 { + return if (k < p.s.len) p.s[k] else 0; } - /// [+-]hh[:mm[:ss]] in seconds. - fn hms(p: *Parser, max_h: i64) !i64 { - var sign: i64 = 1; - if (p.peek() == '+') p.i += 1 else if (p.peek() == '-') { - sign = -1; - p.i += 1; + /// parse_tzname: three or more letters, or three or more letters, + /// digits, `+` and `-` in `<>`. + fn name(p: *Parser) bool { + var j = p.i; + while (std.ascii.isAlphabetic(p.at(j))) j += 1; + if (j - p.i < 3) { + if (p.at(p.i) != '<') return false; + j = p.i + 1; + while (std.ascii.isAlphanumeric(p.at(j)) or p.at(j) == '+' or p.at(j) == '-') j += 1; + if (p.at(j) != '>' or j - p.i - 1 < 3) return false; + j += 1; } - var v = (try p.num(max_h)) * 3600; - if (p.peek() == ':') { - p.i += 1; - v += (try p.num(59)) * 60; - if (p.peek() == ':') { - p.i += 1; - v += try p.num(59); - } - } - return sign * v; + p.i = j; + return true; } - fn rule(p: *Parser) !Rule { - if (p.peek() == 'J') { - p.i += 1; - const n = try p.num(365); - if (n < 1) return error.Bad; - return .{ .julian1 = @intCast(n) }; - } - if (p.peek() == 'M') { - p.i += 1; - const m = try p.num(12); - if (p.peek() != '.') return error.Bad; - p.i += 1; - const w = try p.num(5); - if (p.peek() != '.') return error.Bad; + /// parse_offset: `[+-]` and `Hms.scan`, in seconds west of UTC with the + /// hours capped at 24 and the minutes and seconds at 59. Null when no + /// number follows the sign, which is still taken. + fn offset(p: *Parser) ?i32 { + var sign: i32 = -1; + if (p.at(p.i) == '-' or p.at(p.i) == '+') { + if (p.at(p.i) == '-') sign = 1; p.i += 1; - const d = try p.num(6); - if (m < 1 or w < 1) return error.Bad; - return .{ .mwd = .{ .m = @intCast(m), .w = @intCast(w), .d = @intCast(d) } }; } - return .{ .julian0 = @intCast(try p.num(365)) }; + const h = Hms.scan(p.s, p.i); + p.i = h.end; + if (h.n == 0) return null; + return sign * (@as(i32, @min(h.v[0], 24)) * 3600 + @as(i32, @min(h.v[1], 59)) * 60 + @min(h.v[2], 59)); } - fn ruleTime(p: *Parser) !i32 { - if (p.peek() != '/') return 2 * 3600; - p.i += 1; - return @intCast(try p.hms(167)); + /// parse_rule: `[,]date[/time]` into `r` and `secs`. The date is `Jn`, + /// `n`, `Mm.w.d`, or `default` at the end of the string; the time is + /// `[-]` and `Hms.scan`, with 2 for hours not read and no caps, 02:00 + /// without `/`. False, `i` unmoved, when the date cannot be read, when + /// anything but `/`, `,` or the end follows it, or the end follows `/`; + /// `r` and `secs` keep what was read. + fn rule(p: *Parser, r: *Rule, secs: *i32, default: Rule) bool { + var j = p.i; + if (p.at(j) == ',') j += 1; + const c = p.at(j); + if (c == 'J' or std.ascii.isDigit(c)) { + r.* = if (c == 'J') .{ .julian1 = 0 } else .{ .julian0 = 0 }; + if (c == 'J') { + j += 1; + if (!std.ascii.isDigit(p.at(j))) return false; + } + const start = j; + while (std.ascii.isDigit(p.at(j))) j += 1; + const d = std.fmt.parseInt(u16, p.s[start..j], 10) catch return false; + if (d > 365 or (c == 'J' and d == 0)) return false; + r.* = if (c == 'J') .{ .julian1 = d } else .{ .julian0 = d }; + } else if (c == 'M') { + var v: [3]u16 = .{ 0, 0, 0 }; + var n: usize = 0; + j += 1; + while (n < 3) : (n += 1) { + if (n > 0) { + if (p.at(j) != '.') break; + j += 1; + } + v[n] = scanHu(p.s, &j) orelse break; + } + r.* = .{ .mwd = .{ .m = v[0], .w = v[1], .d = v[2] } }; + if (n < 3 or v[0] < 1 or v[0] > 12 or v[1] < 1 or v[1] > 5 or v[2] > 6) return false; + } else if (c == 0) { + r.* = default; + } else return false; + switch (p.at(j)) { + 0, ',' => secs.* = 2 * 3600, + '/' => { + j += 1; + if (p.at(j) == 0) return false; + const neg = p.at(j) == '-'; + if (neg) j += 1; + const h = Hms.scan(p.s, j); + j = h.end; + const v = @as(i32, if (h.n > 0) h.v[0] else 2) * 3600 + @as(i32, h.v[1]) * 60 + h.v[2]; + secs.* = if (neg) -v else v; + }, + else => return false, + } + p.i = j; + return true; } }; -/// Parse a POSIX TZ rule string, `std offset[dst[offset][,start[/time],end[/time]]]`. -/// A name is three or more letters, or three or more characters in `<>`; -/// an offset is `[+-]hh[:mm[:ss]]` west of UTC. Without its offset, -/// daylight time is one hour ahead of standard time; without rules it runs -/// from the second Sunday in March to the first Sunday in November, and a -/// rule without a time changes at 02:00. Anything else, trailing text -/// included, is `error.Bad`. +/// Parse a POSIX TZ rule string, `std offset[dst[offset][,start[/time],end[/time]]]`, +/// as glibc 2.39 reads it: as far as it can, keeping what it read and +/// ignoring the rest. A name is three or more letters, or three or more +/// letters, digits, `+` and `-` in `<>`; an offset is `[+-]hh[:mm[:ss]]` +/// west of UTC, read as C's `%hu` reads numbers, with hours capped at 24 +/// and minutes and seconds at 59. Without its offset, daylight time is one +/// hour ahead of standard time; text after standard time that is not a +/// name gives daylight time an offset of 0 and is read for rules. Without +/// rules daylight time runs from the second Sunday in March to the first +/// Sunday in November, as in glibc where TZDIR has no posixrules file, and +/// a rule without a time changes at 02:00. A rule that cannot be read keeps +/// what was read of it, and after such a start rule the end rule is not +/// read. `error.Bad` when standard time cannot be read, which glibc takes as +/// UTC. pub fn parsePosix(s: []const u8) !Posix { var p: Parser = .{ .s = s }; - try p.name(); - const std_off: i32 = @intCast(-(try p.hms(24))); - if (p.peek() == null) return .{ .std_off = std_off }; - try p.name(); - var dst_off = std_off + 3600; - if (p.peek() != null and p.peek() != ',') dst_off = @intCast(-(try p.hms(24))); - var start: Rule = .{ .mwd = .{ .m = 3, .w = 2, .d = 0 } }; - var end: Rule = .{ .mwd = .{ .m = 11, .w = 1, .d = 0 } }; - var start_time: i32 = 2 * 3600; - var end_time: i32 = 2 * 3600; - if (p.peek() == ',') { - p.i += 1; - start = try p.rule(); - start_time = try p.ruleTime(); - if (p.peek() != ',') return error.Bad; - p.i += 1; - end = try p.rule(); - end_time = try p.ruleTime(); - } - if (p.peek() != null) return error.Bad; + if (!p.name()) return error.Bad; + if (p.at(p.i) != '+' and p.at(p.i) != '-' and !std.ascii.isDigit(p.at(p.i))) return error.Bad; + const std_off = p.offset() orelse return error.Bad; + if (p.at(p.i) == 0) return .{ .std_off = std_off }; + var dst_off: i32 = 0; + if (p.name()) dst_off = p.offset() orelse std_off + 3600; + var start: Rule = .{ .julian0 = 0 }; + var start_time: i32 = 0; + var end: Rule = .{ .julian0 = 0 }; + var end_time: i32 = 0; + if (p.rule(&start, &start_time, .{ .mwd = .{ .m = 3, .w = 2, .d = 0 } })) + _ = p.rule(&end, &end_time, .{ .mwd = .{ .m = 11, .w = 1, .d = 0 } }); return .{ .std_off = std_off, .dst = .{ .off = dst_off, .start = start, .start_time = start_time, .end = end, .end_time = end_time } }; } @@ -306,19 +391,19 @@ fn loadFile(gpa: Allocator, path: []const u8) !Zone { return .{ .transitions = trans, .offsets = offs, .first_off = first_off, .footer = footer, .arena = arena }; } -/// The zone named by `tz` (the value of TZ, or null when unset). +/// The zone named by `tz` (the value of TZ, or null when unset), with zone +/// files under `tzdir` (the value of TZDIR; /usr/share/zoneinfo when null +/// or empty). pub fn load(gpa: Allocator, tz: ?[]const u8, tzdir: ?[]const u8) Zone { const value = tz orelse return loadFile(gpa, "/etc/localtime") catch .{}; - if (value.len == 0) return .{}; - const name = if (value[0] == ':') value[1..] else value; - const dir = tzdir orelse "/usr/share/zoneinfo"; - if (name.len > 0) { - const path = if (name[0] == '/') gpa.dupe(u8, name) catch return .{} else std.fs.path.join(gpa, &.{ dir, name }) catch return .{}; - defer gpa.free(path); - if (loadFile(gpa, path)) |zone| return zone else |_| {} - } - if (value[0] == ':') return .{}; - const p = parsePosix(value) catch return .{}; + const name = if (value.len > 0 and value[0] == ':') value[1..] else value; + if (name.len == 0) return .{}; + const tzdir_s = tzdir orelse ""; + const dir = if (tzdir_s.len > 0) tzdir_s else "/usr/share/zoneinfo"; + const path = if (name[0] == '/') gpa.dupe(u8, name) catch return .{} else std.fs.path.join(gpa, &.{ dir, name }) catch return .{}; + defer gpa.free(path); + if (loadFile(gpa, path)) |zone| return zone else |_| {} + const p = parsePosix(name) catch return .{}; return .{ .footer = p }; } @@ -336,8 +421,83 @@ test "posix rules" { try std.testing.expectError(error.Bad, parsePosix("X1")); } +test "a rule string is read and applied as glibc reads and applies it" { + const gpa = std.testing.allocator; + // TZ, a date, and what `TZ=... date -d DATE +%s` prints with glibc 2.39, + // null where it refuses the date. + const rows = [_]struct { tz: []const u8, y: i64, m: u8, d: u8, want: ?i64 }{ + // Text after the rules is not read. + .{ .tz = "CET-1CEST,M3.5.0,M10.5.0/3x", .y = 2026, .m = 11, .d = 1, .want = 1793487600 }, + // Without an end rule, daylight time ends on the first Sunday in + // November at 02:00. + .{ .tz = "CET-1CEST,M3.5.0", .y = 2026, .m = 11, .d = 1, .want = 1793484000 }, + // A rule cut short after its date keeps the date, at 00:00. + .{ .tz = "CET-1CEST,M3.5.0,M10.5.0x", .y = 2026, .m = 10, .d = 25, .want = 1792882800 }, + // A time that is no number is 02:00, and the end rule cannot start + // at the x: it stays 1 January at 00:00, and daylight time lasts to + // the year's end. + .{ .tz = "CET-1CEST,M3.5.0/x,M10.5.0/3", .y = 2026, .m = 11, .d = 1, .want = 1793484000 }, + // Without a daylight name, daylight time is UTC. + .{ .tz = "CET-1,M3.5.0,M10.5.0/3", .y = 2026, .m = 7, .d = 1, .want = 1782864000 }, + .{ .tz = "CET-1,M3.5.0,M10.5.0/3", .y = 2026, .m = 11, .d = 1, .want = 1793487600 }, + // With no rules read either, daylight time runs from 1 January at + // 00:00 standard time to the year's end, skipping that midnight. + .{ .tz = "EST5x", .y = 2026, .m = 7, .d = 1, .want = 1782864000 }, + .{ .tz = "EST5x", .y = 2026, .m = 1, .d = 1, .want = null }, + // Hours are capped at 24, after white space and a sign as %hu takes + // them, -1 being 65535. + .{ .tz = "CET-25", .y = 2026, .m = 7, .d = 1, .want = 1782777600 }, + .{ .tz = "CET- 1", .y = 2026, .m = 7, .d = 1, .want = 1782860400 }, + .{ .tz = "CET+-1", .y = 2026, .m = 7, .d = 1, .want = 1782950400 }, + // A space is not part of a name in <>, so the zone is UTC. + .{ .tz = "-1", .y = 2026, .m = 7, .d = 1, .want = 1782864000 }, + // J0 is no day: reading stops there, and the changes fall before + // the year starts. + .{ .tz = "CET-1CEST,J0,J300", .y = 2026, .m = 7, .d = 1, .want = 1782860400 }, + // Up to 1970 the changes fall in 1970: no daylight time in 1960, or + // all of it where daylight time spans the new year. + .{ .tz = "CET-1CEST,M3.5.0,M10.5.0/3", .y = 1960, .m = 7, .d = 1, .want = -299898000 }, + .{ .tz = "AEST-10AEDT,M10.1.0,M4.1.0/3", .y = 1960, .m = 7, .d = 1, .want = -299934000 }, + // The changes are those of the year in UTC: this midnight is in 2026 + // there, after daylight time ended on 31 December. + .{ .tz = "XXX-10YYY,J1/0,J365/0", .y = 2027, .m = 1, .d = 1, .want = 1798725600 }, + }; + for (rows) |r| { + var z = load(gpa, r.tz, null); + defer z.deinit(); + try std.testing.expectEqual(r.want, z.fromLocal(daysFromCivil(r.y, r.m, r.d) * 86400)); + } +} + test "a local midnight inside a DST gap does not exist" { // America/Santiago moves 00:00 to 01:00 on the first Sunday of September. const z: Zone = .{ .footer = try parsePosix("<-04>4<-03>,M9.1.6/24,M4.1.6/24") }; try std.testing.expectEqual(@as(?i64, null), z.fromLocal(daysFromCivil(2026, 9, 6) * 86400)); } + +test "an empty TZDIR is the default directory, as glibc takes it" { + const gpa = std.testing.allocator; + const nov1 = daysFromCivil(2026, 11, 1) * 86400; + var unset = load(gpa, "Asia/Tokyo", null); + defer unset.deinit(); + // A system without the zone files has nothing to compare with. + if (unset.offsetAt(nov1) != 9 * 3600) return error.SkipZigTest; + var empty = load(gpa, "Asia/Tokyo", ""); + defer empty.deinit(); + // `TZDIR= TZ=Asia/Tokyo date -d 20261101 +%s` prints 1793458800. + try std.testing.expectEqual(@as(?i64, 1793458800), empty.fromLocal(nov1)); +} + +test "a rule string after a leading ':' is read, as glibc reads it" { + const gpa = std.testing.allocator; + var z = load(gpa, ":CET-1CEST,M3.5.0,M10.5.0/3", null); + defer z.deinit(); + // `TZ=':CET-1CEST,M3.5.0,M10.5.0/3' date -d 20260701 +%s` prints + // 1782856800, and 1793487600 for 20261101. + try std.testing.expectEqual(@as(?i64, 1782856800), z.fromLocal(daysFromCivil(2026, 7, 1) * 86400)); + try std.testing.expectEqual(@as(?i64, 1793487600), z.fromLocal(daysFromCivil(2026, 11, 1) * 86400)); + var colon = load(gpa, ":", null); + defer colon.deinit(); + // `TZ=: date -d 20261101 +%s` prints 1793491200, the UTC midnight. + try std.testing.expectEqual(@as(?i64, 1793491200), colon.fromLocal(daysFromCivil(2026, 11, 1) * 86400)); +} diff --git a/src/main.zig b/src/main.zig index c182756..f7ec9dd 100644 --- a/src/main.zig +++ b/src/main.zig @@ -428,7 +428,8 @@ fn parseDays(opt: []const u8, v: ?[]const u8) u64 { /// Days since a run directory's name, YYYYMMDD_HHMMSS, at its local /// midnight; null when the name is not a run directory. The name, not the -/// mtime: a later chmod moves the mtime. +/// mtime: compressing the run's logs moves the mtime of the directory they +/// are in, where a chmod changes only the ctime. fn runAgeDays(zone: *const localtime.Zone, name: []const u8, now: i64) ?i64 { if (name.len != 15 or name[8] != '_') return null; if (!allDigits(name[0..8]) or !allDigits(name[9..15])) return null; @@ -585,8 +586,9 @@ fn cmdRotate(c: Ctx, args: []const [:0]const u8) u8 { if (delete_after.? <= compress_after) die("--delete-after must be later than --compress-after", .{}); } - const now: i64 = if (c.getenv("EB_KEEP_LOGS_NOW")) |s| - std.fmt.parseInt(i64, s, 10) catch die("EB_KEEP_LOGS_NOW must be seconds since the epoch, not '{s}'", .{s}) + const now_s = c.getenv("EB_KEEP_LOGS_NOW") orelse ""; + const now: i64 = if (now_s.len > 0) + std.fmt.parseInt(i64, now_s, 10) catch die("EB_KEEP_LOGS_NOW must be seconds since the epoch, not '{s}'", .{now_s}) else blk: { var ts: linux.timespec = undefined; _ = linux.clock_gettime(.REALTIME, &ts); diff --git a/tests/differential.sh b/tests/differential.sh index e133bb8..1be5b00 100644 --- a/tests/differential.sh +++ b/tests/differential.sh @@ -33,9 +33,12 @@ compare() { return fi done - echo "DIFF ${label}: exit ${oc} vs ${nc}" - diff "${work}/o.out" "${work}/n.out" | sed 's/^/ out /' - diff "${work}/o.err" "${work}/n.err" | sed 's/^/ err /' + # On stderr: zig build test shows a script's stderr, not stdout. + { + echo "DIFF ${label}: exit ${oc} vs ${nc}" + diff "${work}/o.out" "${work}/n.out" | sed 's/^/ out /' + diff "${work}/o.err" "${work}/n.err" | sed 's/^/ err /' + } >&2 diffs=$((diffs + 1)) else echo "same ${label}" @@ -111,6 +114,7 @@ compare "rotate, bad compress" rotate "${work}/logs" --compress-after=x compare "rotate, delete not later" rotate "${work}/logs" --compress-after 5 --delete-after 5 compare "rotate, empty delete" rotate "${work}/logs" --compress-after 5 --delete-after "" compare "rotate, nothing to do" rotate "${work}/logs" --compress-after 5 --delete-after 9 +EB_KEEP_LOGS_NOW='' compare "rotate, empty EB_KEEP_LOGS_NOW" rotate "${work}/logs" --compress-after 5 echo "${diffs} differences" [ "${diffs}" -eq 0 ] diff --git a/tests/test_eb_keep_logs.sh b/tests/test_eb_keep_logs.sh index 5474ed2..be475aa 100755 --- a/tests/test_eb_keep_logs.sh +++ b/tests/test_eb_keep_logs.sh @@ -10,13 +10,16 @@ tool="${TOOL_BIN:-${repo_root}/eb-keep-logs}" unset EB_PIPELINE_LOG_DIR fails=0 +# Failures go to stderr: zig build test shows a script's stderr, not stdout. check() { if [ "$2" = "$3" ]; then echo "ok $1" else - echo "FAIL $1" - echo " expected: $3" - echo " got: $2" + { + echo "FAIL $1" + echo " expected: $3" + echo " got: $2" + } >&2 fails=$((fails + 1)) fi } @@ -350,5 +353,71 @@ check "own run through a pipe: not compressed" "$(lsrun "${log_dir}")" "F.stdout EB_KEEP_LOGS_NOW=${next_day} "${tool}" rotate "${piped}" --compress-after 1 > /dev/null 2>&1 check "a finished run is compressed" "$(lsrun "${log_dir}")" "F.stdout.log.gz rotate.log.gz " +# rotate: an empty EB_KEEP_LOGS_NOW is the current time, as an unset one is +now_root="${work}/now" +old_run="$(TZ=UTC date -d '40 days ago' +%Y%m%d)_000000" +young_run="$(TZ=UTC date -d '20 days ago' +%Y%m%d)_000000" +mkdir -p "${now_root}/${old_run}" "${now_root}/${young_run}" +echo old > "${now_root}/${old_run}/H.stdout.log" +echo young > "${now_root}/${young_run}/I.stdout.log" +check "empty EB_KEEP_LOGS_NOW: the current time" \ + "$(TZ=UTC EB_KEEP_LOGS_NOW='' "${tool}" rotate "${now_root}" --compress-after 30 2>&1)" \ + "eb-keep-logs rotate: 1 file compressed, 0 runs deleted under ${now_root}" +check "empty EB_KEEP_LOGS_NOW: the run 40 days old compressed" "$(lsrun "${now_root}/${old_run}")" "H.stdout.log.gz " + +# rotate: with ENV, a run's local midnight is the one GNU date gives, and the +# tool runs with GNU date as date. Thirty days after it the run is 30 days +# old, and 29 a second before. Ubuntu's date is uutils' from 25.10, GNU's +# being gnudate; uutils' reads as UTC some TZ rule strings that glibc reads. +gnu_date= +for d in date gnudate; do + if "${d}" --version 2>/dev/null | grep -q '(GNU coreutils)'; then + gnu_date=$(command -v "${d}") + mkdir -p "${work}/gnu" + ln -s "${gnu_date}" "${work}/gnu/date" + break + fi +done +zoned() { + local label=$1 midnight + shift + if [ -z "${gnu_date}" ]; then + echo "skip ${label}: no GNU date to compare with" >&2 + return + fi + rm -rf "${work}/zoned" + mkdir -p "${work}/zoned/20261101_000000" + echo log > "${work}/zoned/20261101_000000/J.stdout.log" + midnight=$(env "$@" "${gnu_date}" -d 20261101 +%s) + set -- PATH="${work}/gnu:${PATH}" "$@" + env "$@" EB_KEEP_LOGS_NOW=$((midnight + 30 * 86400 - 1)) "${tool}" rotate "${work}/zoned" --compress-after 30 >/dev/null + check "${label}: 29 days old a second before date's midnight" "$(lsrun "${work}/zoned/20261101_000000")" "J.stdout.log " + env "$@" EB_KEEP_LOGS_NOW=$((midnight + 30 * 86400)) "${tool}" rotate "${work}/zoned" --compress-after 30 >/dev/null + check "${label}: 30 days old at date's midnight" "$(lsrun "${work}/zoned/20261101_000000")" "J.stdout.log.gz " +} +zoned "TZ naming a zone file" TZ=Asia/Tokyo +zoned "TZDIR empty" TZDIR= TZ=Asia/Tokyo +zoned "TZ ':' then a rule string" TZ=':AEST-10AEDT,M10.1.0,M4.1.0/3' +zoned "TZ rule string with text after it" TZ='CET-1CEST,M3.5.0,M10.5.0/3x' +zoned "TZ rule string without an end rule" TZ='CET-1CEST,M3.5.0' + +# rotate: a run's age is its name's, not its directory's mtime. A chmod +# leaves the mtime and compressing the logs in the run moves it. +mt_root="${work}/mtime" +mkdir -p "${mt_root}/20261001_120000" "${mt_root}/20261110_120000" +echo old > "${mt_root}/20261001_120000/K.stdout.log" +echo young > "${mt_root}/20261110_120000/L.stdout.log" +touch -d '2026-10-01 12:00' "${mt_root}/20261001_120000" +touch -d '2020-01-01 00:00' "${mt_root}/20261110_120000" +set_mtime=$(date -d '2026-10-01 12:00' +%s) +chmod o-rwx "${mt_root}/20261001_120000" +check "chmod leaves a run's mtime" "$(stat -c %Y "${mt_root}/20261001_120000")" "${set_mtime}" +"${tool}" rotate "${mt_root}" --compress-after 30 >/dev/null +check "compressing a run's logs moves its mtime" \ + "$([ "$(stat -c %Y "${mt_root}/20261001_120000")" != "${set_mtime}" ] && echo moved)" "moved" +check "an old mtime on a young run: not compressed" "$(lsrun "${mt_root}/20261110_120000")" "L.stdout.log " +"${tool}" rotate "${mt_root}" --compress-after 30 --delete-after 40 >/dev/null +check "a new mtime on an old run: deleted" "$(lsrun "${mt_root}")" "20261110_120000 " + if [ "${fails}" -ne 0 ]; then echo "${fails} failed"; exit 1; fi echo "all passed"