-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
init.rs
277 lines (252 loc) · 7.94 KB
/
init.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
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use crate::{
helpers::{
framework::{infer_from_package_json as infer_framework, Framework},
prompts, resolve_tauri_path, template,
},
VersionMetadata,
};
use std::{
collections::BTreeMap,
env::current_dir,
fs::{read_to_string, remove_dir_all},
path::PathBuf,
};
use crate::Result;
use anyhow::Context;
use clap::Parser;
use handlebars::{to_json, Handlebars};
use include_dir::{include_dir, Dir};
const TEMPLATE_DIR: Dir<'_> = include_dir!("templates/app");
const TAURI_CONF_TEMPLATE: &str = include_str!("../templates/tauri.conf.json");
#[derive(Debug, Parser)]
#[clap(about = "Initialize a Tauri project in an existing directory")]
pub struct Options {
/// Skip prompting for values
#[clap(long, env = "CI")]
ci: bool,
/// Force init to overwrite the src-tauri folder
#[clap(short, long)]
force: bool,
/// Enables logging
#[clap(short, long)]
log: bool,
/// Set target directory for init
#[clap(short, long)]
#[clap(default_value_t = current_dir().expect("failed to read cwd").display().to_string())]
directory: String,
/// Path of the Tauri project to use (relative to the cwd)
#[clap(short, long)]
tauri_path: Option<PathBuf>,
/// Name of your Tauri application
#[clap(short = 'A', long)]
app_name: Option<String>,
/// Window title of your Tauri application
#[clap(short = 'W', long)]
window_title: Option<String>,
/// Web assets location, relative to <project-dir>/src-tauri
#[clap(short = 'D', long)]
frontend_dist: Option<String>,
/// Url of your dev server
#[clap(short = 'P', long)]
dev_url: Option<String>,
/// A shell command to run before `tauri dev` kicks in.
#[clap(long)]
before_dev_command: Option<String>,
/// A shell command to run before `tauri build` kicks in.
#[clap(long)]
before_build_command: Option<String>,
}
#[derive(Default)]
struct InitDefaults {
app_name: Option<String>,
framework: Option<Framework>,
}
impl Options {
fn load(mut self) -> Result<Self> {
let package_json_path = PathBuf::from(&self.directory).join("package.json");
let init_defaults = if package_json_path.exists() {
let package_json_text = read_to_string(package_json_path)?;
let package_json: crate::PackageJson = serde_json::from_str(&package_json_text)?;
let (framework, _) = infer_framework(&package_json_text);
InitDefaults {
app_name: package_json.product_name.or(package_json.name),
framework,
}
} else {
Default::default()
};
self.app_name = self.app_name.map(|s| Ok(Some(s))).unwrap_or_else(|| {
prompts::input(
"What is your app name?",
Some(
init_defaults
.app_name
.clone()
.unwrap_or_else(|| "Tauri App".to_string()),
),
self.ci,
true,
)
})?;
self.window_title = self.window_title.map(|s| Ok(Some(s))).unwrap_or_else(|| {
prompts::input(
"What should the window title be?",
Some(
init_defaults
.app_name
.clone()
.unwrap_or_else(|| "Tauri".to_string()),
),
self.ci,
true,
)
})?;
self.frontend_dist = self.frontend_dist.map(|s| Ok(Some(s))).unwrap_or_else(|| prompts::input(
r#"Where are your web assets (HTML/CSS/JS) located, relative to the "<current dir>/src-tauri/tauri.conf.json" file that will be created?"#,
init_defaults.framework.as_ref().map(|f| f.frontend_dist()),
self.ci,
false,
))?;
self.dev_url = self.dev_url.map(|s| Ok(Some(s))).unwrap_or_else(|| {
prompts::input(
"What is the url of your dev server?",
init_defaults.framework.map(|f| f.dev_url()),
self.ci,
true,
)
})?;
self.before_dev_command = self
.before_dev_command
.map(|s| Ok(Some(s)))
.unwrap_or_else(|| {
prompts::input(
"What is your frontend dev command?",
Some("npm run dev".to_string()),
self.ci,
true,
)
})?;
self.before_build_command = self
.before_build_command
.map(|s| Ok(Some(s)))
.unwrap_or_else(|| {
prompts::input(
"What is your frontend build command?",
Some("npm run build".to_string()),
self.ci,
true,
)
})?;
Ok(self)
}
}
pub fn command(mut options: Options) -> Result<()> {
options = options.load()?;
let template_target_path = PathBuf::from(&options.directory).join("src-tauri");
let metadata = serde_json::from_str::<VersionMetadata>(include_str!("../metadata-v2.json"))?;
if template_target_path.exists() && !options.force {
log::warn!(
"Tauri dir ({:?}) not empty. Run `init --force` to overwrite.",
template_target_path
);
} else {
let (tauri_dep, tauri_build_dep) = if let Some(tauri_path) = options.tauri_path {
(
format!(
r#"{{ path = {:?} }}"#,
resolve_tauri_path(&tauri_path, "core/tauri")
),
format!(
"{{ path = {:?} }}",
resolve_tauri_path(&tauri_path, "core/tauri-build")
),
)
} else {
(
format!(r#"{{ version = "{}" }}"#, metadata.tauri),
format!(r#"{{ version = "{}" }}"#, metadata.tauri_build),
)
};
let _ = remove_dir_all(&template_target_path);
let mut handlebars = Handlebars::new();
handlebars.register_escape_fn(handlebars::no_escape);
let mut data = BTreeMap::new();
data.insert("tauri_dep", to_json(tauri_dep));
data.insert("tauri_build_dep", to_json(tauri_build_dep));
data.insert(
"frontend_dist",
to_json(options.frontend_dist.as_deref().unwrap_or("../dist")),
);
data.insert("dev_url", to_json(options.dev_url));
data.insert(
"app_name",
to_json(options.app_name.as_deref().unwrap_or("Tauri App")),
);
data.insert(
"window_title",
to_json(options.window_title.as_deref().unwrap_or("Tauri")),
);
data.insert("before_dev_command", to_json(options.before_dev_command));
data.insert(
"before_build_command",
to_json(options.before_build_command),
);
let mut config = serde_json::from_str(
&handlebars
.render_template(TAURI_CONF_TEMPLATE, &data)
.expect("Failed to render tauri.conf.json template"),
)
.unwrap();
if option_env!("TARGET") == Some("node") {
let mut dir = current_dir().expect("failed to read cwd");
let mut count = 0;
let mut cli_node_module_path = None;
let cli_path = "node_modules/@tauri-apps/cli";
// only go up three folders max
while count <= 2 {
let test_path = dir.join(cli_path);
if test_path.exists() {
let mut node_module_path = PathBuf::from("..");
for _ in 0..count {
node_module_path.push("..");
}
node_module_path.push(cli_path);
node_module_path.push("schema.json");
cli_node_module_path.replace(node_module_path);
break;
}
count += 1;
match dir.parent() {
Some(parent) => {
dir = parent.to_path_buf();
}
None => break,
}
}
if let Some(cli_node_module_path) = cli_node_module_path {
let mut map = serde_json::Map::default();
map.insert(
"$schema".into(),
serde_json::Value::String(
cli_node_module_path
.display()
.to_string()
.replace('\\', "/"),
),
);
let merge_config = serde_json::Value::Object(map);
json_patch::merge(&mut config, &merge_config);
}
}
data.insert(
"tauri_config",
to_json(serde_json::to_string_pretty(&config).unwrap()),
);
template::render(&handlebars, &data, &TEMPLATE_DIR, &options.directory)
.with_context(|| "failed to render Tauri template")?;
}
Ok(())
}