spm_swift_package/core/file/
project_file.rs1use std::{
2 borrow::Cow,
3 path::{Path, PathBuf},
4};
5use xx::file;
6
7use crate::core::file::project_templates::ProjectTemplates;
8
9type Result<T> = std::result::Result<T, String>;
10
11pub struct ProjectFile;
12
13impl ProjectFile {
14 pub fn create_project(project_name: &str) -> Result<()> {
15 let content = ProjectTemplates::project_swift_content();
16 let file_path = Self::module_dir(project_name).join(format!("{project_name}.swift"));
17 Self::write(&file_path, content)
18 }
19
20 pub fn create_test_folder(project_name: &str, test_framework: &str) -> Result<()> {
21 let content = ProjectTemplates::test_content(project_name, test_framework);
22 let file_path = Self::tests_dir(project_name).join(format!("{project_name}Tests.swift"));
23 Self::write(&file_path, content)
24 }
25
26 pub fn create_package(
27 project_name: &str,
28 platform: &str,
29 version: &str,
30 is_plugin: bool,
31 ) -> Result<()> {
32 let content =
33 ProjectTemplates::package_swift_content(project_name, platform, version, is_plugin);
34 Self::root_write(project_name, "Package.swift", content)
35 }
36
37 pub fn create_changelog(project_name: &str) -> Result<()> {
38 Self::root_write(
39 project_name,
40 "CHANGELOG.md",
41 ProjectTemplates::changelog_content(),
42 )
43 }
44
45 pub fn create_readme(project_name: &str) -> Result<()> {
46 Self::root_write(
47 project_name,
48 "README.md",
49 ProjectTemplates::readme_content(project_name),
50 )
51 }
52
53 pub fn create_spi(project_name: &str) -> Result<()> {
54 Self::root_write(
55 project_name,
56 ".spi.yml",
57 ProjectTemplates::spi_content(project_name),
58 )
59 }
60
61 pub fn create_swiftlint(project_name: &str) -> Result<()> {
62 Self::root_write(
63 project_name,
64 ".swiftlint.yml",
65 ProjectTemplates::swiftlint_content(),
66 )
67 }
68
69 fn module_dir(project_name: &str) -> PathBuf {
70 Path::new(project_name).join("Sources").join(project_name)
71 }
72
73 fn tests_dir(project_name: &str) -> PathBuf {
74 Path::new(project_name)
75 .join("Tests")
76 .join(format!("{project_name}Tests"))
77 }
78
79 fn root_write<'a>(project_name: &str, filename: &str, content: Cow<'a, str>) -> Result<()> {
80 let file_path = Path::new(project_name).join(filename);
81 Self::write(&file_path, content)
82 }
83
84 fn write<P: AsRef<Path>, C: AsRef<str>>(path: P, content: C) -> Result<()> {
85 if let Some(parent) = path.as_ref().parent() {
86 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
87 }
88
89 file::write(path.as_ref(), content.as_ref().as_bytes()).map_err(|e| e.to_string())
90 }
91}