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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! Index / staging area operations.

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

use async_trait::async_trait;
use git2::{IndexAddOption, Repository};
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};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexPathOutput {
    pub path: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexPathspecsOutput {
    pub pathspecs: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexUpdateAllOutput {
    pub updated: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexWriteTreeOutput {
    pub tree_oid: String,
}

/// Add a single file to the index.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_git::index::IndexAdd;
/// use ironflow_core::operation::Operation;
///
/// let op = IndexAdd::new("/path/to/repo", "file.txt");
/// assert_eq!(op.kind(), "git");
/// ```
pub struct IndexAdd {
    repo_path: PathBuf,
    path: String,
}

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

    /// Execute and return a typed result.
    pub async fn run(&self, _ctx: &OperationContext) -> Result<IndexPathOutput, OperationError> {
        let repo_path = self.repo_path.clone();
        let file_path = self.path.clone();
        blocking(move || {
            let repo = Repository::open(&repo_path)?;
            let mut index = repo.index()?;
            index.add_path(Path::new(&file_path))?;
            index.write()?;
            Ok(IndexPathOutput { path: file_path })
        })
        .await
    }
}

#[async_trait]
impl Operation for IndexAdd {
    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, "path": self.path }))
    }
}

impl TypedOperation for IndexAdd {
    type Output = IndexPathOutput;
}

/// Add all files matching a pathspec to the index.
///
/// Equivalent to `git add .` when called with `["*"]` or `["."]`.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_git::index::IndexAddAll;
/// use ironflow_core::operation::Operation;
///
/// let op = IndexAddAll::new("/path/to/repo", vec!["*.rs"]);
/// assert_eq!(op.kind(), "git");
/// ```
pub struct IndexAddAll {
    repo_path: PathBuf,
    pathspecs: Vec<String>,
}

impl IndexAddAll {
    /// Create a new add-all operation.
    pub fn new(repo_path: impl Into<PathBuf>, pathspecs: Vec<impl Into<String>>) -> Self {
        Self {
            repo_path: repo_path.into(),
            pathspecs: pathspecs.into_iter().map(Into::into).collect(),
        }
    }

    /// Execute and return a typed result.
    pub async fn run(
        &self,
        _ctx: &OperationContext,
    ) -> Result<IndexPathspecsOutput, OperationError> {
        let repo_path = self.repo_path.clone();
        let pathspecs = self.pathspecs.clone();
        blocking(move || {
            let repo = Repository::open(&repo_path)?;
            let mut index = repo.index()?;
            index.add_all(&pathspecs, IndexAddOption::DEFAULT, None)?;
            index.write()?;
            Ok(IndexPathspecsOutput { pathspecs })
        })
        .await
    }
}

#[async_trait]
impl Operation for IndexAddAll {
    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, "pathspecs": self.pathspecs }))
    }
}

impl TypedOperation for IndexAddAll {
    type Output = IndexPathspecsOutput;
}

/// Remove a file from the index.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_git::index::IndexRemove;
/// use ironflow_core::operation::Operation;
///
/// let op = IndexRemove::new("/path/to/repo", "file.txt");
/// assert_eq!(op.kind(), "git");
/// ```
pub struct IndexRemove {
    repo_path: PathBuf,
    path: String,
}

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

    /// Execute and return a typed result.
    pub async fn run(&self, _ctx: &OperationContext) -> Result<IndexPathOutput, OperationError> {
        let repo_path = self.repo_path.clone();
        let file_path = self.path.clone();
        blocking(move || {
            let repo = Repository::open(&repo_path)?;
            let mut index = repo.index()?;
            index.remove_path(Path::new(&file_path))?;
            index.write()?;
            Ok(IndexPathOutput { path: file_path })
        })
        .await
    }
}

#[async_trait]
impl Operation for IndexRemove {
    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, "path": self.path }))
    }
}

impl TypedOperation for IndexRemove {
    type Output = IndexPathOutput;
}

/// Remove all files matching a pathspec from the index.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_git::index::IndexRemoveAll;
/// use ironflow_core::operation::Operation;
///
/// let op = IndexRemoveAll::new("/path/to/repo", vec!["*.tmp"]);
/// assert_eq!(op.kind(), "git");
/// ```
pub struct IndexRemoveAll {
    repo_path: PathBuf,
    pathspecs: Vec<String>,
}

impl IndexRemoveAll {
    /// Create a new remove-all operation.
    pub fn new(repo_path: impl Into<PathBuf>, pathspecs: Vec<impl Into<String>>) -> Self {
        Self {
            repo_path: repo_path.into(),
            pathspecs: pathspecs.into_iter().map(Into::into).collect(),
        }
    }

    /// Execute and return a typed result.
    pub async fn run(
        &self,
        _ctx: &OperationContext,
    ) -> Result<IndexPathspecsOutput, OperationError> {
        let repo_path = self.repo_path.clone();
        let pathspecs = self.pathspecs.clone();
        blocking(move || {
            let repo = Repository::open(&repo_path)?;
            let mut index = repo.index()?;
            index.remove_all(&pathspecs, None)?;
            index.write()?;
            Ok(IndexPathspecsOutput { pathspecs })
        })
        .await
    }
}

#[async_trait]
impl Operation for IndexRemoveAll {
    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, "pathspecs": self.pathspecs }))
    }
}

impl TypedOperation for IndexRemoveAll {
    type Output = IndexPathspecsOutput;
}

/// Update all tracked files in the index.
///
/// Updates the index with the current content of tracked files.
/// Equivalent to `git add -u`.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_git::index::IndexUpdateAll;
/// use ironflow_core::operation::Operation;
///
/// let op = IndexUpdateAll::new("/path/to/repo");
/// assert_eq!(op.kind(), "git");
/// ```
pub struct IndexUpdateAll {
    repo_path: PathBuf,
}

impl IndexUpdateAll {
    /// Create a new update-all 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<IndexUpdateAllOutput, OperationError> {
        let repo_path = self.repo_path.clone();
        blocking(move || {
            let repo = Repository::open(&repo_path)?;
            let mut index = repo.index()?;
            index.update_all(["*"], None)?;
            index.write()?;
            Ok(IndexUpdateAllOutput { updated: true })
        })
        .await
    }
}

#[async_trait]
impl Operation for IndexUpdateAll {
    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 IndexUpdateAll {
    type Output = IndexUpdateAllOutput;
}

/// Write the index as a tree object.
///
/// Converts the current index into a tree object in the object database.
/// Returns the tree OID.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_git::index::IndexWriteTree;
/// use ironflow_core::operation::Operation;
///
/// let op = IndexWriteTree::new("/path/to/repo");
/// assert_eq!(op.kind(), "git");
/// ```
pub struct IndexWriteTree {
    repo_path: PathBuf,
}

impl IndexWriteTree {
    /// Create a new write-tree 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<IndexWriteTreeOutput, OperationError> {
        let repo_path = self.repo_path.clone();
        blocking(move || {
            let repo = Repository::open(&repo_path)?;
            let mut index = repo.index()?;
            let oid = index.write_tree()?;
            Ok(IndexWriteTreeOutput {
                tree_oid: oid.to_string(),
            })
        })
        .await
    }
}

#[async_trait]
impl Operation for IndexWriteTree {
    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 IndexWriteTree {
    type Output = IndexWriteTreeOutput;
}

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

    use ironflow_core::operation::Operation;

    use super::*;
    use crate::test_helpers::{ctx, init_repo};

    #[tokio::test]
    async fn add_and_remove() {
        let tmp = tempfile::tempdir().unwrap();
        init_repo(tmp.path());
        fs::write(tmp.path().join("new.txt"), "n").unwrap();
        let result = IndexAdd::new(tmp.path(), "new.txt")
            .run(&ctx())
            .await
            .unwrap();
        assert_eq!(result.path, "new.txt");
        let result = IndexRemove::new(tmp.path(), "new.txt")
            .run(&ctx())
            .await
            .unwrap();
        assert_eq!(result.path, "new.txt");
    }

    #[tokio::test]
    async fn add_all_with_glob() {
        let tmp = tempfile::tempdir().unwrap();
        init_repo(tmp.path());
        fs::write(tmp.path().join("a.rs"), "a").unwrap();
        fs::write(tmp.path().join("b.rs"), "b").unwrap();
        let result = IndexAddAll::new(tmp.path(), vec!["*.rs"])
            .run(&ctx())
            .await
            .unwrap();
        assert_eq!(result.pathspecs, vec!["*.rs"]);
    }

    #[tokio::test]
    async fn update_all() {
        let tmp = tempfile::tempdir().unwrap();
        init_repo(tmp.path());
        fs::write(tmp.path().join("file.txt"), "modified").unwrap();
        let result = IndexUpdateAll::new(tmp.path()).run(&ctx()).await.unwrap();
        assert!(result.updated);
    }

    #[tokio::test]
    async fn write_tree_returns_oid() {
        let tmp = tempfile::tempdir().unwrap();
        init_repo(tmp.path());
        let result = IndexWriteTree::new(tmp.path()).run(&ctx()).await.unwrap();
        assert!(!result.tree_oid.is_empty());
    }

    #[tokio::test]
    async fn add_nonexistent_file_fails() {
        let tmp = tempfile::tempdir().unwrap();
        init_repo(tmp.path());
        assert!(
            IndexAdd::new(tmp.path(), "nope.txt")
                .run(&ctx())
                .await
                .is_err()
        );
    }

    #[tokio::test]
    async fn execute_serializes_correctly() {
        let tmp = tempfile::tempdir().unwrap();
        init_repo(tmp.path());
        let value = IndexWriteTree::new(tmp.path())
            .execute(&ctx())
            .await
            .unwrap();
        assert!(value["tree_oid"].is_string());
    }
}