Fix built-in template rename order
This commit is contained in:
1355
Cargo.lock
generated
1355
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -9,13 +9,10 @@ edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.5.32", features = ["derive"] }
|
||||
reqwest = { version = "0.12", features = ["json", "blocking"] }
|
||||
uuid = { version = "1.4", features = ["v4", "fast-rng", "macro-diagnostics"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
toml = "0.8"
|
||||
zip = "2.2.2"
|
||||
walkdir = "2"
|
||||
anyhow = "1.0.97"
|
||||
dirs = "5.0"
|
||||
regex = "1.10"
|
||||
70
build.rs
Normal file
70
build.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
use std::{
|
||||
env, fs, io,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=examples");
|
||||
|
||||
let examples_root = PathBuf::from("examples");
|
||||
let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is not set"));
|
||||
let out_file = out_dir.join("embedded_examples.rs");
|
||||
|
||||
let mut dirs = Vec::new();
|
||||
let mut files = Vec::new();
|
||||
|
||||
if examples_root.is_dir() {
|
||||
collect_examples(&examples_root, &examples_root, &mut dirs, &mut files)
|
||||
.expect("failed to collect example templates");
|
||||
}
|
||||
|
||||
dirs.sort();
|
||||
files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
let mut generated = String::new();
|
||||
generated.push_str(
|
||||
"struct EmbeddedFile {\n path: &'static str,\n contents: &'static [u8],\n}\n\n",
|
||||
);
|
||||
generated.push_str("static EMBEDDED_EXAMPLE_DIRS: &[&str] = &[\n");
|
||||
for dir in &dirs {
|
||||
generated.push_str(&format!(" {:?},\n", dir));
|
||||
}
|
||||
generated.push_str("];\n\n");
|
||||
generated.push_str("static EMBEDDED_EXAMPLE_FILES: &[EmbeddedFile] = &[\n");
|
||||
for (relative_path, absolute_path) in &files {
|
||||
generated.push_str(&format!(
|
||||
" EmbeddedFile {{ path: {:?}, contents: include_bytes!(r#\"{}\"#) }},\n",
|
||||
relative_path,
|
||||
absolute_path.display()
|
||||
));
|
||||
}
|
||||
generated.push_str("];\n");
|
||||
|
||||
fs::write(out_file, generated).expect("failed to write embedded example list");
|
||||
}
|
||||
|
||||
fn collect_examples(
|
||||
root: &Path,
|
||||
dir: &Path,
|
||||
dirs: &mut Vec<String>,
|
||||
files: &mut Vec<(String, PathBuf)>,
|
||||
) -> io::Result<()> {
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
let relative_path = path
|
||||
.strip_prefix(root)
|
||||
.expect("example path is outside examples root")
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
|
||||
if path.is_dir() {
|
||||
dirs.push(relative_path);
|
||||
collect_examples(root, &path, dirs, files)?;
|
||||
} else if path.is_file() {
|
||||
files.push((relative_path, path.canonicalize()?));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,25 +1,20 @@
|
||||
use crate::{
|
||||
config::Config,
|
||||
entity::project::ProjectInfo,
|
||||
template::TemplateEngine,
|
||||
utils::{file, http::HttpClient},
|
||||
commands::CreateArgs, entity::project::ProjectInfo, error::Result, template::TemplateEngine,
|
||||
};
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
use crate::commands::CreateArgs;
|
||||
use crate::error::Result;
|
||||
use crate::utils::git;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub fn execute(args: &CreateArgs, temp_dir: &PathBuf) {
|
||||
if let Err(e) = create_project(&args.name, args.target.as_deref(), temp_dir) {
|
||||
eprintln!("错误: {}", e);
|
||||
include!(concat!(env!("OUT_DIR"), "/embedded_examples.rs"));
|
||||
|
||||
pub fn execute(args: &CreateArgs) {
|
||||
if let Err(e) = create_project(&args.name, args.target.as_deref()) {
|
||||
eprintln!("Error: {}", e);
|
||||
return;
|
||||
}
|
||||
println!("成功: 项目已创建");
|
||||
println!("Success: project created.");
|
||||
}
|
||||
|
||||
fn create_project(name: &str, target: Option<&str>, temp_dir: &PathBuf) -> Result<()> {
|
||||
fn create_project(name: &str, target: Option<&str>) -> Result<()> {
|
||||
let target = target.unwrap_or("default");
|
||||
|
||||
check_example_exists(target)?;
|
||||
@@ -27,30 +22,16 @@ fn create_project(name: &str, target: Option<&str>, temp_dir: &PathBuf) -> Resul
|
||||
let local_dir = PathBuf::from(format!("./{}", name));
|
||||
fs::create_dir(&local_dir)?;
|
||||
|
||||
let template_dir = clone_and_copy_template(target, temp_dir, &local_dir)?;
|
||||
|
||||
initialize_project_with_template(&template_dir, &local_dir, name)?;
|
||||
copy_embedded_template(target, &local_dir)?;
|
||||
initialize_project_with_template(&local_dir, &local_dir, name)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_example_exists(target: &str) -> Result<()> {
|
||||
let check_url = format!(
|
||||
"https://api.github.com/repos/AiYo-Studio/emod-cli/contents/examples/{}",
|
||||
target
|
||||
);
|
||||
|
||||
let client = if cfg!(debug_assertions) {
|
||||
HttpClient::new_with_proxy("http://127.0.0.1:1080")?
|
||||
} else {
|
||||
HttpClient::new()?
|
||||
};
|
||||
|
||||
let resp = client.get(&check_url)?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
if !embedded_example_exists(target) {
|
||||
return Err(crate::error::CliError::NotFound(format!(
|
||||
"示例模板 '{}' 不存在",
|
||||
"example target '{}' was not found in the built-in examples",
|
||||
target
|
||||
)));
|
||||
}
|
||||
@@ -58,21 +39,47 @@ fn check_example_exists(target: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clone_and_copy_template(
|
||||
target: &str,
|
||||
temp_dir: &PathBuf,
|
||||
local_dir: &PathBuf,
|
||||
) -> Result<PathBuf> {
|
||||
let _ = fs::remove_dir_all(format!("{}/tmp", temp_dir.display()));
|
||||
fn embedded_example_exists(target: &str) -> bool {
|
||||
let target = normalize_embedded_path(target);
|
||||
let prefix = format!("{}/", target);
|
||||
|
||||
let config = Config::load();
|
||||
let url = &config.repo_url;
|
||||
git::clone_remote_project(url.to_string(), temp_dir)?;
|
||||
EMBEDDED_EXAMPLE_DIRS
|
||||
.iter()
|
||||
.any(|dir| *dir == target || dir.starts_with(&prefix))
|
||||
|| EMBEDDED_EXAMPLE_FILES
|
||||
.iter()
|
||||
.any(|file| file.path.starts_with(&prefix))
|
||||
}
|
||||
|
||||
let target_dir = PathBuf::from(format!("{}/tmp/examples/{}", temp_dir.display(), target));
|
||||
file::copy_folder(&target_dir, local_dir)?;
|
||||
fn copy_embedded_template(target: &str, local_dir: &PathBuf) -> Result<()> {
|
||||
let target = normalize_embedded_path(target);
|
||||
let prefix = format!("{}/", target);
|
||||
|
||||
Ok(target_dir)
|
||||
for dir in EMBEDDED_EXAMPLE_DIRS {
|
||||
if let Some(relative_path) = dir.strip_prefix(&prefix) {
|
||||
if !relative_path.is_empty() {
|
||||
fs::create_dir_all(local_dir.join(relative_path))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for file in EMBEDDED_EXAMPLE_FILES {
|
||||
let Some(relative_path) = file.path.strip_prefix(&prefix) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let output_path = local_dir.join(relative_path);
|
||||
if let Some(parent) = output_path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::write(output_path, file.contents)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn normalize_embedded_path(path: &str) -> String {
|
||||
path.trim_matches(['/', '\\']).replace('\\', "/")
|
||||
}
|
||||
|
||||
fn initialize_project_with_template(
|
||||
@@ -80,14 +87,10 @@ fn initialize_project_with_template(
|
||||
local_dir: &PathBuf,
|
||||
name: &str,
|
||||
) -> Result<()> {
|
||||
let lower_name = format!(
|
||||
"{}{}",
|
||||
name.chars().next().unwrap().to_lowercase(),
|
||||
&name[1..]
|
||||
);
|
||||
let lower_name = lower_first_char(name)?;
|
||||
|
||||
println!("项目名称: {}", name);
|
||||
println!("标识名称: {}", lower_name);
|
||||
println!("Project name: {}", name);
|
||||
println!("Lower project name: {}", lower_name);
|
||||
|
||||
let project_info = generate_project_info(name, &lower_name);
|
||||
|
||||
@@ -124,10 +127,30 @@ fn initialize_project_with_template(
|
||||
);
|
||||
|
||||
engine.process_directory(local_dir)?;
|
||||
remove_template_config(local_dir)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_template_config(local_dir: &PathBuf) -> Result<()> {
|
||||
let template_config = local_dir.join("template.toml");
|
||||
if template_config.exists() {
|
||||
fs::remove_file(template_config)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn lower_first_char(name: &str) -> Result<String> {
|
||||
let mut chars = name.chars();
|
||||
let Some(first) = chars.next() else {
|
||||
return Err(crate::error::CliError::InvalidInput(
|
||||
"project name cannot be empty".to_string(),
|
||||
));
|
||||
};
|
||||
|
||||
Ok(format!("{}{}", first.to_lowercase(), chars.as_str()))
|
||||
}
|
||||
|
||||
fn generate_project_info(name: &str, lower_name: &str) -> ProjectInfo {
|
||||
ProjectInfo {
|
||||
name: name.to_string(),
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct Config {
|
||||
#[serde(default = "default_repo_url")]
|
||||
pub repo_url: String,
|
||||
}
|
||||
|
||||
fn default_repo_url() -> String {
|
||||
"https://github.com/AiYo-Studio/emod-cli.git".to_string()
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
repo_url: default_repo_url(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn load() -> Self {
|
||||
let config_path = Self::config_path();
|
||||
|
||||
if let Ok(content) = fs::read_to_string(&config_path) {
|
||||
if let Ok(config) = serde_json::from_str(&content) {
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
||||
Self::default()
|
||||
}
|
||||
|
||||
fn config_path() -> PathBuf {
|
||||
let home = dirs::home_dir().expect("无法获取用户主目录");
|
||||
home.join(".emod-cli.json")
|
||||
}
|
||||
}
|
||||
36
src/error.rs
36
src/error.rs
@@ -1,13 +1,11 @@
|
||||
use std::io;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use std::num::ParseIntError;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum CliError {
|
||||
Io(io::Error),
|
||||
Json(serde_json::Error),
|
||||
Network(reqwest::Error),
|
||||
Anyhow(anyhow::Error),
|
||||
Zip(zip::result::ZipError),
|
||||
Walkdir(walkdir::Error),
|
||||
Parse(ParseIntError),
|
||||
@@ -20,17 +18,15 @@ pub enum CliError {
|
||||
impl fmt::Display for CliError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
CliError::Io(e) => write!(f, "IO错误: {}", e),
|
||||
CliError::Json(e) => write!(f, "JSON解析错误: {}", e),
|
||||
CliError::Network(e) => write!(f, "网络错误: {}", e),
|
||||
CliError::Anyhow(e) => write!(f, "{}", e),
|
||||
CliError::Zip(e) => write!(f, "压缩错误: {}", e),
|
||||
CliError::Walkdir(e) => write!(f, "目录遍历错误: {}", e),
|
||||
CliError::Parse(e) => write!(f, "解析错误: {}", e),
|
||||
CliError::Toml(e) => write!(f, "TOML解析错误: {}", e),
|
||||
CliError::NotFound(msg) => write!(f, "未找到: {}", msg),
|
||||
CliError::InvalidData(msg) => write!(f, "无效数据: {}", msg),
|
||||
CliError::InvalidInput(msg) => write!(f, "无效输入: {}", msg),
|
||||
CliError::Io(e) => write!(f, "I/O error: {}", e),
|
||||
CliError::Json(e) => write!(f, "JSON parse error: {}", e),
|
||||
CliError::Zip(e) => write!(f, "ZIP error: {}", e),
|
||||
CliError::Walkdir(e) => write!(f, "directory traversal error: {}", e),
|
||||
CliError::Parse(e) => write!(f, "parse error: {}", e),
|
||||
CliError::Toml(e) => write!(f, "TOML parse error: {}", e),
|
||||
CliError::NotFound(msg) => write!(f, "not found: {}", msg),
|
||||
CliError::InvalidData(msg) => write!(f, "invalid data: {}", msg),
|
||||
CliError::InvalidInput(msg) => write!(f, "invalid input: {}", msg),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,18 +45,6 @@ impl From<serde_json::Error> for CliError {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<reqwest::Error> for CliError {
|
||||
fn from(err: reqwest::Error) -> Self {
|
||||
CliError::Network(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<anyhow::Error> for CliError {
|
||||
fn from(err: anyhow::Error) -> Self {
|
||||
CliError::Anyhow(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<zip::result::ZipError> for CliError {
|
||||
fn from(err: zip::result::ZipError) -> Self {
|
||||
CliError::Zip(err)
|
||||
|
||||
16
src/main.rs
16
src/main.rs
@@ -1,29 +1,17 @@
|
||||
mod commands;
|
||||
mod entity;
|
||||
mod utils;
|
||||
mod error;
|
||||
mod config;
|
||||
mod template;
|
||||
mod utils;
|
||||
|
||||
use crate::commands::{Cli, Commands};
|
||||
use clap::Parser;
|
||||
use std::{env, fs, path::PathBuf};
|
||||
|
||||
fn main() {
|
||||
let cli = Cli::parse();
|
||||
let temp_dir = check_temp_dir();
|
||||
match &cli.command {
|
||||
Commands::Release(args) => commands::release::execute(args),
|
||||
Commands::Create(args) => commands::create::execute(args, &temp_dir),
|
||||
Commands::Create(args) => commands::create::execute(args),
|
||||
Commands::Components(args) => commands::components::execute(args),
|
||||
}
|
||||
}
|
||||
|
||||
fn check_temp_dir() -> PathBuf {
|
||||
let mut temp_dir = env::temp_dir();
|
||||
temp_dir.push("emod-cli");
|
||||
if let Err(e) = fs::create_dir_all(&temp_dir) {
|
||||
eprintln!("Error: Failed to create temp directory: {}", e);
|
||||
}
|
||||
temp_dir
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use regex::Regex;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
@@ -62,7 +62,7 @@ impl TemplateEngine {
|
||||
for (key, var_config) in &self.config.variables {
|
||||
if var_config.required && !self.variables.contains_key(key) {
|
||||
return Err(crate::error::CliError::InvalidInput(format!(
|
||||
"缺少必需的变量: {} ({})",
|
||||
"missing required template variable: {} ({})",
|
||||
key, var_config.description
|
||||
)));
|
||||
}
|
||||
@@ -72,31 +72,19 @@ impl TemplateEngine {
|
||||
|
||||
pub fn process_directory(&self, dir: &Path) -> crate::error::Result<()> {
|
||||
self.validate_variables()?;
|
||||
|
||||
self.replace_in_files(dir)?;
|
||||
|
||||
self.apply_renames(dir)?;
|
||||
|
||||
self.verify_no_placeholders(dir)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn replace_in_files(&self, dir: &Path) -> crate::error::Result<()> {
|
||||
let placeholder_regex = Regex::new(r"\{\{(\w+)\}\}").unwrap();
|
||||
let placeholder_regex = placeholder_regex();
|
||||
|
||||
for entry in WalkDir::new(dir).into_iter().filter_map(|e| e.ok()) {
|
||||
let path = entry.path();
|
||||
|
||||
if !path.is_file() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(ext) = path.extension().and_then(|s| s.to_str()) {
|
||||
if !self.config.process.file_extensions.contains(&ext.to_string()) {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
if !path.is_file() || !self.should_process(path) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -105,7 +93,7 @@ impl TemplateEngine {
|
||||
|
||||
for cap in placeholder_regex.captures_iter(&content) {
|
||||
let placeholder = &cap[0];
|
||||
let var_name = &cap[1];
|
||||
let var_name = placeholder_name(&cap);
|
||||
|
||||
if let Some(value) = self.variables.get(var_name) {
|
||||
updated = updated.replace(placeholder, value);
|
||||
@@ -114,7 +102,7 @@ impl TemplateEngine {
|
||||
|
||||
if updated != content {
|
||||
fs::write(path, updated)?;
|
||||
println!(" - 处理文件: {}", path.display());
|
||||
println!(" - processed template file: {}", path.display());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,7 +110,7 @@ impl TemplateEngine {
|
||||
}
|
||||
|
||||
fn apply_renames(&self, dir: &Path) -> crate::error::Result<()> {
|
||||
for rule in self.config.renames.iter().rev() {
|
||||
for rule in &self.config.renames {
|
||||
let from_path = dir.join(&rule.from);
|
||||
|
||||
if !from_path.exists() {
|
||||
@@ -137,19 +125,19 @@ impl TemplateEngine {
|
||||
}
|
||||
|
||||
fs::rename(&from_path, &to_path)?;
|
||||
println!(" - 重命名: {} -> {}", rule.from, to_path_str);
|
||||
println!(" - renamed: {} -> {}", rule.from, to_path_str);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn replace_placeholders(&self, text: &str) -> String {
|
||||
let placeholder_regex = Regex::new(r"\{\{(\w+)\}\}").unwrap();
|
||||
let placeholder_regex = placeholder_regex();
|
||||
let mut result = text.to_string();
|
||||
|
||||
for cap in placeholder_regex.captures_iter(text) {
|
||||
let placeholder = &cap[0];
|
||||
let var_name = &cap[1];
|
||||
let var_name = placeholder_name(&cap);
|
||||
|
||||
if let Some(value) = self.variables.get(var_name) {
|
||||
result = result.replace(placeholder, value);
|
||||
@@ -160,39 +148,58 @@ impl TemplateEngine {
|
||||
}
|
||||
|
||||
fn verify_no_placeholders(&self, dir: &Path) -> crate::error::Result<()> {
|
||||
let placeholder_regex = Regex::new(r"\{\{(\w+)\}\}").unwrap();
|
||||
let placeholder_regex = placeholder_regex();
|
||||
let mut found_placeholders = Vec::new();
|
||||
|
||||
for entry in WalkDir::new(dir).into_iter().filter_map(|e| e.ok()) {
|
||||
let path = entry.path();
|
||||
|
||||
if !path.is_file() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(ext) = path.extension().and_then(|s| s.to_str()) {
|
||||
if !self.config.process.file_extensions.contains(&ext.to_string()) {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
if !path.is_file() || !self.should_process(path) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let content = fs::read_to_string(path)?;
|
||||
|
||||
for cap in placeholder_regex.captures_iter(&content) {
|
||||
let var_name = &cap[1];
|
||||
let var_name = placeholder_name(&cap);
|
||||
if !self.config.variables.contains_key(var_name) {
|
||||
continue;
|
||||
}
|
||||
found_placeholders.push(format!("{}:{}", path.display(), var_name));
|
||||
}
|
||||
}
|
||||
|
||||
if !found_placeholders.is_empty() {
|
||||
eprintln!("警告: 发现未替换的占位符:");
|
||||
for placeholder in found_placeholders {
|
||||
eprintln!(" - {}", placeholder);
|
||||
}
|
||||
return Err(crate::error::CliError::InvalidData(format!(
|
||||
"unresolved template placeholders: {}",
|
||||
found_placeholders.join(", ")
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn should_process(&self, path: &Path) -> bool {
|
||||
path.extension()
|
||||
.and_then(|s| s.to_str())
|
||||
.map(|ext| {
|
||||
self.config
|
||||
.process
|
||||
.file_extensions
|
||||
.iter()
|
||||
.any(|configured| configured == ext)
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
}
|
||||
|
||||
fn placeholder_regex() -> Regex {
|
||||
Regex::new(r"\{\{(\w+)\}\}|__(\w+)__").unwrap()
|
||||
}
|
||||
|
||||
fn placeholder_name<'a>(cap: &'a regex::Captures<'a>) -> &'a str {
|
||||
cap.get(1)
|
||||
.or_else(|| cap.get(2))
|
||||
.expect("placeholder capture is missing")
|
||||
.as_str()
|
||||
}
|
||||
@@ -2,29 +2,6 @@ use crate::error::Result;
|
||||
use serde_json::Value;
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
pub fn copy_folder(src: &PathBuf, dest: &PathBuf) -> Result<()> {
|
||||
if !src.exists() || !src.is_dir() {
|
||||
return Err(crate::error::CliError::NotFound(format!(
|
||||
"源目录不存在: {}",
|
||||
src.display()
|
||||
)));
|
||||
}
|
||||
if !dest.exists() {
|
||||
fs::create_dir_all(dest)?;
|
||||
}
|
||||
for entry in fs::read_dir(src)? {
|
||||
let entry = entry?;
|
||||
let src_path = entry.path();
|
||||
let dest_path = dest.join(src_path.file_name().unwrap());
|
||||
if src_path.is_file() {
|
||||
fs::copy(&src_path, &dest_path)?;
|
||||
} else if src_path.is_dir() {
|
||||
copy_folder(&src_path, &dest_path)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn read_file_to_json(path: &PathBuf) -> Result<Value> {
|
||||
let file = fs::read_to_string(path)?;
|
||||
let json: Value = serde_json::from_str(&file)?;
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
use std::path::PathBuf;
|
||||
use crate::error::Result;
|
||||
|
||||
pub fn clone_remote_project(url: String, temp_dir: &PathBuf) -> Result<()> {
|
||||
std::process::Command::new("git")
|
||||
.arg("clone")
|
||||
.arg(url)
|
||||
.arg(format!("{}/tmp", temp_dir.display()))
|
||||
.output()?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
use reqwest::blocking::Client;
|
||||
use crate::error::Result;
|
||||
|
||||
pub struct HttpClient {
|
||||
client: Client,
|
||||
}
|
||||
|
||||
impl HttpClient {
|
||||
pub fn new() -> Result<Self> {
|
||||
let client = Client::builder().build()?;
|
||||
Ok(Self { client })
|
||||
}
|
||||
|
||||
pub fn new_with_proxy(proxy_url: &str) -> Result<Self> {
|
||||
let proxy = reqwest::Proxy::all(proxy_url)?;
|
||||
let client = Client::builder().proxy(proxy).build()?;
|
||||
Ok(Self { client })
|
||||
}
|
||||
|
||||
pub fn get(&self, url: &str) -> Result<reqwest::blocking::Response> {
|
||||
Ok(self.client
|
||||
.get(url)
|
||||
.header("User-Agent", "emod-cli")
|
||||
.send()?)
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1 @@
|
||||
pub mod git;
|
||||
pub mod file;
|
||||
pub mod http;
|
||||
Reference in New Issue
Block a user