Browse Source

feat(build): create `dev` alias (#4212)

Lucas Fernandes Nogueira 3 years ago
parent
commit
9cdcf9b3a8

+ 5 - 0
.changes/dev-alias.md

@@ -0,0 +1,5 @@
+---
+"tauri-build": patch
+---
+
+Create `dev` cfg alias.

+ 1 - 0
core/tauri-build/Cargo.toml

@@ -23,6 +23,7 @@ tauri-codegen = { version = "1.0.0-rc.7", path = "../tauri-codegen", optional =
 tauri-utils = { version = "1.0.0-rc.7", path = "../tauri-utils", features = [ "build", "resources" ] }
 cargo_toml = "0.11"
 serde_json = "1"
+heck = "0.4"
 
 [target."cfg(windows)".dependencies]
 winres = "0.1"

+ 23 - 0
core/tauri-build/src/lib.rs

@@ -5,6 +5,7 @@
 #![cfg_attr(doc_cfg, feature(doc_cfg))]
 
 pub use anyhow::Result;
+use heck::ToSnakeCase;
 use tauri_utils::resources::{external_binaries, resource_relpath, ResourcePaths};
 
 use std::path::{Path, PathBuf};
@@ -61,6 +62,26 @@ fn copy_resources(resources: ResourcePaths<'_>, path: &Path) -> Result<()> {
   Ok(())
 }
 
+// checks if the given Cargo feature is enabled.
+fn has_feature(feature: &str) -> bool {
+  // when a feature is enabled, Cargo sets the `CARGO_FEATURE_<name` env var to 1
+  // https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts
+  std::env::var(format!(
+    "CARGO_FEATURE_{}",
+    feature.to_snake_case().to_uppercase()
+  ))
+  .map(|x| x == "1")
+  .unwrap_or(false)
+}
+
+// creates a cfg alias if `has_feature` is true.
+// `alias` must be a snake case string.
+fn cfg_alias(alias: &str, has_feature: bool) {
+  if has_feature {
+    println!("cargo:rustc-cfg={}", alias);
+  }
+}
+
 /// Attributes used on Windows.
 #[allow(dead_code)]
 #[derive(Debug, Default)]
@@ -163,6 +184,8 @@ pub fn try_build(attributes: Attributes) -> Result<()> {
     )?)?
   };
 
+  cfg_alias("dev", !has_feature("custom-protocol"));
+
   let mut manifest = Manifest::from_path("Cargo.toml")?;
   if let Some(tauri) = manifest.dependencies.remove("tauri") {
     let features = match tauri {

+ 1 - 1
core/tauri/src/manager.rs

@@ -338,7 +338,7 @@ impl<R: Runtime> WindowManager<R> {
   ///
   /// * In dev mode, this will be based on the `devPath` configuration value.
   /// * Otherwise, this will be based on the `distDir` configuration value.
-  #[cfg(custom_protocol)]
+  #[cfg(not(dev))]
   fn base_path(&self) -> &AppUrl {
     &self.inner.config.build.dist_dir
   }

+ 2 - 1
examples/api/src-tauri/Cargo.lock

@@ -3052,7 +3052,7 @@ dependencies = [
 
 [[package]]
 name = "tauri"
-version = "1.0.0-rc.12"
+version = "1.0.0-rc.13"
 dependencies = [
  "anyhow",
  "attohttpc",
@@ -3117,6 +3117,7 @@ version = "1.0.0-rc.10"
 dependencies = [
  "anyhow",
  "cargo_toml",
+ "heck 0.4.0",
  "semver 1.0.9",
  "serde_json",
  "tauri-codegen",