forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.9 MiBe587be7Tahinli16 hours ago323 commits

wiki.rs377 lines, 12.5 KiBHistoryRawDownload
1//! Wiki storage. A repo's wiki is a second bare repo (see [`crate::repo::wiki_path`]) whose `main`
2//! branch holds one `<Page-Name>.md` file per page. Web edits are commits made with git plumbing:
3//! `hash-object`, a temporary index, `write-tree`, `commit-tree`, and a compare-and-swap
4//! `update-ref`. Two edits to the same page therefore never overwrite each other silently.
5
6use std::path::{Path, PathBuf};
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use crate::browse::{EntryKind, default_branch_commit, read_text_blob, read_tree};
10use crate::command::{GitCommand, GitEnv};
11use crate::error::{Error, Result};
12use crate::history::zero_oid;
13use crate::repo::init_bare;
14
15/// The branch that holds the pages.
16pub const WIKI_BRANCH: &str = "main";
17/// Extension of a page file.
18const PAGE_EXT: &str = ".md";
19/// Largest page the editor accepts, and the largest one read back.
20pub const MAX_PAGE_BYTES: usize = 256 * 1024;
21/// Longest page name, in characters.
22const MAX_PAGE_NAME: usize = 100;
23
24/// One page edit. `name` is the page name without the extension.
25#[derive(Debug, Clone, Copy)]
26pub struct PageEdit<'a> {
27 pub name: &'a str,
28 pub content: &'a [u8],
29 pub message: &'a str,
30 pub author_name: &'a str,
31 pub author_email: &'a str,
32}
33
34/// True when `name` can name a page: 1 to 100 ASCII letters, digits, `-` or `_`, not starting with
35/// `-`. Dashes stand for spaces in titles, so a page name never has a space or a slash.
36pub fn valid_page_name(name: &str) -> bool {
37 !name.is_empty()
38 && name.len() <= MAX_PAGE_NAME
39 && !name.starts_with('-')
40 && name
41 .bytes()
42 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
43}
44
45/// The file that holds page `name` on the wiki branch.
46pub fn page_file(name: &str) -> String {
47 format!("{name}{PAGE_EXT}")
48}
49
50/// Creates the wiki repo when it is missing. Calling it again is harmless.
51pub async fn ensure_wiki(env: &GitEnv, wiki: &Path) -> Result<()> {
52 if wiki.join("HEAD").is_file() {
53 return Ok(());
54 }
55 init_bare(env, wiki, WIKI_BRANCH).await
56}
57
58/// The commit at the tip of the wiki's `main`. `None` when the wiki is missing or has no page yet.
59pub fn head_commit(wiki: &Path) -> Result<Option<String>> {
60 if !wiki.join("HEAD").is_file() {
61 return Ok(None);
62 }
63 default_branch_commit(wiki, WIKI_BRANCH)
64}
65
66/// Names of the pages at the head, sorted. Files that are not valid page names are skipped.
67pub fn list_pages(wiki: &Path) -> Result<Vec<String>> {
68 let Some(head) = head_commit(wiki)? else {
69 return Ok(Vec::new());
70 };
71 let Some(entries) = read_tree(wiki, &head, "")? else {
72 return Ok(Vec::new());
73 };
74 let mut names: Vec<String> = entries
75 .iter()
76 .filter(|e| matches!(e.kind, EntryKind::Blob | EntryKind::Executable))
77 .filter_map(|e| e.name.strip_suffix(PAGE_EXT))
78 .filter(|name| valid_page_name(name))
79 .map(str::to_owned)
80 .collect();
81 names.sort();
82 Ok(names)
83}
84
85/// The Markdown source of page `name` at the head. `None` when the name is invalid, the page does
86/// not exist, or it is not text.
87pub fn read_page(wiki: &Path, name: &str) -> Result<Option<String>> {
88 if !valid_page_name(name) {
89 return Ok(None);
90 }
91 let Some(head) = head_commit(wiki)? else {
92 return Ok(None);
93 };
94 read_text_blob(wiki, &head, &page_file(name), MAX_PAGE_BYTES)
95}
96
97/// One commit that touched a page.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct PageRevision {
100 pub oid: String,
101 pub author: String,
102 /// Unix seconds of the author date.
103 pub at: i64,
104 pub subject: String,
105}
106
107/// Most revisions `page_history` returns.
108pub const HISTORY_LIMIT: usize = 200;
109
110/// Commits that touched page `name`, newest first, at most [`HISTORY_LIMIT`].
111pub async fn page_history(env: &GitEnv, wiki: &Path, name: &str) -> Result<Vec<PageRevision>> {
112 if !valid_page_name(name) || head_commit(wiki)?.is_none() {
113 return Ok(Vec::new());
114 }
115 let file = page_file(name);
116 let out = GitCommand::new(env, "log")
117 .git_dir(wiki)
118 .arg("--format=%H%x1f%an%x1f%at%x1f%s")
119 .user_opt("--max-count", &HISTORY_LIMIT.to_string())?
120 .user_arg(&format!("refs/heads/{WIKI_BRANCH}"))?
121 .paths(&[file.as_str()])
122 .output()
123 .await?;
124 let text = String::from_utf8_lossy(&out);
125 Ok(text
126 .lines()
127 .filter_map(|line| {
128 let mut parts = line.splitn(4, '\u{1f}');
129 Some(PageRevision {
130 oid: parts.next()?.to_owned(),
131 author: parts.next()?.to_owned(),
132 at: parts.next()?.parse().ok()?,
133 subject: parts.next()?.to_owned(),
134 })
135 })
136 .collect())
137}
138
139static INDEX_SEQ: AtomicU64 = AtomicU64::new(0);
140
141/// A temporary index file inside the wiki repo. Unique per process and call.
142pub(crate) fn temp_index(wiki: &Path) -> PathBuf {
143 let seq = INDEX_SEQ.fetch_add(1, Ordering::Relaxed);
144 let nanos = std::time::SystemTime::now()
145 .duration_since(std::time::UNIX_EPOCH)
146 .map(|d| d.as_nanos())
147 .unwrap_or(0);
148 wiki.join(format!("forge-index-{}-{nanos}-{seq}", std::process::id()))
149}
150
151/// Writes `edit` as a new commit on the wiki's `main`. `base` is the head the editor started from
152/// (`None` when the wiki had no commits). The edit lands only if the head is still `base`; otherwise
153/// it returns `Error::RefMoved` and writes nothing. Returns the new commit.
154pub async fn commit_page(
155 env: &GitEnv,
156 wiki: &Path,
157 base: Option<&str>,
158 edit: &PageEdit<'_>,
159) -> Result<String> {
160 if !valid_page_name(edit.name) {
161 return Err(Error::InvalidInput(format!(
162 "not a valid page name: {:?}",
163 edit.name
164 )));
165 }
166 if edit.content.len() > MAX_PAGE_BYTES {
167 return Err(Error::InvalidInput("page is too large".into()));
168 }
169 ensure_wiki(env, wiki).await?;
170 if head_commit(wiki)?.as_deref() != base {
171 return Err(Error::RefMoved(format!(
172 "wiki {WIKI_BRANCH} moved since the page was opened"
173 )));
174 }
175 let index = temp_index(wiki);
176 let result = write_commit(env, wiki, &index, base, edit).await;
177 // The index is scratch space. A leftover file is harmless, but do not keep it.
178 let _ = tokio::fs::remove_file(&index).await;
179 result
180}
181
182async fn write_commit(
183 env: &GitEnv,
184 wiki: &Path,
185 index: &Path,
186 base: Option<&str>,
187 edit: &PageEdit<'_>,
188) -> Result<String> {
189 let blob = GitCommand::new(env, "hash-object")
190 .git_dir(wiki)
191 .arg("-w")
192 .arg("--stdin")
193 .output_stdin(edit.content)
194 .await?;
195 let blob = String::from_utf8_lossy(&blob).trim().to_owned();
196
197 if let Some(base) = base {
198 GitCommand::new(env, "read-tree")
199 .git_dir(wiki)
200 .env("GIT_INDEX_FILE", index)
201 .user_arg(base)?
202 .status()
203 .await?;
204 }
205 let file = page_file(edit.name);
206 GitCommand::new(env, "update-index")
207 .git_dir(wiki)
208 .env("GIT_INDEX_FILE", index)
209 .arg("--add")
210 .arg("--cacheinfo")
211 .user_arg("100644")?
212 .user_arg(&blob)?
213 .user_arg(&file)?
214 .status()
215 .await?;
216
217 let tree = GitCommand::new(env, "write-tree")
218 .git_dir(wiki)
219 .env("GIT_INDEX_FILE", index)
220 .output()
221 .await?;
222 let tree = String::from_utf8_lossy(&tree).trim().to_owned();
223
224 let mut commit = GitCommand::new(env, "commit-tree")
225 .config("commit.gpgsign=false")
226 .git_dir(wiki)
227 .env("GIT_AUTHOR_NAME", edit.author_name)
228 .env("GIT_AUTHOR_EMAIL", edit.author_email)
229 .env("GIT_COMMITTER_NAME", edit.author_name)
230 .env("GIT_COMMITTER_EMAIL", edit.author_email)
231 .user_arg(&tree)?;
232 if let Some(base) = base {
233 commit = commit.arg("-p").user_arg(base)?;
234 }
235 let commit = commit.arg("-F").arg("-");
236 let oid = commit.output_stdin(edit.message.as_bytes()).await?;
237 let oid = String::from_utf8_lossy(&oid).trim().to_owned();
238
239 // Compare-and-swap: the ref must still hold `base`, or be absent when there was no base.
240 let old = match base {
241 Some(base) => base.to_owned(),
242 None => zero_oid(&oid),
243 };
244 let swapped = GitCommand::new(env, "update-ref")
245 .git_dir(wiki)
246 .arg("-m")
247 .arg("forge wiki edit")
248 .user_arg(&format!("refs/heads/{WIKI_BRANCH}"))?
249 .user_arg(&oid)?
250 .user_arg(&old)?
251 .status()
252 .await;
253 match swapped {
254 Ok(()) => Ok(oid),
255 Err(Error::Failed(msg))
256 if msg.contains("but expected") || msg.contains("unable to resolve reference") =>
257 {
258 Err(Error::RefMoved(format!("wiki {WIKI_BRANCH} moved during the edit")))
259 }
260 Err(e) => Err(e),
261 }
262}
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267 use crate::repo::{repo_path, wiki_path};
268
269 fn env(dir: &Path) -> GitEnv {
270 GitEnv {
271 git_bin: "/usr/bin/git".into(),
272 data_dir: dir.to_path_buf(),
273 }
274 }
275
276 fn edit<'a>(name: &'a str, body: &'a str) -> PageEdit<'a> {
277 PageEdit {
278 name,
279 content: body.as_bytes(),
280 message: "edit",
281 author_name: "Tahinli",
282 author_email: "tahinli@example.test",
283 }
284 }
285
286 #[test]
287 fn page_names_are_strict() {
288 assert!(valid_page_name("Home"));
289 assert!(valid_page_name("Getting-Started_2"));
290 assert!(!valid_page_name(""));
291 assert!(!valid_page_name("-x"));
292 assert!(!valid_page_name("a b"));
293 assert!(!valid_page_name("../etc"));
294 assert!(!valid_page_name("a/b"));
295 assert!(!valid_page_name(&"a".repeat(MAX_PAGE_NAME + 1)));
296 }
297
298 #[test]
299 fn wiki_path_sits_next_to_the_repo() {
300 let id = "01arz3ndektsv4rrffq69g5fav";
301 let main = repo_path(Path::new("/d"), id).unwrap();
302 let wiki = wiki_path(Path::new("/d"), id).unwrap();
303 assert_eq!(
304 wiki.to_string_lossy(),
305 format!("{}.wiki.git", main.with_extension("").display())
306 );
307 assert!(wiki_path(Path::new("/d"), "../x").is_err());
308 }
309
310 #[tokio::test]
311 async fn commit_then_read_list_and_history() {
312 let dir = tempfile::tempdir().unwrap();
313 let env = env(dir.path());
314 let wiki = dir.path().join("w.wiki.git");
315 assert_eq!(head_commit(&wiki).unwrap(), None);
316 assert!(list_pages(&wiki).unwrap().is_empty());
317
318 let first = commit_page(&env, &wiki, None, &edit("Home", "# Hi\n"))
319 .await
320 .unwrap();
321 assert_eq!(head_commit(&wiki).unwrap().as_deref(), Some(first.as_str()));
322 assert_eq!(read_page(&wiki, "Home").unwrap().as_deref(), Some("# Hi\n"));
323
324 let second = commit_page(
325 &env,
326 &wiki,
327 Some(&first),
328 &edit("Getting-Started", "more\n"),
329 )
330 .await
331 .unwrap();
332 assert_eq!(
333 list_pages(&wiki).unwrap(),
334 vec!["Getting-Started".to_owned(), "Home".to_owned()]
335 );
336 assert_eq!(read_page(&wiki, "Home").unwrap().as_deref(), Some("# Hi\n"));
337
338 let history = page_history(&env, &wiki, "Home").await.unwrap();
339 assert_eq!(history.len(), 1);
340 assert_eq!(history[0].oid, first);
341 assert_eq!(history[0].author, "Tahinli");
342 assert_eq!(
343 page_history(&env, &wiki, "Getting-Started").await.unwrap()[0].oid,
344 second
345 );
346 }
347
348 #[tokio::test]
349 async fn stale_base_is_refused_without_writing() {
350 let dir = tempfile::tempdir().unwrap();
351 let env = env(dir.path());
352 let wiki = dir.path().join("w.wiki.git");
353 let first = commit_page(&env, &wiki, None, &edit("Home", "one\n"))
354 .await
355 .unwrap();
356 commit_page(&env, &wiki, Some(&first), &edit("Home", "two\n"))
357 .await
358 .unwrap();
359 let err = commit_page(&env, &wiki, Some(&first), &edit("Home", "lost\n"))
360 .await
361 .unwrap_err();
362 assert!(matches!(err, Error::RefMoved(_)), "{err:?}");
363 assert_eq!(read_page(&wiki, "Home").unwrap().as_deref(), Some("two\n"));
364 }
365
366 #[tokio::test]
367 async fn invalid_name_is_refused() {
368 let dir = tempfile::tempdir().unwrap();
369 let env = env(dir.path());
370 let wiki = dir.path().join("w.wiki.git");
371 let err = commit_page(&env, &wiki, None, &edit("a/b", "x"))
372 .await
373 .unwrap_err();
374 assert!(matches!(err, Error::InvalidInput(_)));
375 assert!(read_page(&wiki, "a/b").unwrap().is_none());
376 }
377}