topgrade 17.4.0

Upgrade all the things
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
use std::fmt::Display;
#[cfg(target_os = "linux")]
use std::os::unix::fs::MetadataExt;
use std::path::PathBuf;

use crate::HOME_DIR;
use color_eyre::eyre::Result;
#[cfg(target_os = "linux")]
use nix::unistd::Uid;
use rust_i18n::t;
use semver::Version;
use tracing::debug;

use crate::command::CommandExt;
use crate::terminal::{print_info, print_separator};
use crate::utils::{PathExt, require};
use crate::{error::SkipStep, execution_context::ExecutionContext};

enum NPMVariant {
    Npm,
    Pnpm,
}

impl NPMVariant {
    const fn short_name(&self) -> &str {
        match self {
            NPMVariant::Npm => "npm",
            NPMVariant::Pnpm => "pnpm",
        }
    }

    const fn is_npm(&self) -> bool {
        matches!(self, NPMVariant::Npm)
    }
}

impl Display for NPMVariant {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.short_name())
    }
}

#[allow(clippy::upper_case_acronyms)]
struct NPM {
    command: PathBuf,
    variant: NPMVariant,
}

impl NPM {
    fn new(command: PathBuf, variant: NPMVariant) -> Self {
        Self { command, variant }
    }

    /// Is the "NPM" version larger than 8.11.0?
    fn is_npm_8(&self, ctx: &ExecutionContext) -> bool {
        let v = self.version(ctx);

        self.variant.is_npm() && matches!(v, Ok(v) if v >= Version::new(8, 11, 0))
    }

    /// Get the most suitable "global location" argument
    /// of this NPM instance.
    ///
    /// If the "NPM" version is larger than 8.11.0, we use
    /// `--location=global`; otherwise, use `-g`.
    fn global_location_arg(&self, ctx: &ExecutionContext) -> &str {
        if self.is_npm_8(ctx) { "--location=global" } else { "-g" }
    }

    #[cfg(target_os = "linux")]
    fn root(&self, ctx: &ExecutionContext) -> Result<PathBuf> {
        let args = ["root", self.global_location_arg(ctx)];
        ctx.execute(&self.command)
            .always()
            .args(args)
            .output_checked_utf8()
            .map(|s| PathBuf::from(s.stdout.trim()))
    }

    fn version(&self, ctx: &ExecutionContext) -> Result<Version> {
        let version_str = ctx
            .execute(&self.command)
            .always()
            .args(["--version"])
            .output_checked_utf8()
            .map(|s| s.stdout.trim().to_owned());
        Version::parse(&version_str?).map_err(std::convert::Into::into)
    }

    fn upgrade(&self, ctx: &ExecutionContext, use_sudo: bool) -> Result<()> {
        let args = ["update", self.global_location_arg(ctx)];
        if use_sudo {
            let sudo = ctx.require_sudo()?;
            sudo.execute(ctx, &self.command)?.args(args).status_checked()?;
        } else {
            ctx.execute(&self.command).args(args).status_checked()?;
        }

        Ok(())
    }

    #[cfg(target_os = "linux")]
    pub fn should_use_sudo(&self, ctx: &ExecutionContext) -> Result<bool> {
        let npm_root = self.root(ctx)?;
        if !npm_root.exists() {
            return Err(SkipStep(format!("{} root at {} doesn't exist", self.variant, npm_root.display())).into());
        }

        let metadata = std::fs::metadata(&npm_root)?;
        let uid = Uid::effective();

        Ok(metadata.uid() != uid.as_raw() && metadata.uid() == 0)
    }
}

struct Yarn {
    command: PathBuf,
}

impl Yarn {
    fn new(command: PathBuf) -> Self {
        Self { command }
    }

    fn has_global_subcmd(&self, ctx: &ExecutionContext) -> bool {
        // Get the version of Yarn. After Yarn 2.x (berry),
        // "yarn global" has been replaced with "yarn dlx".
        //
        // As "yarn dlx" don't need to "upgrade", we
        // ignore the whole task if Yarn is 2.x or above.
        let version = ctx
            .execute(&self.command)
            .always()
            .args(["--version"])
            .output_checked_utf8();

        matches!(version, Ok(ver) if ver.stdout.starts_with('1') || ver.stdout.starts_with('0'))
    }

    #[cfg(target_os = "linux")]
    fn root(&self, ctx: &ExecutionContext) -> Result<PathBuf> {
        let args = ["global", "dir"];
        ctx.execute(&self.command)
            .always()
            .args(args)
            .output_checked_utf8()
            .map(|s| PathBuf::from(s.stdout.trim()))
    }

    fn upgrade(&self, ctx: &ExecutionContext, use_sudo: bool) -> Result<()> {
        let args = ["global", "upgrade"];

        if use_sudo {
            let sudo = ctx.require_sudo()?;
            sudo.execute(ctx, &self.command)?.args(args).status_checked()?;
        } else {
            ctx.execute(&self.command).args(args).status_checked()?;
        }

        Ok(())
    }

    #[cfg(target_os = "linux")]
    pub fn should_use_sudo(&self, ctx: &ExecutionContext) -> Result<bool> {
        let yarn_root = self.root(ctx)?;
        if !yarn_root.exists() {
            return Err(SkipStep(format!("Yarn root at {} doesn't exist", yarn_root.display(),)).into());
        }

        let metadata = std::fs::metadata(&yarn_root)?;
        let uid = Uid::effective();

        Ok(metadata.uid() != uid.as_raw() && metadata.uid() == 0)
    }
}

struct Deno {
    command: PathBuf,
}

impl Deno {
    fn new(command: PathBuf) -> Self {
        Self { command }
    }

    fn upgrade(&self, ctx: &ExecutionContext) -> Result<()> {
        let mut args = vec![];

        let version = ctx.config().deno_version();
        if let Some(version) = version {
            let bin_version = self.version(ctx)?;

            if bin_version >= Version::new(2, 0, 0) {
                args.push(version);
            } else if bin_version >= Version::new(1, 6, 0) {
                match version {
                    "stable" => { /* do nothing, as stable is the default channel to upgrade */ }
                    "rc" => {
                        return Err(SkipStep(
                            "Deno (1.6.0-2.0.0) cannot be upgraded to a release candidate".to_string(),
                        )
                        .into());
                    }
                    "canary" => args.push("--canary"),
                    _ => {
                        if Version::parse(version).is_err() {
                            return Err(SkipStep("Invalid Deno version".to_string()).into());
                        }

                        args.push("--version");
                        args.push(version);
                    }
                }
            } else if bin_version >= Version::new(1, 0, 0) {
                match version {
                    "stable" | "rc" | "canary" => {
                        // Prior to v1.6.0, `deno upgrade` is not able fetch the latest tag version.
                        return Err(
                            SkipStep("Deno (1.0.0-1.6.0) cannot be upgraded to a named channel".to_string()).into(),
                        );
                    }
                    _ => {
                        if Version::parse(version).is_err() {
                            return Err(SkipStep("Invalid Deno version".to_string()).into());
                        }

                        args.push("--version");
                        args.push(version);
                    }
                }
            } else {
                // v0.x cannot be upgraded with `deno upgrade` to v1.x or v2.x
                // nor can be upgraded to a specific version.
                return Err(SkipStep("Unsupported Deno version".to_string()).into());
            }
        }

        ctx.execute(&self.command).arg("upgrade").args(args).status_checked()?;
        Ok(())
    }

    /// Get the version of Deno.
    ///
    /// This function will return the version of Deno installed on the system.
    /// The version is parsed from the output of `deno -V`.
    ///
    /// ```sh
    /// deno -V # deno 1.6.0
    /// ```
    fn version(&self, ctx: &ExecutionContext) -> Result<Version> {
        let version_str = ctx
            .execute(&self.command)
            .always()
            .args(["-V"])
            .output_checked_utf8()
            .map(|s| s.stdout.trim().to_owned().split_off(5)); // remove "deno " prefix
        Version::parse(&version_str?).map_err(std::convert::Into::into)
    }
}

struct VitePlus {
    command: PathBuf,
}

impl VitePlus {
    fn new(command: PathBuf) -> Self {
        Self { command }
    }

    fn self_upgrade(&self, ctx: &ExecutionContext, use_sudo: bool) -> Result<()> {
        let mut args = vec!["upgrade"];

        if ctx.run_type().dry() {
            args.push("--check");
        }

        if use_sudo {
            let sudo = ctx.require_sudo()?;
            sudo.execute(ctx, &self.command)?.args(args).status_checked()?;
        } else {
            ctx.execute(&self.command).args(args).status_checked()?;
        }

        Ok(())
    }

    fn upgrade_packages(&self, ctx: &ExecutionContext, use_sudo: bool) -> Result<()> {
        let args = ["update", "--global"];

        if use_sudo {
            let sudo = ctx.require_sudo()?;
            sudo.execute(ctx, &self.command)?.args(args).status_checked()?;
        } else {
            ctx.execute(&self.command).args(args).status_checked()?;
        }

        Ok(())
    }

    #[cfg(target_os = "linux")]
    pub fn should_use_sudo(&self, _ctx: &ExecutionContext) -> Result<bool> {
        let vp_home = match std::env::var_os("VP_HOME") {
            None => return Ok(false),
            Some(s) if s.is_empty() => return Ok(false),
            Some(s) => s,
        };

        let uid = Uid::effective();
        let metadata = std::fs::metadata(&vp_home)?;

        Ok(metadata.uid() != uid.as_raw() && metadata.uid() == 0)
    }
}

#[cfg(target_os = "linux")]
fn should_use_sudo(npm: &NPM, ctx: &ExecutionContext) -> Result<bool> {
    if npm.should_use_sudo(ctx)? {
        if ctx.config().npm_use_sudo() {
            Ok(true)
        } else {
            Err(SkipStep(format!("{} root is owned by another user which is not the current user. Set use_sudo = true under the [npm] section in your configuration to run {} as sudo", npm.variant, npm.variant))
                .into())
        }
    } else {
        Ok(false)
    }
}

#[cfg(target_os = "linux")]
fn should_use_sudo_viteplus(viteplus: &VitePlus, ctx: &ExecutionContext) -> Result<bool> {
    if viteplus.should_use_sudo(ctx)? {
        if ctx.config().viteplus_use_sudo() {
            Ok(true)
        } else {
            Err(SkipStep("Vite+ root is owned by another user which is not the current user. Set use_sudo = true under the [viteplus] section in your configuration to run Vite+ as sudo".to_string())
                .into())
        }
    } else {
        Ok(false)
    }
}

#[cfg(target_os = "linux")]
fn should_use_sudo_yarn(yarn: &Yarn, ctx: &ExecutionContext) -> Result<bool> {
    if yarn.should_use_sudo(ctx)? {
        if ctx.config().yarn_use_sudo() {
            Ok(true)
        } else {
            Err(SkipStep("Yarn root is owned by another user which is not the current user. Set use_sudo = true under the [yarn] section in your configuration to run Yarn as sudo".to_string())
                .into())
        }
    } else {
        Ok(false)
    }
}

pub fn run_npm_upgrade(ctx: &ExecutionContext) -> Result<()> {
    let npm = require("npm").map(|b| NPM::new(b, NPMVariant::Npm))?;

    print_separator(t!("Node Package Manager"));

    #[cfg(target_os = "linux")]
    {
        npm.upgrade(ctx, should_use_sudo(&npm, ctx)?)
    }

    #[cfg(not(target_os = "linux"))]
    {
        npm.upgrade(ctx, false)
    }
}

pub fn run_pnpm_upgrade(ctx: &ExecutionContext) -> Result<()> {
    let pnpm = require("pnpm").map(|b| NPM::new(b, NPMVariant::Pnpm))?;

    print_separator(t!("Performant Node Package Manager"));

    #[cfg(target_os = "linux")]
    {
        pnpm.upgrade(ctx, should_use_sudo(&pnpm, ctx)?)
    }

    #[cfg(not(target_os = "linux"))]
    {
        pnpm.upgrade(ctx, false)
    }
}

pub fn run_viteplus_upgrade(ctx: &ExecutionContext) -> Result<()> {
    let viteplus = require("vp").map(VitePlus::new)?;

    // This is upstream's preferred branding for the tool
    print_separator("Vite+");

    let use_sudo;

    #[cfg(target_os = "linux")]
    {
        use_sudo = should_use_sudo_viteplus(&viteplus, ctx)?;
    }

    #[cfg(not(target_os = "linux"))]
    {
        use_sudo = false;
    }

    viteplus.self_upgrade(ctx, use_sudo)?;
    viteplus.upgrade_packages(ctx, use_sudo)?;

    Ok(())
}

pub fn run_yarn_upgrade(ctx: &ExecutionContext) -> Result<()> {
    let yarn = require("yarn").map(Yarn::new)?;

    if !yarn.has_global_subcmd(ctx) {
        debug!("Yarn is 2.x or above, skipping global upgrade");
        return Ok(());
    }

    print_separator(t!("Yarn Package Manager"));

    #[cfg(target_os = "linux")]
    {
        yarn.upgrade(ctx, should_use_sudo_yarn(&yarn, ctx)?)
    }

    #[cfg(not(target_os = "linux"))]
    {
        yarn.upgrade(ctx, false)
    }
}

pub fn deno_upgrade(ctx: &ExecutionContext) -> Result<()> {
    let deno = require("deno").map(Deno::new)?;
    let deno_dir = HOME_DIR.join(".deno");

    if !deno.command.canonicalize()?.is_descendant_of(&deno_dir) {
        let skip_reason = SkipStep(t!("Deno installed outside of .deno directory").to_string());
        return Err(skip_reason.into());
    }

    print_separator("Deno");
    deno.upgrade(ctx)
}

/// There is no `volta upgrade` command, so we need to upgrade each package
pub fn run_volta_packages_upgrade(ctx: &ExecutionContext) -> Result<()> {
    let volta = require("volta")?;

    print_separator("Volta");

    if ctx.run_type().dry() {
        print_info(t!("Updating Volta packages..."));
        return Ok(());
    }

    let list_output = ctx
        .execute(&volta)
        .always()
        .args(["list", "--format=plain"])
        .output_checked_utf8()?
        .stdout;

    let installed_packages: Vec<&str> = list_output
        .lines()
        .filter_map(|line| {
            // format is 'kind package@version ...'
            let mut parts = line.split_whitespace();
            parts.next();
            let package_part = parts.next()?;
            let version_index = package_part.rfind('@').unwrap_or(package_part.len());
            Some(package_part[..version_index].trim())
        })
        .collect();

    if installed_packages.is_empty() {
        print_info(t!("No packages installed with Volta"));
        return Ok(());
    }

    for package in &installed_packages {
        ctx.execute(&volta).args(["install", package]).status_checked()?;
    }

    Ok(())
}