ironflow-ops-git 0.1.19

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
//! Fetch and push operations.
//!
//! Every operation here talks to a remote. Over HTTPS they authenticate with
//! the token held in the `git_token` secret (username `oauth2`), both
//! overridable with `token_secret` and `username`. Without that secret they
//! fall back to the SSH agent and the git credential helper.

use std::path::PathBuf;

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

use crate::helpers::{
    GitAuth, auth_builders, blocking_authenticated, credentials_callbacks, to_value,
};

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

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemotePruneOutput {
    pub remote: String,
    pub pruned: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemoteDefaultBranchOutput {
    pub remote: String,
    pub default_branch: Option<String>,
}

/// Fetch from a remote.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_git::fetch::FetchRemote;
/// use ironflow_core::operation::Operation;
///
/// let op = FetchRemote::new("/path/to/repo", "origin", vec!["main"]);
/// assert_eq!(op.kind(), "git");
/// ```
pub struct FetchRemote {
    repo_path: PathBuf,
    remote_name: String,
    refspecs: Vec<String>,
    auth: GitAuth,
}

impl FetchRemote {
    /// Create a new fetch operation.
    pub fn new(
        repo_path: impl Into<PathBuf>,
        remote_name: impl Into<String>,
        refspecs: Vec<impl Into<String>>,
    ) -> Self {
        Self {
            repo_path: repo_path.into(),
            remote_name: remote_name.into(),
            refspecs: refspecs.into_iter().map(Into::into).collect(),
            auth: GitAuth::default(),
        }
    }

    /// Execute and return a typed result.
    ///
    /// # Errors
    ///
    /// Returns [`OperationError::Secret`] if the secret store fails, and
    /// [`OperationError::External`] if the fetch fails. The token never
    /// appears in the message.
    pub async fn run(&self, ctx: &OperationContext) -> Result<FetchPushOutput, OperationError> {
        let repo_path = self.repo_path.clone();
        let remote_name = self.remote_name.clone();
        let refspecs = self.refspecs.clone();
        blocking_authenticated(ctx, &self.auth, move |creds| {
            let repo = Repository::open(&repo_path)?;
            let mut remote = repo.find_remote(&remote_name)?;
            let refs: Vec<&str> = refspecs.iter().map(String::as_str).collect();
            let mut fetch_opts = FetchOptions::new();
            fetch_opts.remote_callbacks(credentials_callbacks(creds));
            remote.fetch(&refs, Some(&mut fetch_opts), None)?;
            Ok(FetchPushOutput {
                remote: remote_name,
                refspecs,
            })
        })
        .await
    }
}

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

impl TypedOperation for FetchRemote {
    type Output = FetchPushOutput;
}

auth_builders!(
    FetchRemote,
    "fetch",
    "\"/path/to/repo\", \"origin\", vec![\"main\"]"
);

/// Push to a remote.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_git::fetch::PushRemote;
/// use ironflow_core::operation::Operation;
///
/// let op = PushRemote::new("/path/to/repo", "origin", vec!["refs/heads/main"]);
/// assert_eq!(op.kind(), "git");
/// ```
pub struct PushRemote {
    repo_path: PathBuf,
    remote_name: String,
    refspecs: Vec<String>,
    auth: GitAuth,
}

impl PushRemote {
    /// Create a new push operation.
    pub fn new(
        repo_path: impl Into<PathBuf>,
        remote_name: impl Into<String>,
        refspecs: Vec<impl Into<String>>,
    ) -> Self {
        Self {
            repo_path: repo_path.into(),
            remote_name: remote_name.into(),
            refspecs: refspecs.into_iter().map(Into::into).collect(),
            auth: GitAuth::default(),
        }
    }

    /// Execute and return a typed result.
    ///
    /// # Errors
    ///
    /// Returns [`OperationError::Secret`] if the secret store fails, and
    /// [`OperationError::External`] if the push fails. The token never
    /// appears in the message.
    pub async fn run(&self, ctx: &OperationContext) -> Result<FetchPushOutput, OperationError> {
        let repo_path = self.repo_path.clone();
        let remote_name = self.remote_name.clone();
        let refspecs = self.refspecs.clone();
        blocking_authenticated(ctx, &self.auth, move |creds| {
            let repo = Repository::open(&repo_path)?;
            let mut remote = repo.find_remote(&remote_name)?;
            let refs: Vec<&str> = refspecs.iter().map(String::as_str).collect();
            let mut push_opts = PushOptions::new();
            push_opts.remote_callbacks(credentials_callbacks(creds));
            remote.push(&refs, Some(&mut push_opts))?;
            Ok(FetchPushOutput {
                remote: remote_name,
                refspecs,
            })
        })
        .await
    }
}

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

impl TypedOperation for PushRemote {
    type Output = FetchPushOutput;
}

auth_builders!(
    PushRemote,
    "fetch",
    "\"/path/to/repo\", \"origin\", vec![\"refs/heads/main\"]"
);

/// Prune stale remote-tracking branches.
///
/// Connects to the remote to list its branches, then deletes the
/// remote-tracking refs whose branch no longer exists there.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_git::fetch::RemotePrune;
/// use ironflow_core::operation::Operation;
///
/// let op = RemotePrune::new("/path/to/repo", "origin");
/// assert_eq!(op.kind(), "git");
/// ```
pub struct RemotePrune {
    repo_path: PathBuf,
    remote_name: String,
    auth: GitAuth,
}

impl RemotePrune {
    /// Create a new prune operation.
    pub fn new(repo_path: impl Into<PathBuf>, remote_name: impl Into<String>) -> Self {
        Self {
            repo_path: repo_path.into(),
            remote_name: remote_name.into(),
            auth: GitAuth::default(),
        }
    }

    /// Execute and return a typed result.
    ///
    /// # Errors
    ///
    /// Returns [`OperationError::Secret`] if the secret store fails, and
    /// [`OperationError::External`] if the connection or the prune fails. The
    /// token never appears in the message.
    pub async fn run(&self, ctx: &OperationContext) -> Result<RemotePruneOutput, OperationError> {
        let repo_path = self.repo_path.clone();
        let remote_name = self.remote_name.clone();
        blocking_authenticated(ctx, &self.auth, move |creds| {
            let repo = Repository::open(&repo_path)?;
            let mut remote = repo.find_remote(&remote_name)?;
            let mut connection =
                remote.connect_auth(Direction::Fetch, Some(credentials_callbacks(creds)), None)?;
            connection.remote().prune(None)?;
            Ok(RemotePruneOutput {
                remote: remote_name,
                pruned: true,
            })
        })
        .await
    }
}

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

impl TypedOperation for RemotePrune {
    type Output = RemotePruneOutput;
}

auth_builders!(RemotePrune, "fetch", "\"/path/to/repo\", \"origin\"");

/// Get the default branch of a remote.
///
/// Connects to the remote and reads the branch its `HEAD` points to.
///
/// # Examples
///
/// ```no_run
/// use ironflow_ops_git::fetch::RemoteDefaultBranch;
/// use ironflow_core::operation::Operation;
///
/// let op = RemoteDefaultBranch::new("/path/to/repo", "origin");
/// assert_eq!(op.kind(), "git");
/// ```
pub struct RemoteDefaultBranch {
    repo_path: PathBuf,
    remote_name: String,
    auth: GitAuth,
}

impl RemoteDefaultBranch {
    /// Create a new default-branch query operation.
    pub fn new(repo_path: impl Into<PathBuf>, remote_name: impl Into<String>) -> Self {
        Self {
            repo_path: repo_path.into(),
            remote_name: remote_name.into(),
            auth: GitAuth::default(),
        }
    }

    /// Execute and return a typed result.
    ///
    /// # Errors
    ///
    /// Returns [`OperationError::Secret`] if the secret store fails, and
    /// [`OperationError::External`] if the connection fails or the remote
    /// has no default branch. The token never appears in the message.
    pub async fn run(
        &self,
        ctx: &OperationContext,
    ) -> Result<RemoteDefaultBranchOutput, OperationError> {
        let repo_path = self.repo_path.clone();
        let remote_name = self.remote_name.clone();
        blocking_authenticated(ctx, &self.auth, move |creds| {
            let repo = Repository::open(&repo_path)?;
            let mut remote = repo.find_remote(&remote_name)?;
            let connection =
                remote.connect_auth(Direction::Fetch, Some(credentials_callbacks(creds)), None)?;
            let default = connection.default_branch()?;
            let name = default.as_str().map(String::from);
            Ok(RemoteDefaultBranchOutput {
                remote: remote_name,
                default_branch: name,
            })
        })
        .await
    }
}

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

impl TypedOperation for RemoteDefaultBranch {
    type Output = RemoteDefaultBranchOutput;
}

auth_builders!(
    RemoteDefaultBranch,
    "fetch",
    "\"/path/to/repo\", \"origin\""
);

#[cfg(test)]
mod tests {
    use git2::Repository;

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

    // Push and fetch over a local bare remote (file://) never hit the
    // credentials callback, but exercising them proves that wiring
    // PushOptions/FetchOptions with RemoteCallbacks does not break the normal
    // flow. The SSH-agent path (the literal issue symptom) needs a live SSH
    // server and is covered in Out of Test Scope.
    fn setup_with_bare_remote() -> (tempfile::TempDir, tempfile::TempDir) {
        let work = tempfile::tempdir().unwrap();
        init_repo(work.path());
        let bare = tempfile::tempdir().unwrap();
        Repository::init_bare(bare.path()).unwrap();
        let repo = Repository::open(work.path()).unwrap();
        repo.remote("origin", bare.path().to_str().unwrap())
            .unwrap();
        (work, bare)
    }

    #[tokio::test]
    async fn push_to_local_bare_remote() {
        let (work, bare) = setup_with_bare_remote();
        let result = PushRemote::new(
            work.path(),
            "origin",
            vec!["refs/heads/master:refs/heads/master"],
        )
        .run(&ctx())
        .await
        .unwrap();
        assert_eq!(result.remote, "origin");
        // The ref must exist on the remote side after the push.
        let bare_repo = Repository::open(bare.path()).unwrap();
        assert!(bare_repo.find_reference("refs/heads/master").is_ok());
    }

    #[tokio::test]
    async fn fetch_from_local_bare_remote() {
        let (work, bare) = setup_with_bare_remote();
        PushRemote::new(
            work.path(),
            "origin",
            vec!["refs/heads/master:refs/heads/master"],
        )
        .run(&ctx())
        .await
        .unwrap();
        // A second clone fetching from the same bare remote must succeed.
        let clone_dir = tempfile::tempdir().unwrap();
        let clone = Repository::init(clone_dir.path()).unwrap();
        clone
            .remote("origin", bare.path().to_str().unwrap())
            .unwrap();
        let result = FetchRemote::new(clone_dir.path(), "origin", vec!["master"])
            .run(&ctx())
            .await
            .unwrap();
        assert_eq!(result.remote, "origin");
    }

    #[tokio::test]
    async fn push_missing_remote_fails() {
        let work = tempfile::tempdir().unwrap();
        init_repo(work.path());
        let result = PushRemote::new(work.path(), "nope", vec!["refs/heads/master"])
            .run(&ctx())
            .await;
        assert!(result.is_err());
    }
}