summaryrefslogtreecommitdiff
path: root/crates/vcs_data/src/data/local.rs
blob: cbf41ba8862ad630febdd02201cdedd107dd8a9a (plain)
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
use std::{collections::HashMap, env::current_dir, path::PathBuf, sync::Arc};

use cfg_file::config::ConfigFile;
use tokio::{fs, sync::Mutex};
use vcs_docs::docs::READMES_LOCAL_WORKSPACE_TODOLIST;

use crate::{
    constants::{CLIENT_FILE_LOCAL_SHEET, CLIENT_FILE_TODOLIST, CLIENT_FILE_WORKSPACE},
    current::{current_local_path, find_local_path},
    data::{
        local::{
            config::LocalConfig,
            local_sheet::{LocalSheet, LocalSheetData},
        },
        member::MemberId,
        sheet::SheetName,
    },
};

pub mod cached_sheet;
pub mod config;
pub mod latest_info;
pub mod local_sheet;
pub mod member_held;

const SHEET_NAME: &str = "{sheet_name}";
const ACCOUNT_NAME: &str = "{account}";

pub struct LocalWorkspace {
    config: Arc<Mutex<LocalConfig>>,
    local_path: PathBuf,
}

impl LocalWorkspace {
    /// Get the path of the local workspace.
    pub fn local_path(&self) -> &PathBuf {
        &self.local_path
    }

    /// Initialize local workspace.
    pub fn init(config: LocalConfig, local_path: impl Into<PathBuf>) -> Option<Self> {
        let local_path = find_local_path(local_path)?;
        Some(Self {
            config: Arc::new(Mutex::new(config)),
            local_path,
        })
    }

    /// Initialize local workspace in the current directory.
    pub fn init_current_dir(config: LocalConfig) -> Option<Self> {
        let local_path = current_local_path()?;
        Some(Self {
            config: Arc::new(Mutex::new(config)),
            local_path,
        })
    }

    /// Setup local workspace
    pub async fn setup_local_workspace(
        local_path: impl Into<PathBuf>,
    ) -> Result<(), std::io::Error> {
        let local_path: PathBuf = local_path.into();

        // Ensure directory is empty
        if local_path.exists() && local_path.read_dir()?.next().is_some() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::DirectoryNotEmpty,
                "DirectoryNotEmpty",
            ));
        }

        // 1. Setup config
        let config = LocalConfig::default();
        LocalConfig::write_to(&config, local_path.join(CLIENT_FILE_WORKSPACE)).await?;

        // 2. Setup README.md
        let readme_content = READMES_LOCAL_WORKSPACE_TODOLIST.trim().to_string();
        fs::write(local_path.join(CLIENT_FILE_TODOLIST), readme_content).await?;

        // On Windows, set the .jv directory as hidden
        let jv_dir = local_path.join(".jv");
        let _ = hide_folder::hide_folder(&jv_dir);

        Ok(())
    }

    /// Get a reference to the local configuration.
    pub fn config(&self) -> Arc<Mutex<LocalConfig>> {
        self.config.clone()
    }

    /// Setup local workspace in current directory
    pub async fn setup_local_workspace_current_dir() -> Result<(), std::io::Error> {
        Self::setup_local_workspace(current_dir()?).await?;
        Ok(())
    }

    /// Get the path to a local sheet.
    pub fn local_sheet_path(&self, member: &MemberId, sheet: &SheetName) -> PathBuf {
        let result = self.local_path.join(
            CLIENT_FILE_LOCAL_SHEET
                .replace(ACCOUNT_NAME, member)
                .replace(SHEET_NAME, sheet),
        );
        result
    }

    /// Read or initialize a local sheet.
    pub async fn local_sheet(
        &self,
        member: &MemberId,
        sheet: &SheetName,
    ) -> Result<LocalSheet<'_>, std::io::Error> {
        let local_sheet_path = self.local_sheet_path(member, sheet);

        if !local_sheet_path.exists() {
            let sheet_data = LocalSheetData {
                mapping: HashMap::new(),
            };
            LocalSheetData::write_to(&sheet_data, local_sheet_path).await?;
            return Ok(LocalSheet {
                local_workspace: self,
                member: member.clone(),
                sheet_name: sheet.clone(),
                data: sheet_data,
            });
        }

        let data = LocalSheetData::read_from(&local_sheet_path).await?;
        let local_sheet = LocalSheet {
            local_workspace: self,
            member: member.clone(),
            sheet_name: sheet.clone(),
            data,
        };

        Ok(local_sheet)
    }
}

mod hide_folder {
    use std::io;
    use std::path::Path;

    #[cfg(windows)]
    use std::os::windows::ffi::OsStrExt;
    #[cfg(windows)]
    use winapi::um::fileapi::{GetFileAttributesW, SetFileAttributesW, INVALID_FILE_ATTRIBUTES};

    pub fn hide_folder(path: &Path) -> io::Result<()> {
        if !path.is_dir() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "Path must be a directory",
            ));
        }

        if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
            if !file_name.starts_with('.') {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "Directory name must start with '.'",
                ));
            }
        } else {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "Invalid directory name",
            ));
        }

        hide_folder_impl(path)
    }

    #[cfg(windows)]
    fn hide_folder_impl(path: &Path) -> io::Result<()> {
        // Convert to Windows wide string format
        let path_str: Vec<u16> = path.as_os_str()
            .encode_wide()
            .chain(Some(0))
            .collect();

        // Get current attributes
        let attrs = unsafe { GetFileAttributesW(path_str.as_ptr()) };
        if attrs == INVALID_FILE_ATTRIBUTES {
            return Err(io::Error::last_os_error());
        }

        // Add hidden attribute flag
        let new_attrs = attrs | winapi::um::winnt::FILE_ATTRIBUTE_HIDDEN;

        // Set new attributes
        let success = unsafe { SetFileAttributesW(path_str.as_ptr(), new_attrs) };
        if success == 0 {
            return Err(io::Error::last_os_error());
        }

        Ok(())
    }

    #[cfg(unix)]
    fn hide_folder_impl(_path: &Path) -> io::Result<()> {
        Ok(())
    }

    #[cfg(not(any(windows, unix)))]
    fn hide_folder_impl(_path: &Path) -> io::Result<()> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "Unsupported operating system",
        ))
    }
}