-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
config.rs
3219 lines (2974 loc) · 104 KB
/
config.rs
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
//! The Tauri configuration used at runtime.
//!
//! It is pulled from a `tauri.conf.json` file and the [`Config`] struct is generated at compile time.
//!
//! # Stability
//! This is a core functionality that is not considered part of the stable API.
//! If you use it, note that it may include breaking changes in the future.
#[cfg(target_os = "linux")]
use heck::ToKebabCase;
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use semver::Version;
use serde::{
de::{Deserializer, Error as DeError, Visitor},
Deserialize, Serialize, Serializer,
};
use serde_json::Value as JsonValue;
use serde_with::skip_serializing_none;
use url::Url;
use std::{
collections::HashMap,
fmt::{self, Display},
fs::read_to_string,
path::PathBuf,
str::FromStr,
};
/// Items to help with parsing content into a [`Config`].
pub mod parse;
pub use self::parse::parse;
/// An URL to open on a Tauri webview window.
#[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(untagged)]
#[non_exhaustive]
pub enum WindowUrl {
/// An external URL.
External(Url),
/// The path portion of an app URL.
/// For instance, to load `tauri://localhost/users/john`,
/// you can simply provide `users/john` in this configuration.
App(PathBuf),
}
impl fmt::Display for WindowUrl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::External(url) => write!(f, "{}", url),
Self::App(path) => write!(f, "{}", path.display()),
}
}
}
impl Default for WindowUrl {
fn default() -> Self {
Self::App("index.html".into())
}
}
/// Targets to bundle.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(untagged)]
pub enum BundleTarget {
/// A list of bundle targets.
All(Vec<String>),
/// A single bundle target.
One(String),
}
impl BundleTarget {
/// Gets the bundle targets as a [`Vec`].
#[allow(dead_code)]
pub fn to_vec(&self) -> Vec<String> {
match self {
Self::All(list) => list.clone(),
Self::One(i) => vec![i.clone()],
}
}
}
/// Configuration for AppImage bundles.
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AppImageConfig {
/// Include additional gstreamer dependencies needed for audio and video playback.
/// This increases the bundle size by ~15-35MB depending on your build system.
#[serde(default)]
pub bundle_media_framework: bool,
}
/// Configuration for Debian (.deb) bundles.
#[skip_serializing_none]
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DebConfig {
/// The list of deb dependencies your application relies on.
pub depends: Option<Vec<String>>,
/// The files to include on the package.
#[serde(default)]
pub files: HashMap<PathBuf, PathBuf>,
}
fn de_minimum_system_version<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
D: Deserializer<'de>,
{
let version = Option::<String>::deserialize(deserializer)?;
match version {
Some(v) if v.is_empty() => Ok(minimum_system_version()),
e => Ok(e),
}
}
/// Configuration for the macOS bundles.
#[skip_serializing_none]
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MacConfig {
/// A list of strings indicating any macOS X frameworks that need to be bundled with the application.
///
/// If a name is used, ".framework" must be omitted and it will look for standard install locations. You may also use a path to a specific framework.
pub frameworks: Option<Vec<String>>,
/// A version string indicating the minimum macOS X version that the bundled application supports. Defaults to `10.13`.
///
/// Setting it to `null` completely removes the `LSMinimumSystemVersion` field on the bundle's `Info.plist`
/// and the `MACOSX_DEPLOYMENT_TARGET` environment variable.
///
/// An empty string is considered an invalid value so the default value is used.
#[serde(
deserialize_with = "de_minimum_system_version",
default = "minimum_system_version"
)]
pub minimum_system_version: Option<String>,
/// Allows your application to communicate with the outside world.
/// It should be a lowercase, without port and protocol domain name.
pub exception_domain: Option<String>,
/// The path to the license file to add to the DMG bundle.
pub license: Option<String>,
/// Identity to use for code signing.
pub signing_identity: Option<String>,
/// Provider short name for notarization.
pub provider_short_name: Option<String>,
/// Path to the entitlements file.
pub entitlements: Option<String>,
}
impl Default for MacConfig {
fn default() -> Self {
Self {
frameworks: None,
minimum_system_version: minimum_system_version(),
exception_domain: None,
license: None,
signing_identity: None,
provider_short_name: None,
entitlements: None,
}
}
}
fn minimum_system_version() -> Option<String> {
Some("10.13".into())
}
/// Configuration for a target language for the WiX build.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WixLanguageConfig {
/// The path to a locale (`.wxl`) file. See <https://wixtoolset.org/documentation/manual/v3/howtos/ui_and_localization/build_a_localized_version.html>.
pub locale_path: Option<String>,
}
/// The languages to build using WiX.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(untagged)]
pub enum WixLanguage {
/// A single language to build, without configuration.
One(String),
/// A list of languages to build, without configuration.
List(Vec<String>),
/// A map of languages and its configuration.
Localized(HashMap<String, WixLanguageConfig>),
}
impl Default for WixLanguage {
fn default() -> Self {
Self::One("en-US".into())
}
}
/// Configuration for the MSI bundle using WiX.
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WixConfig {
/// The installer languages to build. See <https://docs.microsoft.com/en-us/windows/win32/msi/localizing-the-error-and-actiontext-tables>.
#[serde(default)]
pub language: WixLanguage,
/// A custom .wxs template to use.
pub template: Option<PathBuf>,
/// A list of paths to .wxs files with WiX fragments to use.
#[serde(default)]
pub fragment_paths: Vec<PathBuf>,
/// The ComponentGroup element ids you want to reference from the fragments.
#[serde(default)]
pub component_group_refs: Vec<String>,
/// The Component element ids you want to reference from the fragments.
#[serde(default)]
pub component_refs: Vec<String>,
/// The FeatureGroup element ids you want to reference from the fragments.
#[serde(default)]
pub feature_group_refs: Vec<String>,
/// The Feature element ids you want to reference from the fragments.
#[serde(default)]
pub feature_refs: Vec<String>,
/// The Merge element ids you want to reference from the fragments.
#[serde(default)]
pub merge_refs: Vec<String>,
/// Disables the Webview2 runtime installation after app install.
#[serde(default)]
pub skip_webview_install: bool,
/// The path to the license file to render on the installer.
///
/// Must be an RTF file, so if a different extension is provided, we convert it to the RTF format.
pub license: Option<PathBuf>,
/// Create an elevated update task within Windows Task Scheduler.
#[serde(default)]
pub enable_elevated_update_task: bool,
/// Path to a bitmap file to use as the installation user interface banner.
/// This bitmap will appear at the top of all but the first page of the installer.
///
/// The required dimensions are 493px × 58px.
pub banner_path: Option<PathBuf>,
/// Path to a bitmap file to use on the installation user interface dialogs.
/// It is used on the welcome and completion dialogs.
/// The required dimensions are 493px × 312px.
pub dialog_image_path: Option<PathBuf>,
}
/// Windows bundler configuration.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WindowsConfig {
/// Specifies the file digest algorithm to use for creating file signatures.
/// Required for code signing. SHA-256 is recommended.
pub digest_algorithm: Option<String>,
/// Specifies the SHA1 hash of the signing certificate.
pub certificate_thumbprint: Option<String>,
/// Server to use during timestamping.
pub timestamp_url: Option<String>,
/// Whether to use Time-Stamp Protocol (TSP, a.k.a. RFC 3161) for the timestamp server. Your code signing provider may
/// use a TSP timestamp server, like e.g. SSL.com does. If so, enable TSP by setting to true.
#[serde(default)]
pub tsp: bool,
/// Path to the webview fixed runtime to use.
///
/// The fixed version can be downloaded [on the official website](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section).
/// The `.cab` file must be extracted to a folder and this folder path must be defined on this field.
pub webview_fixed_runtime_path: Option<PathBuf>,
/// Validates a second app installation, blocking the user from installing an older version if set to `false`.
///
/// For instance, if `1.2.1` is installed, the user won't be able to install app version `1.2.0` or `1.1.5`.
///
/// The default value of this flag is `true`.
#[serde(default = "default_allow_downgrades")]
pub allow_downgrades: bool,
/// Configuration for the MSI generated with WiX.
pub wix: Option<WixConfig>,
}
impl Default for WindowsConfig {
fn default() -> Self {
Self {
digest_algorithm: None,
certificate_thumbprint: None,
timestamp_url: None,
tsp: false,
webview_fixed_runtime_path: None,
allow_downgrades: default_allow_downgrades(),
wix: None,
}
}
}
fn default_allow_downgrades() -> bool {
true
}
/// Configuration for tauri-bundler.
#[skip_serializing_none]
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct BundleConfig {
/// Whether we should build your app with tauri-bundler or plain `cargo build`
#[serde(default)]
pub active: bool,
/// The bundle targets, currently supports ["deb", "app", "msi", "appimage", "dmg"] or "all"
pub targets: Option<BundleTarget>,
/// The application identifier in reverse domain name notation (e.g. `com.tauri.example`).
/// This string must be unique across applications since it is used in system configurations like
/// the bundle ID and path to the webview data directory.
pub identifier: String,
/// The app's icons
#[serde(default)]
pub icon: Vec<String>,
/// App resources to bundle.
/// Each resource is a path to a file or directory.
/// Glob patterns are supported.
pub resources: Option<Vec<String>>,
/// A copyright string associated with your application.
pub copyright: Option<String>,
/// The application kind.
///
/// Should be one of the following:
/// Business, DeveloperTool, Education, Entertainment, Finance, Game, ActionGame, AdventureGame, ArcadeGame, BoardGame, CardGame, CasinoGame, DiceGame, EducationalGame, FamilyGame, KidsGame, MusicGame, PuzzleGame, RacingGame, RolePlayingGame, SimulationGame, SportsGame, StrategyGame, TriviaGame, WordGame, GraphicsAndDesign, HealthcareAndFitness, Lifestyle, Medical, Music, News, Photography, Productivity, Reference, SocialNetworking, Sports, Travel, Utility, Video, Weather.
pub category: Option<String>,
/// A short description of your application.
pub short_description: Option<String>,
/// A longer, multi-line description of the application.
pub long_description: Option<String>,
/// Configuration for the AppImage bundle.
#[serde(default)]
pub appimage: AppImageConfig,
/// Configuration for the Debian bundle.
#[serde(default)]
pub deb: DebConfig,
/// Configuration for the macOS bundles.
#[serde(rename = "macOS", default)]
pub macos: MacConfig,
/// A list of—either absolute or relative—paths to binaries to embed with your application.
///
/// Note that Tauri will look for system-specific binaries following the pattern "binary-name{-target-triple}{.system-extension}".
///
/// E.g. for the external binary "my-binary", Tauri looks for:
///
/// - "my-binary-x86_64-pc-windows-msvc.exe" for Windows
/// - "my-binary-x86_64-apple-darwin" for macOS
/// - "my-binary-x86_64-unknown-linux-gnu" for Linux
///
/// so don't forget to provide binaries for all targeted platforms.
pub external_bin: Option<Vec<String>>,
/// Configuration for the Windows bundle.
#[serde(default)]
pub windows: WindowsConfig,
}
/// A CLI argument definition.
#[skip_serializing_none]
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CliArg {
/// The short version of the argument, without the preceding -.
///
/// NOTE: Any leading `-` characters will be stripped, and only the first non-character will be used as the short version.
pub short: Option<char>,
/// The unique argument name
pub name: String,
/// The argument description which will be shown on the help information.
/// Typically, this is a short (one line) description of the arg.
pub description: Option<String>,
/// The argument long description which will be shown on the help information.
/// Typically this a more detailed (multi-line) message that describes the argument.
pub long_description: Option<String>,
/// Specifies that the argument takes a value at run time.
///
/// NOTE: values for arguments may be specified in any of the following methods
/// - Using a space such as -o value or --option value
/// - Using an equals and no space such as -o=value or --option=value
/// - Use a short and no space such as -ovalue
#[serde(default)]
pub takes_value: bool,
/// Specifies that the argument may have an unknown number of multiple values. Without any other settings, this argument may appear only once.
///
/// For example, --opt val1 val2 is allowed, but --opt val1 val2 --opt val3 is not.
///
/// NOTE: Setting this requires `takes_value` to be set to true.
#[serde(default)]
pub multiple: bool,
/// Specifies that the argument may appear more than once.
/// For flags, this results in the number of occurrences of the flag being recorded. For example -ddd or -d -d -d would count as three occurrences.
/// For options or arguments that take a value, this does not affect how many values they can accept. (i.e. only one at a time is allowed)
///
/// For example, --opt val1 --opt val2 is allowed, but --opt val1 val2 is not.
#[serde(default)]
pub multiple_occurrences: bool,
/// Specifies how many values are required to satisfy this argument. For example, if you had a
/// `-f <file>` argument where you wanted exactly 3 'files' you would set
/// `number_of_values = 3`, and this argument wouldn't be satisfied unless the user provided
/// 3 and only 3 values.
///
/// **NOTE:** Does *not* require `multiple_occurrences = true` to be set. Setting
/// `multiple_occurrences = true` would allow `-f <file> <file> <file> -f <file> <file> <file>` where
/// as *not* setting it would only allow one occurrence of this argument.
///
/// **NOTE:** implicitly sets `takes_value = true` and `multiple_values = true`.
pub number_of_values: Option<usize>,
/// Specifies a list of possible values for this argument.
/// At runtime, the CLI verifies that only one of the specified values was used, or fails with an error message.
pub possible_values: Option<Vec<String>>,
/// Specifies the minimum number of values for this argument.
/// For example, if you had a -f `<file>` argument where you wanted at least 2 'files',
/// you would set `minValues: 2`, and this argument would be satisfied if the user provided, 2 or more values.
pub min_values: Option<usize>,
/// Specifies the maximum number of values are for this argument.
/// For example, if you had a -f `<file>` argument where you wanted up to 3 'files',
/// you would set .max_values(3), and this argument would be satisfied if the user provided, 1, 2, or 3 values.
pub max_values: Option<usize>,
/// Sets whether or not the argument is required by default.
///
/// - Required by default means it is required, when no other conflicting rules have been evaluated
/// - Conflicting rules take precedence over being required.
#[serde(default)]
pub required: bool,
/// Sets an arg that override this arg's required setting
/// i.e. this arg will be required unless this other argument is present.
pub required_unless_present: Option<String>,
/// Sets args that override this arg's required setting
/// i.e. this arg will be required unless all these other arguments are present.
pub required_unless_present_all: Option<Vec<String>>,
/// Sets args that override this arg's required setting
/// i.e. this arg will be required unless at least one of these other arguments are present.
pub required_unless_present_any: Option<Vec<String>>,
/// Sets a conflicting argument by name
/// i.e. when using this argument, the following argument can't be present and vice versa.
pub conflicts_with: Option<String>,
/// The same as conflictsWith but allows specifying multiple two-way conflicts per argument.
pub conflicts_with_all: Option<Vec<String>>,
/// Tets an argument by name that is required when this one is present
/// i.e. when using this argument, the following argument must be present.
pub requires: Option<String>,
/// Sts multiple arguments by names that are required when this one is present
/// i.e. when using this argument, the following arguments must be present.
pub requires_all: Option<Vec<String>>,
/// Allows a conditional requirement with the signature [arg, value]
/// the requirement will only become valid if `arg`'s value equals `${value}`.
pub requires_if: Option<Vec<String>>,
/// Allows specifying that an argument is required conditionally with the signature [arg, value]
/// the requirement will only become valid if the `arg`'s value equals `${value}`.
pub required_if_eq: Option<Vec<String>>,
/// Requires that options use the --option=val syntax
/// i.e. an equals between the option and associated value.
pub require_equals: Option<bool>,
/// The positional argument index, starting at 1.
///
/// The index refers to position according to other positional argument.
/// It does not define position in the argument list as a whole. When utilized with multiple=true,
/// only the last positional argument may be defined as multiple (i.e. the one with the highest index).
#[cfg_attr(feature = "schema", validate(range(min = 1)))]
pub index: Option<usize>,
}
/// describes a CLI configuration
#[skip_serializing_none]
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CliConfig {
/// Command description which will be shown on the help information.
pub description: Option<String>,
/// Command long description which will be shown on the help information.
pub long_description: Option<String>,
/// Adds additional help information to be displayed in addition to auto-generated help.
/// This information is displayed before the auto-generated help information.
/// This is often used for header information.
pub before_help: Option<String>,
/// Adds additional help information to be displayed in addition to auto-generated help.
/// This information is displayed after the auto-generated help information.
/// This is often used to describe how to use the arguments, or caveats to be noted.
pub after_help: Option<String>,
/// List of arguments for the command
pub args: Option<Vec<CliArg>>,
/// List of subcommands of this command
pub subcommands: Option<HashMap<String, CliConfig>>,
}
impl CliConfig {
/// List of arguments for the command
pub fn args(&self) -> Option<&Vec<CliArg>> {
self.args.as_ref()
}
/// List of subcommands of this command
pub fn subcommands(&self) -> Option<&HashMap<String, CliConfig>> {
self.subcommands.as_ref()
}
/// Command description which will be shown on the help information.
pub fn description(&self) -> Option<&String> {
self.description.as_ref()
}
/// Command long description which will be shown on the help information.
pub fn long_description(&self) -> Option<&String> {
self.description.as_ref()
}
/// Adds additional help information to be displayed in addition to auto-generated help.
/// This information is displayed before the auto-generated help information.
/// This is often used for header information.
pub fn before_help(&self) -> Option<&String> {
self.before_help.as_ref()
}
/// Adds additional help information to be displayed in addition to auto-generated help.
/// This information is displayed after the auto-generated help information.
/// This is often used to describe how to use the arguments, or caveats to be noted.
pub fn after_help(&self) -> Option<&String> {
self.after_help.as_ref()
}
}
/// The window configuration object.
#[skip_serializing_none]
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WindowConfig {
/// The window identifier. It must be alphanumeric.
#[serde(default = "default_window_label")]
pub label: String,
/// The window webview URL.
#[serde(default)]
pub url: WindowUrl,
/// Whether the file drop is enabled or not on the webview. By default it is enabled.
///
/// Disabling it is required to use drag and drop on the frontend on Windows.
#[serde(default = "default_file_drop_enabled")]
pub file_drop_enabled: bool,
/// Whether or not the window starts centered or not.
#[serde(default)]
pub center: bool,
/// The horizontal position of the window's top left corner
pub x: Option<f64>,
/// The vertical position of the window's top left corner
pub y: Option<f64>,
/// The window width.
#[serde(default = "default_width")]
pub width: f64,
/// The window height.
#[serde(default = "default_height")]
pub height: f64,
/// The min window width.
pub min_width: Option<f64>,
/// The min window height.
pub min_height: Option<f64>,
/// The max window width.
pub max_width: Option<f64>,
/// The max window height.
pub max_height: Option<f64>,
/// Whether the window is resizable or not.
#[serde(default = "default_resizable")]
pub resizable: bool,
/// The window title.
#[serde(default = "default_title")]
pub title: String,
/// Whether the window starts as fullscreen or not.
#[serde(default)]
pub fullscreen: bool,
/// Whether the window will be initially hidden or focused.
#[serde(default = "default_focus")]
pub focus: bool,
/// Whether the window is transparent or not.
///
/// Note that on `macOS` this requires the `macos-private-api` feature flag, enabled under `tauri.conf.json > tauri > macOSPrivateApi`.
/// WARNING: Using private APIs on `macOS` prevents your application from being accepted to the `App Store`.
#[serde(default)]
pub transparent: bool,
/// Whether the window is maximized or not.
#[serde(default)]
pub maximized: bool,
/// Whether the window is visible or not.
#[serde(default = "default_visible")]
pub visible: bool,
/// Whether the window should have borders and bars.
#[serde(default = "default_decorations")]
pub decorations: bool,
/// Whether the window should always be on top of other windows.
#[serde(default)]
pub always_on_top: bool,
/// Whether or not the window icon should be added to the taskbar.
#[serde(default)]
pub skip_taskbar: bool,
/// The initial window theme. Defaults to the system theme. Only implemented on Windows.
pub theme: Option<crate::Theme>,
}
impl Default for WindowConfig {
fn default() -> Self {
Self {
label: default_window_label(),
url: WindowUrl::default(),
file_drop_enabled: default_file_drop_enabled(),
center: false,
x: None,
y: None,
width: default_width(),
height: default_height(),
min_width: None,
min_height: None,
max_width: None,
max_height: None,
resizable: default_resizable(),
title: default_title(),
fullscreen: false,
focus: false,
transparent: false,
maximized: false,
visible: default_visible(),
decorations: default_decorations(),
always_on_top: false,
skip_taskbar: false,
theme: None,
}
}
}
fn default_window_label() -> String {
"main".to_string()
}
fn default_width() -> f64 {
800f64
}
fn default_height() -> f64 {
600f64
}
fn default_resizable() -> bool {
true
}
fn default_title() -> String {
"Tauri App".to_string()
}
fn default_focus() -> bool {
true
}
fn default_visible() -> bool {
true
}
fn default_decorations() -> bool {
true
}
fn default_file_drop_enabled() -> bool {
true
}
/// A Content-Security-Policy directive source list.
/// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources#sources>.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", untagged)]
pub enum CspDirectiveSources {
/// An inline list of CSP sources. Same as [`Self::List`], but concatenated with a space separator.
Inline(String),
/// A list of CSP sources. The collection will be concatenated with a space separator for the CSP string.
List(Vec<String>),
}
impl Default for CspDirectiveSources {
fn default() -> Self {
Self::List(Vec::new())
}
}
impl From<CspDirectiveSources> for Vec<String> {
fn from(sources: CspDirectiveSources) -> Self {
match sources {
CspDirectiveSources::Inline(source) => source.split(' ').map(|s| s.to_string()).collect(),
CspDirectiveSources::List(l) => l,
}
}
}
impl CspDirectiveSources {
/// Whether the given source is configured on this directive or not.
pub fn contains(&self, source: &str) -> bool {
match self {
Self::Inline(s) => s.contains(&format!("{} ", source)) || s.contains(&format!(" {}", source)),
Self::List(l) => l.contains(&source.into()),
}
}
/// Appends the given source to this directive.
pub fn push<S: AsRef<str>>(&mut self, source: S) {
match self {
Self::Inline(s) => {
s.push(' ');
s.push_str(source.as_ref());
}
Self::List(l) => {
l.push(source.as_ref().to_string());
}
}
}
/// Extends this CSP directive source list with the given array of sources.
pub fn extend(&mut self, sources: Vec<String>) {
for s in sources {
self.push(s);
}
}
}
/// A Content-Security-Policy definition.
/// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", untagged)]
pub enum Csp {
/// The entire CSP policy in a single text string.
Policy(String),
/// An object mapping a directive with its sources values as a list of strings.
DirectiveMap(HashMap<String, CspDirectiveSources>),
}
impl From<HashMap<String, CspDirectiveSources>> for Csp {
fn from(map: HashMap<String, CspDirectiveSources>) -> Self {
Self::DirectiveMap(map)
}
}
impl From<Csp> for HashMap<String, CspDirectiveSources> {
fn from(csp: Csp) -> Self {
match csp {
Csp::Policy(policy) => {
let mut map = HashMap::new();
for directive in policy.split(';') {
let mut tokens = directive.trim().split(' ');
if let Some(directive) = tokens.next() {
let sources = tokens.map(|s| s.to_string()).collect::<Vec<String>>();
map.insert(directive.to_string(), CspDirectiveSources::List(sources));
}
}
map
}
Csp::DirectiveMap(m) => m,
}
}
}
impl Display for Csp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Policy(s) => write!(f, "{}", s),
Self::DirectiveMap(m) => {
let len = m.len();
let mut i = 0;
for (directive, sources) in m {
let sources: Vec<String> = sources.clone().into();
write!(f, "{} {}", directive, sources.join(" "))?;
i += 1;
if i != len {
write!(f, "; ")?;
}
}
Ok(())
}
}
}
}
/// The possible values for the `dangerous_disable_asset_csp_modification` config option.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(untagged)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub enum DisabledCspModificationKind {
/// If `true`, disables all CSP modification.
/// `false` is the default value and it configures Tauri to control the CSP.
Flag(bool),
/// Disables the given list of CSP directives modifications.
List(Vec<String>),
}
impl DisabledCspModificationKind {
/// Determines whether the given CSP directive can be modified or not.
pub fn can_modify(&self, directive: &str) -> bool {
match self {
Self::Flag(f) => !f,
Self::List(l) => !l.contains(&directive.into()),
}
}
}
impl Default for DisabledCspModificationKind {
fn default() -> Self {
Self::Flag(false)
}
}
/// Security configuration.
#[skip_serializing_none]
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SecurityConfig {
/// The Content Security Policy that will be injected on all HTML files on the built application.
/// If [`dev_csp`](#SecurityConfig.devCsp) is not specified, this value is also injected on dev.
///
/// This is a really important part of the configuration since it helps you ensure your WebView is secured.
/// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
pub csp: Option<Csp>,
/// The Content Security Policy that will be injected on all HTML files on development.
///
/// This is a really important part of the configuration since it helps you ensure your WebView is secured.
/// See <https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP>.
pub dev_csp: Option<Csp>,
/// Freeze the `Object.prototype` when using the custom protocol.
#[serde(default)]
pub freeze_prototype: bool,
/// Disables the Tauri-injected CSP sources.
///
/// At compile time, Tauri parses all the frontend assets and changes the Content-Security-Policy
/// to only allow loading of your own scripts and styles by injecting nonce and hash sources.
/// This stricts your CSP, which may introduce issues when using along with other flexing sources.
///
/// This configuration option allows both a boolean and a list of strings as value.
/// A boolean instructs Tauri to disable the injection for all CSP injections,
/// and a list of strings indicates the CSP directives that Tauri cannot inject.
///
/// **WARNING:** Only disable this if you know what you are doing and have properly configured the CSP.
/// Your application might be vulnerable to XSS attacks without this Tauri protection.
#[serde(default)]
pub dangerous_disable_asset_csp_modification: DisabledCspModificationKind,
}
/// Defines an allowlist type.
pub trait Allowlist {
/// Returns all features associated with the allowlist struct.
fn all_features() -> Vec<&'static str>;
/// Returns the tauri features enabled on this allowlist.
fn to_features(&self) -> Vec<&'static str>;
}
macro_rules! check_feature {
($self:ident, $features:ident, $flag:ident, $feature_name: expr) => {
if $self.$flag {
$features.push($feature_name)
}
};
}
/// Filesystem scope definition.
/// It is a list of glob patterns that restrict the API access from the webview.
///
/// Each pattern can start with a variable that resolves to a system base directory.
/// The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`,
/// `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`,
/// `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(untagged)]
pub enum FsAllowlistScope {
/// A list of paths that are allowed by this scope.
AllowedPaths(Vec<PathBuf>),
/// A complete scope configuration.
Scope {
/// A list of paths that are allowed by this scope.
#[serde(default)]
allow: Vec<PathBuf>,
/// A list of paths that are not allowed by this scope.
/// This gets precedence over the [`Self::Scope::allow`] list.
#[serde(default)]
deny: Vec<PathBuf>,
},
}
impl Default for FsAllowlistScope {
fn default() -> Self {
Self::AllowedPaths(Vec::new())
}
}
impl FsAllowlistScope {
/// The list of allowed paths.
pub fn allowed_paths(&self) -> &Vec<PathBuf> {
match self {
Self::AllowedPaths(p) => p,
Self::Scope { allow, .. } => allow,
}
}
/// The list of forbidden paths.
pub fn forbidden_paths(&self) -> Option<&Vec<PathBuf>> {
match self {
Self::AllowedPaths(_) => None,
Self::Scope { deny, .. } => Some(deny),
}
}
}
/// Allowlist for the file system APIs.
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FsAllowlistConfig {
/// The access scope for the filesystem APIs.
#[serde(default)]
pub scope: FsAllowlistScope,
/// Use this flag to enable all file system API features.
#[serde(default)]
pub all: bool,
/// Read file from local filesystem.
#[serde(default)]
pub read_file: bool,
/// Write file to local filesystem.
#[serde(default)]
pub write_file: bool,
/// Read directory from local filesystem.
#[serde(default)]
pub read_dir: bool,
/// Copy file from local filesystem.
#[serde(default)]
pub copy_file: bool,
/// Create directory from local filesystem.
#[serde(default)]
pub create_dir: bool,
/// Remove directory from local filesystem.
#[serde(default)]
pub remove_dir: bool,
/// Remove file from local filesystem.
#[serde(default)]
pub remove_file: bool,
/// Rename file from local filesystem.
#[serde(default)]
pub rename_file: bool,
}
impl Allowlist for FsAllowlistConfig {
fn all_features() -> Vec<&'static str> {
let allowlist = Self {
scope: Default::default(),
all: false,
read_file: true,
write_file: true,
read_dir: true,
copy_file: true,
create_dir: true,
remove_dir: true,
remove_file: true,
rename_file: true,
};
let mut features = allowlist.to_features();
features.push("fs-all");
features
}
fn to_features(&self) -> Vec<&'static str> {
if self.all {
vec!["fs-all"]
} else {
let mut features = Vec::new();
check_feature!(self, features, read_file, "fs-read-file");
check_feature!(self, features, write_file, "fs-write-file");
check_feature!(self, features, read_dir, "fs-read-dir");
check_feature!(self, features, copy_file, "fs-copy-file");
check_feature!(self, features, create_dir, "fs-create-dir");
check_feature!(self, features, remove_dir, "fs-remove-dir");
check_feature!(self, features, remove_file, "fs-remove-file");
check_feature!(self, features, rename_file, "fs-rename-file");
features
}
}
}
/// Allowlist for the window APIs.
#[derive(Debug, Default, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WindowAllowlistConfig {
/// Use this flag to enable all window API features.
#[serde(default)]
pub all: bool,
/// Allows dynamic window creation.
#[serde(default)]
pub create: bool,
/// Allows centering the window.