ionem 0.2.1

Library for building Ion binary skills with standard self-management commands
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
//! Git CLI wrappers.
//!
//! Use [`require()`] to verify `git` is installed, then call methods on the
//! returned [`Git`] handle:
//!
//! ```ignore
//! let git = git::require()?;
//! let repo = git.repo(project_dir);
//! repo.stage_files(&["Ion.toml", "Ion.lock"])?;
//! if repo.has_staged_changes()? {
//!     let sha = repo.create_commit("chore: update manifest")?;
//! }
//! ```

use std::path::Path;

use super::{Cli, CliError, Result};

/// The `git` CLI descriptor.
pub const CLI: Cli = Cli {
    name: "git",
    hint: "Install from https://git-scm.com",
};

/// Verify `git` is installed and return a handle to run commands.
pub fn require() -> Result<Git> {
    CLI.require()?;
    Ok(Git)
}

/// A validated handle proving the `git` CLI is available.
///
/// Obtained via [`require()`]. Context constructors and standalone
/// operations live here.
pub struct Git;

impl Git {
    /// Create a [`Repo`] context bound to the given working directory.
    pub fn repo<'a>(&self, path: &'a Path) -> Repo<'a> {
        repo(path)
    }

    /// Clone a git repository, or fetch updates if it already exists.
    pub fn clone_or_fetch(&self, url: &str, target: &Path) -> Result<()> {
        clone_or_fetch(url, target)
    }

    /// Initialize a new git repository.
    pub fn init(&self, path: &Path) -> Result<()> {
        init(path)
    }
}

/// Clone a git repository to a target directory. If it already exists, fetch updates.
pub fn clone_or_fetch(url: &str, target: &Path) -> Result<()> {
    if target.join(".git").exists() {
        CLI.run_status(
            CLI.command()
                .args(["fetch", "--all"])
                .current_dir(target)
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null()),
        )
    } else {
        if let Some(parent) = target.parent() {
            std::fs::create_dir_all(parent).map_err(|e| CliError::Spawn {
                cli: CLI.name.to_string(),
                source: e,
            })?;
        }

        CLI.run_status(
            CLI.command()
                .args(["clone", url, &target.display().to_string()])
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null()),
        )
    }
}

/// Checkout a specific ref (branch, tag, or commit SHA).
pub fn checkout(repo: &Path, rev: &str) -> Result<()> {
    CLI.run_status(
        CLI.command()
            .args(["checkout", rev])
            .current_dir(repo)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null()),
    )
}

/// Get the current HEAD commit SHA.
pub fn head_commit(repo: &Path) -> Result<String> {
    CLI.run_command(CLI.command().args(["rev-parse", "HEAD"]).current_dir(repo))
}

/// Get the default branch name for a repo by checking `origin/HEAD` or falling back
/// to `symbolic-ref HEAD`.
pub fn default_branch(repo: &Path) -> Result<String> {
    // Try origin/HEAD first (works for cloned repos)
    let origin_result = CLI.run_command(
        CLI.command()
            .args(["symbolic-ref", "refs/remotes/origin/HEAD"])
            .current_dir(repo),
    );

    if let Ok(full_ref) = origin_result
        && let Some(branch) = full_ref.strip_prefix("refs/remotes/origin/")
    {
        return Ok(branch.to_string());
    }

    // Fallback: local HEAD's branch name
    let local_result = CLI.run_command(
        CLI.command()
            .args(["symbolic-ref", "--short", "HEAD"])
            .current_dir(repo),
    );

    match local_result {
        Ok(branch) => Ok(branch),
        Err(_) => Err(CliError::Failed {
            cli: CLI.name.to_string(),
            code: 1,
            stderr: "Could not determine default branch".to_string(),
        }),
    }
}

/// Reset the working tree to the remote's default branch HEAD.
/// Call this after `clone_or_fetch()` to advance to the latest commit.
pub fn reset_to_remote_head(repo: &Path) -> Result<()> {
    let branch = default_branch(repo)?;
    let remote_ref = format!("origin/{branch}");

    CLI.run_status(
        CLI.command()
            .args(["reset", "--hard", &remote_ref])
            .current_dir(repo)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null()),
    )
}

/// Stage files in a git repository.
pub fn stage_files(repo: &Path, files: &[&str]) -> Result<()> {
    let mut cmd = CLI.command();
    cmd.arg("add")
        .current_dir(repo)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    for file in files {
        cmd.arg(file);
    }
    CLI.run_status(&mut cmd)
}

/// Check if there are staged changes in a git repository.
///
/// Returns `true` if there are staged changes, `false` if there are none.
/// `git diff --cached --quiet` exits with code 1 when there are changes.
pub fn has_staged_changes(repo: &Path) -> Result<bool> {
    let result = CLI.run_status(
        CLI.command()
            .args(["diff", "--cached", "--quiet"])
            .current_dir(repo)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null()),
    );

    match result {
        Ok(()) => Ok(false),
        Err(CliError::Failed { code: 1, .. }) => Ok(true),
        Err(e) => Err(e),
    }
}

/// Create a commit with the given message and return the new HEAD commit SHA.
pub fn create_commit(repo: &Path, message: &str) -> Result<String> {
    CLI.run_status(
        CLI.command()
            .args(["commit", "-m", message])
            .current_dir(repo)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null()),
    )?;

    head_commit(repo)
}

/// Initialize a new git repository at the given path.
pub fn init(path: &Path) -> Result<()> {
    CLI.run_status(
        CLI.command()
            .args(["init", &path.display().to_string()])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null()),
    )
}

// ---------------------------------------------------------------------------
// Repo context
// ---------------------------------------------------------------------------

/// Create a [`Repo`] context bound to the given working directory.
pub fn repo(path: &Path) -> Repo<'_> {
    Repo { path }
}

/// A git repository context that binds a working directory, so you can call
/// multiple operations without repeating the path.
pub struct Repo<'a> {
    path: &'a Path,
}

impl<'a> Repo<'a> {
    /// Checkout a specific ref (branch, tag, or commit SHA).
    pub fn checkout(&self, rev: &str) -> Result<()> {
        checkout(self.path, rev)
    }

    /// Get the current HEAD commit SHA.
    pub fn head_commit(&self) -> Result<String> {
        head_commit(self.path)
    }

    /// Get the default branch name.
    pub fn default_branch(&self) -> Result<String> {
        default_branch(self.path)
    }

    /// Reset the working tree to the remote's default branch HEAD.
    pub fn reset_to_remote_head(&self) -> Result<()> {
        reset_to_remote_head(self.path)
    }

    /// Stage files.
    pub fn stage_files(&self, files: &[&str]) -> Result<()> {
        stage_files(self.path, files)
    }

    /// Check if there are staged changes.
    pub fn has_staged_changes(&self) -> Result<bool> {
        has_staged_changes(self.path)
    }

    /// Create a commit with the given message and return the new HEAD SHA.
    pub fn create_commit(&self, message: &str) -> Result<String> {
        create_commit(self.path, message)
    }

    /// Fetch updates from all remotes (requires an existing clone).
    pub fn fetch_all(&self) -> Result<()> {
        CLI.run_status(
            CLI.command()
                .args(["fetch", "--all"])
                .current_dir(self.path)
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null()),
        )
    }
}

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

    #[test]
    fn default_branch_of_fresh_repo() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path();
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(repo)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "--allow-empty", "-m", "init"])
            .current_dir(repo)
            .output()
            .unwrap();
        let branch = default_branch(repo).unwrap();
        assert!(branch == "main" || branch == "master", "got: {branch}");
    }

    #[test]
    fn reset_to_remote_head_after_clone() {
        let tmp = tempfile::tempdir().unwrap();

        let upstream = tmp.path().join("upstream");
        std::fs::create_dir(&upstream).unwrap();
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(&upstream)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "--allow-empty", "-m", "first"])
            .current_dir(&upstream)
            .output()
            .unwrap();

        let clone_dir = tmp.path().join("clone");
        clone_or_fetch(&upstream.display().to_string(), &clone_dir).unwrap();
        let commit1 = head_commit(&clone_dir).unwrap();

        std::process::Command::new("git")
            .args(["commit", "--allow-empty", "-m", "second"])
            .current_dir(&upstream)
            .output()
            .unwrap();

        clone_or_fetch(&upstream.display().to_string(), &clone_dir).unwrap();
        reset_to_remote_head(&clone_dir).unwrap();
        let commit2 = head_commit(&clone_dir).unwrap();

        assert_ne!(commit1, commit2, "HEAD should have advanced");
    }

    #[test]
    fn head_commit_returns_sha() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path();
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(repo)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "--allow-empty", "-m", "init"])
            .current_dir(repo)
            .output()
            .unwrap();

        let sha = head_commit(repo).unwrap();
        assert_eq!(sha.len(), 40, "SHA should be 40 hex chars, got: {sha}");
        assert!(sha.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn checkout_switches_branch() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path();
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(repo)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "--allow-empty", "-m", "init"])
            .current_dir(repo)
            .output()
            .unwrap();

        // Create a new branch
        std::process::Command::new("git")
            .args(["branch", "test-branch"])
            .current_dir(repo)
            .output()
            .unwrap();

        checkout(repo, "test-branch").unwrap();

        let output = std::process::Command::new("git")
            .args(["symbolic-ref", "--short", "HEAD"])
            .current_dir(repo)
            .output()
            .unwrap();
        let current = String::from_utf8_lossy(&output.stdout).trim().to_string();
        assert_eq!(current, "test-branch");
    }

    #[test]
    fn init_creates_repo() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("new-repo");

        init(&repo).unwrap();

        assert!(repo.join(".git").exists(), ".git directory should exist");
    }

    #[test]
    fn stage_files_and_has_staged_changes() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path();
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(repo)
            .output()
            .unwrap();

        // No staged changes initially
        // (need at least one commit for diff --cached to work reliably)
        std::process::Command::new("git")
            .args(["commit", "--allow-empty", "-m", "init"])
            .current_dir(repo)
            .output()
            .unwrap();

        assert!(!has_staged_changes(repo).unwrap());

        // Create a file and stage it
        std::fs::write(repo.join("hello.txt"), "hello").unwrap();
        stage_files(repo, &["hello.txt"]).unwrap();

        assert!(has_staged_changes(repo).unwrap());
    }

    #[test]
    fn create_commit_returns_sha() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path();
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(repo)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "--allow-empty", "-m", "init"])
            .current_dir(repo)
            .output()
            .unwrap();

        let sha1 = head_commit(repo).unwrap();

        std::fs::write(repo.join("file.txt"), "content").unwrap();
        stage_files(repo, &["file.txt"]).unwrap();
        let sha2 = create_commit(repo, "add file").unwrap();

        assert_ne!(sha1, sha2, "commit should create a new SHA");
        assert_eq!(sha2.len(), 40);
        assert!(sha2.chars().all(|c| c.is_ascii_hexdigit()));
    }
}