ironflow-ops-git 0.1.0

Git operations for Ironflow workflows, powered by git2
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Repository-level operations: init, open, clone, discover, state.

use std::path::{Path, PathBuf};

use async_trait::async_trait;
use git2::{Repository, RepositoryState};
use ironflow_core::error::OperationError;
use ironflow_core::operation::{Operation, OperationContext, TypedOperation};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::helpers::{blocking, to_value};

fn repo_state_label(state: RepositoryState) -> &'static str {
    match state {
        RepositoryState::Clean => "clean",
        RepositoryState::Merge => "merge",
        RepositoryState::Revert | RepositoryState::RevertSequence => "revert",
        RepositoryState::CherryPickSequence | RepositoryState::CherryPick => "cherrypick",
        RepositoryState::Bisect => "bisect",
        RepositoryState::Rebase
        | RepositoryState::RebaseInteractive
        | RepositoryState::RebaseMerge => "rebase",
        RepositoryState::ApplyMailbox | RepositoryState::ApplyMailboxOrRebase => "apply-mailbox",
    }
}

/// Output of [`RepoInit`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepoInitOutput {
    /// Path where the repository was created.
    pub path: PathBuf,
    /// Whether this is a bare repository.
    pub bare: bool,
}

/// Initialize a new Git repository.
///
/// Creates a new repository at the given path. If `bare` is true, creates
/// a bare repository (no working directory).
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_git::repository::RepoInit;
/// use ironflow_core::operation::Operation;
///
/// let op = RepoInit::new("/tmp/my-repo", false);
/// assert_eq!(op.kind(), "git");
/// ```
pub struct RepoInit {
    path: PathBuf,
    bare: bool,
}

impl RepoInit {
    /// Create a new init operation.
    pub fn new(path: impl Into<PathBuf>, bare: bool) -> Self {
        Self {
            path: path.into(),
            bare,
        }
    }

    /// Execute and return a typed result.
    pub async fn run(&self, _ctx: &OperationContext) -> Result<RepoInitOutput, OperationError> {
        let path = self.path.clone();
        let bare = self.bare;
        blocking(move || {
            if bare {
                Repository::init_bare(&path)?;
            } else {
                Repository::init(&path)?;
            }
            Ok(RepoInitOutput { path, bare })
        })
        .await
    }
}

#[async_trait]
impl Operation for RepoInit {
    fn kind(&self) -> &str {
        "git"
    }

    async fn execute(&self, ctx: &OperationContext) -> Result<Value, OperationError> {
        to_value(&self.run(ctx).await?)
    }

    fn input(&self) -> Option<Value> {
        Some(serde_json::json!({ "path": self.path, "bare": self.bare }))
    }
}

impl TypedOperation for RepoInit {
    type Output = RepoInitOutput;
}

/// Output of [`RepoOpen`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepoOpenOutput {
    /// Working directory path (or the bare repo path).
    pub path: PathBuf,
    /// Whether this is a bare repository.
    pub bare: bool,
}

/// Open an existing Git repository.
///
/// Returns the repository path and whether it is bare.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_git::repository::RepoOpen;
/// use ironflow_core::operation::Operation;
///
/// let op = RepoOpen::new("/path/to/repo");
/// assert_eq!(op.kind(), "git");
/// ```
pub struct RepoOpen {
    path: PathBuf,
}

impl RepoOpen {
    /// Create a new open operation.
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into() }
    }

    /// Execute and return a typed result.
    pub async fn run(&self, _ctx: &OperationContext) -> Result<RepoOpenOutput, OperationError> {
        let path = self.path.clone();
        blocking(move || {
            let repo = Repository::open(&path)?;
            let is_bare = repo.is_bare();
            let workdir = repo.workdir().map(Path::to_path_buf);
            Ok(RepoOpenOutput {
                path: workdir.unwrap_or(path),
                bare: is_bare,
            })
        })
        .await
    }
}

#[async_trait]
impl Operation for RepoOpen {
    fn kind(&self) -> &str {
        "git"
    }

    async fn execute(&self, ctx: &OperationContext) -> Result<Value, OperationError> {
        to_value(&self.run(ctx).await?)
    }

    fn input(&self) -> Option<Value> {
        Some(serde_json::json!({ "path": self.path }))
    }
}

impl TypedOperation for RepoOpen {
    type Output = RepoOpenOutput;
}

/// Output of [`RepoClone`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepoCloneOutput {
    /// The cloned URL.
    pub url: String,
    /// Local path of the clone.
    pub path: PathBuf,
}

/// Clone a remote or local repository.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_git::repository::RepoClone;
/// use ironflow_core::operation::Operation;
///
/// let op = RepoClone::new("https://github.com/user/repo.git", "/tmp/clone");
/// assert_eq!(op.kind(), "git");
/// ```
pub struct RepoClone {
    url: String,
    path: PathBuf,
}

impl RepoClone {
    /// Create a new clone operation.
    pub fn new(url: impl Into<String>, path: impl Into<PathBuf>) -> Self {
        Self {
            url: url.into(),
            path: path.into(),
        }
    }

    /// Execute and return a typed result.
    pub async fn run(&self, _ctx: &OperationContext) -> Result<RepoCloneOutput, OperationError> {
        let url = self.url.clone();
        let path = self.path.clone();
        blocking(move || {
            Repository::clone(&url, &path)?;
            Ok(RepoCloneOutput { url, path })
        })
        .await
    }
}

#[async_trait]
impl Operation for RepoClone {
    fn kind(&self) -> &str {
        "git"
    }

    async fn execute(&self, ctx: &OperationContext) -> Result<Value, OperationError> {
        to_value(&self.run(ctx).await?)
    }

    fn input(&self) -> Option<Value> {
        Some(serde_json::json!({ "url": self.url, "path": self.path }))
    }
}

impl TypedOperation for RepoClone {
    type Output = RepoCloneOutput;
}

/// Output of [`RepoDiscover`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepoDiscoverOutput {
    /// Working directory path (if not bare).
    pub path: Option<PathBuf>,
    /// Whether this is a bare repository.
    pub bare: bool,
}

/// Discover a repository by walking parent directories.
///
/// Starts from `start_path` and walks upward until a `.git` directory is found.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_git::repository::RepoDiscover;
/// use ironflow_core::operation::Operation;
///
/// let op = RepoDiscover::new("/path/to/subdir");
/// assert_eq!(op.kind(), "git");
/// ```
pub struct RepoDiscover {
    start_path: PathBuf,
}

impl RepoDiscover {
    /// Create a new discover operation.
    pub fn new(start_path: impl Into<PathBuf>) -> Self {
        Self {
            start_path: start_path.into(),
        }
    }

    /// Execute and return a typed result.
    pub async fn run(&self, _ctx: &OperationContext) -> Result<RepoDiscoverOutput, OperationError> {
        let start = self.start_path.clone();
        blocking(move || {
            let repo = Repository::discover(&start)?;
            let workdir = repo.workdir().map(Path::to_path_buf);
            let is_bare = repo.is_bare();
            Ok(RepoDiscoverOutput {
                path: workdir,
                bare: is_bare,
            })
        })
        .await
    }
}

#[async_trait]
impl Operation for RepoDiscover {
    fn kind(&self) -> &str {
        "git"
    }

    async fn execute(&self, ctx: &OperationContext) -> Result<Value, OperationError> {
        to_value(&self.run(ctx).await?)
    }

    fn input(&self) -> Option<Value> {
        Some(serde_json::json!({ "start_path": self.start_path }))
    }
}

impl TypedOperation for RepoDiscover {
    type Output = RepoDiscoverOutput;
}

/// Output of [`RepoState`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepoStateOutput {
    /// Repository state (e.g. "Clean", "Merge", "Rebase").
    pub state: String,
}

/// Query the current state of the repository.
///
/// Returns the repository state (clean, merge, rebase, etc.).
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_git::repository::RepoState;
/// use ironflow_core::operation::Operation;
///
/// let op = RepoState::new("/path/to/repo");
/// assert_eq!(op.kind(), "git");
/// ```
pub struct RepoState {
    repo_path: PathBuf,
}

impl RepoState {
    /// Create a new state query operation.
    pub fn new(repo_path: impl Into<PathBuf>) -> Self {
        Self {
            repo_path: repo_path.into(),
        }
    }

    /// Execute and return a typed result.
    pub async fn run(&self, _ctx: &OperationContext) -> Result<RepoStateOutput, OperationError> {
        let path = self.repo_path.clone();
        blocking(move || {
            let repo = Repository::open(&path)?;
            let state = repo_state_label(repo.state()).to_string();
            Ok(RepoStateOutput { state })
        })
        .await
    }
}

#[async_trait]
impl Operation for RepoState {
    fn kind(&self) -> &str {
        "git"
    }

    async fn execute(&self, ctx: &OperationContext) -> Result<Value, OperationError> {
        to_value(&self.run(ctx).await?)
    }

    fn input(&self) -> Option<Value> {
        Some(serde_json::json!({ "repo_path": self.repo_path }))
    }
}

impl TypedOperation for RepoState {
    type Output = RepoStateOutput;
}

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

    #[tokio::test]
    async fn init_creates_repo() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("new-repo");
        let op = RepoInit::new(&target, false);
        let result = op.run(&ctx()).await.unwrap();
        assert!(!result.bare);
        assert!(target.join(".git").exists());
    }

    #[tokio::test]
    async fn init_creates_bare_repo() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("bare-repo");
        let op = RepoInit::new(&target, true);
        let result = op.run(&ctx()).await.unwrap();
        assert!(result.bare);
        assert!(target.join("HEAD").exists());
    }

    #[tokio::test]
    async fn clone_local() {
        let tmp = tempfile::tempdir().unwrap();
        let origin = tmp.path().join("origin");
        Repository::init(&origin).unwrap();

        let target = tmp.path().join("clone");
        let url = origin.to_str().unwrap();
        let op = RepoClone::new(url, &target);
        let result = op.run(&ctx()).await.unwrap();
        assert_eq!(result.path, target);
        assert!(target.join(".git").exists());
    }

    #[tokio::test]
    async fn discover_finds_repo() {
        let tmp = tempfile::tempdir().unwrap();
        Repository::init(tmp.path()).unwrap();
        let subdir = tmp.path().join("a").join("b");
        std::fs::create_dir_all(&subdir).unwrap();

        let op = RepoDiscover::new(&subdir);
        let result = op.run(&ctx()).await.unwrap();
        assert!(!result.bare);
    }

    #[tokio::test]
    async fn state_on_clean_repo() {
        let tmp = tempfile::tempdir().unwrap();
        Repository::init(tmp.path()).unwrap();

        let op = RepoState::new(tmp.path());
        let result = op.run(&ctx()).await.unwrap();
        assert_eq!(result.state, "clean");
    }
}