proto_core 0.55.5

Core proto APIs.
Documentation
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
use super::build::*;
pub use super::build_error::ProtoBuildError;
pub use super::install_error::ProtoInstallError;
use crate::checksum::*;
use crate::env::ProtoConsole;
use crate::flow::lock::Locker;
use crate::helpers::{extract_filename_from_url, is_archive_file, is_executable, is_offline};
use crate::lockfile::*;
use crate::tool::Tool;
use crate::tool_spec::ToolSpec;
use crate::utils::log::LogWriter;
use crate::utils::{archive, process};
use proto_pdk_api::*;
use starbase_shell::ShellType;
use starbase_styles::color;
use starbase_utils::net::DownloadOptions;
use starbase_utils::{fs, net, path};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use system_env::System;
use tokio::process::Command;
use tracing::{debug, instrument, warn};

pub use starbase_utils::net::OnChunkFn;
pub type OnPhaseFn = Arc<dyn Fn(InstallPhase) + Send + Sync>;

// Prebuilt: Download -> Verify -> Unpack
// Build: InstallDeps -> CheckRequirements -> ExecuteInstructions -> ...
#[derive(Clone, Debug)]
pub enum InstallPhase {
    Native,
    Download { url: String, file: String },
    Verify { url: String, file: String },
    Unpack { file: String },
    InstallDeps,
    CheckRequirements,
    ExecuteInstructions,
    CloneRepository { url: String },
}

#[derive(Default)]
pub struct InstallOptions {
    pub console: Option<ProtoConsole>,
    pub force: bool,
    pub log_writer: Option<LogWriter>,
    pub on_download_chunk: Option<OnChunkFn>,
    pub on_phase_change: Option<OnPhaseFn>,
    pub skip_prompts: bool,
    pub skip_ui: bool,
    pub strategy: InstallStrategy,
}

/// Installs a tool into proto's store.
pub struct Installer<'tool> {
    tool: &'tool Tool,
    spec: &'tool ToolSpec,

    pub product_dir: PathBuf,
    pub temp_dir: PathBuf,
}

impl<'tool> Installer<'tool> {
    pub fn new(tool: &'tool Tool, spec: &'tool ToolSpec) -> Self {
        Self {
            product_dir: tool.get_product_dir(spec),
            temp_dir: tool.get_temp_dir().to_path_buf(),
            tool,
            spec,
        }
    }

    /// Install a tool into proto, either by downloading and unpacking
    /// a pre-built archive, or by using a native installation method.
    #[instrument(skip(self, options))]
    pub async fn install(
        &self,
        options: InstallOptions,
    ) -> Result<Option<LockRecord>, ProtoInstallError> {
        if self.tool.is_installed(self.spec) && !options.force {
            debug!(
                tool = self.tool.context.as_str(),
                "Tool already installed, continuing"
            );

            return Ok(None);
        }

        if is_offline() {
            return Err(ProtoInstallError::RequiredInternetConnection);
        }

        // Lock the temporary directory instead of the install directory,
        // because the latter needs to be clean for "build from source",
        // and the `.lock` file breaks that contract
        let mut install_lock = fs::lock_directory(&self.temp_dir)?;

        // If this function is defined, it acts like an escape hatch and
        // takes precedence over all other install strategies
        if self
            .tool
            .plugin
            .has_func(PluginFunction::NativeInstall)
            .await
        {
            debug!(
                tool = self.tool.context.as_str(),
                "Installing tool natively"
            );

            options.on_phase_change.as_ref().inspect(|func| {
                func(InstallPhase::Native);
            });

            fs::create_dir_all(&self.product_dir)?;

            let output: NativeInstallOutput = self
                .tool
                .plugin
                .call_func_with(
                    PluginFunction::NativeInstall,
                    NativeInstallInput {
                        context: self.tool.create_plugin_context(self.spec),
                        install_dir: self.tool.to_virtual_path(&self.product_dir),
                        force: options.force,
                    },
                )
                .await?;

            if output.installed {
                let mut record = self.tool.create_locked_record();
                record.checksum = output.checksum;

                // Verify against lockfile
                Locker::new(self.tool).verify_locked_record(self.spec, &record)?;

                return Ok(Some(record));
            }

            if !output.skip_install {
                return Err(ProtoInstallError::FailedInstall {
                    tool: self.tool.get_name().to_owned(),
                    error: output.error.unwrap_or_default(),
                });
            }
        }

        // Build the tool from source
        let result = if matches!(options.strategy, InstallStrategy::BuildFromSource) {
            self.build_from_source(options).await
        }
        // Install from a prebuilt archive
        else {
            self.install_from_prebuilt(options).await
        };

        match result {
            Ok(record) => {
                // Verify against lockfile
                Locker::new(self.tool).verify_locked_record(self.spec, &record)?;

                debug!(
                    tool = self.tool.context.as_str(),
                    install_dir = ?self.product_dir,
                    "Successfully installed tool",
                );

                Ok(Some(record))
            }

            // Clean up if the install failed
            Err(error) => {
                debug!(
                    tool = self.tool.context.as_str(),
                    install_dir = ?self.product_dir,
                    "Failed to install tool, cleaning up",
                );

                install_lock.unlock()?;

                fs::remove_dir_all(&self.product_dir)?;
                fs::remove_dir_all(&self.temp_dir)?;

                Err(error)
            }
        }
    }

    /// Build the tool from source using a set of requirements and instructions
    /// into the `~/.proto/tools/<version>` folder.
    #[instrument(skip(self, options))]
    async fn build_from_source(
        &self,
        options: InstallOptions,
    ) -> Result<LockRecord, ProtoInstallError> {
        debug!(
            tool = self.tool.context.as_str(),
            "Installing tool by building from source"
        );

        if !self
            .tool
            .plugin
            .has_func(PluginFunction::BuildInstructions)
            .await
        {
            return Err(ProtoInstallError::UnsupportedBuildFromSource {
                tool: self.tool.get_name().to_owned(),
            });
        }

        let output: BuildInstructionsOutput = self
            .tool
            .plugin
            .cache_func_with(
                PluginFunction::BuildInstructions,
                BuildInstructionsInput {
                    context: self.tool.create_plugin_context(self.spec),
                    install_dir: self.tool.to_virtual_path(&self.product_dir),
                },
            )
            .await?;

        let mut system = System::default();
        let config = self.tool.proto.load_config()?;

        if let Some(pm) = config.settings.build.system_package_manager.get(&system.os) {
            if let Some(pm) = pm {
                system.manager = Some(*pm);

                debug!(
                    tool = self.tool.context.as_str(),
                    "Overwriting system package manager to {} for {}", pm, system.os
                );
            } else {
                system.manager = None;

                debug!(
                    tool = self.tool.context.as_str(),
                    "Disabling system package manager because {} was disabled for {}",
                    color::property("settings.build.system-package-manager"),
                    system.os
                );
            }
        }

        let mut builder = Builder::new(BuilderOptions {
            config,
            console: options
                .console
                .as_ref()
                .expect("Console required for builder!"),
            install_dir: &self.product_dir,
            http_client: self.tool.proto.get_plugin_loader()?.get_http_client()?,
            log_writer: options
                .log_writer
                .as_ref()
                .expect("Logger required for builder!"),
            on_phase_change: options.on_phase_change.clone(),
            skip_prompts: options.skip_prompts,
            skip_ui: options.skip_ui,
            system,
            temp_dir: &self.temp_dir,
            version: self.spec.get_resolved_version(),
        });

        // The build process may require using itself to build itself,
        // so allow proto to use any available version instead of failing
        unsafe { std::env::set_var(format!("{}_VERSION", self.tool.get_env_var_prefix()), "*") };

        let mut record = self.tool.create_locked_record();

        // Step 0
        log_build_information(&mut builder, &output)?;

        // Step 1
        if config.settings.build.install_system_packages {
            install_system_dependencies(&mut builder, &output).await?;
        } else {
            debug!(
                tool = self.tool.context.as_str(),
                "Not installing system dependencies because {} was disabled",
                color::property("settings.build.install-system-packages"),
            );
        }

        // Step 2
        check_requirements(&mut builder, &output).await?;

        // Step 3
        download_sources(&mut builder, &output, &mut record).await?;

        // Step 4
        execute_instructions(&mut builder, &output, &self.tool.proto).await?;

        Ok(record)
    }

    /// Download the tool (as an archive) from its distribution registry
    /// into the `~/.proto/tools/<version>` folder, and optionally verify checksums.
    #[instrument(skip(self, options))]
    async fn install_from_prebuilt(
        &self,
        options: InstallOptions,
    ) -> Result<LockRecord, ProtoInstallError> {
        debug!(
            tool = self.tool.context.as_str(),
            "Installing tool by downloading a pre-built archive"
        );

        if !self
            .tool
            .plugin
            .has_func(PluginFunction::DownloadPrebuilt)
            .await
        {
            return Err(ProtoInstallError::UnsupportedDownloadPrebuilt {
                tool: self.tool.get_name().to_owned(),
            });
        }

        let client = self.tool.proto.get_plugin_loader()?.get_http_client()?;
        let config = self.tool.proto.load_config()?;

        let output: DownloadPrebuiltOutput = self
            .tool
            .plugin
            .cache_func_with(
                PluginFunction::DownloadPrebuilt,
                DownloadPrebuiltInput {
                    context: self.tool.create_plugin_context(self.spec),
                    install_dir: self.tool.to_virtual_path(&self.product_dir),
                },
            )
            .await?;

        let mut record = self.tool.create_locked_record();

        // Download the prebuilt
        let download_url = config.rewrite_url(output.download_url);
        let download_filename = match output.download_name {
            Some(name) => name,
            None => extract_filename_from_url(&download_url),
        };
        let download_file = self.temp_dir.join(&download_filename);

        record.source = Some(download_url.clone());
        options.on_phase_change.as_ref().inspect(|func| {
            func(InstallPhase::Download {
                url: download_url.clone(),
                file: download_filename.clone(),
            });
        });

        debug!(
            tool = self.tool.context.as_str(),
            "Downloading tool archive"
        );

        net::download_from_url_with_options(
            &download_url,
            &download_file,
            DownloadOptions {
                downloader: Some(Box::new(client.create_downloader())),
                on_chunk: options.on_download_chunk.clone(),
            },
        )
        .await?;

        // Verify against a URL that contains the checksum
        if let Some(checksum_url) = output.checksum_url {
            let checksum_url = config.rewrite_url(checksum_url);
            let checksum_filename = match output.checksum_name {
                Some(name) => name,
                None => extract_filename_from_url(&checksum_url),
            };
            let checksum_file = self.temp_dir.join(&checksum_filename);

            options.on_phase_change.as_ref().inspect(|func| {
                func(InstallPhase::Verify {
                    url: checksum_url.clone(),
                    file: checksum_filename.clone(),
                });
            });

            debug!(
                tool = self.tool.context.as_str(),
                "Downloading tool checksum"
            );

            net::download_from_url_with_options(
                &checksum_url,
                &checksum_file,
                DownloadOptions {
                    downloader: Some(Box::new(client.create_downloader())),
                    on_chunk: None,
                },
            )
            .await?;

            record.checksum = Some(
                self.verify_checksum(
                    &checksum_file,
                    &download_file,
                    output.checksum_public_key.as_deref(),
                )
                .await?,
            );
        }
        // Verify against an explicitly provided checksum
        else if let Some(checksum) = output.checksum {
            let checksum_file = self
                .temp_dir
                .join(format!("CHECKSUM.{:?}", checksum.algo).to_lowercase());

            fs::write_file(&checksum_file, checksum.hash.as_deref().unwrap_or_default())?;

            debug!(
                tool = self.tool.context.as_str(),
                checksum = checksum.to_string(),
                "Using provided checksum"
            );

            record.checksum = Some(
                self.verify_checksum(
                    &checksum_file,
                    &download_file,
                    output
                        .checksum_public_key
                        .as_deref()
                        .or(checksum.key.as_deref()),
                )
                .await?,
            );
        }
        // No available checksum, so generate one ourselves for the lockfile
        else {
            record.checksum = Some(Checksum::sha256(hash_file_contents_sha256(&download_file)?));
        }

        // Attempt to unpack the archive
        debug!(
            tool = self.tool.context.as_str(),
            download_file = ?download_file,
            install_dir = ?self.product_dir,
            "Attempting to unpack archive",
        );

        if self
            .tool
            .plugin
            .has_func(PluginFunction::UnpackArchive)
            .await
        {
            options.on_phase_change.as_ref().inspect(|func| {
                func(InstallPhase::Unpack {
                    file: download_filename.clone(),
                });
            });

            self.tool
                .plugin
                .call_func_without_output(
                    PluginFunction::UnpackArchive,
                    UnpackArchiveInput {
                        input_file: self.tool.to_virtual_path(&download_file),
                        output_dir: self.tool.to_virtual_path(&self.product_dir),
                        context: self.tool.create_plugin_context(self.spec),
                    },
                )
                .await?;
        }
        // Is an archive, unpack it
        else if is_archive_file(&download_file) {
            options.on_phase_change.as_ref().inspect(|func| {
                func(InstallPhase::Unpack {
                    file: download_filename.clone(),
                });
            });

            let (ext, unpacked_path) = archive::unpack_raw(
                &self.product_dir,
                &download_file,
                output.archive_prefix.as_deref(),
            )?;

            // If the archive was `.gz` without tar or other formats,
            // it's a single file, so assume a file and update perms
            if ext == "gz" && unpacked_path.is_file() {
                fs::update_perms(unpacked_path, None)?;
            }
        }
        // Not an archive, assume a file and copy
        else {
            let install_path = self.product_dir.join(path::exe_name(path::encode_component(
                self.tool.get_file_name(),
            )));

            fs::rename(&download_file, &install_path)?;
            fs::update_perms(install_path, None)?;
        }

        // Execute post install script
        if let Some(rel_script) = output.post_script {
            let abs_script = self.product_dir.join(rel_script);

            if !abs_script.exists() {
                warn!(
                    tool = self.tool.context.as_str(),
                    script = ?abs_script,
                    "Post-install script does not exist",
                );
            } else if !is_executable(&abs_script) {
                warn!(
                    tool = self.tool.context.as_str(),
                    script = ?abs_script,
                    "Post-install script is not executable",
                );
            } else {
                debug!(
                    tool = self.tool.context.as_str(),
                    script = ?abs_script,
                    "Executing post-install script",
                );

                let shell = ShellType::detect_with_fallback().build();
                let mut command = Command::new(shell.to_string());
                command.arg("-c");
                command.arg(shell.quote(&abs_script.to_string_lossy()));
                command.current_dir(&self.product_dir);

                process::exec_command(&mut command).await?;
            }
        }

        Ok(record)
    }

    /// Uninstall the tool by deleting the current install directory.
    #[instrument(skip_all)]
    pub async fn uninstall(&self) -> Result<bool, ProtoInstallError> {
        if !self.product_dir.exists() {
            debug!(
                tool = self.tool.context.as_str(),
                "Tool has not been installed, aborting"
            );

            return Ok(false);
        }

        if self
            .tool
            .plugin
            .has_func(PluginFunction::NativeUninstall)
            .await
        {
            debug!(
                tool = self.tool.context.as_str(),
                "Uninstalling tool natively"
            );

            let output: NativeUninstallOutput = self
                .tool
                .plugin
                .call_func_with(
                    PluginFunction::NativeUninstall,
                    NativeUninstallInput {
                        context: self.tool.create_plugin_context(self.spec),
                        uninstall_dir: self.tool.to_virtual_path(&self.product_dir),
                    },
                )
                .await?;

            if !output.uninstalled && !output.skip_uninstall {
                return Err(ProtoInstallError::FailedUninstall {
                    tool: self.tool.get_name().to_owned(),
                    error: output.error.unwrap_or_default(),
                });
            }
        }

        debug!(
            tool = self.tool.context.as_str(),
            install_dir = ?self.product_dir,
            "Deleting install directory"
        );

        fs::remove_dir_all(&self.product_dir)?;

        debug!(
            tool = self.tool.context.as_str(),
            "Successfully uninstalled tool"
        );

        Ok(true)
    }

    /// Verify the downloaded file using the checksum strategy for the tool.
    /// Common strategies are SHA256 and MD5.
    #[instrument(skip(self))]
    pub async fn verify_checksum(
        &self,
        checksum_file: &Path,
        download_file: &Path,
        checksum_public_key: Option<&str>,
    ) -> Result<Checksum, ProtoInstallError> {
        debug!(
            tool = self.tool.context.as_str(),
            download_file = ?download_file,
            checksum_file = ?checksum_file,
            "Verifying checksum of downloaded file",
        );

        let checksum = generate_checksum(download_file, checksum_file, checksum_public_key)?;
        let verified;

        // Allow plugin to provide their own checksum verification method
        if self
            .tool
            .plugin
            .has_func(PluginFunction::VerifyChecksum)
            .await
        {
            let output: VerifyChecksumOutput = self
                .tool
                .plugin
                .call_func_with(
                    PluginFunction::VerifyChecksum,
                    VerifyChecksumInput {
                        checksum_file: self.tool.to_virtual_path(checksum_file),
                        download_file: self.tool.to_virtual_path(download_file),
                        download_checksum: Some(checksum.clone()),
                        context: self.tool.create_plugin_context(self.spec),
                    },
                )
                .await?;

            verified = output.verified;
        }
        // Otherwise attempt to verify it ourselves
        else {
            verified = verify_checksum(download_file, checksum_file, &checksum)?;
        }

        if verified {
            debug!(
                tool = self.tool.context.as_str(),
                "Successfully verified, checksum matches"
            );

            return Ok(checksum);
        }

        Err(ProtoInstallError::InvalidChecksum {
            checksum: checksum_file.to_path_buf(),
            download: download_file.to_path_buf(),
        })
    }
}