Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
509 lines (464 loc) · 17.1 KB
/
Copy pathlib.rs
File metadata and controls
509 lines (464 loc) · 17.1 KB
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Node-API bindings: the seam between the extension host and the Git engine.
//!
//! The ABI is deliberately small — a handful of functions, with structured data carried as JSON.
//! That is not laziness about typing: the alternative, building JavaScript objects property by
//! property across the boundary, costs a Node-API call *per field*, and a page of a thousand
//! commits has tens of thousands of them. Serialising once in Rust and calling `JSON.parse` once
//! in JavaScript is measurably faster, and it keeps the ABI stable while the engine's types evolve.
//!
//! The extension never calls this module directly: `src/backend/addon.ts` wraps it in the typed
//! API, and `src/backend/api.ts` is what replaces the original `DataSource`.
//!
//! Alongside the typed exports sits [`request`], the engine's whole surface as one JSON call —
//! the same method table (`git_graph_core::dispatch`) the typed exports share, for hosts that want the engine without a binding per method.
use napi::bindgen_prelude::*;
use napi_derive::napi;
use git_graph_core::dispatch::RefOptionsPayload;
use git_graph_core::types::LogOptions;
use git_graph_core::{
blob, config, details, diff, gerrit, graph, log, refs, stash, stats, status, Error, RepoManager,
};
/// Open a repository and keep it open.
///
/// Returns the repository root — what `git rev-parse --show-toplevel` prints — because the caller
/// passes any path inside the repository and needs to know which repository it landed in.
#[napi]
pub async fn open_repository(path: String) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
Ok(repo.root().display().to_string())
})
.await
}
/// Drop a repository handle, releasing its object cache and open pack files.
///
/// Worth calling when a folder leaves the workspace; the handles are otherwise meant to live for
/// the whole editor session, which is where the performance comes from.
#[napi]
pub fn close_repository(path: String) {
RepoManager::global().close(&path);
}
/// Drop every repository handle.
#[napi]
pub fn close_all_repositories() {
RepoManager::global().close_all();
}
/// How many repositories are currently open. Exposed for the tests and for diagnostics.
#[napi]
pub fn open_repository_count() -> u32 {
RepoManager::global().open_count() as u32
}
/// The whole engine behind one call: `{"method": "loadCommits", "params": {…}}` in, the method's
/// own JSON document out.
///
/// The typed exports in this file are the extension's contract; this one is the single seam a
/// second host drives — a REPL, a test harness, another language embedding Node — without a
/// binding per method. Both share one method table, `git_graph_core::dispatch`, so they cannot
/// drift. The single interface never throws: a failure — an unknown method, parameters that do
/// not fit, a repository that cannot be opened — is the in-band answer
/// `{"error": "Kind: message"}`, the same string a typed call throws.
#[napi]
pub async fn request(repo: String, request_json: String) -> Result<String> {
run(move || Ok(git_graph_core::dispatch::request(&repo, &request_json))).await
}
/// The repository information the view opens with: branches, tags, remotes, stashes and HEAD.
///
/// `options_json` is a [`RefOptionsPayload`].
#[napi]
pub async fn load_repo_info(path: String, options_json: String) -> Result<String> {
run(move || {
let payload: RefOptionsPayload = decode(&options_json)?;
let repo = RepoManager::global().get(&path)?;
let info = graph::repo_info(&repo, &payload.to_options(), payload.show_stashes)?;
encode(&info)
})
.await
}
/// A page of the graph. `options_json` is a serialised `LogOptions`.
#[napi]
pub async fn load_commits(path: String, options_json: String) -> Result<String> {
run(move || {
let options: LogOptions = decode(&options_json)?;
let repo = RepoManager::global().get(&path)?;
let data = graph::load_commits(&repo, &options)?;
encode(&data)
})
.await
}
/// The refs of a repository, without the commits.
#[napi]
pub async fn load_refs(path: String, options_json: String) -> Result<String> {
run(move || {
let payload: RefOptionsPayload = decode(&options_json)?;
let repo = RepoManager::global().get(&path)?;
let snapshot = refs::read_refs(&repo, &payload.to_options())?;
encode(&snapshot.ref_data)
})
.await
}
/// One commit in full, with the files it changed — their statuses only, without line counts,
/// which arrive separately through [`load_line_counts`] so a many-file commit renders at once.
#[napi]
pub async fn load_commit_details(path: String, hash: String) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
encode(&details::commit_details(&repo, &hash)?)
})
.await
}
/// The `+N/-M` line counts of the given paths, keyed by path.
///
/// `from` is null to diff `to` against its first parent (the Commit Details view), or a revision
/// (the Commit Comparison view, or a stash's base). `paths_json` is a JSON array of paths; binary
/// files come back with null counts, as `git diff --numstat` prints a dash for them.
#[napi]
pub async fn load_line_counts(
path: String,
from: Option<String>,
to: String,
paths_json: String,
) -> Result<String> {
run(move || {
let paths: Vec<String> = decode(&paths_json)?;
let repo = RepoManager::global().get(&path)?;
encode(&diff::line_counts(&repo, from.as_deref(), &to, &paths)?)
})
.await
}
/// The "Uncommitted Changes" row in full.
#[napi]
pub async fn load_uncommitted_details(path: String) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
encode(&details::uncommitted_details(&repo)?)
})
.await
}
/// A stash entry in full. `stash_json` is a serialised `GitCommitStash`.
#[napi]
pub async fn load_stash_details(path: String, hash: String, stash_json: String) -> Result<String> {
run(move || {
let commit_stash: git_graph_core::types::GitCommitStash = decode(&stash_json)?;
let repo = RepoManager::global().get(&path)?;
encode(&details::stash_details(&repo, &hash, &commit_stash)?)
})
.await
}
/// The files that differ between two revisions. An empty `to` compares against the working tree.
#[napi]
pub async fn compare_commits(path: String, from: String, to: String) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
encode(&diff::diff_revisions(&repo, &from, &to)?)
})
.await
}
/// How many uncommitted changes there are — the number the "Uncommitted Changes" row shows.
#[napi]
pub async fn count_uncommitted_changes(path: String, include_untracked: bool) -> Result<u32> {
run(move || {
let repo = RepoManager::global().get(&path)?;
Ok(status::count_changes(&repo, include_untracked)? as u32)
})
.await
}
/// The stashes of a repository, newest first.
#[napi]
pub async fn load_stashes(path: String) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
encode(&stash::read_stashes(&repo)?)
})
.await
}
/// The repository configuration: remotes, identity and diff tool settings.
#[napi]
pub async fn load_config(path: String) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
encode(&config::read_config(&repo)?)
})
.await
}
/// The content of one file at one revision, or a binary marker when it is not text.
#[napi]
pub async fn load_commit_file(path: String, commit_hash: String, file: String) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
encode(&blob::commit_file(&repo, &commit_hash, &file)?)
})
.await
}
/// The unified diff of one file between a commit and its first parent.
#[napi]
pub async fn load_commit_file_diff(
path: String,
commit_hash: String,
file: String,
) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
blob::commit_file_diff(&repo, &commit_hash, &file)
})
.await
}
/// The full commit message of each of the given commits, keyed by hash, as a JSON object.
#[napi]
pub async fn load_commit_bodies(path: String, hashes: Vec<String>) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
encode(&details::commit_bodies(&repo, &hashes)?)
})
.await
}
/// The subject of one commit.
#[napi]
pub async fn load_commit_subject(path: String, hash: String) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
details::commit_subject(&repo, &hash)
})
.await
}
/// The summary of each of the given commits, keyed by hash, as a JSON object.
#[napi]
pub async fn load_commit_summaries(path: String, hashes: Vec<String>) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
encode(&details::commit_summaries(&repo, &hashes)?)
})
.await
}
/// The commits whose message matches a pattern, newest first, as a JSON array.
#[napi]
pub async fn search_history(path: String, query: String) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
encode(&log::search_history(&repo, &query)?)
})
.await
}
/// A tag in full (tagger, message, signature presence), as a JSON object.
#[napi]
pub async fn load_tag_details(path: String, tag_name: String) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
encode(&details::tag_details(&repo, &tag_name)?)
})
.await
}
/// The fetch URL of a remote, or NULL when it is not configured.
#[napi]
pub async fn remote_url(path: String, remote: String) -> Result<Option<String>> {
run(move || {
let repo = RepoManager::global().get(&path)?;
config::remote_url(&repo, &remote)
})
.await
}
/// Where a file was renamed to between a commit and the working tree, or NULL when it was not.
#[napi]
pub async fn new_path_of_renamed_file(
path: String,
commit_hash: String,
old_file_path: String,
) -> Result<Option<String>> {
run(move || {
let repo = RepoManager::global().get(&path)?;
diff::new_path_of_renamed_file(&repo, &commit_hash, &old_file_path)
})
.await
}
/// The roots of the repository's initialised submodules.
#[napi]
pub async fn submodules(path: String) -> Result<Vec<String>> {
run(move || {
let repo = RepoManager::global().get(&path)?;
config::submodules(&repo)
})
.await
}
/// The upstream of the checked-out branch (`origin/main`), or NULL when there is none.
#[napi]
pub async fn current_branch_upstream(path: String) -> Result<Option<String>> {
run(move || {
let repo = RepoManager::global().get(&path)?;
config::current_branch_upstream(&repo)
})
.await
}
/// How many commits are reachable from the shown refs but not from `hash` — `git rev-list --count`.
#[napi]
pub async fn count_commits_before(
path: String,
branches: Option<Vec<String>>,
hash: String,
show_remote_branches: bool,
include_reflogs: bool,
) -> Result<u32> {
run(move || {
let repo = RepoManager::global().get(&path)?;
Ok(log::count_commits_before(
&repo,
branches.as_deref(),
&hash,
show_remote_branches,
include_reflogs,
)? as u32)
})
.await
}
/// The root of the repository containing a path, without keeping the repository open.
#[napi]
pub async fn repo_root(path: String) -> Result<String> {
run(move || git_graph_core::repository::repo_root(&path)).await
}
/// The names of the repository's remotes.
#[napi]
pub async fn remote_names(path: String) -> Result<Vec<String>> {
run(move || {
let repo = RepoManager::global().get(&path)?;
config::remote_names(&repo)
})
.await
}
/// The distinct commit authors of the current branch's history, as a JSON array.
#[napi]
pub async fn authors(path: String) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
encode(&log::authors(&repo)?)
})
.await
}
/// Commit counts per author across all refs (branches, tags, remote-tracking, the stash), merge
/// commits excluded, as a JSON array - what the Statistics view's author table lists.
#[napi]
pub async fn author_stats(path: String) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
encode(&stats::author_stats(&repo)?)
})
.await
}
/// The commit-activity heatmap (author-local weekday/hour) across all refs, merge commits
/// excluded, as a JSON array of non-zero cells.
#[napi]
pub async fn activity_heatmap(path: String) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
encode(&stats::activity_heatmap(&repo)?)
})
.await
}
/// The configuration entries of one location (local or global), last value per key, as JSON.
#[napi]
pub async fn config_list(path: String, local: bool) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
encode(&config::config_list(
&repo,
if local {
config::ConfigLocation::Local
} else {
config::ConfigLocation::Global
},
)?)
})
.await
}
/// The checked-out branch's short name, or NULL when HEAD is detached.
#[napi]
pub async fn current_branch_name(path: String) -> Result<Option<String>> {
run(move || {
let repo = RepoManager::global().get(&path)?;
config::current_branch_name(&repo)
})
.await
}
/// The review states of the given Gerrit changes, parsed from their NoteDb meta histories in one
/// in-process pass, as a JSON array aligned with the input order.
///
/// An entry is NULL when the change's meta ref is not available locally. `url_base`, when given,
/// is prefixed onto each change number to produce the state's web URL.
#[napi]
pub async fn parse_gerrit_metas(
path: String,
remote: String,
changes: Vec<i64>,
url_base: Option<String>,
) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
encode(&gerrit::parse_gerrit_metas(
&repo,
&remote,
&changes,
url_base.as_deref(),
)?)
})
.await
}
/// The local Gerrit change refs of a remote (`refs/remotes/<remote>/changes/**`), as a JSON array
/// of `[refname, hash]` pairs — one in-process scan of the ref store replacing a
/// `git for-each-ref` child process.
#[napi]
pub async fn list_change_refs(path: String, remote: String) -> Result<String> {
run(move || {
let repo = RepoManager::global().get(&path)?;
let refs = gerrit::list_change_refs(&repo, &remote)?;
encode(&refs)
})
.await
}
/// The engine's version, so the extension can report which backend it is running.
#[napi]
pub fn engine_version() -> String {
env!("CARGO_PKG_VERSION").to_string()
}
/* ---------- Plumbing ---------- */
/// Run a blocking engine call off the JavaScript thread.
///
/// The work is CPU- and disk-bound, and it runs on napi's own runtime rather than on libuv's
/// thread pool — which is capped at four threads and is already serving the editor's own file I/O.
///
/// The closure works in the engine's own `Result`, so `?` composes throughout it; the single
/// conversion to a JavaScript error happens here.
async fn run<T, F>(work: F) -> Result<T>
where
F: FnOnce() -> git_graph_core::Result<T> + Send + 'static,
T: Send + 'static,
{
let outcome = napi::tokio::task::spawn_blocking(work)
.await
.map_err(|e| napi::Error::new(napi::Status::GenericFailure, format!("Git: {e}")))?;
outcome.map_err(to_js_error)
}
/// Turn an engine error into the JavaScript error the extension will see.
///
/// The kind is prefixed onto the message so that the TypeScript side can tell "this repository is
/// not usable, fall back to the `git` CLI" from "this operation failed, show the user" — the same
/// `Kind: message` string the single dispatch surface answers in-band.
fn to_js_error(error: Error) -> napi::Error {
napi::Error::new(napi::Status::GenericFailure, error.with_kind_prefix())
}
/// Serialising a response cannot fail for the engine's own types, but a failure would mean the
/// view silently rendered nothing, so it is reported rather than swallowed.
fn encode<T: serde::Serialize>(value: &T) -> git_graph_core::Result<String> {
serde_json::to_string(value).map_err(|e| {
Error::new(
git_graph_core::ErrorKind::Git,
format!("Could not encode the response: {e}"),
)
})
}
/// A malformed request means the TypeScript and Rust sides disagree about the contract, which is
/// a bug rather than a user error — so it names the field that did not fit.
fn decode<T: serde::de::DeserializeOwned>(json: &str) -> git_graph_core::Result<T> {
serde_json::from_str(json).map_err(|e| {
Error::new(
git_graph_core::ErrorKind::InvalidArgument,
format!("Could not decode the request: {e}"),
)
})
}