GitRoot
craft your forge, build your project, grow your community freely
1// SPDX-FileCopyrightText: 2025 Romain Maneschi <romain@gitroot.dev>
2//
3// SPDX-License-Identifier: MIT
4
5use std::{fs, io};
6
7use serde::Serialize;
8
9use crate::imports;
10
11#[derive(Debug, Serialize, Clone, Copy)]
12#[serde(rename_all = "lowercase")]
13pub enum FsBase {
14 WORKTREE, // = "worktree",
15 WEBCONTENT, // = "webcontent",
16 CACHE, // = "cache",
17}
18
19impl FsBase {
20 pub fn as_str(&self) -> &'static str {
21 match self {
22 FsBase::WORKTREE => "worktree",
23 FsBase::WEBCONTENT => "webcontent",
24 FsBase::CACHE => "cache",
25 }
26 }
27}
28
29pub struct Fs {
30 base: FsBase,
31 start: String,
32}
33
34impl Fs {
35 pub fn new(base: FsBase) -> Self {
36 Fs {
37 base,
38 start: format!("/{}", base.as_str()),
39 }
40 }
41
42 pub fn open<S>(&self, path: S) -> Result<String, io::Error>
43 where
44 S: Into<String>,
45 {
46 let prepend = &self.start;
47 fs::read_to_string(format!("{prepend}/{}", path.into()))
48 }
49
50 pub fn exists<S>(&self, path: S) -> Result<bool, io::Error>
51 where
52 S: Into<String>,
53 {
54 let prepend = &self.start;
55 fs::exists(format!("{prepend}/{}", path.into()))
56 }
57
58 pub fn write_content<S>(&self, path: S, content: S) -> Result<(), String>
59 where
60 S: Into<String>,
61 {
62 imports::write_content(self.base, path.into(), content.into())
63 }
64
65 pub fn replace_content<S>(&self, path: S, old_content: S, content: S) -> Result<(), String>
66 where
67 S: Into<String>,
68 {
69 imports::replace_content(self.base, path.into(), old_content.into(), content.into())
70 }
71
72 pub fn copy_file<S>(&self, from_path: S, to_path: S) -> Result<(), String>
73 where
74 S: Into<String>,
75 {
76 imports::copy_file(self.base, from_path.into(), self.base, to_path.into())
77 }
78
79 pub fn copy_file_to_fs<S>(&self, from_path: S, to_fs: &Fs, to_path: S) -> Result<(), String>
80 where
81 S: Into<String>,
82 {
83 imports::copy_file(self.base, from_path.into(), to_fs.base, to_path.into())
84 }
85
86 pub fn delete_file<S>(&self, filename: S) -> Result<(), String>
87 where
88 S: Into<String>,
89 {
90 imports::delete_file(self.base, filename.into())
91 }
92
93 pub fn move_file<S>(&self, from_path: S, to_path: S) -> Result<(), String>
94 where
95 S: Into<String>,
96 {
97 imports::move_file(self.base, from_path.into(), self.base, to_path.into())
98 }
99
100 pub fn move_file_to_fs<S, K>(&self, from_path: S, to_fs: &Fs, to_path: K) -> Result<(), String>
101 where
102 S: Into<String>,
103 K: Into<String>,
104 {
105 imports::move_file(self.base, from_path.into(), to_fs.base, to_path.into())
106 }
107}