Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
86 changes: 85 additions & 1 deletion src/uu/date/src/date.rs
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a minor difference in the error message if an invalid date contains a comment: GNU date shows the comment whereas we don't:

$ date -d "(foo)2026-01-05)"
date: invalid date ‘(foo)2026-01-05)’
$ cargo run -q date -d "(foo)2026-01-05)"
date: invalid date '2026-01-05)'

I'm not sure whether we want to address this issue.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I just noticed a bug ;-)

$ cargo run -q date -d "((foo)2026-01-05)"
date: invalid date '2026-01-05)'
$ date -d "((foo)2026-01-05)"
Fri Jan  9 12:00:00 AM CET 2026

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added upstream:
coreutils/coreutils@210c000

Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

// spell-checker:ignore strtime ; (format) DATEFILE MMDDhhmm ; (vars) datetime datetimes getres AWST ACST AEST
// spell-checker:ignore strtime ; (format) DATEFILE MMDDhhmm ; (vars) datetime datetimes getres AWST ACST AEST foobarbaz

mod locale;

use clap::{Arg, ArgAction, Command};
use jiff::fmt::strtime::{self, BrokenDownTime, Config, PosixCustom};
use jiff::tz::{TimeZone, TimeZoneDatabase};
use jiff::{Timestamp, Zoned};
use std::borrow::Cow;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Write};
Expand Down Expand Up @@ -130,6 +131,52 @@ enum DayDelta {
Next,
}

/// Strip parenthesized comments from a date string.
///
/// GNU date removes balanced parentheses and their content, treating them as comments.
/// If parentheses are unbalanced, everything from the unmatched '(' onwards is ignored.
///
/// Examples:
/// - "2026(comment)-01-05" -> "2026-01-05"
/// - "1(ignore comment to eol" -> "1"
/// - "(" -> ""
/// - "((foo)2026-01-05)" -> ""
fn strip_parenthesized_comments(input: &str) -> Cow<'_, str> {
if !input.contains('(') {
return Cow::Borrowed(input);
}

let mut result = String::with_capacity(input.len());
let mut chars = input.chars();

while let Some(c) = chars.next() {
if c == '(' {
// Look for matching closing parenthesis
let mut depth = 1;
for inner_c in chars.by_ref() {
if inner_c == '(' {
depth += 1;
} else if inner_c == ')' {
depth -= 1;
if depth == 0 {
break;
}
}
}

// If unmatched opening paren (depth > 0), stop processing entirely
if depth > 0 {
break;
}
// If balanced, the parentheses and their content are skipped (comment)
} else {
result.push(c);
}
}

Cow::Owned(result)
}

/// Parse military timezone with optional hour offset.
/// Pattern: single letter (a-z except j) optionally followed by 1-2 digits.
/// Returns Some(total_hours_in_utc) or None if pattern doesn't match.
Expand Down Expand Up @@ -286,7 +333,10 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
// Iterate over all dates - whether it's a single date or a file.
let dates: Box<dyn Iterator<Item = _>> = match settings.date_source {
DateSource::Human(ref input) => {
// GNU compatibility (Comments in parentheses)
let input = strip_parenthesized_comments(input);
let input = input.trim();

// GNU compatibility (Empty string):
// An empty string (or whitespace-only) should be treated as midnight today.
let is_empty_or_whitespace = input.is_empty();
Expand Down Expand Up @@ -887,4 +937,38 @@ mod tests {
assert_eq!(parse_military_timezone_with_offset("m999"), None); // Too long
assert_eq!(parse_military_timezone_with_offset("9m"), None); // Starts with digit
}

#[test]
fn test_strip_parenthesized_comments() {
assert_eq!(strip_parenthesized_comments("hello"), "hello");
assert_eq!(strip_parenthesized_comments("2026-01-05"), "2026-01-05");
assert_eq!(strip_parenthesized_comments("("), "");
assert_eq!(strip_parenthesized_comments("1(comment"), "1");
assert_eq!(
strip_parenthesized_comments("2026-01-05(this is a comment"),
"2026-01-05"
);
assert_eq!(
strip_parenthesized_comments("2026(comment)-01-05"),
"2026-01-05"
);
assert_eq!(strip_parenthesized_comments("()"), "");
assert_eq!(strip_parenthesized_comments("((foo)2026-01-05)"), "");

// These cases test the balanced parentheses removal feature
// which extends beyond what GNU date strictly supports
assert_eq!(strip_parenthesized_comments("a(b)c"), "ac");
assert_eq!(strip_parenthesized_comments("a(b)c(d)e"), "ace");
assert_eq!(strip_parenthesized_comments("(a)(b)"), "");

// When parentheses are unmatched, processing stops at the unmatched opening paren
// In this case "a(b)c(d", the (b) is balanced but (d is unmatched
// We process "a(b)c" and stop at the unmatched "(d"
assert_eq!(strip_parenthesized_comments("a(b)c(d"), "ac");

// Additional edge cases for nested and complex parentheses
assert_eq!(strip_parenthesized_comments("a(b(c)d)e"), "ae"); // Nested balanced
assert_eq!(strip_parenthesized_comments("a(b(c)d"), "a"); // Nested unbalanced
assert_eq!(strip_parenthesized_comments("a(b)c(d)e(f"), "ace"); // Multiple groups, last unmatched
}
}
37 changes: 37 additions & 0 deletions tests/by-util/test_date.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1497,3 +1497,40 @@ fn test_date_format_x_locale_aware() {
.succeeds()
.stdout_is("19/01/1997\n");
}

#[test]
fn test_date_parenthesis_comment() {
// GNU compatibility: Text in parentheses is treated as a comment and removed.
let cases = [
// (input, format, expected_output)
("(", "+%H:%M:%S", "00:00:00\n"),
("1(ignore comment to eol", "+%H:%M:%S", "01:00:00\n"),
("2026-01-05(this is a comment", "+%Y-%m-%d", "2026-01-05\n"),
("2026(this is a comment)-01-05", "+%Y-%m-%d", "2026-01-05\n"),
("((foo)2026-01-05)", "+%H:%M:%S", "00:00:00\n"), // Nested/unbalanced case
("(2026-01-05(foo))", "+%H:%M:%S", "00:00:00\n"), // Balanced parentheses removed (empty result)
];

for (input, format, expected) in cases {
new_ucmd!()
.env("TZ", "UTC")
.arg("-d")
.arg(input)
.arg("-u")
.arg(format)
.succeeds()
.stdout_only(expected);
}
}

#[test]
fn test_date_parenthesis_vs_other_special_chars() {
// Ensure parentheses are special but other chars like [, ., ^ are still rejected
for special_char in ["[", ".", "^"] {
new_ucmd!()
.arg("-d")
.arg(special_char)
.fails()
.stderr_contains("invalid date");
}
}
Loading