tauri_codegen/
lib.rs

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