ubi 0.9.0

The Universal Binary Installer library
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
/// The `builder` module contains the `UbiBuilder` struct which is used to create a `Ubi` instance.
use crate::{
    forge::ForgeType,
    installer::{ArchiveInstaller, ExeInstaller, Installer},
    picker::AssetPicker,
    ubi::Ubi,
};
use anyhow::{anyhow, Context, Result};
use log::debug;
use platforms::{Platform, PlatformReq, OS};
use reqwest::{
    header::{HeaderMap, HeaderValue, USER_AGENT},
    Client,
};
use std::{
    env,
    path::{Path, PathBuf},
    str::FromStr,
};
use url::Url;
use which::which;

/// `UbiBuilder` is used to create a [`Ubi`] instance.
#[derive(Debug, Default)]
#[allow(clippy::module_name_repetitions)]
pub struct UbiBuilder<'a> {
    project: Option<&'a str>,
    tag: Option<&'a str>,
    url: Option<&'a str>,
    install_dir: Option<PathBuf>,
    matching: Option<&'a str>,
    matching_regex: Option<&'a str>,
    exe: Option<&'a str>,
    rename_exe_to: Option<&'a str>,
    extract_all: bool,
    token: Option<&'a str>,
    platform: Option<&'a Platform>,
    is_musl: Option<bool>,
    api_base_url: Option<&'a str>,
    forge: Option<ForgeType>,
    min_age_days: Option<u32>,
}

impl<'a> UbiBuilder<'a> {
    /// Returns a new empty `UbiBuilder`.
    #[must_use]
    pub fn new() -> Self {
        UbiBuilder::default()
    }

    /// Set the project to download from. This can either be just the org/name, like
    /// `houseabsolute/precious`, or the complete forge site URL to the project, like
    /// `https://github.com/houseabsolute/precious`, `https://gitlab.com/gitlab-org/cli`, or
    /// `https://codeberg.org/codeberg/cli`. It also accepts a URL to any page in the project, like
    /// `https://github.com/houseabsolute/precious/releases`.
    ///
    /// You must set this or set `url`, but not both.
    #[must_use]
    pub fn project(mut self, project: &'a str) -> Self {
        self.project = Some(project);
        self
    }

    /// Set the tag to download. By default the most recent release is downloaded.
    ///
    /// You cannot set this with the `url` or `min_age_days` options.
    #[must_use]
    pub fn tag(mut self, tag: &'a str) -> Self {
        self.tag = Some(tag);
        self
    }

    /// Set the URL to download from. This can be provided instead of a project or tag. This will not
    /// use the forge site API, so you will never hit API limits. That in turn means you won't have
    /// to set a token env var except when downloading a release from a private repo when the URL is
    /// set.
    ///
    /// You must set this or set `project`, but not both. You cannot set this with the `tag` or
    /// `min_age_days` options.
    #[must_use]
    pub fn url(mut self, url: &'a str) -> Self {
        self.url = Some(url);
        self
    }

    /// Set the directory to install the binary in. If not set, it will default to `./bin`.
    #[must_use]
    pub fn install_dir<P: AsRef<Path>>(mut self, install_dir: P) -> Self {
        self.install_dir = Some(install_dir.as_ref().to_path_buf());
        self
    }

    /// Set a string to match against the release filename when there are multiple files for your
    /// OS/arch, i.e. "gnu" or "musl". Note that this is only used when there is more than one
    /// matching release filename for your OS/arch. If only one release asset matches your OS/arch,
    /// then this will be ignored.
    #[must_use]
    pub fn matching(mut self, matching: &'a str) -> Self {
        self.matching = Some(matching);
        self
    }

    /// Set a regular expression string that will be matched against release filenames before
    /// matching against your OS/arch. If the pattern yields a single match, that release will be
    /// selected. If no matches are found, then the `Ubi::install_binary` method will return an
    /// error when it is run.
    #[must_use]
    pub fn matching_regex(mut self, matching_regex: &'a str) -> Self {
        self.matching_regex = Some(matching_regex);
        self
    }

    /// Set the name of the executable to look for in archive files. By default this is the same as
    /// the project name, so for `houseabsolute/precious` we look for `precious` or
    /// `precious.exe`. When running on Windows the ".exe" suffix will be added as needed.
    ///
    /// You cannot call `extract_all` if you set this.
    #[must_use]
    pub fn exe(mut self, exe: &'a str) -> Self {
        self.exe = Some(exe);
        self
    }

    /// The name to use when installing the executable. This is useful if the executable in the
    /// archive file has a name that includes a version number or platform information. If this is
    /// not set, then the executable will be installed with the name it has in the archive
    /// file. Note that this name is used as-is, so on Windows, `.exe` will not be appended to the
    /// name given.
    ///
    /// You cannot call `extract_all` if you set this.
    #[must_use]
    pub fn rename_exe_to(mut self, name: &'a str) -> Self {
        self.rename_exe_to = Some(name);
        self
    }

    /// Call this to tell `ubi` to extract all files from the archive. By default `ubi` will look
    /// for an executable in an archive file. But if this is true, it will simply unpack the archive
    /// file in the specified directory.
    ///
    /// You cannot set `exe` when this is true.
    #[must_use]
    pub fn extract_all(mut self) -> Self {
        self.extract_all = true;
        self
    }

    /// Set the minimum age in days for releases. Only releases at least this many days old will be
    /// installed. This is useful for mitigating supply chain attacks. It's especially useful for
    /// projects that use GitHub's immutable releases feature.
    ///
    /// You cannot set this with the `tag` or `url` options.
    #[must_use]
    pub fn min_age_days(mut self, days: u32) -> Self {
        self.min_age_days = Some(days);
        self
    }

    /// Set a token to use for API requests. If this is not set, then `ubi` will look for a token in
    /// the appropriate env var:
    ///
    /// * GitHub - `GITHUB_TOKEN`
    /// * GitLab - `CI_TOKEN`, then `GITLAB_TOKEN`.
    /// * Codeberg/Forgejo - `CODEBERG_TOKEN`, then `FORGEJO_TOKEN`.
    #[must_use]
    pub fn token(mut self, token: &'a str) -> Self {
        self.token = Some(token);
        self
    }

    /// Set a GitHub token to use for API requests. If this is not set then this will be taken from
    /// the `GITHUB_TOKEN` env var if it is set.
    #[deprecated(since = "0.6.0", note = "please use `token` instead")]
    #[must_use]
    pub fn github_token(mut self, token: &'a str) -> Self {
        self.token = Some(token);
        self
    }

    /// Set a GitLab token to use for API requests. If this is not set then this will be taken from
    /// the `CI_JOB_TOKEN` or `GITLAB_TOKEN` env var, if one of these is set. If both are set, then
    /// the value in `CI_JOB_TOKEN` will be used.
    #[deprecated(since = "0.6.0", note = "please use `token` instead")]
    #[must_use]
    pub fn gitlab_token(mut self, token: &'a str) -> Self {
        self.token = Some(token);
        self
    }

    /// Set the platform to download for. If not set it will be determined based on the current
    /// platform's OS/arch.
    #[must_use]
    pub fn platform(mut self, platform: &'a Platform) -> Self {
        self.platform = Some(platform);
        self
    }

    /// Set whether or not the platform uses musl as its libc. This is only relevant for Linux
    /// platforms. If this isn't set then it will be determined based on the current platform's
    /// libc. You cannot set this to `true` on a non-Linux platform.
    #[must_use]
    pub fn is_musl(mut self, is_musl: bool) -> Self {
        self.is_musl = Some(is_musl);
        self
    }

    /// Set the forge type to use for fetching assets and release information. This determines which
    /// REST API is used to get information about releases and to download the release. If this isn't
    /// set, then this will be determined from the hostname in the url, if that is set.  Otherwise,
    /// the default is GitHub.
    #[must_use]
    pub fn forge(mut self, forge: ForgeType) -> Self {
        self.forge = Some(forge);
        self
    }

    /// Set the base URL for the forge site's API. This is useful for testing or if you want to
    /// operate against an Enterprise version of GitHub or GitLab. This should be something like
    /// `https://github.my-corp.example.com/api/v4`.
    #[must_use]
    pub fn api_base_url(mut self, api_base_url: &'a str) -> Self {
        self.api_base_url = Some(api_base_url);
        self
    }

    const TARGET: &'static str = env!("TARGET");

    /// Builds a new [`Ubi`] instance and returns it.
    ///
    /// # Errors
    ///
    /// If you have tried to set incompatible options (setting a `project` or `tag` with a `url`) or
    /// you have not set required options (one of `project` or `url`), then this method will return
    /// an error.
    pub fn build(self) -> Result<Ubi<'a>> {
        if self.project.is_none() && self.url.is_none() {
            return Err(anyhow!("You must set a project or url"));
        }
        if self.url.is_some() && (self.project.is_some() || self.tag.is_some()) {
            return Err(anyhow!("You cannot set a url with a project or tag"));
        }
        if self.exe.is_some() && self.extract_all {
            return Err(anyhow!("You cannot set exe and enable extract_all"));
        }
        if self.rename_exe_to.is_some() && self.extract_all {
            return Err(anyhow!(
                "You cannot set rename_exe_to and enable extract_all"
            ));
        }
        if let Some(days) = self.min_age_days {
            if self.url.is_some() {
                return Err(anyhow!("You cannot set min_age_days with url"));
            }
            if self.tag.is_some() {
                return Err(anyhow!("You cannot set min_age_days with tag"));
            }
            if days == 0 {
                return Err(anyhow!(
                    "min_age_days must be a positive number (greater than 0)"
                ));
            }
        }

        let platform = self.determine_platform()?;

        self.check_musl_setting(&platform)?;

        let asset_url = match self.url {
            Some(url) => {
                Some(Url::parse(url).with_context(|| format!("failed to parse URL: {url}"))?)
            }
            None => None,
        };
        let (project_name, forge_type) =
            parse_project_name(self.project, asset_url.as_ref(), self.forge.clone())?;
        let installer = self.new_installer(&project_name, &platform)?;
        let forge = forge_type.new_forge(
            project_name,
            self.tag.map(String::from),
            self.api_base_url.map(String::from),
            self.token.map(String::from),
        )?;
        let is_musl = self.is_musl.unwrap_or_else(|| platform_is_musl(&platform));

        Ok(Ubi::new(
            forge,
            asset_url,
            AssetPicker::new(
                self.matching,
                self.matching_regex,
                platform,
                is_musl,
                self.extract_all,
            ),
            installer,
            reqwest_client()?,
            self.min_age_days,
        ))
    }

    fn new_installer(&self, project_name: &str, platform: &Platform) -> Result<Box<dyn Installer>> {
        if self.extract_all {
            let install_path =
                install_path(self.install_dir.as_deref(), None).with_context(|| {
                    format!("failed to determine install path for project {project_name}")
                })?;
            Ok(Box::new(ArchiveInstaller::new(
                project_name.to_string(),
                install_path,
            )))
        } else {
            let expect_exe_stem_name = expect_exe_stem_name(self.exe, project_name);
            let install_path = install_path(
                self.install_dir.as_deref(),
                self.rename_exe_to.or(Some(expect_exe_stem_name)),
            )
            .with_context(|| {
                format!("failed to determine install path for executable {expect_exe_stem_name}")
            })?;
            Ok(Box::new(ExeInstaller::new(
                install_path,
                self.rename_exe_to.is_some(),
                expect_exe_stem_name.to_string(),
                platform.target_os == OS::Windows,
            )))
        }
    }

    fn determine_platform(&self) -> Result<Platform> {
        if let Some(p) = self.platform {
            Ok(p.clone())
        } else {
            let req = PlatformReq::from_str(Self::TARGET)
                .with_context(|| format!("failed to parse platform target: {}", Self::TARGET))?;
            Platform::ALL
                .iter()
                .find(|p| req.matches(p))
                .cloned()
                .ok_or(anyhow!(
                    "Could not find any platform matching {}",
                    Self::TARGET
                ))
        }
    }

    fn check_musl_setting(&self, platform: &Platform) -> Result<()> {
        if self.is_musl.unwrap_or_default() && platform.target_os != OS::Linux {
            return Err(anyhow!(
                "You cannot set is_musl to true on a non-Linux platform - the current platform is {}",
                platform.target_os,
            ));
        }
        Ok(())
    }
}

fn parse_project_name(
    project: Option<&str>,
    url: Option<&Url>,
    forge: Option<ForgeType>,
) -> Result<(String, ForgeType)> {
    let (parsed, from) = if let Some(project) = project {
        if project.starts_with("http") {
            (
                Url::parse(project)
                    .with_context(|| format!("failed to parse project URL: {project}"))?,
                format!("--project {project}"),
            )
        } else {
            let base = forge.unwrap_or_default().project_base_url();
            (
                base.join(project).with_context(|| {
                    format!("failed to construct project URL from '{project}' with base URL {base}")
                })?,
                format!("--project {project}"),
            )
        }
    } else if let Some(u) = url {
        (u.clone(), format!("--url {u}"))
    } else {
        unreachable!(
            "Did not get a --project or --url argument but that should be checked in main.rs"
        );
    };

    let forge_type = ForgeType::from_url(&parsed);
    let project_name = forge_type
        .parse_project_name_from_url(&parsed, &from)
        .with_context(|| format!("failed to parse project name from URL {parsed}"))?;

    Ok((project_name, forge_type))
}

fn install_path(install_dir: Option<&Path>, exe: Option<&str>) -> Result<PathBuf> {
    let mut install_dir = if let Some(install_dir) = install_dir {
        install_dir.to_path_buf()
    } else {
        let mut install_dir = env::current_dir().context("failed to get current directory")?;
        install_dir.push("bin");
        install_dir
    };
    if let Some(exe) = exe {
        install_dir.push(exe);
    }
    debug!("install path = {}", install_dir.to_string_lossy());
    Ok(install_dir)
}

fn expect_exe_stem_name<'a>(exe: Option<&'a str>, project_name: &'a str) -> &'a str {
    let name = if let Some(exe) = exe {
        exe
    } else {
        // We know that this contains a slash because it already went through `parse_project_name`
        // successfully.
        project_name.split('/').next_back().unwrap()
    };

    debug!("exe name = {name}");
    name
}

fn platform_is_musl(platform: &Platform) -> bool {
    if platform.target_os != OS::Linux {
        return false;
    }

    let Ok(ls) = which("ls") else {
        return false;
    };
    let Ok(ldd) = which("ldd") else {
        return false;
    };

    let Ok(output) = std::process::Command::new(ldd).arg(ls).output() else {
        return false;
    };
    output.status.success() && String::from_utf8_lossy(&output.stdout).contains("musl")
}

fn reqwest_client() -> Result<Client> {
    let builder = Client::builder().gzip(true);

    let mut headers = HeaderMap::new();
    headers.insert(
        USER_AGENT,
        HeaderValue::from_str(&format!("ubi version {}", super::VERSION))
            .context("failed to create User-Agent header value")?,
    );
    builder
        .default_headers(headers)
        .build()
        .context("failed to build HTTP client")
}

#[cfg(test)]
mod test {
    use super::*;
    use rstest::rstest;

    #[test]
    fn parse_project_name() -> Result<()> {
        let org_and_repo = "some-owner/some-repo";

        let projects = &[
            org_and_repo.to_string(),
            format!("https://github.com/{org_and_repo}"),
            format!("https://github.com/{org_and_repo}/releases"),
            format!("https://github.com/{org_and_repo}/actions/runs/4275745616"),
        ];
        for p in projects {
            let (project_name, forge_type) = super::parse_project_name(Some(p), None, None)?;
            assert_eq!(
                project_name, org_and_repo,
                "got the right project from --project {p}",
            );
            assert_eq!(forge_type, ForgeType::GitHub);

            let (project_name, forge_type) =
                super::parse_project_name(Some(p), None, Some(ForgeType::GitHub))?;
            assert_eq!(
                project_name, org_and_repo,
                "got the right project from --project {p}",
            );
            assert_eq!(forge_type, ForgeType::GitHub);
        }

        {
            let url = Url::parse("https://github.com/houseabsolute/precious/releases/download/v0.1.7/precious-Linux-x86_64-musl.tar.gz")?;
            let (project_name, forge_type) = super::parse_project_name(None, Some(&url), None)?;
            assert_eq!(
                project_name, "houseabsolute/precious",
                "got the right project from the --url",
            );
            assert_eq!(forge_type, ForgeType::GitHub);

            let (project_name, forge_type) =
                super::parse_project_name(None, Some(&url), Some(ForgeType::GitHub))?;
            assert_eq!(
                project_name, "houseabsolute/precious",
                "got the right project from the --url",
            );
            assert_eq!(forge_type, ForgeType::GitHub);
        }

        Ok(())
    }

    #[rstest]
    #[case::precious(None, "houseabsolute/precious", "precious")]
    #[case::foo(Some("foo"), "houseabsolute/precious", "foo")]
    #[case::terra_transformer(
        None,
        "https://gitlab.com/gitlab-com/gl-infra/terra-transformer",
        "terra-transformer"
    )]
    fn expect_exe_stem_name(
        #[case] exe: Option<&'static str>,
        #[case] project_name: &'static str,
        #[case] expect: &'static str,
    ) {
        assert_eq!(super::expect_exe_stem_name(exe, project_name), expect);
    }

    #[test]
    fn min_age_days_zero_validation() {
        let result = UbiBuilder::new()
            .project("houseabsolute/ubi")
            .min_age_days(0)
            .build();

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("min_age_days must be a positive number"));
    }
}