rustic-git 0.6.0

A Rustic Git - clean type-safe API over git cli
Documentation
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use std::path::Path;
use std::path::PathBuf;
use std::sync::OnceLock;

use crate::error::{GitError, Result};
use crate::utils::{git, git_raw};

static GIT_CHECKED: OnceLock<Result<()>> = OnceLock::new();

#[derive(Debug)]
pub struct Repository {
    repo_path: PathBuf,
}

impl Repository {
    /// Ensure that Git is available in the system PATH.
    ///
    /// This function checks if the `git` command is available in the system PATH.
    /// The result is cached, so subsequent calls are very fast.
    /// If Git is not found, it returns a `GitError::CommandFailed` with an appropriate error message.
    ///
    /// # Returns
    ///
    /// A `Result` containing either `Ok(())` if Git is available or a `GitError`.
    pub fn ensure_git() -> Result<()> {
        GIT_CHECKED
            .get_or_init(|| {
                git_raw(&["--version"], None)
                    .map_err(|_| GitError::CommandFailed("Git not found in PATH".to_string()))
                    .map(|_| ())
            })
            .clone()
    }

    /// Open an existing Git repository at the specified path.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to an existing Git repository.
    ///
    /// # Returns
    ///
    /// A `Result` containing either the opened `Repository` instance or a `GitError`.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::ensure_git()?;

        let path_ref = path.as_ref();

        // Check if the path exists
        if !path_ref.exists() {
            return Err(GitError::CommandFailed(format!(
                "Path does not exist: {}",
                path_ref.display()
            )));
        }

        // Check if it's a valid git repository by running git status
        let _stdout = git(&["status", "--porcelain"], Some(path_ref)).map_err(|_| {
            GitError::CommandFailed(format!("Not a git repository: {}", path_ref.display()))
        })?;

        Ok(Self {
            repo_path: path_ref.to_path_buf(),
        })
    }

    /// Initialize a new Git repository at the specified path.
    ///
    /// # Arguments
    ///
    /// * `path` - The path where the repository should be initialized.
    /// * `bare` - Whether the repository should be bare or not.
    ///
    /// # Returns
    ///
    /// A `Result` containing either the initialized `Repository` instance or a `GitError`.
    pub fn init<P: AsRef<Path>>(path: P, bare: bool) -> Result<Self> {
        Self::ensure_git()?;

        let mut args = vec!["init"];
        if bare {
            args.push("--bare");
        }
        args.push(path.as_ref().to_str().unwrap_or(""));

        let _stdout = git(&args, None)?;

        Ok(Self {
            repo_path: path.as_ref().to_path_buf(),
        })
    }

    pub fn repo_path(&self) -> &Path {
        &self.repo_path
    }

    /// Get a configuration manager for this repository
    ///
    /// Returns a `RepoConfig` instance that can be used to get and set
    /// git configuration values for this repository.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rustic_git::Repository;
    /// use std::env;
    ///
    /// let test_path = env::temp_dir().join("test");
    /// let repo = Repository::init(&test_path, false)?;
    /// repo.config().set_user("John Doe", "john@example.com")?;
    ///
    /// let (name, email) = repo.config().get_user()?;
    /// assert_eq!(name, "John Doe");
    /// assert_eq!(email, "john@example.com");
    /// # Ok::<(), rustic_git::GitError>(())
    /// ```
    pub fn config(&self) -> crate::commands::RepoConfig<'_> {
        crate::commands::RepoConfig::new(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;
    use std::fs;

    #[test]
    fn test_git_init_creates_repository() {
        let test_path = env::temp_dir().join("test_repo");

        // Clean up if exists
        if test_path.exists() {
            fs::remove_dir_all(&test_path).unwrap();
        }

        // Initialize repository
        let repo = Repository::init(&test_path, false).unwrap();

        // Check that .git directory was created
        assert!(test_path.join(".git").exists());
        assert_eq!(repo.repo_path(), test_path.as_path());

        // Clean up
        fs::remove_dir_all(&test_path).unwrap();
    }

    #[test]
    fn test_git_init_bare_repository() {
        let test_path = env::temp_dir().join("test_bare_repo");

        // Clean up if exists
        if test_path.exists() {
            fs::remove_dir_all(&test_path).unwrap();
        }

        // Initialize bare repository
        let repo = Repository::init(&test_path, true).unwrap();

        // Check that bare repo files were created (no .git subdirectory)
        assert!(test_path.join("HEAD").exists());
        assert!(test_path.join("objects").exists());
        assert!(!test_path.join(".git").exists());
        assert_eq!(repo.repo_path(), test_path.as_path());

        // Clean up
        fs::remove_dir_all(&test_path).unwrap();
    }

    #[test]
    fn test_open_existing_repository() {
        let test_path = env::temp_dir().join("test_open_repo");

        // Clean up if exists
        if test_path.exists() {
            fs::remove_dir_all(&test_path).unwrap();
        }

        // First create a repository
        let _created_repo = Repository::init(&test_path, false).unwrap();

        // Now open the existing repository
        let opened_repo = Repository::open(&test_path).unwrap();
        assert_eq!(opened_repo.repo_path(), test_path.as_path());

        // Clean up
        fs::remove_dir_all(&test_path).unwrap();
    }

    #[test]
    fn test_open_nonexistent_path() {
        let test_path = env::temp_dir().join("nonexistent_repo_path");

        // Ensure path doesn't exist
        if test_path.exists() {
            fs::remove_dir_all(&test_path).unwrap();
        }

        // Try to open non-existent repository
        let result = Repository::open(&test_path);
        assert!(result.is_err());

        if let Err(GitError::CommandFailed(msg)) = result {
            assert!(msg.contains("Path does not exist"));
        } else {
            panic!("Expected CommandFailed error");
        }
    }

    #[test]
    fn test_open_non_git_directory() {
        let test_path = env::temp_dir().join("not_a_git_repo");

        // Clean up if exists and create a regular directory
        if test_path.exists() {
            fs::remove_dir_all(&test_path).unwrap();
        }
        fs::create_dir(&test_path).unwrap();

        // Try to open directory that's not a git repository
        let result = Repository::open(&test_path);
        assert!(result.is_err());

        if let Err(GitError::CommandFailed(msg)) = result {
            assert!(msg.contains("Not a git repository"));
        } else {
            panic!("Expected CommandFailed error");
        }

        // Clean up
        fs::remove_dir_all(&test_path).unwrap();
    }

    #[test]
    fn test_repo_path_method() {
        let test_path = env::temp_dir().join("test_repo_path");

        // Clean up if exists
        if test_path.exists() {
            fs::remove_dir_all(&test_path).unwrap();
        }

        // Initialize repository
        let repo = Repository::init(&test_path, false).unwrap();

        // Test repo_path method
        assert_eq!(repo.repo_path(), test_path.as_path());

        // Clean up
        fs::remove_dir_all(&test_path).unwrap();
    }

    #[test]
    fn test_repo_path_method_after_open() {
        let test_path = env::temp_dir().join("test_repo_path_open");

        // Clean up if exists
        if test_path.exists() {
            fs::remove_dir_all(&test_path).unwrap();
        }

        // Initialize and then open repository
        let _created_repo = Repository::init(&test_path, false).unwrap();
        let opened_repo = Repository::open(&test_path).unwrap();

        // Test repo_path method on opened repository
        assert_eq!(opened_repo.repo_path(), test_path.as_path());

        // Clean up
        fs::remove_dir_all(&test_path).unwrap();
    }

    #[test]
    fn test_ensure_git_caching() {
        // Call ensure_git multiple times to test caching
        let result1 = Repository::ensure_git();
        let result2 = Repository::ensure_git();
        let result3 = Repository::ensure_git();

        assert!(result1.is_ok());
        assert!(result2.is_ok());
        assert!(result3.is_ok());
    }

    #[test]
    fn test_init_with_empty_string_path() {
        let result = Repository::init("", false);
        // This might succeed or fail depending on git's behavior with empty paths
        // The important thing is it doesn't panic
        let _ = result;
    }

    #[test]
    fn test_open_with_empty_string_path() {
        let result = Repository::open("");
        assert!(result.is_err());

        match result.unwrap_err() {
            GitError::CommandFailed(msg) => {
                assert!(
                    msg.contains("Path does not exist") || msg.contains("Not a git repository")
                );
            }
            _ => panic!("Expected CommandFailed error"),
        }
    }

    #[test]
    fn test_init_with_relative_path() {
        let test_path = env::temp_dir().join("relative_test_repo");

        // Clean up if exists
        if test_path.exists() {
            fs::remove_dir_all(&test_path).unwrap();
        }

        let result = Repository::init(&test_path, false);

        if let Ok(repo) = result {
            assert_eq!(repo.repo_path(), test_path.as_path());

            // Clean up
            fs::remove_dir_all(&test_path).unwrap();
        }
    }

    #[test]
    fn test_open_with_relative_path() {
        let test_path = env::temp_dir().join("relative_open_repo");

        // Clean up if exists
        if test_path.exists() {
            fs::remove_dir_all(&test_path).unwrap();
        }

        // Create the repo first
        let _created = Repository::init(&test_path, false).unwrap();

        // Now open with relative path
        let result = Repository::open(&test_path);
        assert!(result.is_ok());

        let repo = result.unwrap();
        assert_eq!(repo.repo_path(), test_path.as_path());

        // Clean up
        fs::remove_dir_all(&test_path).unwrap();
    }

    #[test]
    fn test_init_with_unicode_path() {
        let test_path = env::temp_dir().join("测试_repo_🚀");

        // Clean up if exists
        if test_path.exists() {
            fs::remove_dir_all(&test_path).unwrap();
        }

        let result = Repository::init(&test_path, false);

        if let Ok(repo) = result {
            assert_eq!(repo.repo_path(), test_path.as_path());

            // Clean up
            fs::remove_dir_all(&test_path).unwrap();
        }
    }

    #[test]
    fn test_path_with_spaces() {
        let test_path = env::temp_dir().join("test repo with spaces");

        // Clean up if exists
        if test_path.exists() {
            fs::remove_dir_all(&test_path).unwrap();
        }

        let result = Repository::init(&test_path, false);

        if let Ok(repo) = result {
            assert_eq!(repo.repo_path(), test_path.as_path());

            // Clean up
            fs::remove_dir_all(&test_path).unwrap();
        }
    }

    #[test]
    fn test_very_long_path() {
        let long_component = "a".repeat(100);
        let test_path = env::temp_dir().join(&long_component);

        // Clean up if exists
        if test_path.exists() {
            fs::remove_dir_all(&test_path).unwrap();
        }

        let result = Repository::init(&test_path, false);

        if let Ok(repo) = result {
            assert_eq!(repo.repo_path(), test_path.as_path());

            // Clean up
            fs::remove_dir_all(&test_path).unwrap();
        }
    }
}