feat(stdlib): Mid2 M7 datetime and url

Add calendar moments as {unix,zone,iso} maps and URL/query parse
helpers in lib/ with thin host_* forwards; gold and public demos.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-09 09:14:18 +08:00
1 parent ff1870cedc
commit 08c48f3acb
23 files changed
+1002 -15

No files matched your search

+1
View File
@@ -3,6 +3,7 @@
## Unreleased
### Added
- **中层标准库 Mid2 M7**:`lib/datetime` / `日期时间`(`{unix,zone,iso}` · parse/format/add/in_zone)与 `lib/url` / `地址`(parse · query_parse/stringify);金样与 public `14-datetime-url`。设计 [stdlib-datetime.md](doc/design/stdlib-datetime.md) · [stdlib-url.md](doc/design/stdlib-url.md)。
- **文档**:中层标准库 Mid 之后缺口盘点与 Mid2(M7–M10)设计/路线——[stdlib-gaps-after-mid.md](doc/research/stdlib-gaps-after-mid.md) · [stdlib-mid2.md](doc/design/stdlib-mid2.md) · [stdlib-mid2.md](doc/roadmap/stdlib-mid2.md)。
### Fixed
+2
View File
@@ -34,6 +34,8 @@
| [design/stdlib-modules.md](design/stdlib-modules.md) | **L1:文件/系统/时间/JSON/网络/数学/外联/插件** |
| [design/stdlib-mid.md](design/stdlib-mid.md) | **中层 Mid M1–M6(已落地)** |
| [design/stdlib-mid2.md](design/stdlib-mid2.md) | **中层 Mid2:datetime / url / toml / html / fs++** |
| [design/stdlib-datetime.md](design/stdlib-datetime.md) | **`lib/datetime`(Mid2 M7)** |
| [design/stdlib-url.md](design/stdlib-url.md) | **`lib/url`(Mid2 M7)** |
| [research/stdlib-gaps-after-mid.md](research/stdlib-gaps-after-mid.md) | **Mid 之后缺口盘点**(对照 Python/Go) |
| [roadmap/stdlib-mid.md](roadmap/stdlib-mid.md) | **Mid M1–M6 路线(done)** |
| [roadmap/stdlib-mid2.md](roadmap/stdlib-mid2.md) | **Mid2 M7–M10 路线(规划)** |
+40
View File
@@ -0,0 +1,40 @@
# 设计:`lib/datetime` / `lib/日期时间`(Mid2 M7)
| | |
|---|---|
| 状态 | **已落地** |
| 日期 | 2026-09-09 |
| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §2.1 |
| 宿主 | `src/host/datetime.rs` · `host_datetime_*` |
---
## 1. 时刻形状
每次返回 **map**:
| 键 | 含义 |
|----|------|
| `unix` | 秒级 Unix 戳(int) |
| `zone` | 固定偏移文本,如 `+08:00` / `+00:00` |
| `iso` | RFC3339(秒精度) |
`to_unix` 也接受裸 int 或 ISO 文本。
## 2. API
| EN | ZH | 说明 |
|----|-----|------|
| `now` | `现在` | UTC 此刻(wasm 无时钟桥则失败) |
| `from_unix` | `自戳` | `unix` + 可选 `zone` |
| `to_unix` | `成戳` | |
| `parse` | `解析` | 默认 RFC3339 / `YYYY-MM-DD[ HH:MM:SS]`;`pattern=` |
| `format` | `格式化` | `rfc3339`/`date`/`time` 或 strftime |
| `add` | `加` | `days`/`hours`/`minutes`/`seconds` |
| `in_zone` | `时区` | 同瞬间换区 |
**区名**:`+HH:MM` / `UTC` / `Z`,以及少量固定偏移别名(如 `Asia/Shanghai`)。**不做**完整 tzdb / DST。
## 3. 与 `lib/time`
`lib/time` 保留极简 unix/format/parse/sleep。日历语义用本库。
+2 -2
View File
@@ -2,8 +2,8 @@
| | |
|---|---|
| 状态 | **Draft · 锁定方向** |
| 日期 | 2026-09-08 |
| 状态 | **Draft · M7 已落地;M8–M10 锁定方向** |
| 日期 | 2026-09-09 |
| 缺口盘点 | [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md) |
| 路线图 | [stdlib-mid2.md](../roadmap/stdlib-mid2.md) |
| 宪法 | [stdlib-mid.md](stdlib-mid.md) §3(准入 / 不准入 **不变**) |
+3 -1
View File
@@ -26,6 +26,8 @@
| **命令行** | `lib/cli.mq.md` | `lib/命令行.mq.md` | **Mid M5** |
| **日志** | `lib/log.mq.md` | `lib/日志.mq.md` | **Mid M6** |
| **标识** | `lib/uuid.mq.md` | `lib/标识.mq.md` | **Mid M6** |
| **日期时间** | `lib/datetime.mq.md` | `lib/日期时间.mq.md` | **Mid2 M7** |
| **地址** | `lib/url.mq.md` | `lib/地址.mq.md` | **Mid2 M7** |
| 浏览器效应 | `lib/browser.mq.md` | `lib/浏览器.mq.md` | WASM 客户端效应助手(GFM + helpers;勿用 `json.set` 链) |
| 文件 | `lib/fs.mq.md` | `lib/文件.mq.md` | 已有 + Mid M2:`copy_file` / `move` / `make_temp` |
| 系统 | `lib/sys.mq.md` | `lib/系统.mq.md` | 已有(含 `load_dotenv`) |
@@ -42,7 +44,7 @@
**中层已落地:** M1–M6(含 log / uuid)— 见 [stdlib-mid.md](stdlib-mid.md) · [stdlib-log-uuid.md](stdlib-log-uuid.md)。
**下一波 Mid2(规划,未进表):** `datetime` · `url` · `toml`(只读)· `html.escape` · `fs` 再厚 — [stdlib-mid2.md](stdlib-mid2.md) · [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md)。
**Mid2:** **M7 done**(`datetime` · `url`)— [stdlib-datetime.md](stdlib-datetime.md) · [stdlib-url.md](stdlib-url.md);M8+ 见 [stdlib-mid2.md](stdlib-mid2.md) · [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md)。
设计细节:[stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md)。
+24
View File
@@ -0,0 +1,24 @@
# 设计:`lib/url` / `lib/地址`(Mid2 M7)
| | |
|---|---|
| 状态 | **已落地** |
| 日期 | 2026-09-09 |
| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §2.2 |
| 宿主 | `src/host/url_ops.rs` · `host_url_*`(手写子集,无 `url` crate) |
---
## 1. 与 `net.url_encode`
| API | 用途 |
|-----|------|
| `net.url_encode` | **单段** form 编码(空格→`+`) |
| `url.parse` | 整 URL → `{scheme,userinfo,host,port,path,query,fragment}` |
| `url.query_parse` / `query_stringify` | 查询串 ↔ map(重复键→列表;空格→`%20`) |
## 2. 解析子集
`scheme://[userinfo@]host[:port]/path[?query][#fragment]`,含 IPv6 `[addr]`。缺 path 时规范为 `/`。
**不做**:相对 URL join、完整 WHATWG 边角、IDNA 规范化(host 原样保留)。
+1 -1
View File
@@ -126,7 +126,7 @@ catalog / 工具配置若走向 TOML,只读 `toml.parse` 性价比高。YAML
| 优先级 | 波次草案 | 内容 |
|--------|----------|------|
| **高** | **M7** | `datetime`(日历/时区子集)+ `url`(parse/query) |
| **高** | **M7** | `datetime` + `url` — **done** |
| **高** | **M8** | `toml` 只读 + `html.escape` + `encoding` base32 |
| **中** | **M9** | `fs` 加厚(dirs/stat/walk) |
| **低** | **M10** | `stats` 薄 · 可选 zip · 结构化 log 字段 |
+8 -9
View File
@@ -2,8 +2,8 @@
| | |
|---|---|
| 状态 | **Active · 规划** |
| 日期 | 2026-09-08 |
| 状态 | **Active · M7 已落地 · M8–M10 规划** |
| 日期 | 2026-09-09 |
| 设计 | [stdlib-mid2.md](../design/stdlib-mid2.md) |
| 缺口 | [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md) |
| 前序 | [stdlib-mid.md](stdlib-mid.md)(**M1–M6 done**) |
@@ -32,17 +32,16 @@ M10 收口糖(可选) stats 薄 · log 字段 · (zip 默认跳过)
## 1. 波次明细
### M7 — datetime + url — **todo**
### M7 — datetime + url — **done**
| 交付 | 说明 |
|------|------|
| `lib/datetime` · `日期时间` | now/parse/format/add/unix/zone 子集 |
| `lib/url` · `地址`(或 `net` 加厚) | parse · query_parse/stringify |
| `lib/url` · `地址` | parse · query_parse/stringify(手写;无 `url` crate) |
| Host | `host_datetime_*` · `host_url_*` |
| 金样 | `tests/lib/datetime-smoke` · `url-smoke` |
| public | 短页「解析带时区的时间戳 / 拆 query」 |
**刻意不做:** 农历、完整 tz 管理 UI、URL 规范化全部 WHATWG 边角。
| 金样 | `tests/lib/datetime-smoke` · `url-smoke`(中英) |
| public | `14-datetime-url` · `14-日期时间地址` |
| 设计 | [stdlib-datetime.md](../design/stdlib-datetime.md) · [stdlib-url.md](../design/stdlib-url.md) |
### M8 — toml + html + encoding — **todo**
@@ -74,7 +73,7 @@ M10 收口糖(可选) stats 薄 · log 字段 · (zip 默认跳过)
## 2. 进度勾选
- [ ] M7 datetime + url
- [x] M7 datetime + url
- [ ] M8 toml + html + base32
- [ ] M9 fs 加厚
- [ ] M10 可选
+54
View File
@@ -0,0 +1,54 @@
---
title: lib/datetime
description: Calendar moments as maps {unix, zone, iso} (Mid2 M7). Fixed offsets + a few IANA aliases.
---
## now
Current UTC moment map.
**> host_datetime_now**
## from_unix
+ `unix`
+ `zone`=None
**> host_datetime_from_unix unix=`unix` zone=`zone`**
## to_unix
+ `dt`
**> host_datetime_to_unix dt=`dt`**
## parse
+ `text`
+ `pattern`=None
RFC3339 / `YYYY-MM-DD[ HH:MM:SS]` by default; `pattern=` is strftime or `rfc3339`.
**> host_datetime_parse text=`text` pattern=`pattern`**
## format
+ `dt`
+ `style`=None
Styles: `rfc3339` (default), `date`, `time`, or a strftime pattern.
**> host_datetime_format dt=`dt` style=`style`**
## add
+ `dt`
+ `days`=None
+ `hours`=None
+ `minutes`=None
+ `seconds`=None
**> host_datetime_add dt=`dt` days=`days` hours=`hours` minutes=`minutes` seconds=`seconds`**
## in_zone
+ `dt`
+ `zone`
Re-express the same instant in `+08:00` / `UTC` / fixed aliases like `Asia/Shanghai`.
**> host_datetime_in_zone dt=`dt` zone=`zone`**
+23
View File
@@ -0,0 +1,23 @@
---
title: lib/url
description: Parse URLs and query strings (Mid2 M7). Segment encoding stays in net.url_encode.
---
## parse
+ `text`
Returns `{scheme, userinfo, host, port, path, query, fragment}`.
**> host_url_parse text=`text`**
## query_parse
+ `text`
Parse `a=1&b=2` into a map; repeated keys become a list.
**> host_url_query_parse text=`text`**
## query_stringify
+ `map`
**> host_url_query_stringify map=`map`**
+19
View File
@@ -0,0 +1,19 @@
---
title: lib/地址
description: 解析 URL 与查询串(中层 Mid2 M7)。单段编码仍用 `网络.网址编码`。
---
## 解析
+ `内容`
**> host_url_parse text=`内容`**
## 查询解析
+ `内容`
**> host_url_query_parse text=`内容`**
## 查询串化
+ `表`
**> host_url_query_stringify map=`表`**
+46
View File
@@ -0,0 +1,46 @@
---
title: lib/日期时间
description: 日历时刻 map `{unix, zone, iso}`(中层 Mid2 M7)。固定偏移与少量 IANA 别名。
---
## 现在
**> host_datetime_now**
## 自戳
+ `秒`
+ `区`=None
**> host_datetime_from_unix unix=`秒` zone=`区`**
## 成戳
+ `时刻`
**> host_datetime_to_unix dt=`时刻`**
## 解析
+ `内容`
+ `格式`=None
**> host_datetime_parse text=`内容` pattern=`格式`**
## 格式化
+ `时刻`
+ `样式`=None
**> host_datetime_format dt=`时刻` style=`样式`**
## 加
+ `时刻`
+ `天`=None
+ `小时`=None
+ `分钟`=None
+ `秒数`=None
**> host_datetime_add dt=`时刻` days=`天` hours=`小时` minutes=`分钟` seconds=`秒数`**
## 时区
+ `时刻`
+ `区`
**> host_datetime_in_zone dt=`时刻` zone=`区`**
+19
View File
@@ -0,0 +1,19 @@
---
title: Mid stdlib — datetime and url
description: Calendar moments + URL/query parse (Mid2 M7)
import dt:lib/datetime.mq.md
import url:lib/url.mq.md
---
# Time and addresses without plugins
Moments are maps `{unix, zone, iso}`. Parse HTTPS URLs and round-trip query strings in `lib/url` (segment encoding stays in `net.url_encode`).
# main
*epoch = > dt.from_unix unix=0 zone="Asia/Shanghai"*
> print text=`epoch`[^iso]
*u = > url.parse text="https://example.com/path?q=1#top"*
> print text=`u`[^host]
> print text=`u`[^query]
@@ -0,0 +1,19 @@
---
title: 中层标准库 — 日期时间与地址
description: 日历时刻 + URL/查询串(Mid2 M7)
导入 日时:lib/日期时间.mq.md
导入 址:lib/地址.mq.md
---
# 无需插件的时间与地址
时刻是 map `{unix, zone, iso}`。用 `地址` 拆 HTTPS URL 与查询串。
# main
*epoch = > 日时.自戳 秒=0 区="Asia/Shanghai"*
> print text=`epoch`[^iso]
*u = > 址.解析 内容="https://example.com/path?q=1"*
> print text=`u`[^host]
> print text=`u`[^query]
+302
View File
@@ -0,0 +1,302 @@
//! Calendar / timezone subset for Mid2 M7 (`lib/datetime`).
//!
//! Moments are plain maps: `{unix, zone, iso}`. Zone is a fixed offset (`+08:00`)
//! or alias (`UTC`); a few fixed-offset IANA names are accepted. Full tzdb is out of scope.
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, NaiveDateTime, TimeZone, Utc};
use crate::value::Value;
fn as_i64(v: &Value, label: &str) -> Result<i64, String> {
match v {
Value::Int(n) => Ok(*n),
_ => Err(format!("{label} must be int")),
}
}
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
match v {
Value::Text(s) => Ok(s.as_str()),
_ => Err(format!("{label} must be text")),
}
}
fn optional_i64(v: Option<&Value>, label: &str) -> Result<i64, String> {
match v {
None | Some(Value::None) => Ok(0),
Some(x) => as_i64(x, label),
}
}
fn format_offset(off: FixedOffset) -> String {
let secs = off.local_minus_utc();
let sign = if secs >= 0 { '+' } else { '-' };
let abs = secs.abs();
let h = abs / 3600;
let m = (abs % 3600) / 60;
format!("{sign}{h:02}:{m:02}")
}
fn parse_zone(s: &str) -> Result<FixedOffset, String> {
let s = s.trim();
if s.is_empty() || s.eq_ignore_ascii_case("utc") || s.eq_ignore_ascii_case("gmt") || s == "Z" {
return FixedOffset::east_opt(0).ok_or_else(|| "invalid UTC offset".into());
}
// Common fixed-offset IANA aliases (no DST).
let aliased = match s {
"Asia/Shanghai" | "Asia/Hong_Kong" | "Asia/Taipei" | "Asia/Singapore" => Some(8 * 3600),
"Asia/Tokyo" | "Asia/Seoul" => Some(9 * 3600),
"Asia/Kolkata" | "Asia/Calcutta" => Some(5 * 3600 + 30 * 60),
"Europe/Moscow" => Some(3 * 3600),
"America/Phoenix" => Some(-7 * 3600),
"Pacific/Honolulu" => Some(-10 * 3600),
_ => None,
};
if let Some(secs) = aliased {
return FixedOffset::east_opt(secs).ok_or_else(|| format!("invalid zone: {s}"));
}
let (sign, rest) = if let Some(r) = s.strip_prefix('+') {
(1i32, r)
} else if let Some(r) = s.strip_prefix('-') {
(-1i32, r)
} else {
return Err(format!(
"unknown zone {s:?}; use +HH:MM / -HH:MM / UTC or a fixed-offset alias (e.g. Asia/Shanghai)"
));
};
let (hh, mm) = if let Some((h, m)) = rest.split_once(':') {
(
h.parse::<i32>()
.map_err(|_| format!("bad zone hour in {s}"))?,
m.parse::<i32>()
.map_err(|_| format!("bad zone minute in {s}"))?,
)
} else if rest.len() == 4 && rest.chars().all(|c| c.is_ascii_digit()) {
(
rest[..2]
.parse::<i32>()
.map_err(|_| format!("bad zone hour in {s}"))?,
rest[2..]
.parse::<i32>()
.map_err(|_| format!("bad zone minute in {s}"))?,
)
} else if rest.len() == 2 && rest.chars().all(|c| c.is_ascii_digit()) {
(
rest.parse::<i32>()
.map_err(|_| format!("bad zone hour in {s}"))?,
0,
)
} else {
return Err(format!("bad zone offset {s}"));
};
if !(0..=14).contains(&hh) || !(0..60).contains(&mm) {
return Err(format!("zone offset out of range: {s}"));
}
let secs = sign * (hh * 3600 + mm * 60);
FixedOffset::east_opt(secs).ok_or_else(|| format!("invalid zone offset: {s}"))
}
fn moment(unix: i64, zone: FixedOffset) -> Result<Value, String> {
let dt = zone
.timestamp_opt(unix, 0)
.single()
.ok_or_else(|| format!("invalid unix timestamp: {unix}"))?;
Ok(Value::Map(vec![
("unix".into(), Value::Int(unix)),
("zone".into(), Value::Text(format_offset(zone))),
(
"iso".into(),
Value::Text(dt.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)),
),
]))
}
fn zone_of_moment(m: &[(String, Value)]) -> Result<FixedOffset, String> {
for (k, v) in m {
if k == "zone" {
return parse_zone(as_text(v, "zone")?);
}
}
Ok(FixedOffset::east_opt(0).unwrap())
}
fn unix_of_value(v: &Value) -> Result<(i64, FixedOffset), String> {
match v {
Value::Int(n) => Ok((*n, FixedOffset::east_opt(0).unwrap())),
Value::Map(entries) => {
let mut unix = None;
for (k, val) in entries {
if k == "unix" {
unix = Some(as_i64(val, "unix")?);
}
}
let unix = unix.ok_or_else(|| "datetime map needs unix".to_string())?;
Ok((unix, zone_of_moment(entries)?))
}
Value::Text(s) => {
// Treat bare ISO/RFC3339 text as a moment.
let parsed = parse_text(s, None)?;
unix_of_value(&parsed)
}
_ => Err("datetime needs int unix, moment map, or ISO text".into()),
}
}
pub fn now() -> Result<Value, String> {
#[cfg(target_arch = "wasm32")]
{
return Err("datetime.now unavailable in browser wasm (no clock bridge yet)".into());
}
#[cfg(not(target_arch = "wasm32"))]
{
let secs = Utc::now().timestamp();
moment(secs, FixedOffset::east_opt(0).unwrap())
}
}
pub fn from_unix(unix: &Value, zone: Option<&Value>) -> Result<Value, String> {
let secs = as_i64(unix, "unix")?;
let off = match zone {
None | Some(Value::None) => FixedOffset::east_opt(0).unwrap(),
Some(z) => parse_zone(as_text(z, "zone")?)?,
};
moment(secs, off)
}
pub fn to_unix(dt: &Value) -> Result<Value, String> {
let (secs, _) = unix_of_value(dt)?;
Ok(Value::Int(secs))
}
fn parse_text(text: &str, pattern: Option<&str>) -> Result<Value, String> {
if let Some(pat) = pattern {
if pat.eq_ignore_ascii_case("rfc3339") || pat.eq_ignore_ascii_case("iso") {
return parse_rfc3339(text);
}
if let Ok(dt) = DateTime::parse_from_str(text, pat) {
return moment(dt.timestamp(), *dt.offset());
}
let naive = NaiveDateTime::parse_from_str(text, pat)
.or_else(|_| {
NaiveDate::parse_from_str(text, pat).map(|d| d.and_hms_opt(0, 0, 0).unwrap())
})
.map_err(|e| format!("datetime.parse: {e}"))?;
return moment(naive.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap());
}
if let Ok(v) = parse_rfc3339(text) {
return Ok(v);
}
if let Ok(dt) = NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M:%S") {
return moment(dt.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap());
}
if let Ok(dt) = NaiveDateTime::parse_from_str(text, "%Y-%m-%dT%H:%M:%S") {
return moment(dt.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap());
}
if let Ok(d) = NaiveDate::parse_from_str(text, "%Y-%m-%d") {
let dt = d.and_hms_opt(0, 0, 0).unwrap();
return moment(dt.and_utc().timestamp(), FixedOffset::east_opt(0).unwrap());
}
Err(format!(
"datetime.parse: unrecognized {text:?}; pass pattern= or use RFC3339 / YYYY-MM-DD"
))
}
fn parse_rfc3339(text: &str) -> Result<Value, String> {
let dt = DateTime::parse_from_rfc3339(text).map_err(|e| format!("datetime.parse: {e}"))?;
moment(dt.timestamp(), *dt.offset())
}
pub fn parse(text: &Value, pattern: Option<&Value>) -> Result<Value, String> {
let t = as_text(text, "text")?;
let pat = match pattern {
None | Some(Value::None) => None,
Some(p) => Some(as_text(p, "pattern")?),
};
parse_text(t, pat)
}
pub fn format(dt: &Value, style: Option<&Value>) -> Result<Value, String> {
let (secs, zone) = unix_of_value(dt)?;
let local = zone
.timestamp_opt(secs, 0)
.single()
.ok_or_else(|| format!("invalid unix timestamp: {secs}"))?;
let style = match style {
None | Some(Value::None) => "rfc3339",
Some(s) => as_text(s, "style")?,
};
let out = match style {
"rfc3339" | "iso" => local.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
"date" => local.format("%Y-%m-%d").to_string(),
"time" => local.format("%H:%M:%S").to_string(),
other => local.format(other).to_string(),
};
Ok(Value::Text(out))
}
pub fn add(
dt: &Value,
days: Option<&Value>,
hours: Option<&Value>,
minutes: Option<&Value>,
seconds: Option<&Value>,
) -> Result<Value, String> {
let (secs, zone) = unix_of_value(dt)?;
let days = optional_i64(days, "days")?;
let hours = optional_i64(hours, "hours")?;
let minutes = optional_i64(minutes, "minutes")?;
let seconds = optional_i64(seconds, "seconds")?;
let delta = Duration::days(days)
+ Duration::hours(hours)
+ Duration::minutes(minutes)
+ Duration::seconds(seconds);
let new_secs = secs
.checked_add(delta.num_seconds())
.ok_or_else(|| "datetime.add overflow".to_string())?;
moment(new_secs, zone)
}
pub fn in_zone(dt: &Value, zone: &Value) -> Result<Value, String> {
let (secs, _) = unix_of_value(dt)?;
let off = parse_zone(as_text(zone, "zone")?)?;
moment(secs, off)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_unix_utc_iso() {
let m = from_unix(&Value::Int(0), None).unwrap();
let Value::Map(entries) = m else { panic!() };
let iso = entries.iter().find(|(k, _)| k == "iso").unwrap().1.clone();
assert_eq!(iso, Value::Text("1970-01-01T00:00:00Z".into()));
}
#[test]
fn shanghai_alias() {
let m = from_unix(&Value::Int(0), Some(&Value::Text("Asia/Shanghai".into()))).unwrap();
let Value::Map(entries) = m else { panic!() };
let iso = entries.iter().find(|(k, _)| k == "iso").unwrap().1.clone();
assert_eq!(iso, Value::Text("1970-01-01T08:00:00+08:00".into()));
}
#[test]
fn parse_rfc3339_roundtrip() {
let m = parse(
&Value::Text("2020-01-02T03:04:05+08:00".into()),
None,
)
.unwrap();
let u = to_unix(&m).unwrap();
assert_eq!(u, Value::Int(1_577_905_445));
}
#[test]
fn add_day() {
let m = from_unix(&Value::Int(0), None).unwrap();
let n = add(&m, Some(&Value::Int(1)), None, None, None).unwrap();
assert_eq!(to_unix(&n).unwrap(), Value::Int(86_400));
}
}
+75 -2
View File
@@ -3,8 +3,8 @@
use std::collections::HashMap;
use crate::host::{
cli, csv, encoding, fs, hash, json, log, math, net, path, re, secrets, sys, text_ops, time,
uuid_ops, writeback, HostContext,
cli, csv, datetime, encoding, fs, hash, json, log, math, net, path, re, secrets, sys, text_ops,
time, url_ops, uuid_ops, writeback, HostContext,
};
#[cfg(feature = "exec-host")]
use crate::host::{foreign, subtask};
@@ -176,6 +176,16 @@ pub enum HostFn {
LogSetLevel = 167,
LogLine = 168,
UuidV4 = 169,
DatetimeNow = 170,
DatetimeFromUnix = 171,
DatetimeToUnix = 172,
DatetimeParse = 173,
DatetimeFormat = 174,
DatetimeAdd = 175,
DatetimeInZone = 176,
UrlParse = 177,
UrlQueryParse = 178,
UrlQueryStringify = 179,
}
@@ -342,6 +352,16 @@ impl HostFn {
167 => Self::LogSetLevel,
168 => Self::LogLine,
169 => Self::UuidV4,
170 => Self::DatetimeNow,
171 => Self::DatetimeFromUnix,
172 => Self::DatetimeToUnix,
173 => Self::DatetimeParse,
174 => Self::DatetimeFormat,
175 => Self::DatetimeAdd,
176 => Self::DatetimeInZone,
177 => Self::UrlParse,
178 => Self::UrlQueryParse,
179 => Self::UrlQueryStringify,
_ => return None,
})
}
@@ -511,6 +531,16 @@ impl HostFn {
"host_log_set_level" | "log_set_level" => Self::LogSetLevel,
"host_log_line" | "log_line" => Self::LogLine,
"host_uuid_v4" | "uuid_v4" => Self::UuidV4,
"host_datetime_now" | "datetime_now" => Self::DatetimeNow,
"host_datetime_from_unix" | "datetime_from_unix" => Self::DatetimeFromUnix,
"host_datetime_to_unix" | "datetime_to_unix" => Self::DatetimeToUnix,
"host_datetime_parse" | "datetime_parse" => Self::DatetimeParse,
"host_datetime_format" | "datetime_format" => Self::DatetimeFormat,
"host_datetime_add" | "datetime_add" => Self::DatetimeAdd,
"host_datetime_in_zone" | "datetime_in_zone" => Self::DatetimeInZone,
"host_url_parse" | "url_parse" => Self::UrlParse,
"host_url_query_parse" | "url_query_parse" => Self::UrlQueryParse,
"host_url_query_stringify" | "url_query_stringify" => Self::UrlQueryStringify,
_ => return None,
})
}
@@ -667,6 +697,16 @@ impl HostFn {
Self::LogSetLevel => "host_log_set_level",
Self::LogLine => "host_log_line",
Self::UuidV4 => "host_uuid_v4",
Self::DatetimeNow => "host_datetime_now",
Self::DatetimeFromUnix => "host_datetime_from_unix",
Self::DatetimeToUnix => "host_datetime_to_unix",
Self::DatetimeParse => "host_datetime_parse",
Self::DatetimeFormat => "host_datetime_format",
Self::DatetimeAdd => "host_datetime_add",
Self::DatetimeInZone => "host_datetime_in_zone",
Self::UrlParse => "host_url_parse",
Self::UrlQueryParse => "host_url_query_parse",
Self::UrlQueryStringify => "host_url_query_stringify",
Self::WritebackRecord => "host_writeback_record",
Self::WritebackGet => "host_writeback_get",
Self::WritebackClear => "host_writeback_clear",
@@ -789,6 +829,15 @@ impl HostFn {
Self::LogSetLevel => &["level"],
Self::LogLine => &["level", "text"],
Self::UuidV4 => &[],
Self::DatetimeNow => &[],
Self::DatetimeFromUnix => &["unix"],
Self::DatetimeToUnix => &["dt"],
Self::DatetimeParse => &["text"],
Self::DatetimeFormat => &["dt"],
Self::DatetimeAdd => &["dt"],
Self::DatetimeInZone => &["dt", "zone"],
Self::UrlParse | Self::UrlQueryParse => &["text"],
Self::UrlQueryStringify => &["map"],
Self::WritebackRecord => &["value"],
Self::WritebackGet | Self::WritebackClear => &[],
Self::WritebackList => &[],
@@ -827,6 +876,10 @@ impl HostFn {
Self::TextReplace => &["count"],
Self::TextPad => &["fill", "align"],
Self::CliParse => &["args"],
Self::DatetimeFromUnix => &["zone"],
Self::DatetimeParse => &["pattern"],
Self::DatetimeFormat => &["style"],
Self::DatetimeAdd => &["days", "hours", "minutes", "seconds"],
_ => &[],
}
}
@@ -1272,6 +1325,26 @@ pub fn call_host(
HostFn::LogSetLevel => log::set_level(ctx, require(bound, "level")?),
HostFn::LogLine => log::line(ctx, require(bound, "level")?, require(bound, "text")?),
HostFn::UuidV4 => uuid_ops::v4(),
HostFn::DatetimeNow => datetime::now(),
HostFn::DatetimeFromUnix => {
datetime::from_unix(require(bound, "unix")?, bound.get("zone"))
}
HostFn::DatetimeToUnix => datetime::to_unix(require(bound, "dt")?),
HostFn::DatetimeParse => datetime::parse(require(bound, "text")?, bound.get("pattern")),
HostFn::DatetimeFormat => datetime::format(require(bound, "dt")?, bound.get("style")),
HostFn::DatetimeAdd => datetime::add(
require(bound, "dt")?,
bound.get("days"),
bound.get("hours"),
bound.get("minutes"),
bound.get("seconds"),
),
HostFn::DatetimeInZone => {
datetime::in_zone(require(bound, "dt")?, require(bound, "zone")?)
}
HostFn::UrlParse => url_ops::parse(require(bound, "text")?),
HostFn::UrlQueryParse => url_ops::query_parse(require(bound, "text")?),
HostFn::UrlQueryStringify => url_ops::query_stringify(require(bound, "map")?),
HostFn::OuterCallLine => Ok(Value::Int(
ctx.call_site_lines
.first()
+2
View File
@@ -9,6 +9,7 @@ pub mod collection;
mod dispatch;
mod cli;
mod csv;
mod datetime;
mod encoding;
pub mod event_bus;
#[cfg(feature = "exec-host")]
@@ -23,6 +24,7 @@ mod path;
mod re;
mod secrets;
mod text_ops;
mod url_ops;
mod uuid_ops;
#[cfg(feature = "plugin-host")]
pub mod plugin;
+254
View File
@@ -0,0 +1,254 @@
//! URL parse / query helpers for Mid2 M7 (`lib/url`).
//! Distinct from `net::url_encode` (single-segment form encoding).
//! Hand-rolled subset (no `url` crate): scheme://[userinfo@]host[:port]/path[?query][#frag].
use crate::value::Value;
fn as_text<'a>(v: &'a Value, label: &str) -> Result<&'a str, String> {
match v {
Value::Text(s) => Ok(s.as_str()),
_ => Err(format!("{label} must be text")),
}
}
fn encode_component(s: &str) -> String {
let mut out = String::new();
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(b as char);
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
fn decode_component(s: &str) -> Result<String, String> {
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'+' => {
out.push(b' ');
i += 1;
}
b'%' if i + 2 < bytes.len() => {
let h = |c: u8| -> Result<u8, String> {
match c {
b'0'..=b'9' => Ok(c - b'0'),
b'a'..=b'f' => Ok(c - b'a' + 10),
b'A'..=b'F' => Ok(c - b'A' + 10),
_ => Err(format!("bad percent escape in {s:?}")),
}
};
let v = (h(bytes[i + 1])? << 4) | h(bytes[i + 2])?;
out.push(v);
i += 3;
}
b'%' => return Err(format!("truncated percent escape in {s:?}")),
c => {
out.push(c);
i += 1;
}
}
}
String::from_utf8(out).map_err(|e| format!("url decode utf8: {e}"))
}
/// Parse `scheme://[userinfo@]host[:port]/path[?query][#fragment]`.
pub fn parse(text: &Value) -> Result<Value, String> {
let raw = as_text(text, "text")?;
let (scheme, rest) = raw
.split_once("://")
.ok_or_else(|| format!("url.parse: missing :// in {raw:?}"))?;
if scheme.is_empty()
|| !scheme
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
{
return Err(format!("url.parse: bad scheme in {raw:?}"));
}
let (before_frag, fragment) = match rest.split_once('#') {
Some((a, b)) => (a, b),
None => (rest, ""),
};
let (before_query, query) = match before_frag.split_once('?') {
Some((a, b)) => (a, b),
None => (before_frag, ""),
};
let (authority, path) = if let Some(i) = before_query.find('/') {
(&before_query[..i], &before_query[i..])
} else {
(before_query, "")
};
let (userinfo, hostport) = if let Some((u, h)) = authority.rsplit_once('@') {
(u, h)
} else {
("", authority)
};
let (host, port) = if hostport.starts_with('[') {
// IPv6 literal [addr]:port
let end = hostport
.find(']')
.ok_or_else(|| format!("url.parse: bad IPv6 host in {raw:?}"))?;
let host = &hostport[1..end];
let rest = &hostport[end + 1..];
if rest.is_empty() {
(host, Value::None)
} else if let Some(p) = rest.strip_prefix(':') {
let n: i64 = p
.parse()
.map_err(|_| format!("url.parse: bad port in {raw:?}"))?;
(host, Value::Int(n))
} else {
return Err(format!("url.parse: bad hostport in {raw:?}"));
}
} else if let Some((h, p)) = hostport.rsplit_once(':') {
if p.chars().all(|c| c.is_ascii_digit()) && !p.is_empty() {
let n: i64 = p
.parse()
.map_err(|_| format!("url.parse: bad port in {raw:?}"))?;
(h, Value::Int(n))
} else {
(hostport, Value::None)
}
} else {
(hostport, Value::None)
};
let path = if path.is_empty() {
"/".to_string()
} else {
path.to_string()
};
Ok(Value::Map(vec![
("scheme".into(), Value::Text(scheme.to_string())),
("userinfo".into(), Value::Text(userinfo.to_string())),
("host".into(), Value::Text(host.to_string())),
("port".into(), port),
("path".into(), Value::Text(path)),
("query".into(), Value::Text(query.to_string())),
("fragment".into(), Value::Text(fragment.to_string())),
]))
}
pub fn query_parse(text: &Value) -> Result<Value, String> {
let raw = as_text(text, "text")?;
let raw = raw.strip_prefix('?').unwrap_or(raw);
let mut map: Vec<(String, Value)> = Vec::new();
if raw.is_empty() {
return Ok(Value::Map(map));
}
for pair in raw.split('&') {
if pair.is_empty() {
continue;
}
let (k, v) = match pair.split_once('=') {
Some((k, v)) => (k, v),
None => (pair, ""),
};
let key = decode_component(k)?;
let val = Value::Text(decode_component(v)?);
if let Some((_, slot)) = map.iter_mut().find(|(kk, _)| *kk == key) {
match slot {
Value::List(xs) => xs.push(val),
other => {
let prev = std::mem::replace(other, Value::None);
*other = Value::List(vec![prev, val]);
}
}
} else {
map.push((key, val));
}
}
Ok(Value::Map(map))
}
pub fn query_stringify(map: &Value) -> Result<Value, String> {
let entries = match map {
Value::Map(m) => m,
Value::None => return Ok(Value::Text(String::new())),
_ => return Err("url.query_stringify: map required".into()),
};
let mut parts: Vec<String> = Vec::new();
for (k, v) in entries {
let key = encode_component(k);
match v {
Value::List(xs) => {
for x in xs {
match x {
Value::Text(s) => {
parts.push(format!("{key}={}", encode_component(s)));
}
Value::Int(n) => {
parts.push(format!("{key}={}", encode_component(&n.to_string())));
}
Value::Bool(b) => {
parts.push(format!("{key}={}", encode_component(&b.to_string())));
}
Value::None => parts.push(format!("{key}=")),
_ => {
return Err("url.query_stringify: list values must be scalar".into())
}
}
}
}
Value::Text(s) => parts.push(format!("{key}={}", encode_component(s))),
Value::Int(n) => parts.push(format!("{key}={}", encode_component(&n.to_string()))),
Value::Bool(b) => parts.push(format!("{key}={}", encode_component(&b.to_string()))),
Value::None => parts.push(format!("{key}=")),
_ => return Err("url.query_stringify: values must be scalar or list".into()),
}
}
Ok(Value::Text(parts.join("&")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_https_query() {
let m = parse(&Value::Text(
"https://user:pass@example.com:8443/a/b?x=1&y=2#frag".into(),
))
.unwrap();
let Value::Map(entries) = m else { panic!() };
let get = |k: &str| {
entries
.iter()
.find(|(kk, _)| kk == k)
.map(|(_, v)| v.clone())
.unwrap()
};
assert_eq!(get("scheme"), Value::Text("https".into()));
assert_eq!(get("host"), Value::Text("example.com".into()));
assert_eq!(get("port"), Value::Int(8443));
assert_eq!(get("path"), Value::Text("/a/b".into()));
assert_eq!(get("query"), Value::Text("x=1&y=2".into()));
assert_eq!(get("fragment"), Value::Text("frag".into()));
assert_eq!(get("userinfo"), Value::Text("user:pass".into()));
}
#[test]
fn query_roundtrip() {
let q = query_parse(&Value::Text("a=1&b=hello%20w&a=2".into())).unwrap();
let s = query_stringify(&q).unwrap();
assert_eq!(s, Value::Text("a=1&a=2&b=hello%20w".into()));
}
#[test]
fn empty_path_becomes_slash() {
let m = parse(&Value::Text("https://example.com".into())).unwrap();
let Value::Map(entries) = m else { panic!() };
let path = entries.iter().find(|(k, _)| k == "path").unwrap().1.clone();
assert_eq!(path, Value::Text("/".into()));
}
}
+32
View File
@@ -1181,6 +1181,38 @@ fn lib_log_uuid_zh_smoke() {
assert_out("tests/lib/日志-标识-烟测.mq.md", "INFO 中文信息\n36");
}
#[test]
fn lib_datetime_smoke() {
assert_out(
"tests/lib/datetime-smoke.mq.md",
"1970-01-01T00:00:00Z\n1970-01-01T08:00:00+08:00\n1577905445\n86400\n1970-01-01",
);
}
#[test]
fn lib_datetime_smoke_zh() {
assert_out(
"tests/lib/日期时间-烟测.mq.md",
"1970-01-01T00:00:00Z\n1970-01-01T08:00:00+08:00\n1577905445",
);
}
#[test]
fn lib_url_smoke() {
assert_out(
"tests/lib/url-smoke.mq.md",
"https\nexample.com\n8443\n/a/b\nx=1&y=2\nfrag\nhi x\n1\n2\na=1&a=2&b=hi%20x",
);
}
#[test]
fn lib_url_smoke_zh() {
assert_out(
"tests/lib/地址-烟测.mq.md",
"https\nexample.com\n/a\nx=1",
);
}
#[test]
fn lib_re_smoke() {
assert_out(
+23
View File
@@ -0,0 +1,23 @@
---
title: lib/datetime smoke
import dt:lib/datetime.mq.md
---
# main
*m = > dt.from_unix unix=0*
> print text=`m`[^iso]
*sh = > dt.in_zone dt=`m` zone="Asia/Shanghai"*
> print text=`sh`[^iso]
*p = > dt.parse text="2020-01-02T03:04:05+08:00"*
*u = > dt.to_unix dt=`p`*
> print text=`u`
*n = > dt.add dt=`m` days=1*
*nu = > dt.to_unix dt=`n`*
> print text=`nu`
*d = > dt.format dt=`sh` style="date"*
> print text=`d`
+25
View File
@@ -0,0 +1,25 @@
---
title: lib/url smoke
import url:lib/url.mq.md
---
# main
*u = > url.parse text="https://example.com:8443/a/b?x=1&y=2#frag"*
> print text=`u`[^scheme]
> print text=`u`[^host]
> print text=`u`[^port]
> print text=`u`[^path]
> print text=`u`[^query]
> print text=`u`[^fragment]
*q = > url.query_parse text="a=1&b=hi%20x&a=2"*
> print text=`q`[^b]
*as = `q`[^a]*
*a0 = > at value=`as` index=0*
*a1 = > at value=`as` index=1*
> print text=`a0`
> print text=`a1`
*s = > url.query_stringify map=`q`*
> print text=`s`
+12
View File
@@ -0,0 +1,12 @@
---
title: lib/地址 烟测
导入 址:lib/地址.mq.md
---
# main
*u = > 址.解析 内容="https://example.com/a?x=1"*
> print text=`u`[^scheme]
> print text=`u`[^host]
> print text=`u`[^path]
> print text=`u`[^query]
+16
View File
@@ -0,0 +1,16 @@
---
title: lib/日期时间 烟测
导入 日时:lib/日期时间.mq.md
---
# main
*m = > 日时.自戳 秒=0*
> print text=`m`[^iso]
*sh = > 日时.时区 时刻=`m` 区="Asia/Shanghai"*
> print text=`sh`[^iso]
*p = > 日时.解析 内容="2020-01-02T03:04:05+08:00"*
*u = > 日时.成戳 时刻=`p`*
> print text=`u`