git-spawn 0.2.0

Async wrapper around the git CLI: builder commands, typed parsers, high-level workflow helpers
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
//! High-level handle for operating on a git repository.
//!
//! A [`Repository`] is a cheap, cloneable reference to a working tree path.
//! It is the entry point for most users: construct one via
//! [`Repository::open`], [`Repository::init`], or [`Repository::clone`], then
//! call the accessor methods ([`Repository::add`], [`Repository::commit`],
//! [`Repository::log`], ...) to build commands pre-scoped to this repo.
//!
//! ```no_run
//! use git_spawn::{GitCommand, Repository};
//!
//! # async fn example() -> git_spawn::Result<()> {
//! // Create a fresh repo and commit a file into it.
//! let repo = Repository::init("/tmp/demo").await?;
//! std::fs::write(repo.path().join("hello.txt"), "hi")?;
//! repo.add().path("hello.txt").execute().await?;
//! repo.commit().message("first").execute().await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Cloning an existing repo
//!
//! ```no_run
//! # use git_spawn::Repository;
//! # async fn example() -> git_spawn::Result<()> {
//! let repo = Repository::clone(
//!     "https://github.com/octocat/Hello-World.git",
//!     "/tmp/hello-world",
//! ).await?;
//! assert!(repo.git_dir().exists());
//! # Ok(())
//! # }
//! ```

use crate::command::{
    GitCommand, add::AddCommand, bisect::BisectCommand, branch::BranchCommand,
    checkout::CheckoutCommand, cherry_pick::CherryPickCommand, clone::CloneCommand,
    commit::CommitCommand, config::ConfigCommand, describe::DescribeCommand, diff::DiffCommand,
    fetch::FetchCommand, grep::GrepCommand, init::InitCommand, log::LogCommand,
    ls_files::LsFilesCommand, ls_tree::LsTreeCommand, merge::MergeCommand, mv::MvCommand,
    pull::PullCommand, push::PushCommand, rebase::RebaseCommand, reflog::ReflogCommand,
    remote::RemoteCommand, reset::ResetCommand, restore::RestoreCommand,
    rev_parse::RevParseCommand, rm::RmCommand, show::ShowCommand, show_ref::ShowRefCommand,
    stash::StashCommand, status::StatusCommand, submodule::SubmoduleCommand, switch::SwitchCommand,
    symbolic_ref::SymbolicRefCommand, tag::TagCommand, worktree::WorktreeCommand,
};
use crate::error::{Error, Result};
use std::path::{Path, PathBuf};

/// A handle to a git working tree.
///
/// Construction does not spawn `git`. [`Repository::open`] only verifies that
/// a `.git` directory (or file, for worktrees/submodules) exists at the path.
#[derive(Debug, Clone)]
pub struct Repository {
    path: PathBuf,
}

impl Repository {
    /// Open an existing repository at `path` without running `git`.
    ///
    /// Returns [`Error::NotARepository`] if `path/.git` does not exist.
    pub fn open(path: impl Into<PathBuf>) -> Result<Self> {
        let path = path.into();
        let dotgit = path.join(".git");
        if !dotgit.exists() {
            return Err(Error::not_a_repository(path.display().to_string()));
        }
        Ok(Self { path })
    }

    /// Construct a [`Repository`] for `path` without checking that it exists.
    ///
    /// Use this when you are about to run `init` or `clone` into the path.
    #[must_use]
    pub fn new_unchecked(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into() }
    }

    /// Working-tree path.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Path to the `.git` directory (or file) inside the working tree.
    #[must_use]
    pub fn git_dir(&self) -> PathBuf {
        self.path.join(".git")
    }

    /// Initialize a new repository at `path`.
    ///
    /// Equivalent to `git init <path>`. Returns the created [`Repository`].
    pub async fn init(path: impl Into<PathBuf>) -> Result<Self> {
        let path = path.into();
        if let Some(parent) = path.parent() {
            if !parent.as_os_str().is_empty() && !parent.exists() {
                std::fs::create_dir_all(parent).map_err(Error::from)?;
            }
        }
        if !path.exists() {
            std::fs::create_dir_all(&path).map_err(Error::from)?;
        }
        InitCommand::in_directory(path).execute().await
    }

    /// Clone `url` into `path`.
    pub async fn clone(url: impl Into<String>, path: impl Into<PathBuf>) -> Result<Self> {
        let mut cmd = CloneCommand::new(url);
        cmd.directory(path);
        cmd.execute().await
    }

    /// Build an [`AddCommand`] scoped to this repository.
    #[must_use]
    pub fn add(&self) -> AddCommand {
        let mut c = AddCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`CommitCommand`] scoped to this repository.
    #[must_use]
    pub fn commit(&self) -> CommitCommand {
        let mut c = CommitCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`StatusCommand`] scoped to this repository.
    #[must_use]
    pub fn status(&self) -> StatusCommand {
        let mut c = StatusCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`LogCommand`] scoped to this repository.
    #[must_use]
    pub fn log(&self) -> LogCommand {
        let mut c = LogCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`DiffCommand`] scoped to this repository.
    #[must_use]
    pub fn diff(&self) -> DiffCommand {
        let mut c = DiffCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`ShowCommand`] scoped to this repository.
    #[must_use]
    pub fn show(&self) -> ShowCommand {
        let mut c = ShowCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`BranchCommand`] scoped to this repository.
    #[must_use]
    pub fn branch(&self) -> BranchCommand {
        let mut c = BranchCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`CheckoutCommand`] scoped to this repository.
    #[must_use]
    pub fn checkout(&self) -> CheckoutCommand {
        let mut c = CheckoutCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`SwitchCommand`] scoped to this repository.
    #[must_use]
    pub fn switch(&self) -> SwitchCommand {
        let mut c = SwitchCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`MergeCommand`] scoped to this repository.
    #[must_use]
    pub fn merge(&self) -> MergeCommand {
        let mut c = MergeCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`RebaseCommand`] scoped to this repository.
    #[must_use]
    pub fn rebase(&self) -> RebaseCommand {
        let mut c = RebaseCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`PullCommand`] scoped to this repository.
    #[must_use]
    pub fn pull(&self) -> PullCommand {
        let mut c = PullCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`PushCommand`] scoped to this repository.
    #[must_use]
    pub fn push(&self) -> PushCommand {
        let mut c = PushCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`FetchCommand`] scoped to this repository.
    #[must_use]
    pub fn fetch(&self) -> FetchCommand {
        let mut c = FetchCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`RemoteCommand`] scoped to this repository.
    #[must_use]
    pub fn remote(&self, action: RemoteCommand) -> RemoteCommand {
        let mut c = action;
        c.current_dir(&self.path);
        c
    }

    /// Build a [`TagCommand`] scoped to this repository.
    #[must_use]
    pub fn tag(&self) -> TagCommand {
        let mut c = TagCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`StashCommand`] scoped to this repository.
    #[must_use]
    pub fn stash(&self, action: StashCommand) -> StashCommand {
        let mut c = action;
        c.current_dir(&self.path);
        c
    }

    /// Build a [`ResetCommand`] scoped to this repository.
    #[must_use]
    pub fn reset(&self) -> ResetCommand {
        let mut c = ResetCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`RestoreCommand`] scoped to this repository.
    #[must_use]
    pub fn restore(&self) -> RestoreCommand {
        let mut c = RestoreCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build an [`RmCommand`] scoped to this repository.
    #[must_use]
    pub fn rm(&self) -> RmCommand {
        let mut c = RmCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build an [`MvCommand`] scoped to this repository.
    pub fn mv(&self, src: impl Into<String>, dst: impl Into<String>) -> MvCommand {
        let mut c = MvCommand::new(src, dst);
        c.current_dir(&self.path);
        c
    }

    /// Build a [`CherryPickCommand`] scoped to this repository.
    #[must_use]
    pub fn cherry_pick(&self) -> CherryPickCommand {
        let mut c = CherryPickCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`GrepCommand`] scoped to this repository with the given pattern.
    pub fn grep(&self, pattern: impl Into<String>) -> GrepCommand {
        let mut c = GrepCommand::new(pattern);
        c.current_dir(&self.path);
        c
    }

    /// Build a [`ConfigCommand`] scoped to this repository.
    #[must_use]
    pub fn config(&self, action: ConfigCommand) -> ConfigCommand {
        let mut c = action;
        c.current_dir(&self.path);
        c
    }

    /// Build a [`ReflogCommand`] scoped to this repository.
    #[must_use]
    pub fn reflog(&self, action: ReflogCommand) -> ReflogCommand {
        let mut c = action;
        c.current_dir(&self.path);
        c
    }

    /// Build a [`WorktreeCommand`] scoped to this repository.
    #[must_use]
    pub fn worktree(&self, action: WorktreeCommand) -> WorktreeCommand {
        let mut c = action;
        c.current_dir(&self.path);
        c
    }

    /// Build a [`SubmoduleCommand`] scoped to this repository.
    #[must_use]
    pub fn submodule(&self, action: SubmoduleCommand) -> SubmoduleCommand {
        let mut c = action;
        c.current_dir(&self.path);
        c
    }

    /// Build a [`BisectCommand`] scoped to this repository.
    #[must_use]
    pub fn bisect(&self, action: BisectCommand) -> BisectCommand {
        let mut c = action;
        c.current_dir(&self.path);
        c
    }

    /// Build a [`RevParseCommand`] scoped to this repository.
    #[must_use]
    pub fn rev_parse(&self) -> RevParseCommand {
        let mut c = RevParseCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`DescribeCommand`] scoped to this repository.
    #[must_use]
    pub fn describe(&self) -> DescribeCommand {
        let mut c = DescribeCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build an [`LsFilesCommand`] scoped to this repository.
    #[must_use]
    pub fn ls_files(&self) -> LsFilesCommand {
        let mut c = LsFilesCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build an [`LsTreeCommand`] for `tree`, scoped to this repository.
    pub fn ls_tree(&self, tree: impl Into<String>) -> LsTreeCommand {
        let mut c = LsTreeCommand::new(tree);
        c.current_dir(&self.path);
        c
    }

    /// Build a [`ShowRefCommand`] scoped to this repository.
    #[must_use]
    pub fn show_ref(&self) -> ShowRefCommand {
        let mut c = ShowRefCommand::new();
        c.current_dir(&self.path);
        c
    }

    /// Build a [`SymbolicRefCommand`] scoped to this repository.
    ///
    /// Construct `action` with [`SymbolicRefCommand::read`],
    /// [`SymbolicRefCommand::set`], or [`SymbolicRefCommand::delete`].
    #[must_use]
    pub fn symbolic_ref(&self, action: SymbolicRefCommand) -> SymbolicRefCommand {
        let mut c = action;
        c.current_dir(&self.path);
        c
    }
}

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

    #[test]
    fn open_missing_repo_errors() {
        let tmp = tempfile::tempdir().unwrap();
        let err = Repository::open(tmp.path()).unwrap_err();
        assert!(matches!(err, Error::NotARepository { .. }));
    }

    #[test]
    fn new_unchecked_does_not_check() {
        let repo = Repository::new_unchecked("/definitely/not/here");
        assert_eq!(repo.path(), Path::new("/definitely/not/here"));
    }
}