Skip to main content

rootle_provider/
lib.rs

1//! Provider seam (plans/0005): the TUI talks to source-control backends
2//! through this trait — never to a concrete API. `github` is the
3//! in-tree reference implementation; external providers are child
4//! processes speaking NDJSON-RPC over stdio (`stdio.rs`), so any
5//! internal system can be wrapped with a small script.
6//!
7//! Contract rules that matter:
8//! - Repos are opaque "group/project" strings; the UI never parses them.
9//! - `sha` is an opaque *content id*: it MUST change when content
10//!   changes (the cache design is content-keyed and immutable).
11//! - URL building (yank) and cloning use provider-supplied fields —
12//!   no GitHub URL grammar outside the GitHub impl.
13
14/// The client's search render budget (protocol v1.4 advisory,
15/// doc/provider-protocol.md): sent as `limit` on every `search/code`
16/// so the provider stops scanning at ~N and sets `truncated: true`
17/// instead of computing hits the view would clip. The view's render
18/// cap is this same number.
19pub const RENDER_BUDGET: usize = 500;
20
21pub mod id;
22
23pub use id::{Generation, GitRef, OwnerId, RepoId, RepoPath, Sha};
24
25mod commit;
26pub use commit::{CommitDetail, CommitFile, CommitStatistics, FileStatus};
27
28/// One repo in an org listing (protocol v1.4): the name plus whatever
29/// metadata the backend reports. Everything past `name` is optional —
30/// a provider with only names sends the string form on the wire and
31/// every field here stays default.
32#[derive(Debug, Clone, Default, PartialEq, Eq)]
33pub struct RepoInfo {
34    pub name: String,
35    pub description: Option<String>,
36    pub private: bool,
37    pub archived: bool,
38    /// ISO-8601 last-push timestamp when the backend knows it.
39    pub pushed_at: Option<String>,
40}
41
42impl RepoInfo {
43    /// A bare name — selection-driven flows where no listing metadata
44    /// exists.
45    pub fn bare(name: impl Into<String>) -> Self {
46        RepoInfo {
47            name: name.into(),
48            ..Default::default()
49        }
50    }
51}
52
53impl From<String> for RepoInfo {
54    fn from(name: String) -> Self {
55        RepoInfo::bare(name)
56    }
57}
58
59impl From<&str> for RepoInfo {
60    fn from(name: &str) -> Self {
61        RepoInfo::bare(name)
62    }
63}
64
65/// Structured provider error (plans/0008 §2): the protocol v1.1
66/// `data.kind` taxonomy carried from the wire to the UI instead of a
67/// bare string. Unknown or absent kinds degrade to `Other`, which
68/// renders exactly like the old unstructured toast.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct ProviderError {
71    pub kind: ErrorKind,
72    pub message: String,
73    /// `rate_limited`: the provider's advertised backoff, if any.
74    pub retry_after: Option<std::time::Duration>,
75}
76
77/// The v1.1 `data.kind` open enum. Wire-unknown kinds map to `Other`.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
79#[serde(rename_all = "snake_case")]
80pub enum ErrorKind {
81    Auth,
82    RateLimited,
83    NotFound,
84    Network,
85    Timeout,
86    Provider,
87    Other,
88}
89
90impl ErrorKind {
91    pub fn as_str(self) -> &'static str {
92        match self {
93            Self::Auth => "auth",
94            Self::RateLimited => "rate_limited",
95            Self::NotFound => "not_found",
96            Self::Network => "network",
97            Self::Timeout => "timeout",
98            Self::Provider => "provider",
99            Self::Other => "other",
100        }
101    }
102}
103
104impl ProviderError {
105    pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
106        ProviderError {
107            kind,
108            message: message.into(),
109            retry_after: None,
110        }
111    }
112
113    pub fn other(message: impl Into<String>) -> Self {
114        Self::new(ErrorKind::Other, message)
115    }
116
117    pub fn with_retry_after(mut self, retry: std::time::Duration) -> Self {
118        self.retry_after = Some(retry);
119        self
120    }
121}
122
123impl std::fmt::Display for ProviderError {
124    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125        f.write_str(&self.message)
126    }
127}
128
129impl std::error::Error for ProviderError {}
130
131impl From<String> for ProviderError {
132    fn from(message: String) -> Self {
133        Self::other(message)
134    }
135}
136
137impl From<&str> for ProviderError {
138    fn from(message: &str) -> Self {
139        Self::other(message)
140    }
141}
142
143pub type ProviderResult<T> = std::result::Result<T, ProviderError>;
144
145/// What a provider supports; the UI degrades on `false`. `file_search`
146/// (v1.3) covers path-only search (the `path:` grammar); absent on the
147/// wire it inherits `code_search` — a forge with filename search but
148/// no global content index (Bitbucket Cloud, GitLab without Advanced
149/// Search) says `code_search: false, file_search: true`.
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151pub struct Capabilities {
152    pub orgs: bool,
153    pub code_search: bool,
154    pub file_search: bool,
155    /// v1.5 (plans/0016 M1): revision awareness — all default false;
156    /// absent means default-branch-only, the honest answer for
157    /// backends that can't answer (Bitbucket has no blame API).
158    pub refs: bool,
159    pub log: bool,
160    pub blame: bool,
161    /// v1.6 (plans/0028): commit detail — full message, changed files,
162    /// per-file unified hunks. Default false, same family as the v1.5
163    /// trio.
164    pub commit: bool,
165}
166
167/// One ref (branch or tag) — `repo/refs` item.
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct RefInfo {
170    pub name: String,
171    pub sha: String,
172    pub is_default: bool,
173}
174
175/// `repo/refs` reply.
176#[derive(Debug, Clone, Default, PartialEq, Eq)]
177pub struct RepoRefs {
178    pub branches: Vec<RefInfo>,
179    pub tags: Vec<RefInfo>,
180}
181
182/// `repo/log` item — newest first on the wire.
183#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
184pub struct LogEntry {
185    pub sha: String,
186    pub subject: String,
187    pub author: String,
188    /// ISO-8601.
189    pub date: String,
190}
191
192/// `repo/blame` range — 1-based inclusive lines, coalesced by sha.
193#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
194pub struct BlameRange {
195    pub start_line: u32,
196    pub end_line: u32,
197    pub sha: String,
198    pub author: String,
199    pub date: String,
200}
201
202/// Repo/org search result for the launch popup.
203#[derive(Debug, Clone, PartialEq, Eq)]
204pub enum SearchItem {
205    /// "group/project"
206    Repo(String),
207    /// org/group name
208    Org(String),
209}
210
211/// UI-facing tree node (path relative to repo root).
212#[derive(Debug, Clone, PartialEq, Eq)]
213pub struct TreeNode {
214    pub path: String,
215    pub is_dir: bool,
216    pub sha: String,
217    pub size: Option<u64>,
218}
219
220/// A repo's recursive tree plus routing metadata.
221#[derive(Debug, Clone)]
222pub struct TreeResult {
223    pub entries: Vec<TreeNode>,
224    pub truncated: bool,
225    pub branch: String,
226}
227
228/// One code-search hit. `matches` are the matched substrings — an
229/// empty vec is a legal **path-only hit** ("this file matched"). When
230/// `matches` is non-empty the UI locates them in the blob for real
231/// line numbers; `line`, when the provider knows it, is the anchor
232/// used as-is (the first occurrence of a substring is often not the
233/// occurrence that matched).
234#[derive(Debug, Clone)]
235pub struct CodeMatch {
236    pub repo: String,
237    pub path: String,
238    pub sha: String,
239    pub branch: String,
240    pub matches: Vec<String>,
241    /// v1.1: provider knows its index is stale for this hit (the UI
242    /// shows a stale chip until client-side locating self-heals).
243    pub located: bool,
244    /// v1.3: provider-known line number (1-based); `None` = unknown,
245    /// the UI locates or anchors at 1.
246    pub line: Option<u32>,
247}
248
249/// Code-search outcome metadata: the provider's own truncation signal
250/// (plans/0008 §4) and, for indexed backends, when the index was
251/// built (`located: false` covers the per-hit case; this is the
252/// index-wide one — a lagging index is worth a badge next to the
253/// results).
254#[derive(Debug, Clone)]
255pub struct SearchCodeResult {
256    pub hits: Vec<CodeMatch>,
257    pub truncated: bool,
258    /// v1.3: e.g. "2026-08-20T14:00:00Z"; `None` = live or unknown.
259    pub index_as_of: Option<String>,
260}
261
262/// The backend contract. Blocking; calls run on worker threads.
263pub trait Provider: Send + Sync {
264    fn name(&self) -> &str;
265    fn capabilities(&self) -> Capabilities;
266    /// Repo + org search for the launch popup (orgs first).
267    fn search(&self, query: &str) -> ProviderResult<Vec<SearchItem>>;
268    /// Repo names of an org/group, with listing metadata when the
269    /// backend reports it (v1.4).
270    fn org_repos(&self, org: &str) -> ProviderResult<Vec<RepoInfo>>;
271    /// Full recursive tree of a repo — at `ref` (branch/tag/sha) when
272    /// given (v1.5), else the default branch.
273    fn fetch_tree(&self, repo: &RepoId, ref_: Option<&GitRef>) -> ProviderResult<TreeResult>;
274    /// Blob bytes by content id.
275    fn fetch_blob(&self, repo: &RepoId, sha: &Sha) -> ProviderResult<Vec<u8>>;
276
277    /// The repo's default-branch source as a gzip tarball — fuel for
278    /// the local-grep fallback when a repo-scoped code search returns
279    /// nothing (GitHub's index does not cover young/low-activity
280    /// repos; the tree can't lie, the index can). Optional: the
281    /// default refuses and the fallback is simply unavailable —
282    /// external providers grow it when the wire protocol does.
283    fn source_tarball(&self, repo: &RepoId) -> ProviderResult<Vec<u8>> {
284        let _ = repo;
285        Err(ProviderError::other(
286            "source tarball not supported by this provider",
287        ))
288    }
289    fn refs(&self, repo: &RepoId) -> ProviderResult<RepoRefs> {
290        let _ = repo;
291        Err(ProviderError::new(
292            ErrorKind::Provider,
293            "provider has no revision listing",
294        ))
295    }
296    /// v1.5: commit log, newest first; `limit` rides the bounded-
297    /// compute contract — stop at ~N, the bool is `truncated`
298    /// (capability `log`).
299    fn log(
300        &self,
301        repo: &RepoId,
302        path: Option<&str>,
303        ref_: Option<&GitRef>,
304        limit: Option<usize>,
305    ) -> ProviderResult<(Vec<LogEntry>, bool)> {
306        let _ = (repo, path, ref_, limit);
307        Err(ProviderError::new(
308            ErrorKind::Provider,
309            "provider has no commit log",
310        ))
311    }
312    /// v1.5: file bytes + content id at a path and ref — the
313    /// open-at-commit call (capability `log`'s companion).
314    fn blob_at(
315        &self,
316        repo: &RepoId,
317        path: &str,
318        ref_: Option<&GitRef>,
319    ) -> ProviderResult<(Vec<u8>, Sha)> {
320        let _ = (repo, path, ref_);
321        Err(ProviderError::new(
322            ErrorKind::Provider,
323            "provider cannot serve blobs at a ref",
324        ))
325    }
326    /// v1.5: blame ranges, 1-based inclusive, coalesced (capability
327    /// `blame`).
328    fn blame(
329        &self,
330        repo: &RepoId,
331        path: &str,
332        ref_: Option<&GitRef>,
333    ) -> ProviderResult<Vec<BlameRange>> {
334        let _ = (repo, path, ref_);
335        Err(ProviderError::new(
336            ErrorKind::Provider,
337            "provider has no blame",
338        ))
339    }
340    /// v1.6 (plans/0028): one commit's detail — message, changed
341    /// files, unified hunks (capability `commit`).
342    fn commit(&self, repo: &RepoId, sha: &Sha) -> ProviderResult<CommitDetail> {
343        let _ = (repo, sha);
344        Err(ProviderError::new(
345            ErrorKind::Provider,
346            "provider has no commit detail",
347        ))
348    }
349
350    /// Code search; `q` is the full query string with qualifiers.
351    fn search_code(&self, q: &str) -> ProviderResult<SearchCodeResult>;
352
353    /// Modeline icon: a builtin name ("github", "gitlab", "bitbucket",
354    /// "folder" — rendered as its Nerd Font glyph when nerd_font is
355    /// on) or a single literal glyph the terminal can render. The
356    /// provider declares its own (handshake `icon`, protocol v1.3);
357    /// the in-tree github provider owns the one rootle hardcodes.
358    fn icon(&self) -> Option<String> {
359        None
360    }
361
362    /// Progressive code search (protocol v1.3, plans/0011): `on_hits`
363    /// may fire from any thread, any number of times, strictly before
364    /// this call returns. When the provider streamed, the result is
365    /// metadata-only — `hits` empty, `truncated` authoritative.
366    /// Default: one `search_code` call, one `on_hits` batch — every
367    /// provider streams; page-shaped backends stream page-by-page.
368    fn search_code_progressive(
369        &self,
370        q: &str,
371        on_hits: &(dyn Fn(&[CodeMatch]) + Send + Sync),
372    ) -> ProviderResult<SearchCodeResult> {
373        let result = self.search_code(q)?;
374        on_hits(&result.hits);
375        Ok(SearchCodeResult {
376            hits: Vec::new(),
377            truncated: result.truncated,
378            index_as_of: result.index_as_of,
379        })
380    }
381
382    /// Advisory cancellation (protocol v1.1): tells the backend the
383    /// caller no longer needs the in-flight request. Best-effort —
384    /// replies may still arrive and are always handled. Default: nothing
385    /// to cancel (in-process providers drop work via generations).
386    fn advise_cancel(&self) {}
387
388    /// One-shot UI notice for the status line (plans/0008 §5) — e.g.
389    /// a stdio child's successful restart. Drained once per route.
390    /// Default: nothing to say.
391    fn take_notice(&self) -> Option<String> {
392        None
393    }
394
395    /// Cache usage the provider reported at initialize (bytes), when
396    /// it participates in the advisory cache budget (protocol v1.2) —
397    /// surfaced in :settings next to the provider row.
398    fn cache_usage(&self) -> Option<u64> {
399        None
400    }
401
402    /// URL `git clone` accepts for a repo (clone wizard, plans/0004).
403    fn clone_url(&self, repo: &RepoId) -> ProviderResult<String>;
404    /// Browser URL for yank (␣ y): repo root, or a path inside it.
405    /// `is_file` picks the grammar (GitHub: blob vs tree); `line`
406    /// adds a fragment when Some. `branch` is `None` for the default
407    /// branch (the provider resolves it).
408    fn web_url(
409        &self,
410        repo: &RepoId,
411        path: &str,
412        branch: Option<&GitRef>,
413        line: Option<u32>,
414        end: Option<u32>,
415        is_file: bool,
416    ) -> ProviderResult<String>;
417
418    /// Browser URL for an org/group page.
419    fn org_url(&self, org: &str) -> ProviderResult<String>;
420}
421pub mod paths;