-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
773 lines (711 loc) Β· 25.5 KB
/
Copy pathmod.rs
File metadata and controls
773 lines (711 loc) Β· 25.5 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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
use anyhow::{bail, Context, Result};
use console::style;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use crate::trust::parse_source_ref;
mod create;
mod install;
mod list;
mod publish;
mod recommend;
mod remove;
mod run_plugin;
mod search;
mod update;
mod validate;
#[cfg(feature = "wasm")]
mod wasm;
#[cfg(test)]
mod tests;
// βββ Internal imports for the run() dispatcher βββββββββββββββββββββββββββββ
use create::create_plugin;
use install::install_action;
use list::{audit_plugins, list_plugins};
use publish::publish_plugin;
use recommend::recommend_plugins;
use remove::remove_plugin;
use run_plugin::{run_hook, run_plugin_cmd};
use search::search_plugins;
use update::update_plugins;
use validate::validate_plugin;
use install::check_tier_capabilities;
#[cfg(test)]
use run_plugin::{apply_protocol, resolve_plugin_source_dir, which_fledge_plugin};
// βββ Constants βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/// The curated set of plugins fledge endorses as "the default install."
///
/// These are the plugins that took over commands removed from core in
/// v0.15 (the tight-core refactor). Running `fledge plugins install --defaults`
/// installs all of them so a fresh fledge install gets back to feature
/// parity with v0.14 in one command.
///
/// Every entry is pinned to a release tag (`owner/repo@vX.Y.Z`).
/// Bump the tag here when adopting a new plugin release.
pub const DEFAULT_PLUGINS: &[&str] = &[
"CorvidLabs/fledge-plugin-github@v0.4.0",
"CorvidLabs/fledge-plugin-deps@v0.2.0",
"CorvidLabs/fledge-plugin-metrics@v0.2.1",
];
/// Per-command JSON schema versions. Each constant tracks the wire shape of one
/// `plugins` subcommand's `--json` envelope independently so that future shape
/// changes can bump exactly the affected envelope without semantically
/// corrupting the meaning of `schema_version` for unrelated commands. Additive
/// changes (new optional fields) do not bump.
const PLUGINS_INSTALL_SCHEMA: u32 = 1;
const PLUGINS_UPDATE_SCHEMA: u32 = 1;
const PLUGINS_REMOVE_SCHEMA: u32 = 1;
const PLUGINS_LIST_SCHEMA: u32 = 1;
const PLUGINS_AUDIT_SCHEMA: u32 = 1;
const PLUGINS_SEARCH_SCHEMA: u32 = 1;
const PLUGINS_RECOMMEND_SCHEMA: u32 = 1;
const PLUGINS_CREATE_SCHEMA: u32 = 1;
const PLUGINS_PUBLISH_SCHEMA: u32 = 1;
const PLUGINS_VALIDATE_SCHEMA: u32 = 1;
// βββ Types βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
#[derive(Debug, Deserialize)]
struct PluginManifest {
pub(super) plugin: PluginMeta,
#[serde(default)]
pub(super) commands: Vec<PluginCommand>,
#[serde(default)]
pub(super) hooks: PluginHooks,
#[serde(default)]
pub(super) capabilities: PluginCapabilities,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PluginCapabilities {
#[serde(default)]
pub exec: bool,
#[serde(default)]
pub store: bool,
#[serde(default)]
pub metadata: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filesystem: Option<String>,
#[serde(default)]
pub network: bool,
}
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct PluginMeta {
pub(super) name: String,
pub(super) version: String,
pub(super) description: Option<String>,
pub(super) author: Option<String>,
pub(super) protocol: Option<String>,
#[serde(default)]
pub(super) runtime: Option<String>,
}
impl PluginMeta {
fn is_wasm(&self) -> bool {
self.runtime.as_deref() == Some("wasm")
}
}
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct PluginCommand {
pub(super) name: String,
pub(super) description: Option<String>,
pub(super) binary: String,
}
#[derive(Debug, Deserialize, Default)]
struct PluginHooks {
pub(super) build: Option<String>,
pub(super) post_install: Option<String>,
pub(super) post_remove: Option<String>,
pub(super) pre_init: Option<String>,
pub(super) post_work_start: Option<String>,
pub(super) pre_push: Option<String>,
}
impl PluginHooks {
fn has_any(&self) -> bool {
self.build.is_some()
|| self.post_install.is_some()
|| self.post_remove.is_some()
|| self.pre_init.is_some()
|| self.post_work_start.is_some()
|| self.pre_push.is_some()
}
fn iter_defined(&self) -> Vec<(&str, &str)> {
let mut hooks = Vec::new();
if let Some(ref c) = self.pre_push {
hooks.push(("pre_push", c.as_str()));
}
if let Some(ref c) = self.build {
hooks.push(("build", c.as_str()));
}
if let Some(ref c) = self.post_install {
hooks.push(("post_install", c.as_str()));
}
if let Some(ref c) = self.post_remove {
hooks.push(("post_remove", c.as_str()));
}
if let Some(ref c) = self.pre_init {
hooks.push(("pre_init", c.as_str()));
}
if let Some(ref c) = self.post_work_start {
hooks.push(("post_work_start", c.as_str()));
}
hooks
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
struct PluginsRegistry {
#[serde(default)]
pub(super) plugins: Vec<PluginEntry>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
struct PluginEntry {
pub(super) name: String,
pub(super) source: String,
pub(super) version: String,
pub(super) installed: String,
#[serde(default)]
pub(super) commands: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) pinned_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) capabilities: Option<PluginCapabilities>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) runtime: Option<String>,
}
pub struct PluginOptions {
pub action: PluginAction,
pub json: bool,
}
pub enum PluginAction {
Install {
source: Option<String>,
force: bool,
copy: bool,
/// Install the curated set of default plugins (DEFAULT_PLUGINS)
defaults: bool,
},
Remove {
name: String,
},
Update {
name: Option<String>,
/// Update only the curated set of default plugins (DEFAULT_PLUGINS) β skip community plugins
defaults: bool,
},
List,
Audit,
Search {
query: Option<String>,
author: Option<String>,
topic: Option<String>,
trust_tier: Option<crate::trust::TrustTier>,
limit: usize,
interactive: bool,
},
Recommend,
Run {
name: String,
args: Vec<String>,
},
Publish {
path: PathBuf,
org: Option<String>,
private: bool,
description: Option<String>,
yes: bool,
},
Create {
name: String,
output: PathBuf,
description: Option<String>,
yes: bool,
wasm: bool,
},
Validate {
path: PathBuf,
strict: bool,
json: bool,
},
}
// βββ Dispatcher ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
pub fn run(opts: PluginOptions) -> Result<()> {
match opts.action {
PluginAction::Install {
source,
force,
copy,
defaults,
} => install_action(source.as_deref(), force, copy, defaults, opts.json),
PluginAction::Remove { name } => remove_plugin(&name, opts.json),
PluginAction::Update { name, defaults } => {
update_plugins(name.as_deref(), defaults, opts.json)
}
PluginAction::List => list_plugins(opts.json),
PluginAction::Audit => audit_plugins(opts.json),
PluginAction::Search {
query,
author,
topic,
trust_tier,
limit,
interactive,
} => search_plugins(
query.as_deref(),
author.as_deref(),
topic.as_deref(),
trust_tier,
limit,
interactive,
opts.json,
),
PluginAction::Recommend => recommend_plugins(opts.json),
PluginAction::Run { name, args } => run_plugin_cmd(&name, &args),
PluginAction::Publish {
path,
org,
private,
description,
yes,
} => publish_plugin(
&path,
org.as_deref(),
private,
description.as_deref(),
yes,
opts.json,
),
PluginAction::Create {
name,
output,
description,
yes,
wasm,
} => create_plugin(&name, &output, description.as_deref(), yes, wasm, opts.json),
PluginAction::Validate { path, strict, json } => validate_plugin(&path, strict, json),
}
}
pub fn run_lifecycle_hook(event: &str) -> Result<()> {
let registry = load_registry()?;
for entry in ®istry.plugins {
// Require explicit exec = true; plugins without capabilities declared cannot run hooks
match &entry.capabilities {
Some(caps) if caps.exec => {}
_ => continue,
}
let plugin_dir = plugins_dir().join(&entry.name);
let manifest_path = plugin_dir.join("plugin.toml");
if !manifest_path.exists() {
continue;
}
let content = match fs::read_to_string(&manifest_path) {
Ok(c) => c,
Err(_) => continue,
};
let manifest: PluginManifest = match toml::from_str(&content) {
Ok(m) => m,
Err(_) => continue,
};
let hook = match event {
"pre_init" => &manifest.hooks.pre_init,
"post_work_start" => &manifest.hooks.post_work_start,
"pre_push" => &manifest.hooks.pre_push,
_ => &None,
};
if let Some(hook_cmd) = hook {
// Progress goes to stderr so it never corrupts a `--json` stdout
// envelope (lifecycle hooks fire mid-command, e.g. `work start --json`).
eprintln!(
" {} {} ({})",
style("βΆοΈ").cyan().bold(),
style(format!("Plugin hook: {event}")).dim(),
style(&entry.name).cyan()
);
run_hook(&plugin_dir, hook_cmd, &format!("{}/{event}", entry.name))?;
}
}
Ok(())
}
pub fn resolve_plugin_command(name: &str) -> Option<PathBuf> {
let bin_dir = plugin_bin_dir();
let base = format!("fledge-{name}");
let bin_path = bin_dir.join(&base);
if bin_path.exists() {
return Some(bin_path);
}
if cfg!(windows) {
for ext in &[".exe", ".bat", ".cmd"] {
let with_ext = bin_dir.join(format!("{base}{ext}"));
if with_ext.exists() {
return Some(with_ext);
}
}
}
run_plugin::which_fledge_plugin(name)
}
// βββ Registry helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
fn plugins_dir() -> PathBuf {
dirs::config_dir()
.unwrap_or_else(std::env::temp_dir)
.join("fledge")
.join("plugins")
}
fn plugin_bin_dir() -> PathBuf {
plugins_dir().join("bin")
}
fn registry_path() -> PathBuf {
dirs::config_dir()
.unwrap_or_else(std::env::temp_dir)
.join("fledge")
.join("plugins.toml")
}
fn load_registry() -> Result<PluginsRegistry> {
load_registry_from(®istry_path())
}
fn load_registry_from(path: &Path) -> Result<PluginsRegistry> {
if !path.exists() {
return Ok(PluginsRegistry {
plugins: Vec::new(),
});
}
match read_and_parse_registry(path) {
Ok(registry) => Ok(registry),
Err(first_error) => {
// A registration by an older fledge (pre-atomic-write) may be
// mid-rewrite; one short retry rides out the window instead of
// resolving every plugin subcommand to "unrecognized".
std::thread::sleep(std::time::Duration::from_millis(50));
read_and_parse_registry(path).map_err(|_| {
eprintln!(
"warning: plugins.toml at {} is unreadable or corrupt β plugin \
subcommands will not resolve this invocation: {first_error:#}",
path.display()
);
first_error
})
}
}
}
fn read_and_parse_registry(path: &Path) -> Result<PluginsRegistry> {
let content = fs::read_to_string(path).context("reading plugins.toml")?;
toml::from_str(&content).context("parsing plugins.toml")
}
fn save_registry(registry: &PluginsRegistry) -> Result<()> {
save_registry_to(®istry_path(), registry)
}
fn save_registry_to(path: &Path, registry: &PluginsRegistry) -> Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let content = toml::to_string_pretty(registry).context("serializing plugins.toml")?;
// Write-then-rename so concurrent readers never observe a truncated
// file. `fs::write` truncates in place, and any fledge invocation
// that reads the registry during the rewrite parses partial TOML β
// dispatch then reports a perfectly registered plugin command as
// "unrecognized subcommand". Same-directory rename is atomic on
// POSIX, so readers see either the old registry or the new one.
let tmp = path.with_extension(format!("toml.tmp.{}", std::process::id()));
if let Err(error) = fs::write(&tmp, content) {
let _ = fs::remove_file(&tmp);
return Err(error).context("writing plugins.toml temp file");
}
// Windows refuses the rename with a sharing violation while another
// process has the destination open for reading; retry briefly. On
// POSIX the first attempt always wins.
let mut last_error = None;
for _ in 0..20 {
match fs::rename(&tmp, path) {
Ok(()) => return Ok(()),
Err(error) => {
last_error = Some(error);
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
}
let _ = fs::remove_file(&tmp);
Err(last_error.expect("rename attempted at least once"))
.context("atomically replacing plugins.toml")
}
// βββ Source helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
fn normalize_source(source: &str) -> String {
let (base, _) = parse_source_ref(source);
if base.starts_with("https://") || base.starts_with("git@") {
base.to_string()
} else if base.contains('/') {
format!("https://github.com/{}.git", base)
} else {
base.to_string()
}
}
fn extract_name_from_source(source: &str) -> String {
let (base, _) = parse_source_ref(source);
base.rsplit('/')
.next()
.unwrap_or(base)
.trim_end_matches(".git")
.to_string()
}
// βββ Build helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
fn detect_build_command(plugin_dir: &Path) -> Option<(&'static str, Vec<&'static str>)> {
if plugin_dir.join("Cargo.toml").exists() {
Some(("Rust", vec!["cargo", "build", "--release"]))
} else if plugin_dir.join("Package.swift").exists() {
Some(("Swift", vec!["swift", "build", "-c", "release"]))
} else if plugin_dir.join("go.mod").exists() {
Some(("Go", vec!["go", "build", "."]))
} else if plugin_dir.join("package.json").exists() {
Some(("Node", vec!["npm", "install"]))
} else {
None
}
}
fn run_build(plugin_dir: &Path, manifest: &PluginManifest) -> Result<()> {
if let Some(hook) = &manifest.hooks.build {
run_hook(plugin_dir, hook, "build")?;
return Ok(());
}
if let Some((lang, cmd)) = detect_build_command(plugin_dir) {
let sp = crate::spinner::Spinner::start(&format!("Building ({lang}):"));
let status = Command::new(cmd[0])
.args(&cmd[1..])
.current_dir(plugin_dir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
.status()
.with_context(|| format!("running {lang} build"))?;
sp.finish();
if !status.success() {
bail!("Build failed. Check your {lang} toolchain is installed.");
}
}
Ok(())
}
// βββ Security helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
fn validate_command_name(name: &str) -> Result<()> {
if name.is_empty()
|| name.contains('/')
|| name.contains('\\')
|| name.contains('\0')
|| name.starts_with('.')
|| name.starts_with('-')
|| name == ".."
{
bail!(
"Invalid plugin command name '{}'. Names must be alphanumeric with hyphens/underscores.",
name
);
}
Ok(())
}
fn link_commands(
plugin_dir: &Path,
bin_dir: &Path,
manifest: &PluginManifest,
) -> Result<Vec<String>> {
let mut command_names = Vec::new();
for cmd in &manifest.commands {
validate_command_name(&cmd.name)?;
for component in std::path::Path::new(&cmd.binary).components() {
if matches!(component, std::path::Component::ParentDir) {
bail!(
"Plugin '{}' binary '{}' contains path traversal (..)",
manifest.plugin.name,
cmd.binary
);
}
}
#[cfg_attr(not(windows), allow(unused_mut))]
let mut binary_path = plugin_dir.join(&cmd.binary);
// On Windows, compiled binaries have .exe extension even when the
// manifest omits it.
#[cfg(windows)]
if !binary_path.exists() && binary_path.extension().is_none() {
let with_exe = binary_path.with_extension("exe");
if with_exe.exists() {
binary_path = with_exe;
}
}
if let Ok(canonical_binary) = binary_path.canonicalize() {
let canonical_dir = plugin_dir
.canonicalize()
.unwrap_or_else(|_| plugin_dir.to_path_buf());
if !canonical_binary.starts_with(&canonical_dir) {
bail!(
"Plugin '{}' binary '{}' resolves outside the plugin directory",
manifest.plugin.name,
cmd.binary
);
}
}
if !binary_path.exists() {
let mut hint = format!(
"Plugin '{}' references binary '{}' which does not exist.",
manifest.plugin.name, cmd.binary
);
if let Some((lang, _)) = detect_build_command(plugin_dir) {
hint.push_str(&format!(
"\n This looks like a {} project. Add a build hook to plugin.toml:",
lang
));
hint.push_str("\n [hooks]");
let example = match lang {
"Rust" => "build = \"cargo build --release\"",
"Swift" => "build = \"swift build -c release\"",
"Go" => "build = \"go build .\"",
_ => "build = \"scripts/build.sh\"",
};
hint.push_str(&format!("\n {example}"));
}
bail!("{hint}");
}
make_executable(&binary_path)?;
let link_name = if cfg!(windows) {
format!("fledge-{}.exe", cmd.name)
} else {
format!("fledge-{}", cmd.name)
};
let link_path = bin_dir.join(&link_name);
if link_path.exists() || link_path.is_symlink() {
fs::remove_file(&link_path).ok();
}
create_symlink(&binary_path, &link_path).with_context(|| {
format!(
"creating symlink {} -> {}",
link_path.display(),
binary_path.display()
)
})?;
command_names.push(cmd.name.clone());
}
Ok(command_names)
}
fn validate_plugin_name(name: &str) -> Result<()> {
if name.is_empty()
|| name.starts_with('.')
|| name.contains('/')
|| name.contains('\\')
|| name == ".."
{
bail!("Invalid plugin source: repo name '{}' is not safe.", name);
}
Ok(())
}
fn remove_plugin_path(path: &Path) -> Result<()> {
if !path.exists() && !path.is_symlink() {
return Ok(());
}
let metadata =
fs::symlink_metadata(path).with_context(|| format!("inspecting {}", path.display()))?;
if metadata.file_type().is_symlink() {
#[cfg(windows)]
{
if path.is_dir() {
fs::remove_dir(path)
.with_context(|| format!("removing directory symlink {}", path.display()))?;
} else {
fs::remove_file(path)
.with_context(|| format!("removing file symlink {}", path.display()))?;
}
}
#[cfg(not(windows))]
{
fs::remove_file(path)
.with_context(|| format!("removing symlink {}", path.display()))?;
}
} else if metadata.is_file() {
fs::remove_file(path).with_context(|| format!("removing file {}", path.display()))?;
} else {
fs::remove_dir_all(path)
.with_context(|| format!("removing directory {}", path.display()))?;
}
Ok(())
}
fn copy_dir_all(source: &Path, destination: &Path) -> Result<()> {
fs::create_dir_all(destination)
.with_context(|| format!("creating {}", destination.display()))?;
for entry in fs::read_dir(source).with_context(|| format!("reading {}", source.display()))? {
let entry = entry?;
let source_path = entry.path();
let destination_path = destination.join(entry.file_name());
let metadata = fs::symlink_metadata(&source_path)
.with_context(|| format!("inspecting {}", source_path.display()))?;
if metadata.file_type().is_symlink() {
let target = fs::read_link(&source_path)
.with_context(|| format!("reading symlink {}", source_path.display()))?;
create_symlink(&target, &destination_path)
.with_context(|| format!("copying symlink {}", source_path.display()))?;
} else if metadata.is_dir() {
copy_dir_all(&source_path, &destination_path)?;
} else {
fs::copy(&source_path, &destination_path)
.with_context(|| format!("copying {}", source_path.display()))?;
}
}
Ok(())
}
// βββ Git auth helper βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
fn apply_git_auth(cmd: &mut Command) {
let config = crate::config::Config::load().ok();
let token = config.as_ref().and_then(|c| c.github_token());
if let Some(ref t) = token {
use base64::Engine;
let credentials = format!("x-access-token:{}", t);
let encoded = base64::engine::general_purpose::STANDARD.encode(&credentials);
let header_value = format!("Authorization: Basic {}", encoded);
let existing: usize = std::env::var("GIT_CONFIG_COUNT")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(0);
cmd.env("GIT_CONFIG_COUNT", (existing + 1).to_string())
.env(format!("GIT_CONFIG_KEY_{existing}"), "http.extraheader")
.env(format!("GIT_CONFIG_VALUE_{existing}"), &header_value);
}
}
// βββ Platform helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
#[cfg(unix)]
fn make_executable(path: &Path) -> Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let metadata = fs::metadata(path)?;
let mut perms = metadata.permissions();
let mode = perms.mode();
if mode & 0o111 == 0 {
perms.set_mode(mode | 0o755);
fs::set_permissions(path, perms)?;
}
}
#[cfg(not(unix))]
{
let _ = path;
}
Ok(())
}
#[cfg(not(unix))]
fn make_executable(_path: &Path) -> Result<()> {
Ok(())
}
fn create_symlink(original: &Path, link: &Path) -> Result<()> {
#[cfg(unix)]
{
std::os::unix::fs::symlink(original, link)?;
}
#[cfg(windows)]
{
// Symlink creation on Windows requires Developer Mode or elevated
// privileges. Fall back to copying the file when symlink fails.
std::os::windows::fs::symlink_file(original, link)
.or_else(|_| std::fs::copy(original, link).map(|_| ()))?;
}
Ok(())
}
fn create_dir_symlink(original: &Path, link: &Path) -> Result<()> {
#[cfg(unix)]
{
std::os::unix::fs::symlink(original, link)?;
}
#[cfg(windows)]
{
std::os::windows::fs::symlink_dir(original, link)
.or_else(|_| copy_dir_all(original, link))?;
}
Ok(())
}