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
|
mod sectiondata;
mod tags;
pub use sectiondata::SectionData;
pub use tags::Tags;
use core::fmt;
use std::str::FromStr;
use camino::{Utf8Path, Utf8PathBuf};
use tokio::sync::RwLock;
use crate::{WikError, WikFile, fs::Open, git::GitContext, quotes_decode, quotes_encode};
pub struct Tables {
posts: Table<Tags>,
sections: Table<SectionData>,
}
impl Tables {
const POSTS: &'static str = ".wikarden/table/posts";
const SECTIONS: &'static str = ".wikarden/table/sections";
pub async fn new(root: &Utf8Path) -> Result<Self, WikError> {
Self::init(root)?;
let posts_path = root.join(Self::POSTS);
let sections_path = root.join(Self::SECTIONS);
let posts = Table::new_and_load(posts_path).await?;
let sections = Table::new_and_load(sections_path).await?;
Ok(Self { posts, sections })
}
fn init(root: &Utf8Path) -> Result<(), WikError> {
let mut parent = root.join(Self::POSTS);
parent.pop();
if let Err(_e) = std::fs::create_dir_all(&parent) {
Err(WikError::DirectoryCreation { path: parent })
} else {
Ok(())
}
}
pub async fn has_page<S: AsRef<str>>(&self, name: S) -> bool {
self.posts.has(name).await
}
pub async fn has_section<S: AsRef<str>>(&self, section: S) -> bool {
self.sections.has(section).await
}
pub async fn get_sections(&self) -> Vec<TableEntry<SectionData>> {
self.sections.entries().await
}
pub async fn add_page<S: Into<String>>(&self, name: S, data: Tags) -> Result<(), WikError> {
self.posts
.add(TableEntry {
name: name.into(),
data,
})
.await;
self.posts.save().await
}
pub async fn add_section<S: Into<String>>(
&self,
section: S,
data: SectionData,
) -> Result<(), WikError> {
self.sections
.add(TableEntry {
name: section.into(),
data,
})
.await;
self.sections.save().await
}
pub async fn del_page<S: AsRef<str>>(&self, name: S) -> Result<(), WikError> {
self.posts.del(name.as_ref()).await;
self.posts.save().await
}
pub async fn del_section<S: AsRef<str>>(&self, section: S) -> Result<(), WikError> {
self.sections.del(section.as_ref()).await;
self.sections.save().await
}
pub async fn replace_sections(
&self,
data: Vec<TableEntry<SectionData>>,
) -> Result<(), WikError> {
self.sections.replace_entries(data).await;
self.sections.save().await
}
pub fn sections(&self) -> &Table<SectionData> {
&self.sections
}
pub fn posts(&self) -> &Table<Tags> {
&self.posts
}
pub fn git_add(gtx: &mut GitContext) {
gtx.add_rel(Self::POSTS.into()).unwrap();
gtx.add_rel(Self::SECTIONS.into()).unwrap();
}
}
pub(crate) struct Table<D: TableData> {
path: Utf8PathBuf,
entries: RwLock<Vec<TableEntry<D>>>,
}
impl<D: TableData> Table<D> {
pub async fn new_and_load(path: Utf8PathBuf) -> Result<Self, WikError> {
let entries = Self::load(&path).await?;
Ok(Self {
path,
entries: RwLock::new(entries),
})
}
pub async fn replace_entries(&self, entries: Vec<TableEntry<D>>) {
let mut lock = self.entries.write().await;
*lock = entries;
}
pub async fn has<S: AsRef<str>>(&self, name: S) -> bool {
let lock = self.entries.read().await;
lock.iter()
.position(|te| te.name.eq(name.as_ref()))
.is_some()
}
//TODO: gen 2026-08: this should insert in sorted order instead of then sorting
pub async fn add(&self, entry: TableEntry<D>) {
let mut lock = self.entries.write().await;
lock.push(entry);
Self::sort(&mut lock);
}
pub async fn del(&self, name: &str) -> Option<TableEntry<D>> {
let mut lock = self.entries.write().await;
match lock.iter().position(|e| e.name == name) {
None => return None,
Some(idx) => Some(lock.remove(idx)),
}
}
pub async fn entry_data(&self, name: &str) -> Option<D> {
let lock = self.entries.read().await;
match lock.iter().position(|e| e.name == name) {
None => return None,
Some(idx) => Some(lock[idx].data.clone()),
}
}
pub async fn modify_entry<F>(&self, name: &str, f: F) -> Result<bool, WikError>
where
F: FnOnce(&mut TableEntry<D>),
{
let mut lock = self.entries.write().await;
match lock.iter().position(|e| e.name == name) {
None => return Ok(false),
Some(idx) => {
let mut entry = &mut lock[idx];
f(&mut entry);
Self::sort(&mut lock);
drop(lock);
self.save().await?;
Ok(true)
}
}
}
pub async fn modify_entry_data<F>(&self, name: &str, f: F) -> Result<bool, WikError>
where
F: FnOnce(&mut D),
{
let mut lock = self.entries.write().await;
let actioned = match lock.iter().position(|e| e.name == name) {
None => false,
Some(idx) => {
let entry = &mut lock[idx];
f(&mut entry.data);
true
}
};
drop(lock);
self.save().await.map(|_| actioned)
}
pub async fn entries(&self) -> Vec<TableEntry<D>> {
let lock = self.entries.read().await;
lock.clone()
}
fn sort(entries: &mut [TableEntry<D>]) {
entries.sort_by(|a, b| a.name.cmp(&b.name));
}
pub async fn save(&self) -> Result<(), WikError> {
let mut lock = self.entries.write().await;
Self::sort(&mut lock);
let mut file = WikFile::open(self.path.clone(), Open::Create).await?;
file.write_all_strs(lock.iter()).await
}
async fn load(path: &Utf8Path) -> Result<Vec<TableEntry<D>>, WikError> {
let file = WikFile::open(path.to_owned(), Open::CreateAppend).await?;
let content = file.read_to_string().await?;
let mut entries = vec![];
for line in content.lines() {
let entry = TableEntry::from_str(line).unwrap();
entries.push(entry);
}
Self::sort(&mut entries);
Ok(entries)
}
}
pub trait TableData: std::fmt::Debug + std::fmt::Display + Clone {
fn parse(raw: &str) -> Result<Self, &'static str>
where
Self: Sized;
}
#[derive(Clone, Debug)]
pub struct TableEntry<D: TableData> {
name: String,
data: D,
}
impl<D: TableData> TableEntry<D> {
pub fn new(name: String, data: D) -> Self {
Self { name, data }
}
pub fn into_name(self) -> String {
self.name
}
pub fn name(&self) -> &str {
&self.name
}
pub fn set_name(&mut self, name: String) {
self.name = name;
}
pub fn data(&self) -> &D {
&self.data
}
}
impl<D: TableData> fmt::Display for TableEntry<D> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let quoted = quotes_encode(&self.name);
writeln!(f, "{quoted}\t{}", self.data)
}
}
impl<D: TableData> FromStr for TableEntry<D> {
type Err = &'static str;
fn from_str(raw: &str) -> Result<Self, &'static str> {
let decode = quotes_decode(raw);
match decode {
None => Err("string does not start with a quote"),
Some((name, rest)) => {
let data_str = rest.trim_start();
let data = D::parse(data_str)?;
Ok(Self { name, data })
}
}
}
}
/*
impl FromStr for JournalLine {
type Err = &'static str;
fn from_str(raw: &str) -> Result<Self, Self::Err> {
let decode = quotes_decode(raw);
match decode {
None => Err("string does not start with quote"),
Some((path, rest)) => {
let time_str = rest.trim_start();
let time: i64 = match time_str.parse() {
Err(_) => return Err("time is not a number"),
Ok(stamp) => stamp,
};
match OffsetDateTime::from_unix_timestamp(time) {
Err(_) => Err("timestamp is not valid"),
Ok(time) => Ok(Self {
path: path.into(),
time,
}),
}
}
}
}
}
*/
|