File size: 10,503 Bytes
2d8be8f | 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 | // Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::PluginIosFramework;
use crate::Result;
use crate::{
error::{Context, ErrorExt},
helpers::{prompts, resolve_tauri_path, template},
VersionMetadata,
};
use clap::Parser;
use handlebars::{to_json, Handlebars};
use heck::{ToKebabCase, ToPascalCase, ToSnakeCase};
use include_dir::{include_dir, Dir};
use std::ffi::{OsStr, OsString};
use std::{
collections::BTreeMap,
env::current_dir,
fs::{create_dir_all, remove_dir_all, File, OpenOptions},
path::{Component, Path, PathBuf},
};
pub const TEMPLATE_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/templates/plugin");
#[derive(Debug, Parser)]
#[clap(about = "Initialize a Tauri plugin project on an existing directory")]
pub struct Options {
/// Name of your Tauri plugin.
/// If not specified, it will be inferred from the current directory.
pub(crate) plugin_name: Option<String>,
/// Initializes a Tauri plugin without the TypeScript API
#[clap(long)]
pub(crate) no_api: bool,
/// Initialize without an example project.
#[clap(long)]
pub(crate) no_example: bool,
/// Set target directory for init
#[clap(short, long)]
#[clap(default_value_t = current_dir().expect("failed to read cwd").display().to_string())]
pub(crate) directory: String,
/// Author name
#[clap(short, long)]
pub(crate) author: Option<String>,
/// Whether to initialize an Android project for the plugin.
#[clap(long)]
pub(crate) android: bool,
/// Whether to initialize an iOS project for the plugin.
#[clap(long)]
pub(crate) ios: bool,
/// Whether to initialize Android and iOS projects for the plugin.
#[clap(long)]
pub(crate) mobile: bool,
/// Type of framework to use for the iOS project.
#[clap(long)]
#[clap(default_value_t = PluginIosFramework::default())]
pub(crate) ios_framework: PluginIosFramework,
/// Generate github workflows
#[clap(long)]
pub(crate) github_workflows: bool,
/// Initializes a Tauri core plugin (internal usage)
#[clap(long, hide(true))]
pub(crate) tauri: bool,
/// Path of the Tauri project to use (relative to the cwd)
#[clap(short, long)]
pub(crate) tauri_path: Option<PathBuf>,
}
impl Options {
fn load(&mut self) {
if self.author.is_none() {
self.author.replace(if self.tauri {
"Tauri Programme within The Commons Conservancy".into()
} else {
"You".into()
});
}
}
}
pub fn command(mut options: Options) -> Result<()> {
options.load();
let plugin_name = match options.plugin_name {
None => super::infer_plugin_name(&options.directory)?,
Some(name) => name,
};
let template_target_path = PathBuf::from(options.directory);
let metadata = crates_metadata()?;
if std::fs::read_dir(&template_target_path)
.fs_context(
"failed to read target directory",
template_target_path.clone(),
)?
.count()
> 0
{
log::warn!("Plugin dir ({:?}) not empty.", template_target_path);
} else {
let (tauri_dep, tauri_example_dep, tauri_build_dep, tauri_plugin_dep) =
if let Some(tauri_path) = options.tauri_path {
(
format!(
r#"{{ path = {:?} }}"#,
resolve_tauri_path(&tauri_path, "crates/tauri")
),
format!(
r#"{{ path = {:?} }}"#,
resolve_tauri_path(&tauri_path, "crates/tauri")
),
format!(
"{{ path = {:?}, default-features = false }}",
resolve_tauri_path(&tauri_path, "crates/tauri-build")
),
format!(
r#"{{ path = {:?}, features = ["build"] }}"#,
resolve_tauri_path(&tauri_path, "crates/tauri-plugin")
),
)
} else {
(
format!(r#"{{ version = "{}" }}"#, metadata.tauri),
format!(r#"{{ version = "{}" }}"#, metadata.tauri),
format!(
r#"{{ version = "{}", default-features = false }}"#,
metadata.tauri_build
),
format!(
r#"{{ version = "{}", features = ["build"] }}"#,
metadata.tauri_plugin
),
)
};
let _ = remove_dir_all(&template_target_path);
let mut handlebars = Handlebars::new();
handlebars.register_escape_fn(handlebars::no_escape);
let mut data = BTreeMap::new();
plugin_name_data(&mut data, &plugin_name);
data.insert("tauri_dep", to_json(tauri_dep));
data.insert("tauri_example_dep", to_json(tauri_example_dep));
data.insert("tauri_build_dep", to_json(tauri_build_dep));
data.insert("tauri_plugin_dep", to_json(tauri_plugin_dep));
data.insert("author", to_json(options.author));
if options.tauri {
data.insert(
"license_header",
to_json(
"// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT\n\n"
.replace(" ", "")
.replace(" //", "//"),
),
);
}
let plugin_id = if options.android || options.mobile {
let plugin_id = prompts::input(
"What should be the Android Package ID for your plugin?",
Some(format!("com.plugin.{plugin_name}")),
false,
false,
)?
.unwrap();
data.insert("android_package_id", to_json(&plugin_id));
Some(plugin_id)
} else {
None
};
let ios_framework = options.ios_framework;
let mut created_dirs = Vec::new();
template::render_with_generator(
&handlebars,
&data,
&TEMPLATE_DIR,
&template_target_path,
&mut |mut path| {
let mut components = path.components();
let root = components.next().unwrap();
if let Component::Normal(component) = root {
match component.to_str().unwrap() {
"__example-api" => {
if options.no_api || options.no_example {
return Ok(None);
} else {
path = Path::new("examples").join(components.collect::<PathBuf>());
}
}
"__example-basic" => {
if options.no_api && !options.no_example {
path = Path::new("examples").join(components.collect::<PathBuf>());
} else {
return Ok(None);
}
}
".github" if !options.github_workflows => return Ok(None),
"android" => {
if options.android || options.mobile {
return generate_android_out_file(
&path,
&template_target_path,
&plugin_id.as_ref().unwrap().replace('.', "/"),
&mut created_dirs,
);
} else {
return Ok(None);
}
}
"ios-spm" | "ios-xcode" if !(options.ios || options.mobile) => return Ok(None),
"ios-spm" if !matches!(ios_framework, PluginIosFramework::Spm) => return Ok(None),
"ios-xcode" if !matches!(ios_framework, PluginIosFramework::Xcode) => return Ok(None),
"ios-spm" | "ios-xcode" => {
let folder_name = components.next().unwrap().as_os_str().to_string_lossy();
let new_folder_name = folder_name.replace("{{ plugin_name }}", &plugin_name);
let new_folder_name = OsString::from(&new_folder_name);
path = [
Component::Normal(OsStr::new("ios")),
Component::Normal(&new_folder_name),
]
.into_iter()
.chain(components)
.collect::<PathBuf>();
}
"guest-js" | "rollup.config.js" | "tsconfig.json" | "package.json"
if options.no_api =>
{
return Ok(None);
}
_ => (),
}
}
let path = template_target_path.join(path);
let parent = path.parent().unwrap().to_path_buf();
if !created_dirs.contains(&parent) {
create_dir_all(&parent)?;
created_dirs.push(parent);
}
File::create(path).map(Some)
},
)
.with_context(|| "failed to render plugin template")?;
}
let permissions_dir = template_target_path.join("permissions");
std::fs::create_dir(&permissions_dir).fs_context(
"failed to create `permissions` directory",
permissions_dir.clone(),
)?;
let default_permissions = r#"[default]
description = "Default permissions for the plugin"
permissions = ["allow-ping"]
"#;
std::fs::write(permissions_dir.join("default.toml"), default_permissions).fs_context(
"failed to write default permissions file",
permissions_dir.join("default.toml"),
)?;
Ok(())
}
pub fn plugin_name_data(data: &mut BTreeMap<&'static str, serde_json::Value>, plugin_name: &str) {
data.insert("plugin_name_original", to_json(plugin_name));
data.insert("plugin_name", to_json(plugin_name.to_kebab_case()));
data.insert(
"plugin_name_snake_case",
to_json(plugin_name.to_snake_case()),
);
data.insert(
"plugin_name_pascal_case",
to_json(plugin_name.to_pascal_case()),
);
}
pub fn crates_metadata() -> Result<VersionMetadata> {
serde_json::from_str::<VersionMetadata>(include_str!("../../metadata-v2.json"))
.context("failed to parse Tauri version metadata")
}
pub fn generate_android_out_file(
path: &Path,
dest: &Path,
package_path: &str,
created_dirs: &mut Vec<PathBuf>,
) -> std::io::Result<Option<File>> {
let mut iter = path.iter();
let root = iter.next().unwrap().to_str().unwrap();
let path = match (root, path.extension().and_then(|o| o.to_str())) {
("src", Some("kt")) => {
let parent = path.parent().unwrap();
let file_name = path.file_name().unwrap();
let out_dir = dest.join(parent).join(package_path);
out_dir.join(file_name)
}
_ => dest.join(path),
};
let parent = path.parent().unwrap().to_path_buf();
if !created_dirs.contains(&parent) {
create_dir_all(&parent)?;
created_dirs.push(parent);
}
let mut options = OpenOptions::new();
options.write(true);
#[cfg(unix)]
if path.file_name().unwrap() == std::ffi::OsStr::new("gradlew") {
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o755);
}
if !path.exists() {
options.create(true).open(path).map(Some)
} else {
Ok(None)
}
}
|