lib.rs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. pub use self::context::{context_codegen, ContextData};
  5. use std::{
  6. borrow::Cow,
  7. path::{Path, PathBuf},
  8. };
  9. pub use tauri_utils::config::{parse::ConfigError, Config};
  10. mod context;
  11. pub mod embedded_assets;
  12. #[doc(hidden)]
  13. pub mod vendor;
  14. /// Represents all the errors that can happen while reading the config during codegen.
  15. #[derive(Debug, thiserror::Error)]
  16. #[non_exhaustive]
  17. pub enum CodegenConfigError {
  18. #[error("unable to access current working directory: {0}")]
  19. CurrentDir(std::io::Error),
  20. // this error should be "impossible" because we use std::env::current_dir() - cover it anyways
  21. #[error("Tauri config file has no parent, this shouldn't be possible. file an issue on https://github.com/tauri-apps/tauri - target {0}")]
  22. Parent(PathBuf),
  23. #[error("unable to parse inline JSON TAURI_CONFIG env var: {0}")]
  24. FormatInline(serde_json::Error),
  25. #[error("{0}")]
  26. ConfigError(#[from] ConfigError),
  27. }
  28. /// Get the [`Config`] from the `TAURI_CONFIG` environmental variable, or read from the passed path.
  29. ///
  30. /// If the passed path is relative, it should be relative to the current working directory of the
  31. /// compiling crate.
  32. pub fn get_config(path: &Path) -> Result<(Config, PathBuf), CodegenConfigError> {
  33. let path = if path.is_relative() {
  34. let cwd = std::env::current_dir().map_err(CodegenConfigError::CurrentDir)?;
  35. Cow::Owned(cwd.join(path))
  36. } else {
  37. Cow::Borrowed(path)
  38. };
  39. // in the future we may want to find a way to not need the TAURI_CONFIG env var so that
  40. // it is impossible for the content of two separate configs to get mixed up. The chances are
  41. // already unlikely unless the developer goes out of their way to run the cli on a different
  42. // project than the target crate.
  43. let config = if let Ok(env) = std::env::var("TAURI_CONFIG") {
  44. serde_json::from_str(&env).map_err(CodegenConfigError::FormatInline)?
  45. } else {
  46. tauri_utils::config::parse(path.to_path_buf())?
  47. };
  48. // this should be impossible because of the use of `current_dir()` above, but handle it anyways
  49. let parent = path
  50. .parent()
  51. .map(ToOwned::to_owned)
  52. .ok_or_else(|| CodegenConfigError::Parent(path.into_owned()))?;
  53. Ok((config, parent))
  54. }