forge_doc/preprocessor/git_source.rs
1use super::{Preprocessor, PreprocessorId};
2use crate::{Document, PreprocessorOutput};
3use std::path::PathBuf;
4
5/// [GitSource] preprocessor id.
6pub const GIT_SOURCE_ID: PreprocessorId = PreprocessorId("git_source");
7
8/// The git source preprocessor.
9///
10/// This preprocessor writes to [Document]'s context.
11#[derive(Debug)]
12pub struct GitSource {
13 /// The project root.
14 pub root: PathBuf,
15 /// The current commit hash.
16 pub commit: Option<String>,
17 /// The repository url.
18 pub repository: Option<String>,
19}
20
21impl Preprocessor for GitSource {
22 fn id(&self) -> PreprocessorId {
23 GIT_SOURCE_ID
24 }
25
26 fn preprocess(&self, documents: Vec<Document>) -> Result<Vec<Document>, eyre::Error> {
27 if let Some(ref repo) = self.repository {
28 let repo = repo.trim_end_matches('/');
29 let commit = self.commit.clone().unwrap_or("master".to_owned());
30 for document in &documents {
31 if document.from_library {
32 continue;
33 }
34 let git_url = format!(
35 "{repo}/blob/{commit}/{}",
36 document.item_path.strip_prefix(&self.root)?.display()
37 );
38 document.add_context(self.id(), PreprocessorOutput::GitSource(git_url));
39 }
40 }
41
42 Ok(documents)
43 }
44}