Skip to main content

gitpoulpi_hosting/local_markdown/
client.rs

1//! The local Markdown issue source as a [`HostingClient`].
2//!
3//! `project` is the folder (absolute, or relative to the caller's working
4//! directory: the frontends resolve a repository-relative link against the
5//! repository root with [`resolve_folder`] before they ask). Nothing here
6//! opens a socket; the transport is never used.
7
8use std::path::{Path, PathBuf};
9
10use crate::client::{CreatedIssue, CreatedPullRequest, HostingClient, NewIssue, NewPullRequest};
11use crate::conversation::{
12    Comment, ConversationCaps, ItemKey, ItemKind, PageCursor, PostingIdentity, TimelineOpts,
13    TimelinePage,
14};
15use crate::integration::Integration;
16use crate::metadata::{HostedLabel, HostedMilestone, IssueEdit, ItemMeta, MetaKind};
17use crate::model::{
18    Choice, HostedUser, IssueCreateOptions, IssueFilter, IssueState, IssueSummary, StateFilter,
19    TokenCheck,
20};
21use crate::project::{HostedProject, HostedSshKey};
22use crate::{Error, Result};
23
24use super::store::{Issue, NewNote, Patch, Store};
25
26/// The `file://` URL of a note (what "open" hands to the system).
27pub fn file_url(path: &Path) -> String {
28    let text = path.to_string_lossy().replace('\\', "/");
29    let encoded: String = text
30        .split('/')
31        .map(|seg| {
32            let mut out = String::new();
33            for b in seg.bytes() {
34                if b.is_ascii_alphanumeric()
35                    || matches!(b, b'-' | b'_' | b'.' | b'~' | b':' | b'@' | b'+' | b',')
36                {
37                    out.push(b as char);
38                } else {
39                    out.push_str(&format!("%{b:02X}"));
40                }
41            }
42            out
43        })
44        .collect::<Vec<_>>()
45        .join("/");
46    if encoded.starts_with('/') {
47        format!("file://{encoded}")
48    } else {
49        format!("file:///{encoded}")
50    }
51}
52
53/// The path a `file://` URL ([`file_url`]) names.
54pub fn path_from_file_url(url: &str) -> Option<PathBuf> {
55    let rest = url.strip_prefix("file://")?;
56    let mut bytes = Vec::with_capacity(rest.len());
57    let raw = rest.as_bytes();
58    let mut i = 0;
59    while i < raw.len() {
60        if raw[i] == b'%' && i + 2 < raw.len() {
61            let hex = std::str::from_utf8(&raw[i + 1..i + 3]).ok()?;
62            bytes.push(u8::from_str_radix(hex, 16).ok()?);
63            i += 3;
64        } else {
65            bytes.push(raw[i]);
66            i += 1;
67        }
68    }
69    let text = String::from_utf8(bytes).ok()?;
70    // `file:///C:/x` carries the drive after the slash.
71    let text = if text.len() > 2 && text.as_bytes()[2] == b':' && text.starts_with('/') {
72        text[1..].to_string()
73    } else {
74        text
75    };
76    Some(PathBuf::from(text))
77}
78
79/// The note of issue `id` in `folder`, when there is one.
80pub fn note_path(integration: &Integration, folder: &str, id: u64) -> Option<PathBuf> {
81    store_for(integration, folder).get(id).ok().map(|i| i.path)
82}
83
84fn store_for(integration: &Integration, folder: &str) -> Store {
85    let folder = if folder.trim().is_empty() {
86        integration.url.as_str()
87    } else {
88        folder
89    };
90    Store::new(folder, integration.local.clone().unwrap_or_default())
91}
92
93pub(crate) struct LocalMarkdownClient {
94    pub(super) integration: Integration,
95}
96
97impl LocalMarkdownClient {
98    pub(crate) fn new(integration: Integration) -> Self {
99        Self { integration }
100    }
101
102    pub(super) fn store(&self, project: &str) -> Store {
103        store_for(&self.integration, project)
104    }
105
106    pub(super) fn me(&self) -> String {
107        let settings = self.integration.local.clone().unwrap_or_default();
108        if !settings.me.trim().is_empty() {
109            return settings.me.trim().to_string();
110        }
111        match &self.integration.user {
112            Some(u) if !u.login.is_empty() => u.login.clone(),
113            _ => self.integration.display_name().to_string(),
114        }
115    }
116
117    fn summary(&self, issue: &Issue) -> IssueSummary {
118        let settings = self.integration.local.clone().unwrap_or_default();
119        let prefix = settings.reference_prefix.trim();
120        let reference = if prefix.is_empty() {
121            format!("#{}", issue.id)
122        } else {
123            format!("{prefix}-{}", issue.id)
124        };
125        let closed = issue.status.eq_ignore_ascii_case(settings.done());
126        IssueSummary {
127            branch_name: None,
128            number: issue.id,
129            id: issue.id.to_string(),
130            reference: reference.clone(),
131            kind_label: None,
132            status_label: Some(issue.status.clone()),
133            iid_label: reference,
134            title: issue.title.clone(),
135            state: if closed {
136                IssueState::Closed
137            } else {
138                IssueState::Open
139            },
140            author: String::new(),
141            assignees: issue.assignees.clone(),
142            labels: issue.labels.clone(),
143            web_url: file_url(&issue.path),
144            updated_at: issue.updated.clone(),
145            milestone: issue.milestone.clone(),
146        }
147    }
148
149    /// The distinct milestone titles, sorted: the 1-based position is the
150    /// id the pickers send back.
151    fn milestone_titles(&self, project: &str) -> Result<Vec<String>> {
152        Ok(self.store(project).used_values()?.milestones)
153    }
154
155    fn milestone_by_id(&self, project: &str, id: u64) -> Result<String> {
156        let titles = self.milestone_titles(project)?;
157        usize::try_from(id)
158            .ok()
159            .and_then(|i| i.checked_sub(1))
160            .and_then(|i| titles.get(i).cloned())
161            .ok_or_else(|| Error::Local(format!("no milestone {id} in this folder")))
162    }
163}
164
165#[async_trait::async_trait]
166impl HostingClient for LocalMarkdownClient {
167    fn integration(&self) -> &Integration {
168        &self.integration
169    }
170
171    async fn list_projects(&self) -> Result<Vec<HostedProject>> {
172        let root = self.integration.url.trim().to_string();
173        let mut folders = vec![root.clone()];
174        let path = Path::new(&root);
175        // An absolute folder (a vault) also offers its sub-folders.
176        if path.is_absolute() {
177            if let Ok(entries) = std::fs::read_dir(path) {
178                let mut subs: Vec<String> = entries
179                    .filter_map(|e| e.ok())
180                    .filter(|e| e.path().is_dir())
181                    .filter_map(|e| {
182                        let name = e.file_name().to_string_lossy().into_owned();
183                        (!name.starts_with('.')).then(|| e.path().to_string_lossy().into_owned())
184                    })
185                    .collect();
186                subs.sort();
187                folders.extend(subs.into_iter().take(200));
188            }
189        }
190        Ok(folders
191            .into_iter()
192            .map(|full| HostedProject {
193                integration_id: self.integration.id.clone(),
194                id: full.clone(),
195                name: Path::new(&full)
196                    .file_name()
197                    .map(|n| n.to_string_lossy().into_owned())
198                    .unwrap_or_else(|| full.clone()),
199                full_name: full.clone(),
200                description: None,
201                default_branch: None,
202                ssh_url: None,
203                https_url: None,
204                web_url: Some(file_url(Path::new(&full))),
205                private: true,
206            })
207            .collect())
208    }
209
210    async fn list_ssh_keys(&self) -> Result<Vec<HostedSshKey>> {
211        Err(self.unsupported("list_ssh_keys"))
212    }
213
214    async fn upload_ssh_key(&self, _title: &str, _public_key: &str) -> Result<HostedSshKey> {
215        Err(self.unsupported("upload_ssh_key"))
216    }
217
218    async fn create_pull_request(&self, _req: &NewPullRequest) -> Result<CreatedPullRequest> {
219        Err(self.unsupported("create_pull_request"))
220    }
221
222    fn conversation_caps(&self, kind: ItemKind) -> ConversationCaps {
223        ConversationCaps::local_markdown(kind)
224    }
225
226    async fn posting_identity(&self, _project: &str) -> Result<PostingIdentity> {
227        self.conv_identity().await
228    }
229
230    async fn item_timeline(
231        &self,
232        project: &str,
233        key: &ItemKey,
234        older: Option<&PageCursor>,
235        opts: &TimelineOpts,
236    ) -> Result<TimelinePage> {
237        self.conv_timeline(project, key, older, opts).await
238    }
239
240    async fn post_item_comment(
241        &self,
242        project: &str,
243        key: &ItemKey,
244        body: &str,
245        internal: bool,
246    ) -> Result<Comment> {
247        self.conv_post(project, key, body, internal).await
248    }
249
250    async fn edit_item_comment(
251        &self,
252        project: &str,
253        key: &ItemKey,
254        comment_id: &str,
255        body: &str,
256    ) -> Result<Comment> {
257        self.conv_edit(project, key, comment_id, body).await
258    }
259
260    async fn delete_item_comment(
261        &self,
262        project: &str,
263        key: &ItemKey,
264        comment_id: &str,
265    ) -> Result<()> {
266        self.conv_delete(project, key, comment_id).await
267    }
268
269    async fn current_user(&self) -> Result<HostedUser> {
270        Ok(HostedUser {
271            login: self.me(),
272            name: String::new(),
273            id: String::new(),
274            web_url: None,
275        })
276    }
277
278    async fn check_token(&self) -> Result<TokenCheck> {
279        // No token: "connected" means the folder is readable.
280        let dir = Path::new(self.integration.url.trim());
281        if self.integration.url.trim().is_empty() {
282            return Err(Error::Local("no folder is set".into()));
283        }
284        if dir.is_absolute() && !dir.is_dir() {
285            return Err(Error::Local(format!("`{}` is not a folder", dir.display())));
286        }
287        Ok(TokenCheck {
288            user: self.current_user().await?,
289            scopes: None,
290            missing_scopes: Vec::new(),
291            expires_at: None,
292            ..Default::default()
293        })
294    }
295
296    async fn list_issues(&self, project: &str, filter: &IssueFilter) -> Result<Vec<IssueSummary>> {
297        let store = self.store(project);
298        let settings = self.integration.local.clone().unwrap_or_default();
299        let done = settings.done().to_string();
300        let me = self.me();
301        let wanted: Vec<String> = filter
302            .query
303            .as_deref()
304            .unwrap_or("")
305            .split(',')
306            .map(|s| s.trim().to_lowercase())
307            .filter(|s| !s.is_empty())
308            .collect();
309        let mut rows: Vec<Issue> = store
310            .list()?
311            .into_iter()
312            .filter(|i| {
313                let closed = i.status.eq_ignore_ascii_case(&done);
314                match filter.state {
315                    StateFilter::Open => !closed,
316                    StateFilter::Closed => closed,
317                    StateFilter::All => true,
318                }
319            })
320            .filter(|i| {
321                !filter.assigned_to_me || i.assignees.iter().any(|a| a.eq_ignore_ascii_case(&me))
322            })
323            .filter(|i| wanted.is_empty() || wanted.contains(&i.status.to_lowercase()))
324            .collect();
325        // Newest first, like the hosts.
326        rows.sort_by_key(|a| std::cmp::Reverse(a.id));
327        Ok(rows.iter().map(|i| self.summary(i)).collect())
328    }
329
330    async fn create_issue(&self, req: &NewIssue) -> Result<CreatedIssue> {
331        let store = self.store(&req.project);
332        let milestone = match req.milestone {
333            Some(id) => Some(self.milestone_by_id(&req.project, id)?),
334            None => None,
335        };
336        let made = store.create(&NewNote {
337            title: req.title.clone(),
338            body: req.body.clone(),
339            assignees: req.assignees.clone(),
340            labels: req.labels.clone(),
341            milestone,
342            status: req.list_id.clone().unwrap_or_default(),
343        })?;
344        let summary = self.summary(&made);
345        Ok(CreatedIssue {
346            number: made.id,
347            web_url: summary.web_url,
348            reference: summary.reference,
349        })
350    }
351
352    async fn issue_create_options(&self, project: &str) -> Result<IssueCreateOptions> {
353        let statuses = self.store(project).used_values()?.statuses;
354        Ok(IssueCreateOptions {
355            types: Vec::new(),
356            default_list: statuses.first().cloned(),
357            lists: statuses
358                .into_iter()
359                .map(|s| Choice {
360                    id: s.clone(),
361                    label: s,
362                })
363                .collect(),
364            default_type: None,
365        })
366    }
367
368    async fn project_members(&self, project: &str, query: &str) -> Result<Vec<HostedUser>> {
369        let mut logins = self.store(project).used_values()?.assignees;
370        let me = self.me();
371        if !logins.iter().any(|l| l.eq_ignore_ascii_case(&me)) {
372            logins.insert(0, me);
373        }
374        let q = query.trim().to_lowercase();
375        Ok(logins
376            .into_iter()
377            .filter(|l| q.is_empty() || l.to_lowercase().contains(&q))
378            .map(|login| HostedUser {
379                login,
380                ..HostedUser::default()
381            })
382            .collect())
383    }
384
385    async fn project_labels(&self, project: &str) -> Result<Vec<HostedLabel>> {
386        Ok(self
387            .store(project)
388            .used_values()?
389            .labels
390            .into_iter()
391            .map(|name| HostedLabel {
392                name,
393                ..HostedLabel::default()
394            })
395            .collect())
396    }
397
398    async fn project_milestones(&self, project: &str) -> Result<Vec<HostedMilestone>> {
399        Ok(self
400            .milestone_titles(project)?
401            .into_iter()
402            .enumerate()
403            .map(|(i, title)| HostedMilestone {
404                id: i as u64 + 1,
405                title,
406                due_on: None,
407                state: "open".into(),
408            })
409            .collect())
410    }
411
412    async fn item_meta(&self, project: &str, number: u64, _kind: MetaKind) -> Result<ItemMeta> {
413        let issue = self.store(project).get(number)?;
414        let titles = self.milestone_titles(project)?;
415        let milestone = issue.milestone.as_ref().and_then(|m| {
416            titles.iter().position(|t| t == m).map(|i| HostedMilestone {
417                id: i as u64 + 1,
418                title: m.clone(),
419                due_on: None,
420                state: "open".into(),
421            })
422        });
423        Ok(ItemMeta {
424            assignees: issue.assignees,
425            reviewers: Vec::new(),
426            labels: issue.labels,
427            milestone,
428        })
429    }
430
431    async fn update_issue(&self, project: &str, number: u64, edit: &IssueEdit) -> Result<()> {
432        let milestone = match edit.milestone {
433            Some(Some(id)) => Some(Some(self.milestone_by_id(project, id)?)),
434            Some(None) => Some(None),
435            None => None,
436        };
437        self.store(project).update(
438            number,
439            &Patch {
440                assignees: edit.assignees.clone(),
441                labels: edit.labels.clone(),
442                milestone,
443                ..Patch::default()
444            },
445        )?;
446        Ok(())
447    }
448
449    fn board_source(&self) -> crate::board::BoardSource {
450        crate::board::BoardSource::LocalStatus
451    }
452
453    async fn issue_statuses(&self, project: &str) -> Result<Vec<String>> {
454        Ok(self.store(project).used_values()?.statuses)
455    }
456
457    async fn set_issue_status(&self, project: &str, number: u64, status: &str) -> Result<()> {
458        self.store(project).update(
459            number,
460            &Patch {
461                status: Some(status.to_string()),
462                ..Patch::default()
463            },
464        )?;
465        Ok(())
466    }
467
468    async fn set_issue_state(&self, project: &str, number: u64, closed: bool) -> Result<()> {
469        let settings = self.integration.local.clone().unwrap_or_default();
470        let status = if closed {
471            settings.done().to_string()
472        } else {
473            settings.open_status()
474        };
475        self.set_issue_status(project, number, &status).await
476    }
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482    use gitpoulpi_config::{IntegrationKind, LocalMarkdownSettings};
483
484    fn block_on<T>(f: impl std::future::Future<Output = T>) -> T {
485        tokio::runtime::Builder::new_current_thread()
486            .build()
487            .unwrap()
488            .block_on(f)
489    }
490
491    fn client(dir: &Path) -> LocalMarkdownClient {
492        let mut i = Integration::new(
493            "notes",
494            IntegrationKind::LocalMarkdown,
495            dir.to_string_lossy(),
496        );
497        i.local = Some(LocalMarkdownSettings {
498            me: "kai".into(),
499            ..LocalMarkdownSettings::default()
500        });
501        LocalMarkdownClient::new(i)
502    }
503
504    #[test]
505    fn create_list_edit_close_reopen() {
506        let dir = tempfile::tempdir().unwrap();
507        let c = client(dir.path());
508        let p = dir.path().to_string_lossy().into_owned();
509        let made = block_on(c.create_issue(&NewIssue {
510            project: p.clone(),
511            title: "First".into(),
512            body: "Body".into(),
513            assignees: vec!["kai".into()],
514            labels: vec!["bug".into()],
515            ..NewIssue::default()
516        }))
517        .unwrap();
518        assert_eq!((made.number, made.reference.as_str()), (1, "#1"));
519        block_on(c.create_issue(&NewIssue {
520            project: p.clone(),
521            title: "Second".into(),
522            ..NewIssue::default()
523        }))
524        .unwrap();
525        let open = IssueFilter::default();
526        let list = block_on(c.list_issues(&p, &open)).unwrap();
527        assert_eq!(list.iter().map(|i| i.number).collect::<Vec<_>>(), [2, 1]);
528        let mine = IssueFilter {
529            assigned_to_me: true,
530            ..IssueFilter::default()
531        };
532        assert_eq!(block_on(c.list_issues(&p, &mine)).unwrap().len(), 1);
533
534        block_on(c.update_issue(
535            &p,
536            2,
537            &IssueEdit {
538                labels: Some(vec!["ui".into()]),
539                assignees: Some(vec!["ana".into()]),
540                ..IssueEdit::default()
541            },
542        ))
543        .unwrap();
544        let meta = block_on(c.item_meta(&p, 2, MetaKind::Issue)).unwrap();
545        assert_eq!(
546            (meta.labels, meta.assignees),
547            (vec!["ui".into()], vec!["ana".into()])
548        );
549        let labels = block_on(c.project_labels(&p)).unwrap();
550        assert_eq!(labels.len(), 2);
551
552        block_on(c.set_issue_state(&p, 1, true)).unwrap();
553        assert_eq!(block_on(c.list_issues(&p, &open)).unwrap().len(), 1);
554        let closed = IssueFilter {
555            state: StateFilter::Closed,
556            ..IssueFilter::default()
557        };
558        let done = block_on(c.list_issues(&p, &closed)).unwrap();
559        assert_eq!(done[0].state, IssueState::Closed);
560        block_on(c.set_issue_state(&p, 1, false)).unwrap();
561        assert_eq!(block_on(c.list_issues(&p, &open)).unwrap().len(), 2);
562        let all = IssueFilter {
563            state: StateFilter::All,
564            query: Some("doing".into()),
565            ..IssueFilter::default()
566        };
567        assert!(block_on(c.list_issues(&p, &all)).unwrap().is_empty());
568    }
569
570    #[test]
571    fn milestones_round_trip_through_their_position() {
572        let dir = tempfile::tempdir().unwrap();
573        let c = client(dir.path());
574        let p = dir.path().to_string_lossy().into_owned();
575        std::fs::write(
576            dir.path().join("1-a.md"),
577            "---\nid: 1\ntitle: A\nmilestone: v0.2\n---\n",
578        )
579        .unwrap();
580        std::fs::write(
581            dir.path().join("2-b.md"),
582            "---\nid: 2\ntitle: B\nmilestone: v0.1\n---\n",
583        )
584        .unwrap();
585        let ms = block_on(c.project_milestones(&p)).unwrap();
586        assert_eq!(
587            ms.iter().map(|m| m.title.as_str()).collect::<Vec<_>>(),
588            ["v0.1", "v0.2"]
589        );
590        block_on(c.update_issue(
591            &p,
592            2,
593            &IssueEdit {
594                milestone: Some(Some(2)),
595                ..IssueEdit::default()
596            },
597        ))
598        .unwrap();
599        let meta = block_on(c.item_meta(&p, 2, MetaKind::Issue)).unwrap();
600        assert_eq!(meta.milestone.unwrap().title, "v0.2");
601        block_on(c.update_issue(
602            &p,
603            2,
604            &IssueEdit {
605                milestone: Some(None),
606                ..IssueEdit::default()
607            },
608        ))
609        .unwrap();
610        assert!(block_on(c.item_meta(&p, 2, MetaKind::Issue))
611            .unwrap()
612            .milestone
613            .is_none());
614    }
615
616    #[test]
617    fn urls_and_folders() {
618        assert_eq!(file_url(Path::new("/a b/c#1.md")), "file:///a%20b/c%231.md");
619        assert_eq!(
620            path_from_file_url("file:///a%20b/c%231.md"),
621            Some(PathBuf::from("/a b/c#1.md"))
622        );
623        assert_eq!(
624            path_from_file_url(&file_url(Path::new("/x/\u{e9}t\u{e9}.md"))),
625            Some(PathBuf::from("/x/\u{e9}t\u{e9}.md"))
626        );
627        assert_eq!(
628            crate::resolve_local_folder(Path::new("/repo"), "docs/issues"),
629            PathBuf::from("/repo/docs/issues")
630        );
631        assert_eq!(
632            crate::resolve_local_folder(Path::new("/repo"), "/vault/Issues"),
633            PathBuf::from("/vault/Issues")
634        );
635    }
636}