-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.rs
More file actions
407 lines (357 loc) · 12 KB
/
context.rs
File metadata and controls
407 lines (357 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Database context: `/v1/databases/{id}/context` sync with `./{NAME}.md` in the current directory.
use crate::api::ApiClient;
use crossterm::style::Stylize;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::HashSet;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::sync::LazyLock;
/// Matches runtimedb `MAX_TABLE_NAME_LENGTH` / `validate_table_name` rules for context keys.
pub const MAX_CONTEXT_NAME_LEN: usize = 128;
/// Matches runtimedb workspace context content cap.
pub const MAX_CONTEXT_CONTENT_CHARS: usize = 512_000;
static RESERVED_WORDS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
[
"select", "from", "where", "insert", "update", "delete", "create", "drop", "alter",
"table", "index", "view", "and", "or", "not", "null", "true", "false", "in", "is", "like",
"between", "join", "on", "as", "order", "by", "group", "having", "limit", "offset",
"union", "all", "distinct", "case", "when", "then", "else", "end", "exists", "any", "some",
]
.into_iter()
.collect()
});
#[derive(Debug, Deserialize, Serialize)]
struct DatabaseContextEntry {
name: String,
content: String,
updated_at: String,
}
#[derive(Deserialize)]
struct ListResponse {
contexts: Vec<DatabaseContextEntry>,
}
#[derive(Deserialize)]
struct GetResponse {
context: DatabaseContextEntry,
}
#[derive(Deserialize)]
struct UpsertResponse {
context: DatabaseContextEntry,
}
/// Normalizes a context name from the CLI: trims, takes the final path segment, and strips a
/// trailing `.md` (any ASCII case) so `USER.md` or `./USER.md` refer to context stem `USER`.
pub fn normalize_context_cli_name(name: &str) -> String {
let trimmed = name.trim();
let basename = std::path::Path::new(trimmed)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(trimmed);
const MD_SUFFIX: &str = ".md";
let md_len = MD_SUFFIX.len();
let bytes = basename.as_bytes();
if bytes.len() >= md_len {
let i = bytes.len() - md_len;
// Inspect bytes only: avoid slicing `str` at `i` until we know the last `md_len` bytes are
// ASCII `.md` (so `i` is a UTF-8 char boundary — e.g. `x𝕌` must not index `basename[2..]`).
if bytes[i] == b'.'
&& bytes[i + 1].eq_ignore_ascii_case(&b'm')
&& bytes[i + 2].eq_ignore_ascii_case(&b'd')
{
return basename[..i].to_string();
}
}
basename.to_string()
}
/// Validates a context stem (API `name` and basename before `.md`).
/// Same rules as runtimedb `validate_table_name`.
pub fn validate_context_stem(name: &str) -> Result<(), String> {
if name.is_empty() {
return Err("name cannot be empty".into());
}
if name.len() > MAX_CONTEXT_NAME_LEN {
return Err(format!(
"name exceeds maximum length of {} (got {})",
MAX_CONTEXT_NAME_LEN,
name.len()
));
}
let mut chars = name.chars();
if let Some(first) = chars.next()
&& !first.is_ascii_alphabetic()
&& first != '_'
{
return Err(format!(
"name must start with a letter or underscore, got '{first}'"
));
}
for c in chars {
if !c.is_ascii_alphanumeric() && c != '_' {
return Err(format!("name contains invalid character '{c}'"));
}
}
if RESERVED_WORDS.contains(name.to_lowercase().as_str()) {
return Err(format!(
"'{name}' is a SQL reserved word and cannot be used as a context name"
));
}
Ok(())
}
fn local_md_path(name: &str) -> PathBuf {
std::env::current_dir()
.unwrap_or_else(|e| {
eprintln!("error: could not read current directory: {e}");
std::process::exit(1);
})
.join(format!("{name}.md"))
}
fn fetch_context(
api: &ApiClient,
database_id: &str,
name: &str,
) -> Result<DatabaseContextEntry, reqwest::StatusCode> {
let path = format!("/databases/{database_id}/context/{name}");
let (status, body) = api.get_raw(&path);
if status == reqwest::StatusCode::NOT_FOUND {
return Err(status);
}
if !status.is_success() {
eprintln!("{}", format!("error: HTTP {status}").red());
eprintln!("{body}");
std::process::exit(1);
}
let parsed: GetResponse = serde_json::from_str(&body).unwrap_or_else(|e| {
eprintln!("error parsing response: {e}");
std::process::exit(1);
});
Ok(parsed.context)
}
pub fn list(workspace_id: &str, database_id: &str, prefix: Option<&str>, format: &str) {
let api = ApiClient::new(Some(workspace_id));
let body: ListResponse = api.get(&format!("/databases/{database_id}/context"));
let mut rows: Vec<DatabaseContextEntry> = body.contexts;
if let Some(p) = prefix {
rows.retain(|c| c.name.starts_with(p));
}
match format {
"json" => println!("{}", serde_json::to_string_pretty(&rows).unwrap()),
"yaml" => print!("{}", serde_yaml::to_string(&rows).unwrap()),
"table" => {
if rows.is_empty() {
eprintln!("{}", "No contexts found.".dark_grey());
} else {
let table_rows: Vec<Vec<String>> = rows
.iter()
.map(|c| {
vec![
c.name.clone(),
crate::util::format_date(&c.updated_at),
c.content.chars().count().to_string(),
]
})
.collect();
crate::table::print(&["NAME", "UPDATED", "CHARS"], &table_rows);
}
}
_ => unreachable!(),
}
}
pub fn show(workspace_id: &str, database_id: &str, name: &str) {
let name = normalize_context_cli_name(name);
if let Err(e) = validate_context_stem(&name) {
eprintln!("error: {e}");
std::process::exit(1);
}
let api = ApiClient::new(Some(workspace_id));
match fetch_context(&api, database_id, &name) {
Ok(ctx) => {
print!("{}", ctx.content);
if !ctx.content.ends_with('\n') {
println!();
}
}
Err(reqwest::StatusCode::NOT_FOUND) => {
eprintln!(
"{}",
format!("error: no context named '{name}' in this database.").red()
);
eprintln!(
"{}",
format!("Create ./{name}.md locally, then run: hotdata context push {name}")
.dark_grey()
);
std::process::exit(1);
}
Err(status) => panic!("unexpected error status from fetch_context: {status}"),
}
}
pub fn pull(workspace_id: &str, database_id: &str, name: &str, force: bool, dry_run: bool) {
let name = normalize_context_cli_name(name);
if let Err(e) = validate_context_stem(&name) {
eprintln!("error: {e}");
std::process::exit(1);
}
let path = local_md_path(&name);
if !dry_run && !force && path.exists() {
eprintln!(
"{}",
format!(
"error: {} already exists (use --force to overwrite)",
path.display()
)
.red()
);
std::process::exit(1);
}
let api = ApiClient::new(Some(workspace_id));
let ctx = match fetch_context(&api, database_id, &name) {
Ok(c) => c,
Err(reqwest::StatusCode::NOT_FOUND) => {
eprintln!(
"{}",
format!("error: no context named '{name}' in this database.").red()
);
std::process::exit(1);
}
Err(status) => panic!("unexpected error status from fetch_context: {status}"),
};
let n_chars = ctx.content.chars().count();
if dry_run {
eprintln!(
"{}",
format!("would write {} chars to {}", n_chars, path.display()).dark_grey()
);
return;
}
let mut f = fs::File::create(&path).unwrap_or_else(|e| {
eprintln!("error: could not create {}: {e}", path.display());
std::process::exit(1);
});
if let Err(e) = f.write_all(ctx.content.as_bytes()) {
eprintln!("error: could not write {}: {e}", path.display());
std::process::exit(1);
}
println!(
"{}",
format!(
"wrote {} (updated {})",
path.display(),
crate::util::format_date(&ctx.updated_at)
)
.green()
);
}
pub fn push(workspace_id: &str, database_id: &str, name: &str, dry_run: bool) {
let name = normalize_context_cli_name(name);
if let Err(e) = validate_context_stem(&name) {
eprintln!("error: {e}");
std::process::exit(1);
}
let path = local_md_path(&name);
if !path.is_file() {
eprintln!(
"{}",
format!("error: {} does not exist or is not a file", path.display()).red()
);
std::process::exit(1);
}
let content = fs::read_to_string(&path).unwrap_or_else(|e| {
eprintln!("error: could not read {}: {e}", path.display());
std::process::exit(1);
});
let n_chars = content.chars().count();
if n_chars > MAX_CONTEXT_CONTENT_CHARS {
eprintln!(
"error: file is {} characters; maximum allowed is {}",
n_chars, MAX_CONTEXT_CONTENT_CHARS
);
std::process::exit(1);
}
if dry_run {
eprintln!(
"{}",
format!("would POST {} characters as context '{name}'", n_chars).dark_grey()
);
return;
}
let api = ApiClient::new(Some(workspace_id));
let body = json!({ "name": &name, "content": content });
let resp: UpsertResponse = api.post(&format!("/databases/{database_id}/context"), &body);
println!(
"{}",
format!(
"pushed '{}' (updated {})",
name,
crate::util::format_date(&resp.context.updated_at)
)
.green()
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn validate_accepts_datamodel() {
validate_context_stem("DATAMODEL").unwrap();
}
#[test]
fn validate_rejects_reserved() {
assert!(validate_context_stem("select").is_err());
}
#[test]
fn validate_rejects_dot() {
assert!(validate_context_stem("foo.md").is_err());
}
#[test]
fn validate_rejects_leading_digit() {
assert!(validate_context_stem("1abc").is_err());
}
#[test]
fn validate_accepts_leading_underscore() {
validate_context_stem("_private").unwrap();
}
#[test]
fn validate_accepts_max_length() {
let s = format!("a{}", "b".repeat(127));
assert_eq!(s.len(), 128);
validate_context_stem(&s).unwrap();
}
#[test]
fn validate_rejects_too_long() {
let s = format!("a{}", "b".repeat(128));
assert_eq!(s.len(), 129);
assert!(validate_context_stem(&s).is_err());
}
#[test]
fn validate_rejects_reserved_uppercase() {
assert!(validate_context_stem("SELECT").is_err());
}
#[test]
fn normalize_strips_trailing_md() {
assert_eq!(normalize_context_cli_name("USER.md"), "USER");
assert_eq!(normalize_context_cli_name("USER.MD"), "USER");
assert_eq!(normalize_context_cli_name(" USER.md "), "USER");
}
#[test]
fn normalize_accepts_path_with_md() {
assert_eq!(normalize_context_cli_name("./DATAMODEL.md"), "DATAMODEL");
}
#[test]
fn normalize_preserves_stem_without_md() {
assert_eq!(normalize_context_cli_name("DATAMODEL"), "DATAMODEL");
}
#[test]
fn normalize_strips_md_one_char_stem() {
assert_eq!(normalize_context_cli_name("a.md"), "a");
}
#[test]
fn normalize_does_not_panic_multibyte_stem_without_md() {
// 1 ASCII byte + 4-byte UTF-8; byte index 2 is inside the codepoint — must not slice there.
assert_eq!(normalize_context_cli_name("x𝕌"), "x𝕌");
}
#[test]
fn normalize_strips_md_after_multibyte_char() {
assert_eq!(normalize_context_cli_name("x𝕌.md"), "x𝕌");
}
}