Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

project name formatter, new util moment_format_to_chrono with test

Ilya28c833f724f3
diff --git a/Cargo.lock b/Cargo.lock
index 1141acf3c..ab6a3c1df 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -177,9 +177,9 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aho-corasick"
-version = "1.1.3"
+version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
dependencies = [
"memchr",
]
@@ -1174,6 +1174,7 @@ dependencies = [
name = "cap-desktop"
version = "0.3.82"
dependencies = [
+ "aho-corasick",
"anyhow",
"async-stream",
"axum",
@@ -1221,9 +1222,11 @@ dependencies = [
"png 0.17.16",
"posthog-rs",
"rand 0.8.5",
+ "regex",
"relative-path",
"reqwest 0.12.24",
"rodio",
+ "sanitize-filename",
"scap-direct3d",
"scap-screencapturekit",
"scap-targets",
@@ -1598,6 +1601,7 @@ dependencies = [
name = "cap-utils"
version = "0.1.0"
dependencies = [
+ "aho-corasick",
"directories 5.0.1",
"flume",
"futures",
@@ -4122,7 +4126,7 @@ dependencies = [
"libc",
"percent-encoding",
"pin-project-lite",
- "socket2 0.5.10",
+ "socket2 0.6.0",
"system-configuration 0.6.1",
"tokio",
"tower-service",
@@ -4809,7 +4813,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667"
dependencies = [
"cfg-if",
- "windows-targets 0.48.5",
+ "windows-targets 0.53.3",
]
[[package]]
@@ -6826,7 +6830,7 @@ dependencies = [
"quinn-udp",
"rustc-hash 2.1.1",
"rustls 0.23.31",
- "socket2 0.5.10",
+ "socket2 0.6.0",
"thiserror 2.0.16",
"tokio",
"tracing",
@@ -6863,7 +6867,7 @@ dependencies = [
"cfg_aliases 0.2.1",
"libc",
"once_cell",
- "socket2 0.5.10",
+ "socket2 0.6.0",
"tracing",
"windows-sys 0.60.2",
]
@@ -7638,6 +7642,15 @@ dependencies = [
"winapi-util",
]
+[[package]]
+name = "sanitize-filename"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc984f4f9ceb736a7bb755c3e3bd17dc56370af2600c9780dcc48c66453da34d"
+dependencies = [
+ "regex",
+]
+
[[package]]
name = "scap-cpal"
version = "0.1.0"
@@ -11088,7 +11101,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "windows-sys 0.48.0",
+ "windows-sys 0.61.0",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
index 0b35f66d4..268db6c43 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,11 @@
[workspace]
resolver = "2"
-members = ["apps/cli", "apps/desktop/src-tauri", "crates/*", "crates/workspace-hack"]
+members = [
+ "apps/cli",
+ "apps/desktop/src-tauri",
+ "crates/*",
+ "crates/workspace-hack",
+]
[workspace.dependencies]
anyhow = { version = "1.0.86" }
@@ -40,6 +45,7 @@ sentry = { version = "0.42.0", features = [
] }
tracing = "0.1.41"
futures = "0.3.31"
+aho-corasick = "1.1.4"
cidre = { git = "https://github.com/CapSoftware/cidre", rev = "bf84b67079a8", features = [
"macos_12_7",
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 02b6b2738..c58d51c6a 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -20,11 +20,11 @@ swift-rs = { version = "1.0.6", features = ["build"] }
[dependencies]
tauri = { workspace = true, features = [
- "macos-private-api",
- "protocol-asset",
- "tray-icon",
- "image-png",
- "devtools",
+ "macos-private-api",
+ "protocol-asset",
+ "tray-icon",
+ "image-png",
+ "devtools",
] }
tauri-specta = { version = "=2.0.0-rc.20", features = ["derive", "typescript"] }
tauri-plugin-dialog = "2.2.0"
@@ -60,6 +60,7 @@ tracing.workspace = true
tempfile = "3.9.0"
ffmpeg.workspace = true
chrono = { version = "0.4.31", features = ["serde"] }
+regex = "1.10.4"
rodio = "0.19.0"
png = "0.17.13"
device_query = "4.0.1"
@@ -106,22 +107,24 @@ tauri-plugin-sentry = "0.5.0"
thiserror.workspace = true
bytes = "1.10.1"
async-stream = "0.3.6"
+sanitize-filename = "0.6.0"
tracing-futures = { version = "0.2.5", features = ["futures-03"] }
tracing-opentelemetry = "0.32.0"
opentelemetry = "0.31.0"
-opentelemetry-otlp = "0.31.0" #{ version = , features = ["http-proto", "reqwest-client"] }
+opentelemetry-otlp = "0.31.0" #{ version = , features = ["http-proto", "reqwest-client"] }
opentelemetry_sdk = { version = "0.31.0", features = ["rt-tokio", "trace"] }
posthog-rs = "0.3.7"
workspace-hack = { version = "0.1", path = "../../../crates/workspace-hack" }
+aho-corasick.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
core-graphics = "0.24.0"
core-foundation = "0.10.0"
objc2-app-kit = { version = "0.3.0", features = [
- "NSWindow",
- "NSResponder",
- "NSHapticFeedback",
+ "NSWindow",
+ "NSResponder",
+ "NSHapticFeedback",
] }
cocoa = "0.26.0"
objc = "0.2.7"
@@ -131,10 +134,10 @@ cidre = { workspace = true }
[target.'cfg(target_os= "windows")'.dependencies]
windows = { workspace = true, features = [
- "Win32_Foundation",
- "Win32_System",
- "Win32_UI_WindowsAndMessaging",
- "Win32_Graphics_Gdi",
+ "Win32_Foundation",
+ "Win32_System",
+ "Win32_UI_WindowsAndMessaging",
+ "Win32_Graphics_Gdi",
] }
windows-sys = { workspace = true }
diff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rs
index fbd618985..96a81e1cf 100644
--- a/apps/desktop/src-tauri/src/general_settings.rs
+++ b/apps/desktop/src-tauri/src/general_settings.rs
@@ -120,6 +120,8 @@ pub struct GeneralSettingsStore {
pub delete_instant_recordings_after_upload: bool,
#[serde(default = "default_instant_mode_max_resolution")]
pub instant_mode_max_resolution: u32,
+ #[serde(default)]
+ pub default_project_name_template: Option<String>,
}
fn default_enable_native_camera_preview() -> bool {
@@ -184,6 +186,7 @@ impl Default for GeneralSettingsStore {
excluded_windows: default_excluded_windows(),
delete_instant_recordings_after_upload: false,
instant_mode_max_resolution: 1920,
+ default_project_name_template: None,
}
}
}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 9529e3210..302924089 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -7,6 +7,7 @@ use cap_project::{
TimelineConfiguration, TimelineSegment, UploadMeta, ZoomMode, ZoomSegment,
cursor::CursorEvents,
};
+use cap_recording::RecordingOptionCaptureTarget;
use cap_recording::feeds::camera::CameraFeedLock;
use cap_recording::{
RecordingMode,
@@ -19,10 +20,14 @@ use cap_recording::{
studio_recording,
};
use cap_rendering::ProjectRecordingsMeta;
-use cap_utils::{ensure_dir, spawn_actor};
+use cap_utils::{ensure_dir, moment_format_to_chrono, spawn_actor};
use futures::stream;
+use lazy_static::lazy_static;
+use regex::Regex;
use serde::{Deserialize, Serialize};
use specta::Type;
+use std::borrow::Cow;
+use std::sync::OnceLock;
use std::{
collections::{HashMap, VecDeque},
path::PathBuf,
@@ -257,6 +262,131 @@ pub enum RecordingAction {
UpgradeRequired,
}
+lazy_static! {
+ static ref DATE_REGEX: Regex = Regex::new(r"\{date(?::([^}]+))?\}").unwrap();
+ static ref TIME_REGEX: Regex = Regex::new(r"\{time(?::([^}]+))?\}").unwrap();
+ static ref DATETIME_REGEX: Regex = Regex::new(r"\{datetime(?::([^}]+))?\}").unwrap();
+ static ref TIMESTAMP_REGEX: Regex = Regex::new(r"\{timestamp(?::([^}]+))?\}").unwrap();
+}
+
+pub const DEFAULT_FILENAME_TEMPLATE: &str = "{target} {datetime}";
+
+/// Formats the project name using a template string.
+///
+/// # Template Variables
+///
+/// The template supports the following variables that will be replaced with actual values:
+///
+/// ## Recording Mode Variables
+/// - `{recording_mode}` - The recording mode: "Studio" or "Instant"
+/// - `{mode}` - Short form of recording mode: "studio" or "instant"
+///
+/// ## Target Variables
+/// - `{target_kind}` - The type of capture target: "Display", "Window", or "Area"
+/// - `{target_name}` - The specific name of the target (e.g., "Built-in Retina Display", "Chrome", etc.)
+/// - `{target}` - Combined target information (e.g., "Display (Built-in Retina Display)")
+///
+/// ## Date/Time Variables
+/// - `{date}` - Current date in YYYY-MM-DD format (e.g., "2025-09-11")
+/// - `{time}` - Current time in HH:MM AM/PM format (e.g., "3:23 PM")
+/// - `{datetime}` - Combined date and time (e.g., "2025-09-11 3:23 PM")
+/// - `{timestamp}` - Unix timestamp (e.g., "1705326783")
+///
+/// ## Customizable Date/Time Formats
+/// You can customize date and time formats by adding moment format specifiers:
+/// - `{date:YYYY-MM-DD}` - Custom date format
+/// - `{time:HH:mm}` - 24-hour time format
+/// - `{time:hh:mm A}` - 12-hour time with AM/PM
+/// - `{datetime:YYYY-MM-DD HH:mm}` - Combined custom format
+///
+/// ## Examples
+///
+/// `{recording_mode} Recording {target_kind} ({target_name}) {date} {time}`
+/// -> "Instant Recording Display (Built-in Retina Display) 2025-11-12 3:23 PM"
+///
+/// `{recording_mode} Recording {target_kind} ({target_name}) {date} {time}`
+/// -> "instant_display_20250115_1523"
+///
+/// `Cap {target} - {datetime:YYYY-MM-DD HH:mm}`
+/// -> "Cap Display (Built-in Retina Display) - 2025-11-12 15:23"
+///
+///
+/// # Arguments
+///
+/// * `template` - The template string with variables to replace
+/// * `inputs` - The recording inputs containing target and mode information
+///
+/// # Returns
+///
+/// Returns `String` with the formatted project name
+pub fn format_project_name<'a>(
+ template: Option<&str>,
+ target_name: &'a str,
+ target_kind: &'a str,
+ recording_mode: RecordingMode,
+ datetime: chrono::DateTime<chrono::Local>,
+) -> String {
+ static AC: OnceLock<aho_corasick::AhoCorasick> = OnceLock::new();
+ let template = template.unwrap_or(DEFAULT_FILENAME_TEMPLATE);
+
+ // Get recording mode information
+ let (recording_mode, mode) = match recording_mode {
+ RecordingMode::Studio => ("Studio", "studio"),
+ RecordingMode::Instant => ("Instant", "instant"),
+ };
+
+ let ac = AC.get_or_init(|| {
+ aho_corasick::AhoCorasick::new(&[
+ "{recording_mode}",
+ "{mode}",
+ "{target_kind}",
+ "{target_name}",
+ "{target}",
+ ])
+ .expect("Failed to build AhoCorasick automaton")
+ });
+
+ let target_combined = format!("{target_kind} ({target_name})");
+ let result = ac
+ .try_replace_all(
+ &template,
+ &[
+ recording_mode,
+ mode,
+ target_kind,
+ target_name,
+ &target_combined,
+ ],
+ )
+ .expect("AhoCorasick replace should never fail with default configuration");
+
+ let result = DATE_REGEX.replace_all(&result, |caps: &regex::Captures| {
+ let format = caps.get(1).map(|m| m.as_str()).unwrap_or("%Y-%m-%d");
+ let chrono_format = moment_format_to_chrono(format);
+ datetime.format(&chrono_format).to_string()
+ });
+
+ let result = TIME_REGEX.replace_all(&result, |caps: &regex::Captures| {
+ let format = caps.get(1).map(|m| m.as_str()).unwrap_or("%l:%M %p");
+ let chrono_format = moment_format_to_chrono(format);
+ datetime.format(&chrono_format).to_string()
+ });
+
+ let result = DATETIME_REGEX.replace_all(&result, |caps: &regex::Captures| {
+ let format = caps.get(1).map(|m| m.as_str()).unwrap_or("%Y-%m-%d %H:%M");
+ let chrono_format = moment_format_to_chrono(format);
+ datetime.format(&chrono_format).to_string()
+ });
+
+ let result = TIMESTAMP_REGEX.replace_all(&result, |caps: &regex::Captures| {
+ caps.get(1)
+ .map(|m| datetime.format(m.as_str()).to_string())
+ .unwrap_or_else(|| datetime.timestamp().to_string())
+ });
+
+ result.into_owned()
+}
+
#[tauri::command]
#[specta::specta]
#[tracing::instrument(name = "recording", skip_all)]
@@ -269,16 +399,37 @@ pub async fn start_recording(
return Err("Recording already in progress".to_string());
}
- let id = uuid::Uuid::new_v4().to_string();
let general_settings = GeneralSettingsStore::get(&app).ok().flatten();
let general_settings = general_settings.as_ref();
- let recording_dir = app
- .path()
- .app_data_dir()
- .unwrap()
- .join("recordings")
- .join(format!("{id}.cap"));
+ let project_name = format_project_name(
+ general_settings
+ .and_then(|s| s.default_project_name_template.clone())
+ .as_deref(),
+ inputs
+ .capture_target
+ .title()
+ .as_deref()
+ .unwrap_or("Unknown"),
+ inputs.capture_target.kind_str(),
+ inputs.mode,
+ chrono::Local::now(),
+ );
+
+ let filename = sanitize_filename::sanitize_with_options(
+ &project_name,
+ sanitize_filename::Options {
+ replacement: "-",
+ ..Default::default()
+ },
+ );
+
+ let recordings_base_dir = app.path().app_data_dir().unwrap().join("recordings");
+
+ let recording_dir = recordings_base_dir.join(&cap_utils::ensure_unique_filename(
+ &filename,
+ &recordings_base_dir,
+ )?);
ensure_dir(&recording_dir).map_err(|e| format!("Failed to create recording directory: {e}"))?;
state_mtx
@@ -351,17 +502,10 @@ pub async fn start_recording(
RecordingMode::Studio => None,
};
- let date_time = if cfg!(windows) {
- // Windows doesn't support colon in file paths
- chrono::Local::now().format("%Y-%m-%d %H.%M.%S")
- } else {
- chrono::Local::now().format("%Y-%m-%d %H:%M:%S")
- };
-
let meta = RecordingMeta {
platform: Some(Platform::default()),
project_path: recording_dir.clone(),
- pretty_name: format!("{target_name} {date_time}"),
+ pretty_name: project_name,
inner: match inputs.mode {
RecordingMode::Studio => {
RecordingMetaInner::Studio(StudioRecordingMeta::MultipleSegments {
diff --git a/crates/recording/src/sources/screen_capture/mod.rs b/crates/recording/src/sources/screen_capture/mod.rs
index 4120b047b..0353d5bb5 100644
--- a/crates/recording/src/sources/screen_capture/mod.rs
+++ b/crates/recording/src/sources/screen_capture/mod.rs
@@ -193,6 +193,14 @@ impl ScreenCaptureTarget {
Self::Area { screen, .. } => Display::from_id(screen).and_then(|d| d.name()),
}
}
+
+ pub fn kind_str(&self) -> &str {
+ match self {
+ ScreenCaptureTarget::Display { .. } => "Display",
+ ScreenCaptureTarget::Window { .. } => "Window",
+ ScreenCaptureTarget::Area { .. } => "Area",
+ }
+ }
}
pub struct ScreenCaptureConfig<TCaptureFormat: ScreenCaptureFormat> {
diff --git a/crates/utils/Cargo.toml b/crates/utils/Cargo.toml
index c1b9db8e1..1c01fbd36 100644
--- a/crates/utils/Cargo.toml
+++ b/crates/utils/Cargo.toml
@@ -8,13 +8,13 @@ nix = { version = "0.29.0", features = ["fs"] }
[target.'cfg(windows)'.dependencies]
windows = { version = "0.58.0", features = [
- "Win32_Foundation",
- "Win32_System",
- "Win32_System_WindowsProgramming",
- "Win32_Security",
- "Win32_Storage_FileSystem",
- "Win32_System_Pipes",
- "Win32_System_Diagnostics_Debug",
+ "Win32_Foundation",
+ "Win32_System",
+ "Win32_System_WindowsProgramming",
+ "Win32_Security",
+ "Win32_Storage_FileSystem",
+ "Win32_System_Pipes",
+ "Win32_System_Diagnostics_Debug",
] }
windows-sys = "0.52.0"
@@ -27,6 +27,7 @@ serde_json = "1.0"
flume = "0.11.0"
tracing.workspace = true
directories = "5.0"
+aho-corasick.workspace = true
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[lints]
diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rs
index 73ef3f41d..d5f9482c8 100644
--- a/crates/utils/src/lib.rs
+++ b/crates/utils/src/lib.rs
@@ -1,5 +1,6 @@
-use std::{future::Future, path::PathBuf};
+use std::{borrow::Cow, future::Future, path::PathBuf, sync::OnceLock};
+use aho_corasick::{AhoCorasickBuilder, MatchKind};
use tracing::Instrument;
/// Wrapper around tokio::spawn that inherits the current tracing subscriber and span.
@@ -16,3 +17,216 @@ pub fn ensure_dir(path: &PathBuf) -> Result<PathBuf, std::io::Error> {
std::fs::create_dir_all(path)?;
Ok(path.clone())
}
+
+/// Generates a unique filename by appending incremental numbers if conflicts exist.
+///
+/// This function takes a base filename and ensures it's unique by appending `(1)`, `(2)`, etc.
+/// if a file with the same name already exists. It works with any file extension.
+///
+/// # Arguments
+///
+/// * `base_filename` - The desired filename (with extension)
+/// * `parent_dir` - The directory where the file should be created
+///
+/// # Returns
+///
+/// Returns the unique filename that doesn't conflict with existing files.
+///
+/// # Example
+///
+/// ```rust
+/// let unique_name = ensure_unique_filename("My Recording.cap", &recordings_dir);
+/// // If "My Recording.cap" exists, returns "My Recording (1).cap"
+/// // If that exists too, returns "My Recording (2).cap", etc.
+///
+/// let unique_name = ensure_unique_filename("document.pdf", &documents_dir);
+/// // If "document.pdf" exists, returns "document (1).pdf"
+/// ```
+pub fn ensure_unique_filename(
+ base_filename: &str,
+ parent_dir: &std::path::Path,
+) -> Result<String, String> {
+ let initial_path = parent_dir.join(base_filename);
+
+ if !initial_path.exists() {
+ println!("Ensure unique filename: is free!");
+ return Ok(base_filename.to_string());
+ }
+
+ let path = std::path::Path::new(base_filename);
+ let (name_without_ext, extension) = if let Some(ext) = path.extension() {
+ let name_without_ext = path
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or(base_filename);
+ let extension = format!(".{}", ext.to_string_lossy());
+ (name_without_ext, extension)
+ } else {
+ (base_filename, String::new())
+ };
+
+ let mut counter = 1;
+
+ loop {
+ let numbered_filename = if extension.is_empty() {
+ format!("{} ({})", name_without_ext, counter)
+ } else {
+ format!("{} ({}){}", name_without_ext, counter, &extension)
+ };
+
+ let test_path = parent_dir.join(&numbered_filename);
+
+ println!("Ensure unique filename: test path count \"{counter}\"");
+
+ if !test_path.exists() {
+ println!(
+ "Ensure unique filename: Found free! \"{}\"",
+ &test_path.display()
+ );
+ return Ok(numbered_filename);
+ }
+
+ counter += 1;
+
+ // prevent infinite loop
+ if counter > 1000 {
+ return Err(
+ "Too many filename conflicts, unable to create unique filename".to_string(),
+ );
+ }
+ }
+}
+
+/// Converts user-friendly template format strings to chrono format strings.
+///
+/// This function translates common template format patterns to chrono format specifiers,
+/// allowing users to write intuitive date/time formats that get converted to chrono's format.
+///
+/// # Supported Format Patterns
+///
+/// ## Year
+/// - `YYYY` → `%Y` - Year with century (e.g., 2025)
+/// - `YY` → `%y` - Year without century (e.g., 25)
+///
+/// ## Month
+/// - `MMMM` → `%B` - Full month name (e.g., January)
+/// - `MMM` → `%b` - Abbreviated month name (e.g., Jan)
+/// - `MM` → `%m` - Month as zero-padded number (01-12)
+/// - `M` → `%-m` - Month as number (1-12, no padding)
+///
+/// ## Day
+/// - `DDDD` → `%A` - Full weekday name (e.g., Monday)
+/// - `DDD` → `%a` - Abbreviated weekday name (e.g., Mon)
+/// - `DD` → `%d` - Day of month as zero-padded number (01-31)
+/// - `D` → `%-d` - Day of month as number (1-31, no padding)
+///
+/// ## Hour
+/// - `HH` → `%H` - Hour (24-hour) as zero-padded number (00-23)
+/// - `H` → `%-H` - Hour (24-hour) as number (0-23, no padding)
+/// - `hh` → `%I` - Hour (12-hour) as zero-padded number (01-12)
+/// - `h` → `%-I` - Hour (12-hour) as number (1-12, no padding)
+///
+/// ## Minute
+/// - `mm` → `%M` - Minute as zero-padded number (00-59)
+/// - `m` → `%-M` - Minute as number (0-59, no padding)
+///
+/// ## Second
+/// - `ss` → `%S` - Second as zero-padded number (00-59)
+/// - `s` → `%-S` - Second as number (0-59, no padding)
+///
+/// ## AM/PM
+/// - `A` → `%p` - AM/PM (uppercase)
+/// - `a` → `%P` - am/pm (lowercase)
+///
+/// ## Examples
+///
+/// ```
+/// // Basic formats
+/// YYYY-MM-DD HH:mm → %Y-%m-%d %H:%M
+/// // Output: "2025-01-15 14:30"
+///
+/// // Full month and day names
+/// MMMM DD, YYYY → %B %d, %Y
+/// // Output: "January 15, 2025"
+///
+/// // Abbreviated names
+/// DDD, MMM D, YYYY → %a, %b %-d, %Y
+/// // Output: "Mon, Jan 15, 2025"
+///
+/// // Compact format
+/// YYYYMMDD_HHmmss → %Y%m%d_%H%M%S
+/// // Output: "20250115_143045"
+///
+/// // 12-hour format with full names
+/// DDDD, MMMM DD at h:mm A → %A, %B %d at %-I:%M %p
+/// // Output: "Monday, January 15 at 2:30 PM"
+///
+/// // ISO week date
+/// YYYY-Www-D → %G-W%V-%u
+/// // Output: "2025-W03-1"
+/// ```
+///
+/// # Note
+///
+/// Pattern matching is case-sensitive and processes longer patterns first to avoid
+/// conflicts (e.g., `MMMM` is matched before `MM`).
+pub fn moment_format_to_chrono(template_format: &str) -> Cow<'_, str> {
+ static AC: OnceLock<aho_corasick::AhoCorasick> = OnceLock::new();
+
+ let ac = AC.get_or_init(|| {
+ // Order still matters (longer first helps readability), but using LeftmostLongest
+ // ensures overlapping shorter patterns won't also match.
+ AhoCorasickBuilder::new()
+ .match_kind(MatchKind::LeftmostLongest)
+ .build(&[
+ "MMMM", "MMM", "MM", "M", "DDDD", "DDD", "DD", "D", "YYYY", "YY", "HH", "H", "hh",
+ "h", "mm", "m", "ss", "s", "A", "a",
+ ])
+ .expect("Failed to build AhoCorasick automaton")
+ });
+
+ if !ac.is_match(template_format) {
+ return Cow::Borrowed(template_format);
+ }
+
+ let replacements = [
+ "%B", "%b", "%m", "%-m", // Month
+ "%A", "%a", "%d", "%-d", // Day
+ "%Y", "%y", // Year
+ "%H", "%-H", // Hour (24)
+ "%I", "%-I", // Hour (12)
+ "%M", "%-M", // Minute
+ "%S", "%-S", // Second
+ "%p", "%P", // AM/PM
+ ];
+
+ let replaced = ac
+ .try_replace_all(template_format, &replacements)
+ .expect("AhoCorasick replace should never fail with default configuration");
+
+ Cow::Owned(replaced)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn moment_format_to_chrono_converts_and_preserves_borrowed_when_unchanged() {
+ let input = "YYYY-MM-DD HH:mm:ss A a DDDD - DD - MMMM";
+ let out = moment_format_to_chrono(input);
+ let expected = "%Y-%m-%d %H:%M:%S %p %P %A - %d - %B";
+ assert_eq!(
+ out, expected,
+ "Converted format must match expected chrono format"
+ );
+
+ // Identity / borrowed case: no tokens -> should return Cow::Borrowed
+ let unchanged = "--";
+ let out2 = moment_format_to_chrono(unchanged);
+ match out2 {
+ Cow::Borrowed(s) => assert_eq!(s, unchanged),
+ Cow::Owned(_) => panic!("Expected Cow::Borrowed for unchanged input"),
+ }
+ }
+}