about summary refs log tree commit diff
path: root/wikarden/src/wikarden.rs
blob: 71f7410efc18a648c907fe7d8366284a4d28b433 (plain)
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use std::borrow::Cow;

use camino::{Utf8Path, Utf8PathBuf};

use crate::{
	JournalName, Settings, WikError,
	error::FileOp,
	fs::{self, EitherPath, Open, WikFile, WikPath},
	git::GitContext,
	journal::{Journal, JournalLine},
	table::{SectionData, TableEntry, Tables, Tags},
};

pub enum CommitMessage<'a> {
	None,
	Borrow(&'a str),
	Owned(String),
}

impl<'a> Into<Option<Cow<'a, str>>> for CommitMessage<'a> {
	fn into(self) -> Option<Cow<'a, str>> {
		match self {
			Self::None => None,
			Self::Borrow(s) => Some(Cow::Borrowed(s)),
			Self::Owned(own) => Some(Cow::Owned(own)),
		}
	}
}

impl<'a, T: Into<CommitMessage<'a>>> From<Option<T>> for CommitMessage<'a> {
	fn from(opt: Option<T>) -> Self {
		match opt {
			None => Self::None,
			Some(msg) => msg.into(),
		}
	}
}

impl From<String> for CommitMessage<'static> {
	fn from(owned: String) -> Self {
		Self::Owned(owned)
	}
}

impl<'a> From<&'a str> for CommitMessage<'a> {
	fn from(s: &'a str) -> Self {
		Self::Borrow(s)
	}
}

pub struct Source {
	pub path: WikPath,
	pub data: String,
}

pub enum PathType {
	Page,
	Section,
}

pub struct Wikarden {
	root: Utf8PathBuf,
	journal: Journal,
	tables: Tables,

	settings: Settings,
}

impl Wikarden {
	const DRAFT_DIR: &'static str = ".wikarden/drafts";

	pub async fn new<Root: Into<Utf8PathBuf>>(
		root: Root,
		settings: Settings,
	) -> Result<Self, WikError> {
		let root = root.into();
		Self::init(&root)?;

		Ok(Self {
			root: root.clone(),
			journal: Journal::init(&root).await?,
			tables: Tables::new(&root).await?,

			settings,
		})
	}

	fn init(root: &Utf8Path) -> Result<(), WikError> {
		let draft_path = root.join(Self::DRAFT_DIR);

		if let Err(_e) = std::fs::create_dir_all(&draft_path) {
			Err(WikError::DirectoryCreation { path: draft_path })
		} else {
			Ok(())
		}
	}

	pub async fn refresh_sections(&self) -> Result<(), WikError> {
		let res = read_sections_from_fs(&self.root).await;
		match res {
			Err(e) => WikError::file_operation(FileOp::Read, self.root.clone(), e),
			Ok(sections) => {
				let entries = sections
					.into_iter()
					.map(|n| TableEntry::new(n, SectionData::default()))
					.collect();

				self.tables.replace_sections(entries).await
			}
		}
	}

	pub async fn sections(&self) -> Vec<String> {
		self.tables
			.get_sections()
			.await
			.into_iter()
			.map(|te| te.into_name())
			.collect()
	}

	pub async fn journal_tail(&self, kind: JournalName, count: usize) -> Vec<JournalLine> {
		self.journal.journal_tail(kind, count).await
	}

	pub async fn path_type<P: Into<WikPath>>(&self, path: P) -> Option<PathType> {
		let path = path.into();

		match self.page_exists(path.clone()).await {
			Ok(true) => return Some(PathType::Page),
			Ok(false) => match self.section_exists(path.clone()).await {
				false => None,
				true => Some(PathType::Section),
			},
			Err(WikError::SectionNoexist { .. }) => None,
			Err(_) => unreachable!(),
		}
	}

	// assumes the post stable stays up to date
	pub async fn page_exists<P: Into<WikPath>>(&self, path: P) -> Result<bool, WikError> {
		let path = path.into();
		self.check_parent_section(&path).await?;
		Ok(self.tables.has_page(path).await)
	}

	// assumes the section table stays up to date
	pub async fn section_exists<P: Into<WikPath>>(&self, path: P) -> bool {
		self.tables.has_section(path.into()).await
	}

	//MARK: Page Handling
	pub async fn source<P: Into<WikPath>>(&self, path: P) -> Result<Source, WikError> {
		let path = path.into();
		let file = self.file_from_path(path.clone(), Open::Read).await?;
		let content = file.read_to_string().await?;

		Ok(Source {
			path,
			data: content,
		})
	}

	pub async fn create<Path, Content, Message>(
		&self,
		path: Path,
		content: Content,
		commit: Message,
	) -> Result<(), WikError>
	where
		Path: Into<WikPath>,
		Content: AsRef<str>,
		Message: Into<CommitMessage<'static>>,
	{
		let path = path.into();

		if self.page_exists(path.clone()).await? {
			return Err(WikError::page_exists(path));
		}

		let mut file = self.file_from_path(path.clone(), Open::Create).await?;
		file.write_str(content.as_ref()).await?;
		file.done().await?;

		self.tables.add_page(path.as_ref(), Tags::default()).await?;

		self.journal
			.push(JournalName::Created, path.clone())
			.await?;

		self.git_commit_file(
			path.clone(),
			commit.into(),
			format!("created page '{path}'"),
		)
	}

	pub async fn move_page<FromPath: Into<WikPath>, ToPath: Into<WikPath>>(
		&self,
		from: FromPath,
		to: ToPath,
	) -> Result<(), WikError> {
		let from = from.into();
		let to = to.into();

		if !self.page_exists(from.clone()).await? {
			return Err(WikError::page_noexists(from));
		}

		if self.page_exists(to.clone()).await? {
			return Err(WikError::page_exists(to));
		}

		let safe_from = EitherPath::from(from.clone()).safe(&self.root)?;
		let safe_to = EitherPath::safe_nonexist(&self.root, &to)?;
		if let Err(e) = tokio::fs::rename(safe_from.0, &safe_to.0).await {
			return WikError::file_operation(FileOp::Write, safe_to.0, e);
		}

		self.journal
			.rename(JournalName::Created, from.clone(), to.clone())
			.await?;

		self.journal
			.rename(JournalName::Modified, from.clone(), to.clone())
			.await?;

		self.tables
			.posts()
			.modify_entry(from.as_ref(), |te| te.set_name(to.to_string()))
			.await?;

		Ok(())
	}

	pub async fn modify<Path, Content, Message>(
		&self,
		path: Path,
		new_content: Content,
		commit: Message,
	) -> Result<(), WikError>
	where
		Path: Into<WikPath>,
		Content: AsRef<str>,
		Message: Into<CommitMessage<'static>>,
	{
		let path = path.into();

		if !self.page_exists(path.clone()).await? {
			return Err(WikError::page_noexists(path));
		}

		let mut file = self.file_from_path(path.clone(), Open::Write).await?;
		file.write_str(new_content.as_ref()).await?;
		file.done().await?;

		self.journal
			.push(JournalName::Modified, path.clone())
			.await?;

		self.git_commit_file(path.clone(), commit.into(), format!("edited page '{path}'"))
	}

	pub async fn delete<P: Into<WikPath>>(&self, path: P) -> Result<(), WikError> {
		let path = path.into();

		if !self.page_exists(path.clone()).await? {
			return Err(WikError::page_noexists(path));
		}

		let safe = EitherPath::Wik(path.clone()).safe(&self.root)?;
		WikFile::remove(safe).await?;

		self.tables.del_page(&path).await?;

		self.journal.del(JournalName::Created, path.clone()).await?;
		self.journal
			.del(JournalName::Modified, path.clone())
			.await?;

		self.git_commit_file(
			path.clone(),
			CommitMessage::None,
			format!("deleted page '{path}'"),
		)
	}

	pub async fn create_section<P: Into<WikPath>>(
		&self,
		path: P,
		commit: Option<Cow<'static, str>>,
	) -> Result<(), WikError> {
		let path = path.into();
		self.check_parent_section(&path).await?;

		if self.tables.has_section(&path).await {
			return Err(WikError::section_exists(path));
		}

		let system_path = EitherPath::safe_nonexist(&self.root, &path)?;
		fs::create_dir(system_path).await?;

		self.tables
			.add_section(path.as_ref(), SectionData::default())
			.await?;

		let wikarden_message = format!("created section '{path}'");
		let message = Self::make_commit_message(commit, wikarden_message);
		let git = self.get_git();
		self.finish_git(git, message)
	}

	pub async fn get_section_data<P: Into<WikPath>>(
		&self,
		path: P,
	) -> Result<SectionData, WikError> {
		let path = path.into();

		match self.tables.sections().entry_data(path.as_ref()).await {
			None => Err(WikError::section_noexist(path)),
			Some(data) => Ok(data),
		}
	}

	pub async fn modify_section_data<P: Into<WikPath>, F>(
		&self,
		path: P,
		commit: Option<Cow<'static, str>>,
		f: F,
	) -> Result<(), WikError>
	where
		F: FnOnce(&mut SectionData),
	{
		let path = path.into();

		if !self.section_exists(path.clone()).await {
			return Err(WikError::section_noexist(path));
		}

		let sections = self.tables.sections();
		sections.modify_entry_data(path.as_ref(), f).await?;

		let wikarden_message = format!("modified section '{path}'");
		let message = Self::make_commit_message(commit, wikarden_message);
		let git = self.get_git();
		self.finish_git(git, message)
	}

	//MARK: Utilities
	async fn file_from_path<P: Into<WikPath>>(
		&self,
		path: P,
		flags: Open,
	) -> Result<WikFile, WikError> {
		let safe = EitherPath::safe_nonexist(&self.root, &path.into())?;
		WikFile::open(safe.0, flags).await
	}

	async fn check_parent_section(&self, path: &WikPath) -> Result<(), WikError> {
		if let Some(parent) = path.parent() {
			if !self.section_exists(parent.clone()).await {
				return Err(WikError::section_noexist(parent));
			}
		}

		Ok(())
	}

	/// Creates a new git commit, including the provided path. It also commits
	/// the tables and journals
	fn git_commit_file<P: Into<EitherPath>>(
		&self,
		path: P,
		user_message: CommitMessage<'static>,
		our_message: String,
	) -> Result<(), WikError> {
		let safe = path.into().safe(&self.root)?;
		let mut git = self.get_git();
		git.add(&safe)?;

		let message = Self::make_commit_message(user_message.into(), our_message.into());
		self.finish_git(git, message)
	}

	fn make_commit_message(
		user_message: Option<Cow<'static, str>>,
		our_message: String,
	) -> Cow<'static, str> {
		match user_message {
			None => Cow::Owned(our_message),
			Some(user) => Cow::Owned(format!("{user}\n\n{our_message}")),
		}
	}

	/// Creates a new [GitContext] with the Tables and Journal already added
	/// to the commit
	fn get_git(&self) -> GitContext {
		let mut git = GitContext::open(&self.root);
		Tables::git_add(&mut git);
		self.journal.git_add(&mut git);
		git
	}

	/// Writes the index and then makes a commit with the provided string
	fn finish_git(&self, mut git: GitContext, commit: Cow<'static, str>) -> Result<(), WikError> {
		git.write_index()?;
		git.commit(self.settings.signature(), commit)?;
		Ok(())
	}
}

/// Reads the filesystem looking for sections.
async fn read_sections_from_fs(root: &Utf8Path) -> Result<Vec<String>, std::io::Error> {
	let mut sections = vec![];

	let mut dirs = tokio::fs::read_dir(root).await?;
	while let Some(entry) = dirs.next_entry().await? {
		let name = entry.file_name();
		let path = entry.path();

		if !name.to_string_lossy().starts_with(".") {
			let meta = entry.metadata().await?;
			if meta.is_dir() {
				match path.to_str() {
					None => (),
					Some(s) => {
						let stripped = s.strip_prefix(&format!("{root}/")).unwrap();
						sections.push(stripped.to_owned());
						let subsec = Box::pin(read_sections_from_fs(s.into())).await?;
						sections.extend(subsec.iter().map(|s| format!("{stripped}/{s}")));
					}
				}
			}
		}
	}

	return Ok(sections);
}