ソースを参照

fix(cli): fix printing paths on Windows (#6137)

Amr Bashir 2 年 前
コミット
9da996073f

+ 7 - 0
.changes/cli-windows-paths-print.md

@@ -0,0 +1,7 @@
+---
+"cli.rs": "patch"
+"tauri-bundler": "patch"
+---
+
+On Windows, printing consistent paths on Windows with backslashs only.
+

+ 13 - 1
core/tauri-utils/src/lib.rs

@@ -5,7 +5,10 @@
 //! Tauri utility helpers
 #![warn(missing_docs, rust_2018_idioms)]
 
-use std::fmt::Display;
+use std::{
+  fmt::Display,
+  path::{Path, PathBuf},
+};
 
 use semver::Version;
 use serde::{Deserialize, Deserializer, Serialize, Serializer};
@@ -294,3 +297,12 @@ macro_rules! debug_eprintln {
     $crate::consume_unused_variable!($($arg)*);
   };
 }
+
+/// Reconstructs a path from its components using the platform separator then converts it to String
+pub fn display_path<P: AsRef<Path>>(p: P) -> String {
+  p.as_ref()
+    .components()
+    .collect::<PathBuf>()
+    .display()
+    .to_string()
+}

+ 3 - 1
tooling/bundler/src/bundle.rs

@@ -15,6 +15,8 @@ mod settings;
 mod updater_bundle;
 mod windows;
 
+use tauri_utils::display_path;
+
 pub use self::{
   category::AppCategory,
   settings::{
@@ -101,7 +103,7 @@ pub fn bundle_project(settings: Settings) -> crate::Result<Vec<Bundle>> {
       if bundle.package_type == crate::PackageType::Updater {
         note = " (updater)";
       }
-      writeln!(printable_paths, "        {}{}", path.display(), note).unwrap();
+      writeln!(printable_paths, "        {}{}", display_path(path), note).unwrap();
     }
   }
 

+ 4 - 3
tooling/bundler/src/bundle/updater_bundle.rs

@@ -21,6 +21,7 @@ use crate::{
   },
   Settings,
 };
+use tauri_utils::display_path;
 
 use std::{
   fs::{self, File},
@@ -93,7 +94,7 @@ fn bundle_update_macos(settings: &Settings, bundles: &[Bundle]) -> crate::Result
   create_tar(source_path, &osx_archived_path)
     .with_context(|| "Failed to tar.gz update directory")?;
 
-  info!(action = "Bundling"; "{} ({})", osx_archived, osx_archived_path.display());
+  info!(action = "Bundling"; "{} ({})", osx_archived, display_path(&osx_archived_path));
 
   Ok(vec![osx_archived_path])
 }
@@ -135,7 +136,7 @@ fn bundle_update_linux(settings: &Settings, bundles: &[Bundle]) -> crate::Result
   create_tar(source_path, &appimage_archived_path)
     .with_context(|| "Failed to tar.gz update directory")?;
 
-  info!(action = "Bundling"; "{} ({})", appimage_archived, appimage_archived_path.display());
+  info!(action = "Bundling"; "{} ({})", appimage_archived, display_path(&appimage_archived_path));
 
   Ok(vec![appimage_archived_path])
 }
@@ -216,7 +217,7 @@ fn bundle_update_windows(settings: &Settings, bundles: &[Bundle]) -> crate::Resu
         });
     let archived_path = archived_path.with_extension(format!("{}.zip", bundle_name));
 
-    info!(action = "Bundling"; "{}", archived_path.display());
+    info!(action = "Bundling"; "{}", display_path(&archived_path));
 
     // Create our gzip file
     create_zip(&source_path, &archived_path).with_context(|| "Failed to zip update bundle")?;

+ 5 - 4
tooling/bundler/src/bundle/windows/msi/wix.rs

@@ -25,6 +25,7 @@ use std::{
   path::{Path, PathBuf},
   process::Command,
 };
+use tauri_utils::display_path;
 use tauri_utils::{config::WebviewInstallMode, resources::resource_relpath};
 use uuid::Uuid;
 
@@ -313,7 +314,7 @@ fn run_candle(
     wxs_file_path.to_string_lossy().to_string(),
     format!(
       "-dSourceDir={}",
-      settings.binary_path(main_binary).display()
+      display_path(settings.binary_path(main_binary))
     ),
   ];
 
@@ -361,7 +362,7 @@ fn run_light(
     "-ext".to_string(),
     "WixUtilExtension".to_string(),
     "-o".to_string(),
-    output_path.display().to_string(),
+    display_path(output_path),
   ];
 
   args.extend(arguments);
@@ -799,14 +800,14 @@ pub fn build_wix_app_installer(
         }
       ),
       "-loc".into(),
-      locale_path.display().to_string(),
+      display_path(&locale_path),
       "*.wixobj".into(),
     ];
     let msi_output_path = output_path.join("output.msi");
     let msi_path = app_installer_output_path(settings, &language, &app_version, updater)?;
     create_dir_all(msi_path.parent().unwrap())?;
 
-    info!(action = "Running"; "light to produce {}", msi_path.display());
+    info!(action = "Running"; "light to produce {}", display_path(&msi_path));
 
     run_light(
       wix_toolset_path,

+ 2 - 1
tooling/bundler/src/bundle/windows/nsis.rs

@@ -15,6 +15,7 @@ use crate::{
   },
   Settings,
 };
+use tauri_utils::display_path;
 
 use anyhow::Context;
 use handlebars::{to_json, Handlebars};
@@ -385,7 +386,7 @@ fn build_nsis_app_installer(
   ));
   create_dir_all(nsis_installer_path.parent().unwrap())?;
 
-  info!(action = "Running"; "makensis.exe to produce {}", nsis_installer_path.display());
+  info!(action = "Running"; "makensis.exe to produce {}", display_path(&nsis_installer_path));
 
   #[cfg(target_os = "windows")]
   let mut nsis_cmd = Command::new(_nsis_toolset_path.join("makensis.exe"));

+ 3 - 1
tooling/bundler/src/bundle/windows/util.rs

@@ -75,8 +75,10 @@ fn verify(data: &Vec<u8>, hash: &str, mut hasher: impl Digest) -> crate::Result<
 
 #[cfg(target_os = "windows")]
 pub fn try_sign(file_path: &PathBuf, settings: &Settings) -> crate::Result<()> {
+  use tauri_utils::display_path;
+
   if let Some(certificate_thumbprint) = settings.windows().certificate_thumbprint.as_ref() {
-    info!(action = "Signing"; "{}", file_path.display());
+    info!(action = "Signing"; "{}", display_path(file_path));
     sign(
       file_path,
       &SignParams {

+ 1 - 1
tooling/cli/src/build.rs

@@ -393,7 +393,7 @@ fn print_signed_updater_archive(output_paths: &[PathBuf]) -> crate::Result<()> {
     #[cfg(windows)]
     info!(
       "        {}",
-      path.display().to_string().replacen(r"\\?\", "", 1)
+      tauri_utils::display_path(path).replacen(r"\\?\", "", 1)
     );
   }
   Ok(())

+ 5 - 5
tooling/cli/src/info.rs

@@ -288,7 +288,7 @@ fn webview2_version() -> crate::Result<Option<String>> {
   );
   // check 64bit machine-wide installation
   let output = Command::new(&powershell_path)
-      .args(&["-NoProfile", "-Command"])
+      .args(["-NoProfile", "-Command"])
       .arg("Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' | ForEach-Object {$_.pv}")
       .output()?;
   if output.status.success() {
@@ -298,7 +298,7 @@ fn webview2_version() -> crate::Result<Option<String>> {
   }
   // check 32bit machine-wide installation
   let output = Command::new(&powershell_path)
-        .args(&["-NoProfile", "-Command"])
+        .args(["-NoProfile", "-Command"])
         .arg("Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' | ForEach-Object {$_.pv}")
         .output()?;
   if output.status.success() {
@@ -308,7 +308,7 @@ fn webview2_version() -> crate::Result<Option<String>> {
   }
   // check user-wide installation
   let output = Command::new(&powershell_path)
-      .args(&["-NoProfile", "-Command"])
+      .args(["-NoProfile", "-Command"])
       .arg("Get-ItemProperty -Path 'HKCU:\\SOFTWARE\\Microsoft\\EdgeUpdate\\Clients\\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}' | ForEach-Object {$_.pv}")
       .output()?;
   if output.status.success() {
@@ -342,7 +342,7 @@ fn build_tools_version() -> crate::Result<Option<Vec<String>>> {
     }
   }
   let output = cross_command(vswhere.to_str().unwrap())
-    .args(&[
+    .args([
       "-prerelease",
       "-products",
       "*",
@@ -636,7 +636,7 @@ pub fn command(_options: Options) -> Result<()> {
       InfoBlock::new("MSVC", "").display();
       for i in build_tools {
         indent(6);
-        println!("{}", format!("{} {}", "-".cyan(), i));
+        println!("{} {}", "-".cyan(), i);
       }
     }
   }

+ 4 - 6
tooling/cli/src/interface/rust.rs

@@ -37,6 +37,7 @@ use crate::helpers::{
   app_paths::{app_dir, tauri_dir},
   config::{nsis_settings, reload as reload_config, wix_settings, Config},
 };
+use tauri_utils::display_path;
 
 mod cargo_config;
 mod desktop;
@@ -431,10 +432,10 @@ impl Rust {
     .unwrap();
     for path in watch_folders {
       if !ignore_matcher.is_ignore(path, true) {
-        info!("Watching {} for changes...", path.display());
+        info!("Watching {} for changes...", display_path(path));
         lookup(path, |file_type, p| {
           if p != path {
-            debug!("Watching {} for changes...", p.display());
+            debug!("Watching {} for changes...", display_path(&p));
             let _ = watcher.watcher().watch(
               &p,
               if file_type.is_dir() {
@@ -474,10 +475,7 @@ impl Rust {
             } else {
               info!(
                 "File {} changed. Rebuilding application...",
-                event_path
-                  .strip_prefix(app_path)
-                  .unwrap_or(&event_path)
-                  .display()
+                display_path(event_path.strip_prefix(app_path).unwrap_or(&event_path))
               );
               // When tauri.conf.json is changed, rewrite_manifest will be called
               // which will trigger the watcher again

+ 17 - 7
tooling/cli/src/interface/rust/cargo_config.rs

@@ -5,6 +5,8 @@ use std::{
   path::{Path, PathBuf},
 };
 
+use tauri_utils::display_path;
+
 struct PathAncestors<'a> {
   current: Option<&'a Path>,
 }
@@ -51,10 +53,18 @@ impl Config {
     let mut config = Self::default();
 
     let get_config = |path: PathBuf| -> Result<ConfigSchema> {
-      let contents = fs::read_to_string(&path)
-        .with_context(|| format!("failed to read configuration file `{}`", path.display()))?;
-      toml::from_str(&contents)
-        .with_context(|| format!("could not parse TOML configuration in `{}`", path.display()))
+      let contents = fs::read_to_string(&path).with_context(|| {
+        format!(
+          "failed to read configuration file `{}`",
+          display_path(&path)
+        )
+      })?;
+      toml::from_str(&contents).with_context(|| {
+        format!(
+          "could not parse TOML configuration in `{}`",
+          display_path(&path)
+        )
+      })
     };
 
     for current in PathAncestors::new(path) {
@@ -121,9 +131,9 @@ fn get_file_path(
       if !skip_warning {
         log::warn!(
           "Both `{}` and `{}` exist. Using `{}`",
-          possible.display(),
-          possible_with_extension.display(),
-          possible.display()
+          display_path(&possible),
+          display_path(&possible_with_extension),
+          display_path(&possible)
         );
       }
     }

+ 3 - 2
tooling/cli/src/interface/rust/desktop.rs

@@ -1,5 +1,6 @@
 use super::{AppSettings, DevChild, ExitReason, Options, RustAppSettings, Target};
 use crate::CommandExt;
+use tauri_utils::display_path;
 
 use anyhow::Context;
 use heck::ToKebabCase;
@@ -365,8 +366,8 @@ fn rename_app(
     rename(bin_path, &product_path).with_context(|| {
       format!(
         "failed to rename `{}` to `{}`",
-        bin_path.display(),
-        product_path.display(),
+        display_path(bin_path),
+        display_path(&product_path),
       )
     })?;
     Ok(product_path)

+ 3 - 2
tooling/cli/src/signer/generate.rs

@@ -8,6 +8,7 @@ use crate::{
 };
 use clap::Parser;
 use std::path::PathBuf;
+use tauri_utils::display_path;
 
 #[derive(Debug, Parser)]
 #[clap(about = "Generate keypair to sign files")]
@@ -42,8 +43,8 @@ pub fn command(mut options: Options) -> Result<()> {
 
     println!(
         "\nYour keypair was generated successfully\nPrivate: {} (Keep it secret!)\nPublic: {}\n---------------------------",
-        secret_path.display(),
-        public_path.display()
+        display_path(secret_path),
+        display_path(public_path)
         )
   } else {
     println!(

+ 2 - 1
tooling/cli/src/signer/sign.rs

@@ -10,6 +10,7 @@ use crate::{
 };
 use anyhow::Context;
 use clap::Parser;
+use tauri_utils::display_path;
 
 #[derive(Debug, Parser)]
 #[clap(about = "Sign a file")]
@@ -51,7 +52,7 @@ pub fn command(mut options: Options) -> Result<()> {
 
   println!(
            "\nYour file was signed successfully, You can find the signature here:\n{}\n\nPublic signature:\n{}\n\nMake sure to include this into the signature field of your update server.",
-           manifest_dir.display(),
+           display_path(manifest_dir),
            base64::encode(signature.to_string())
          );