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
use serde::Deserialize;

use once_cell::sync::OnceCell;
use std::collections::HashMap;

static CONFIG: OnceCell<Config> = OnceCell::new();

#[derive(PartialEq, Deserialize, Debug)]
#[serde(tag = "window", rename_all = "camelCase")]
pub struct WindowConfig {
  #[serde(default = "default_width")]
  pub width: i32,
  #[serde(default = "default_height")]
  pub height: i32,
  #[serde(default = "default_resizable")]
  pub resizable: bool,
  #[serde(default = "default_title")]
  pub title: String,
  #[serde(default)]
  pub fullscreen: bool,
}

fn default_width() -> i32 {
  800
}

fn default_height() -> i32 {
  600
}

fn default_resizable() -> bool {
  true
}

fn default_title() -> String {
  "Tauri App".to_string()
}

fn default_window() -> WindowConfig {
  WindowConfig {
    width: default_width(),
    height: default_height(),
    resizable: default_resizable(),
    title: default_title(),
    fullscreen: false,
  }
}

#[derive(PartialEq, Deserialize, Debug)]
#[serde(tag = "embeddedServer", rename_all = "camelCase")]
pub struct EmbeddedServerConfig {
  #[serde(default = "default_host")]
  pub host: String,
  #[serde(default = "default_port")]
  pub port: String,
}

fn default_host() -> String {
  "http://127.0.0.1".to_string()
}

fn default_port() -> String {
  "random".to_string()
}

fn default_embedded_server() -> EmbeddedServerConfig {
  EmbeddedServerConfig {
    host: default_host(),
    port: default_port(),
  }
}

#[derive(PartialEq, Deserialize, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct CliArg {
  pub short: Option<char>,
  pub name: String,
  pub description: Option<String>,
  pub long_description: Option<String>,
  pub takes_value: Option<bool>,
  pub multiple: Option<bool>,
  pub multiple_occurrences: Option<bool>,
  pub number_of_values: Option<u64>,
  pub possible_values: Option<Vec<String>>,
  pub min_values: Option<u64>,
  pub max_values: Option<u64>,
  pub required: Option<bool>,
  pub required_unless: Option<String>,
  pub required_unless_all: Option<Vec<String>>,
  pub required_unless_one: Option<Vec<String>>,
  pub conflicts_with: Option<String>,
  pub conflicts_with_all: Option<Vec<String>>,
  pub requires: Option<String>,
  pub requires_all: Option<Vec<String>>,
  pub requires_if: Option<Vec<String>>,
  pub required_if: Option<Vec<String>>,
  pub require_equals: Option<bool>,
  pub index: Option<u64>,
}

#[derive(PartialEq, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct CliSubcommand {
  description: Option<String>,
  long_description: Option<String>,
  before_help: Option<String>,
  after_help: Option<String>,
  args: Option<Vec<CliArg>>,
  subcommands: Option<HashMap<String, CliSubcommand>>,
}

#[derive(PartialEq, Deserialize, Debug)]
#[serde(tag = "cli", rename_all = "camelCase")]
pub struct CliConfig {
  description: Option<String>,
  long_description: Option<String>,
  before_help: Option<String>,
  after_help: Option<String>,
  args: Option<Vec<CliArg>>,
  subcommands: Option<HashMap<String, CliSubcommand>>,
}

pub trait Cli {
  fn args(&self) -> Option<&Vec<CliArg>>;
  fn subcommands(&self) -> Option<&HashMap<String, CliSubcommand>>;
  fn description(&self) -> Option<&String>;
  fn long_description(&self) -> Option<&String>;
  fn before_help(&self) -> Option<&String>;
  fn after_help(&self) -> Option<&String>;
}

macro_rules! impl_cli {
  ( $($field_name:ident),+ $(,)?) => {
    $(
      impl Cli for $field_name {

        fn args(&self) -> Option<&Vec<CliArg>> {
          self.args.as_ref()
        }

        fn subcommands(&self) -> Option<&HashMap<String, CliSubcommand>> {
          self.subcommands.as_ref()
        }

        fn description(&self) -> Option<&String> {
          self.description.as_ref()
        }

        fn long_description(&self) -> Option<&String> {
          self.description.as_ref()
        }

        fn before_help(&self) -> Option<&String> {
          self.before_help.as_ref()
        }

        fn after_help(&self) -> Option<&String> {
          self.after_help.as_ref()
        }
      }
    )+
  }
}

#[derive(PartialEq, Deserialize, Debug)]
#[serde(tag = "bundle", rename_all = "camelCase")]
pub struct BundleConfig {
  pub identifier: String,
}

fn default_bundle() -> BundleConfig {
  BundleConfig {
    identifier: String::from(""),
  }
}

impl_cli!(CliSubcommand, CliConfig);

#[derive(PartialEq, Deserialize, Debug)]
#[serde(tag = "tauri", rename_all = "camelCase")]
pub struct TauriConfig {
  #[serde(default = "default_window")]
  pub window: WindowConfig,
  #[serde(default = "default_embedded_server")]
  pub embedded_server: EmbeddedServerConfig,
  #[serde(default)]
  pub cli: Option<CliConfig>,
  #[serde(default = "default_bundle")]
  pub bundle: BundleConfig,
}

#[derive(PartialEq, Deserialize, Debug)]
#[serde(tag = "build", rename_all = "camelCase")]
pub struct BuildConfig {
  #[serde(default = "default_dev_path")]
  pub dev_path: String,
}

fn default_dev_path() -> String {
  "".to_string()
}

#[derive(PartialEq, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Config {
  #[serde(default = "default_tauri")]
  pub tauri: TauriConfig,
  #[serde(default = "default_build")]
  pub build: BuildConfig,
}

fn default_tauri() -> TauriConfig {
  TauriConfig {
    window: default_window(),
    embedded_server: default_embedded_server(),
    cli: None,
    bundle: default_bundle(),
  }
}

fn default_build() -> BuildConfig {
  BuildConfig {
    dev_path: default_dev_path(),
  }
}

pub fn get() -> crate::Result<&'static Config> {
  if let Some(config) = CONFIG.get() {
    return Ok(config);
  }
  let config: Config = match option_env!("TAURI_CONFIG") {
    Some(config) => serde_json::from_str(config).expect("failed to parse TAURI_CONFIG env"),
    None => {
      let config = include_str!(concat!(env!("OUT_DIR"), "/tauri.conf.json"));
      serde_json::from_str(&config).expect("failed to read tauri.conf.json")
    }
  };

  CONFIG
    .set(config)
    .map_err(|_| anyhow::anyhow!("failed to set CONFIG"))?;

  let config = CONFIG.get().unwrap();
  Ok(config)
}

#[cfg(test)]
mod test {
  use super::*;
  // generate a test_config based on the test fixture
  fn create_test_config() -> Config {
    let mut subcommands = std::collections::HashMap::new();
    subcommands.insert(
      "update".to_string(),
      CliSubcommand {
        description: Some("Updates the app".to_string()),
        long_description: None,
        before_help: None,
        after_help: None,
        args: Some(vec![CliArg {
          short: Some('b'),
          name: "background".to_string(),
          description: Some("Update in background".to_string()),
          ..Default::default()
        }]),
        subcommands: None,
      },
    );
    Config {
      tauri: TauriConfig {
        window: WindowConfig {
          width: 800,
          height: 600,
          resizable: true,
          title: String::from("Tauri API Validation"),
          fullscreen: false,
        },
        embedded_server: EmbeddedServerConfig {
          host: String::from("http://127.0.0.1"),
          port: String::from("random"),
        },
        bundle: BundleConfig {
          identifier: String::from("com.tauri.communication"),
        },
        cli: Some(CliConfig {
          description: Some("Tauri communication example".to_string()),
          long_description: None,
          before_help: None,
          after_help: None,
          args: Some(vec![
            CliArg {
              short: Some('c'),
              name: "config".to_string(),
              takes_value: Some(true),
              description: Some("Config path".to_string()),
              ..Default::default()
            },
            CliArg {
              short: Some('t'),
              name: "theme".to_string(),
              takes_value: Some(true),
              description: Some("App theme".to_string()),
              possible_values: Some(vec![
                "light".to_string(),
                "dark".to_string(),
                "system".to_string(),
              ]),
              ..Default::default()
            },
            CliArg {
              short: Some('v'),
              name: "verbose".to_string(),
              multiple_occurrences: Some(true),
              description: Some("Verbosity level".to_string()),
              ..Default::default()
            },
          ]),
          subcommands: Some(subcommands),
        }),
      },
      build: BuildConfig {
        dev_path: String::from("../dist"),
      },
    }
  }

  #[test]
  // test the get function.  Will only resolve to true if the TAURI_CONFIG variable is set properly to the fixture.
  fn test_get() {
    // get test_config
    let test_config = create_test_config();

    // call get();
    let config = get();

    // check to see if there is an OK or Err, on Err fail test.
    match config {
      // On Ok, check that the config is the same as the test config.
      Ok(c) => {
        println!("{:?}", c);
        assert_eq!(c, &test_config)
      }
      Err(_) => assert!(false),
    }
  }

  #[test]
  // test all of the default functions
  fn test_defaults() {
    // get default tauri config
    let t_config = default_tauri();
    // get default build config
    let b_config = default_build();
    // get default dev path
    let d_path = default_dev_path();
    // get default embedded server
    let de_server = default_embedded_server();
    // get default window
    let d_window = default_window();
    // get default title
    let d_title = default_title();
    // get default bundle
    let d_bundle = default_bundle();

    // create a tauri config.
    let tauri = TauriConfig {
      window: WindowConfig {
        width: 800,
        height: 600,
        resizable: true,
        title: String::from("Tauri App"),
        fullscreen: false,
      },
      embedded_server: EmbeddedServerConfig {
        host: String::from("http://127.0.0.1"),
        port: String::from("random"),
      },
      bundle: BundleConfig {
        identifier: String::from(""),
      },
      cli: None,
    };

    // create a build config
    let build = BuildConfig {
      dev_path: String::from(""),
    };

    // test the configs
    assert_eq!(t_config, tauri);
    assert_eq!(b_config, build);
    assert_eq!(de_server, tauri.embedded_server);
    assert_eq!(d_bundle, tauri.bundle);
    assert_eq!(d_path, String::from(""));
    assert_eq!(d_title, tauri.window.title);
    assert_eq!(d_window, tauri.window);
  }
}