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
mod build_source;

use crate::shapes::StringOrVec;
use rustc_hash::FxHashMap;
use std::path::PathBuf;
use version_spec::{CalVer, SemVer, SpecError, UnresolvedVersionSpec, VersionSpec};
use warpgate_api::*;

pub use build_source::*;
pub use semver::{Version, VersionReq};

fn is_false(value: &bool) -> bool {
    !(*value)
}

api_struct!(
    /// Information about the current state of the tool.
    pub struct ToolContext {
        /// The version of proto (the core crate) calling plugin functions.
        #[serde(default)]
        pub proto_version: Option<Version>,

        /// Virtual path to the tool's installation directory.
        pub tool_dir: VirtualPath,

        /// Current version. Will be a "latest" alias if not resolved.
        pub version: VersionSpec,
    }
);

api_enum!(
    /// Supported types of plugins.
    #[derive(Default)]
    pub enum PluginType {
        #[default]
        Language,
        DependencyManager,
        CLI,
    }
);

api_struct!(
    /// Input passed to the `register_tool` function.
    pub struct ToolMetadataInput {
        /// ID of the tool, as it was configured.
        pub id: String,
    }
);

api_struct!(
    /// Controls aspects of the tool inventory.
    #[serde(default)]
    pub struct ToolInventoryMetadata {
        /// Disable progress bars when installing or uninstalling tools.
        #[serde(skip_serializing_if = "is_false")]
        pub disable_progress_bars: bool,

        /// Override the tool inventory directory (where all versions are installed).
        /// This is an advanced feature and should only be used when absolutely necessary.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub override_dir: Option<VirtualPath>,

        /// Suffix to append to all versions when labeling directories.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub version_suffix: Option<String>,
    }
);

api_struct!(
    /// Output returned by the `register_tool` function.
    pub struct ToolMetadataOutput {
        /// Default alias or version to use as a fallback.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub default_version: Option<UnresolvedVersionSpec>,

        /// Controls aspects of the tool inventory.
        #[serde(default)]
        pub inventory: ToolInventoryMetadata,

        /// Human readable name of the tool.
        pub name: String,

        /// Version of the plugin.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub plugin_version: Option<String>,

        /// Names of commands that will self-upgrade the tool,
        /// and should be blocked from happening.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        pub self_upgrade_commands: Vec<String>,

        /// Type of the tool.
        #[serde(rename = "type")]
        pub type_of: PluginType,
    }
);

// VERSION DETECTION

api_struct!(
    /// Output returned by the `detect_version_files` function.
    #[serde(default)]
    pub struct DetectVersionOutput {
        /// List of files that should be checked for version information.
        #[serde(skip_serializing_if = "Vec::is_empty")]
        pub files: Vec<String>,

        /// List of path patterns to ignore when traversing directories.
        #[serde(skip_serializing_if = "Vec::is_empty")]
        pub ignore: Vec<String>,
    }
);

api_struct!(
    /// Input passed to the `parse_version_file` function.
    pub struct ParseVersionFileInput {
        /// File contents to parse/extract a version from.
        pub content: String,

        /// Name of file that's being parsed.
        pub file: String,
    }
);

api_struct!(
    /// Output returned by the `parse_version_file` function.
    #[serde(default)]
    pub struct ParseVersionFileOutput {
        /// The version that was extracted from the file.
        /// Can be a semantic version or a version requirement/range.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub version: Option<UnresolvedVersionSpec>,
    }
);

// DOWNLOAD, BUILD, INSTALL, VERIFY

api_struct!(
    /// Input passed to the `native_install` function.
    pub struct NativeInstallInput {
        /// Current tool context.
        pub context: ToolContext,

        /// Virtual directory to install to.
        pub install_dir: VirtualPath,
    }
);

api_struct!(
    /// Output returned by the `native_install` function.
    pub struct NativeInstallOutput {
        /// Error message if the install failed.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub error: Option<String>,

        /// Whether the install was successful.
        pub installed: bool,

        /// Whether to skip the install process or not.
        #[serde(default)]
        pub skip_install: bool,
    }
);

api_struct!(
    /// Input passed to the `native_uninstall` function.
    pub struct NativeUninstallInput {
        /// Current tool context.
        pub context: ToolContext,
    }
);

api_struct!(
    /// Output returned by the `native_uninstall` function.
    pub struct NativeUninstallOutput {
        /// Error message if the uninstall failed.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub error: Option<String>,

        /// Whether the install was successful.
        pub uninstalled: bool,

        /// Whether to skip the uninstall process or not.
        #[serde(default)]
        pub skip_uninstall: bool,
    }
);

api_struct!(
    /// Input passed to the `download_prebuilt` function.
    pub struct DownloadPrebuiltInput {
        /// Current tool context.
        pub context: ToolContext,

        /// Virtual directory to install to.
        pub install_dir: VirtualPath,
    }
);

api_struct!(
    /// Output returned by the `download_prebuilt` function.
    pub struct DownloadPrebuiltOutput {
        /// Name of the direct folder within the archive that contains the tool,
        /// and will be removed when unpacking the archive.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub archive_prefix: Option<String>,

        /// File name of the checksum to download. If not provided,
        /// will attempt to extract it from the URL.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub checksum_name: Option<String>,

        /// Public key to use for checksum verification.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub checksum_public_key: Option<String>,

        /// A secure URL to download the checksum file for verification.
        /// If the tool does not support checksum verification, this setting can be omitted.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub checksum_url: Option<String>,

        /// File name of the archive to download. If not provided,
        /// will attempt to extract it from the URL.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub download_name: Option<String>,

        /// A secure URL to download the tool/archive.
        pub download_url: String,
    }
);

api_struct!(
    /// Input passed to the `unpack_archive` function.
    pub struct UnpackArchiveInput {
        /// Current tool context.
        pub context: ToolContext,

        /// Virtual path to the downloaded file.
        pub input_file: VirtualPath,

        /// Virtual directory to unpack the archive into, or copy the binary to.
        pub output_dir: VirtualPath,
    }
);

api_struct!(
    /// Output returned by the `verify_checksum` function.
    pub struct VerifyChecksumInput {
        /// Current tool context.
        pub context: ToolContext,

        /// Virtual path to the checksum file.
        pub checksum_file: VirtualPath,

        /// Virtual path to the downloaded file.
        pub download_file: VirtualPath,
    }
);

api_struct!(
    /// Output returned by the `verify_checksum` function.
    pub struct VerifyChecksumOutput {
        pub verified: bool,
    }
);

// EXECUTABLES, BINARYS, GLOBALS

api_struct!(
    /// Input passed to the `locate_executables` function.
    pub struct LocateExecutablesInput {
        /// Current tool context.
        pub context: ToolContext,
    }
);

api_struct!(
    /// Configuration for generated shim and symlinked binary files.
    #[serde(default)]
    pub struct ExecutableConfig {
        /// The file to execute, relative from the tool directory.
        /// Does *not* support virtual paths.
        ///
        /// The following scenarios are powered by this field:
        /// - Is the primary executable.
        /// - For primary and secondary bins, the source file to be symlinked,
        ///   and the extension to use for the symlink file itself.
        /// - For primary shim, this field is ignored.
        /// - For secondary shims, the file to execute.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub exe_path: Option<PathBuf>,

        /// The executable path to use for symlinking binaries instead of `exe_path`.
        /// This should only be used when `exe_path` is a non-standard executable.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub exe_link_path: Option<PathBuf>,

        /// Do not symlink a binary in `~/.proto/bin`.
        #[serde(skip_serializing_if = "is_false")]
        pub no_bin: bool,

        /// Do not generate a shim in `~/.proto/shims`.
        #[serde(skip_serializing_if = "is_false")]
        pub no_shim: bool,

        /// The parent executable name required to execute the local executable path.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub parent_exe_name: Option<String>,

        /// Custom args to prepend to user-provided args within the generated shim.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub shim_before_args: Option<StringOrVec>,

        /// Custom args to append to user-provided args within the generated shim.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub shim_after_args: Option<StringOrVec>,

        /// Custom environment variables to set when executing the shim.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub shim_env_vars: Option<FxHashMap<String, String>>,
    }
);

impl ExecutableConfig {
    pub fn new<T: AsRef<str>>(exe_path: T) -> Self {
        Self {
            exe_path: Some(PathBuf::from(exe_path.as_ref())),
            ..ExecutableConfig::default()
        }
    }

    pub fn with_parent<T: AsRef<str>, P: AsRef<str>>(exe_path: T, parent_exe: P) -> Self {
        Self {
            exe_path: Some(PathBuf::from(exe_path.as_ref())),
            parent_exe_name: Some(parent_exe.as_ref().to_owned()),
            ..ExecutableConfig::default()
        }
    }
}

api_struct!(
    /// Output returned by the `locate_executables` function.
    #[serde(default)]
    pub struct LocateExecutablesOutput {
        /// Relative directory path from the tool install directory in which
        /// pre-installed executables can be located.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub exes_dir: Option<PathBuf>,

        /// List of directory paths to find the globals installation directory.
        /// Each path supports environment variable expansion.
        #[serde(skip_serializing_if = "Vec::is_empty")]
        pub globals_lookup_dirs: Vec<String>,

        /// A string that all global binaries are prefixed with, and will be removed
        /// when listing and filtering available globals.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub globals_prefix: Option<String>,

        /// Configures the primary/default executable to create.
        /// If not provided, a primary shim and binary will *not* be created.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub primary: Option<ExecutableConfig>,

        /// Configures secondary/additional executables to create.
        /// The map key is the name of the shim/binary file.
        #[serde(skip_serializing_if = "FxHashMap::is_empty")]
        pub secondary: FxHashMap<String, ExecutableConfig>,
    }
);

// VERSION RESOLVING

api_struct!(
    /// Input passed to the `load_versions` function.
    pub struct LoadVersionsInput {
        /// The alias or version currently being resolved.
        pub initial: UnresolvedVersionSpec,
    }
);

api_struct!(
    /// Output returned by the `load_versions` function.
    #[serde(default)]
    pub struct LoadVersionsOutput {
        /// Latest canary version.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub canary: Option<UnresolvedVersionSpec>,

        /// Latest stable version.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub latest: Option<UnresolvedVersionSpec>,

        /// Mapping of aliases (channels, etc) to a version.
        #[serde(skip_serializing_if = "FxHashMap::is_empty")]
        pub aliases: FxHashMap<String, UnresolvedVersionSpec>,

        /// List of available production versions to install.
        #[serde(skip_serializing_if = "Vec::is_empty")]
        pub versions: Vec<VersionSpec>,
    }
);

impl LoadVersionsOutput {
    /// Create the output from a list of strings that'll be parsed as versions.
    /// The latest version will be the highest version number.
    pub fn from(values: Vec<String>) -> Result<Self, SpecError> {
        let mut versions = vec![];

        for value in values {
            versions.push(VersionSpec::parse(&value)?);
        }

        Ok(Self::from_versions(versions))
    }

    /// Create the output from a list of version specifications.
    /// The latest version will be the highest version number.
    pub fn from_versions(versions: Vec<VersionSpec>) -> Self {
        let mut output = LoadVersionsOutput::default();
        let mut latest = Version::new(0, 0, 0);
        let mut calver = false;

        for version in versions {
            if let Some(inner) = version.as_version() {
                if inner.pre.is_empty() && inner.build.is_empty() && inner > &latest {
                    inner.clone_into(&mut latest);
                    calver = matches!(version, VersionSpec::Calendar(_));
                }
            }

            output.versions.push(version);
        }

        output.latest = Some(if calver {
            UnresolvedVersionSpec::Calendar(CalVer(latest))
        } else {
            UnresolvedVersionSpec::Semantic(SemVer(latest))
        });

        output
            .aliases
            .insert("latest".into(), output.latest.clone().unwrap());

        output
    }
}

api_struct!(
    /// Input passed to the `resolve_version` function.
    pub struct ResolveVersionInput {
        /// The alias or version currently being resolved.
        pub initial: UnresolvedVersionSpec,
    }
);

api_struct!(
    /// Output returned by the `resolve_version` function.
    #[serde(default)]
    pub struct ResolveVersionOutput {
        /// New alias or version candidate to resolve.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub candidate: Option<UnresolvedVersionSpec>,

        /// An explicitly resolved version to be used as-is.
        /// Note: Only use this field if you know what you're doing!
        #[serde(skip_serializing_if = "Option::is_none")]
        pub version: Option<VersionSpec>,
    }
);

// MISCELLANEOUS

api_struct!(
    /// Input passed to the `sync_manifest` function.
    pub struct SyncManifestInput {
        /// Current tool context.
        pub context: ToolContext,
    }
);

api_struct!(
    /// Output returned by the `sync_manifest` function.
    #[serde(default)]
    pub struct SyncManifestOutput {
        /// List of versions that are currently installed. Will replace
        /// what is currently in the manifest.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub versions: Option<Vec<VersionSpec>>,

        /// Whether to skip the syncing process or not.
        pub skip_sync: bool,
    }
);

api_struct!(
    /// Input passed to the `sync_shell_profile` function.
    pub struct SyncShellProfileInput {
        /// Current tool context.
        pub context: ToolContext,

        /// Arguments passed after `--` that was directly passed to the tool's binary.
        pub passthrough_args: Vec<String>,
    }
);

api_struct!(
    /// Output returned by the `sync_shell_profile` function.
    pub struct SyncShellProfileOutput {
        /// An environment variable to check for in the shell profile.
        /// If the variable exists, injecting path and exports will be avoided.
        pub check_var: String,

        /// A mapping of environment variables that will be injected as exports.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub export_vars: Option<FxHashMap<String, String>>,

        /// A list of paths to prepend to the `PATH` environment variable.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub extend_path: Option<Vec<String>>,

        /// Whether to skip the syncing process or not.
        #[serde(default)]
        pub skip_sync: bool,
    }
);