spm_swift_package/domain/file/
project_file.rs1use std::fs;
2use std::io::Write;
3
4use crate::domain::file::project_templates::*;
5
6pub struct ProjectFile;
7
8impl ProjectFile {
9 pub fn create_project(project_name: &str) -> Result<(), String> {
10 let path = format!("{}/Sources/{}", project_name, project_name);
11 Self::create_dir(&path)?;
12
13 let content = ProjectTemplates::project_swift_content();
14 let file_path = format!(
15 "{}/Sources/{}/{}.swift",
16 project_name, project_name, project_name
17 );
18 Self::write_file(&file_path, &content)?;
19 Ok(())
20 }
21
22 pub fn create_test_folder(project_name: &str) -> Result<(), String> {
23 let path = format!("{}/Tests/{}Tests", project_name, project_name);
24 Self::create_dir(&path)?;
25
26 let content = ProjectTemplates::test_content(project_name);
27 let file_path = format!(
28 "{}/Tests/{}Tests/{}Tests.swift",
29 project_name, project_name, project_name
30 );
31 Self::write_file(&file_path, &content)?;
32 Ok(())
33 }
34
35 pub fn create_package(project_name: &str, platform: &str, version: &str) -> Result<(), String> {
36 let content = ProjectTemplates::package_swift_content(project_name, platform, version);
37 Self::base_root_project(project_name, "Package.swift", content)
38 }
39
40 pub fn create_changelog(project_name: &str) -> Result<(), String> {
41 let content = ProjectTemplates::changelog_content();
42 Self::base_root_project(project_name, "CHANGELOG.md", content)
43 }
44
45 pub fn create_readme(project_name: &str) -> Result<(), String> {
46 let content = ProjectTemplates::readme_content(project_name);
47 Self::base_root_project(project_name, "README.md", content)
48 }
49
50 pub fn create_spi(project_name: &str) -> Result<(), String> {
51 let content = ProjectTemplates::spi_content(project_name);
52 Self::base_root_project(project_name, ".spi.yml", content)
53 }
54
55 pub fn create_swiftlint(project_name: &str) -> Result<(), String> {
56 let content = ProjectTemplates::swiftlint_content();
57 Self::base_root_project(project_name, ".swiftlint.yml", content)
58 }
59
60 pub fn create_mise(project_name: &str, tag: &str) -> Result<(), String> {
61 let content = ProjectTemplates::mise_content(tag);
62 Self::base_root_project(project_name, "mise.toml", content)
63 }
64
65 fn base_root_project(project_name: &str, name_file: &str, content: String) -> Result<(), String> {
66 let path = project_name.to_string();
67 Self::create_dir(&path)?;
68 let file_path = format!("{}/{}", project_name, name_file);
69 Self::write_file(&file_path, &content)
70 }
71
72 fn create_dir(path: &str) -> Result<(), String> {
73 fs::create_dir_all(path).map_err(|e| format!("Error creating directory '{}': {}", path, e))
74 }
75
76 fn write_file(path: &str, content: &str) -> Result<(), String> {
77 let mut file =
78 fs::File::create(path).map_err(|e| format!("Error creating file '{}': {}", path, e))?;
79 file
80 .write_all(content.as_bytes())
81 .map_err(|e| format!("Error writing to file '{}': {}", path, e))
82 }
83}