gitsw 0.1.0

A smart Git branch switcher with automatic stash management and dependency installation
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
use anyhow::{anyhow, Context, Result};
use git2::{
    build::CheckoutBuilder, BranchType, Oid, Repository, Signature, StashFlags, Status,
    StatusOptions,
};

pub struct GitRepo {
    repo: Repository,
}

impl GitRepo {
    /// Open repository from current directory
    pub fn open() -> Result<Self> {
        let repo = Repository::discover(".").context("Not a git repository")?;
        Ok(Self { repo })
    }

    /// Get the path to the .git directory
    pub fn git_dir(&self) -> &std::path::Path {
        self.repo.path()
    }

    /// Get the working directory path
    pub fn workdir(&self) -> Result<&std::path::Path> {
        self.repo
            .workdir()
            .ok_or_else(|| anyhow!("Bare repository has no working directory"))
    }

    /// Get current branch name (HEAD)
    pub fn get_current_branch(&self) -> Result<String> {
        let head = self.repo.head().context("Failed to get HEAD")?;

        if head.is_branch() {
            let name = head
                .shorthand()
                .ok_or_else(|| anyhow!("Invalid branch name"))?;
            Ok(name.to_string())
        } else {
            // Detached HEAD - return commit hash
            let oid = head.target().ok_or_else(|| anyhow!("No target for HEAD"))?;
            Ok(format!("(detached at {})", &oid.to_string()[..7]))
        }
    }

    /// Check if there are uncommitted changes (staged or unstaged)
    pub fn has_uncommitted_changes(&self) -> Result<bool> {
        let mut opts = StatusOptions::new();
        opts.include_untracked(true)
            .recurse_untracked_dirs(true)
            .exclude_submodules(true);

        let statuses = self.repo.statuses(Some(&mut opts))?;

        for entry in statuses.iter() {
            let status = entry.status();
            if status.intersects(
                Status::INDEX_NEW
                    | Status::INDEX_MODIFIED
                    | Status::INDEX_DELETED
                    | Status::INDEX_RENAMED
                    | Status::INDEX_TYPECHANGE
                    | Status::WT_NEW
                    | Status::WT_MODIFIED
                    | Status::WT_DELETED
                    | Status::WT_RENAMED
                    | Status::WT_TYPECHANGE,
            ) {
                return Ok(true);
            }
        }

        Ok(false)
    }

    /// Get a summary of uncommitted changes
    pub fn get_changes_summary(&self) -> Result<String> {
        let mut opts = StatusOptions::new();
        opts.include_untracked(true)
            .recurse_untracked_dirs(true)
            .exclude_submodules(true);

        let statuses = self.repo.statuses(Some(&mut opts))?;

        let mut staged = 0;
        let mut modified = 0;
        let mut untracked = 0;

        for entry in statuses.iter() {
            let status = entry.status();
            if status.intersects(
                Status::INDEX_NEW
                    | Status::INDEX_MODIFIED
                    | Status::INDEX_DELETED
                    | Status::INDEX_RENAMED
                    | Status::INDEX_TYPECHANGE,
            ) {
                staged += 1;
            }
            if status.intersects(
                Status::WT_MODIFIED
                    | Status::WT_DELETED
                    | Status::WT_RENAMED
                    | Status::WT_TYPECHANGE,
            ) {
                modified += 1;
            }
            if status.contains(Status::WT_NEW) {
                untracked += 1;
            }
        }

        let mut parts = Vec::new();
        if staged > 0 {
            parts.push(format!("{} staged", staged));
        }
        if modified > 0 {
            parts.push(format!("{} modified", modified));
        }
        if untracked > 0 {
            parts.push(format!("{} untracked", untracked));
        }

        Ok(parts.join(", "))
    }

    /// Create a stash with the given message, returns the stash OID
    pub fn stash_save(&mut self, message: &str) -> Result<Oid> {
        let signature = self.get_signature()?;
        let oid = self
            .repo
            .stash_save(&signature, message, Some(StashFlags::INCLUDE_UNTRACKED))?;
        Ok(oid)
    }

    /// Apply a stash by its OID
    pub fn stash_apply(&mut self, target_oid: Oid) -> Result<()> {
        let index = self.find_stash_index(target_oid)?;
        self.repo.stash_apply(index, None)?;
        Ok(())
    }

    /// Drop a stash by its OID
    pub fn stash_drop(&mut self, target_oid: Oid) -> Result<()> {
        let index = self.find_stash_index(target_oid)?;
        self.repo.stash_drop(index)?;
        Ok(())
    }

    /// Find stash index by OID
    fn find_stash_index(&mut self, target_oid: Oid) -> Result<usize> {
        let mut found_index: Option<usize> = None;

        self.repo.stash_foreach(|index, _message, oid| {
            if *oid == target_oid {
                found_index = Some(index);
                false // Stop iteration
            } else {
                true // Continue
            }
        })?;

        found_index.ok_or_else(|| anyhow!("Stash not found with OID: {}", target_oid))
    }

    /// List all stashes with their messages
    pub fn list_stashes(&mut self) -> Result<Vec<StashInfo>> {
        let mut stashes = Vec::new();

        self.repo.stash_foreach(|index, message, oid| {
            stashes.push(StashInfo {
                index,
                message: message.to_string(),
                oid: *oid,
            });
            true
        })?;

        Ok(stashes)
    }

    /// Switch to target branch
    pub fn switch_branch(&self, branch_name: &str) -> Result<()> {
        // First try to find the branch
        let branch = self
            .repo
            .find_branch(branch_name, BranchType::Local)
            .with_context(|| format!("Branch '{}' not found", branch_name))?;

        let reference = branch.get();
        let tree = reference.peel_to_tree()?;

        // Checkout the tree
        let mut checkout_builder = CheckoutBuilder::new();
        checkout_builder.safe();

        self.repo
            .checkout_tree(tree.as_object(), Some(&mut checkout_builder))?;

        // Update HEAD
        let refname = reference
            .name()
            .ok_or_else(|| anyhow!("Invalid reference name"))?;
        self.repo.set_head(refname)?;

        Ok(())
    }

    /// List all local branches
    pub fn list_branches(&self) -> Result<Vec<String>> {
        let mut branches = Vec::new();

        for branch in self.repo.branches(Some(BranchType::Local))? {
            let (branch, _) = branch?;
            if let Some(name) = branch.name()? {
                branches.push(name.to_string());
            }
        }

        Ok(branches)
    }

    /// Get the default signature for commits/stashes
    fn get_signature(&self) -> Result<Signature<'static>> {
        // Try to get from config first
        if let Ok(sig) = self.repo.signature() {
            return Ok(Signature::now(
                sig.name().unwrap_or("git-switch"),
                sig.email().unwrap_or("git-switch@local"),
            )?);
        }

        // Fallback
        Ok(Signature::now("git-switch", "git-switch@local")?)
    }

    /// Check if a branch exists
    pub fn branch_exists(&self, name: &str) -> bool {
        self.repo.find_branch(name, BranchType::Local).is_ok()
    }

    /// Create a new branch from HEAD
    pub fn create_branch(&self, name: &str) -> Result<()> {
        let head = self.repo.head()?;
        let head_commit = head.peel_to_commit()?;
        self.repo.branch(name, &head_commit, false)?;
        Ok(())
    }

    /// Discard all uncommitted changes (reset to HEAD)
    pub fn discard_changes(&self) -> Result<()> {
        let head = self.repo.head()?;
        let head_commit = head.peel_to_commit()?;
        let tree = head_commit.tree()?;

        // Force checkout to discard all changes
        let mut checkout_builder = CheckoutBuilder::new();
        checkout_builder.force();
        checkout_builder.remove_untracked(true);

        self.repo
            .checkout_tree(tree.as_object(), Some(&mut checkout_builder))?;

        // Reset index to HEAD
        self.repo
            .reset(head_commit.as_object(), git2::ResetType::Hard, None)?;

        Ok(())
    }

    /// Delete a local branch
    pub fn delete_branch(&self, name: &str) -> Result<()> {
        let mut branch = self
            .repo
            .find_branch(name, BranchType::Local)
            .with_context(|| format!("Branch '{}' not found", name))?;
        branch.delete()?;
        Ok(())
    }

    /// Fetch from a remote
    pub fn fetch(&self, remote_name: &str) -> Result<()> {
        let mut remote = self
            .repo
            .find_remote(remote_name)
            .with_context(|| format!("Remote '{}' not found", remote_name))?;

        let refspecs: Vec<String> = remote
            .fetch_refspecs()?
            .iter()
            .filter_map(|s| s.map(String::from))
            .collect();

        let refspec_strs: Vec<&str> = refspecs.iter().map(|s| s.as_str()).collect();

        remote.fetch(&refspec_strs, None, None)?;
        Ok(())
    }

    /// Pull latest changes (fetch + merge) for current branch
    pub fn pull(&mut self) -> Result<()> {
        let head = self.repo.head()?;
        if !head.is_branch() {
            return Err(anyhow!("Cannot pull in detached HEAD state"));
        }

        let branch_name = head
            .shorthand()
            .ok_or_else(|| anyhow!("Invalid branch name"))?;

        // Get upstream branch
        let branch = self.repo.find_branch(branch_name, BranchType::Local)?;
        let upstream = branch.upstream().context("No upstream branch configured")?;

        let upstream_name = upstream
            .name()?
            .ok_or_else(|| anyhow!("Invalid upstream branch name"))?;

        // Parse remote name from upstream (e.g., "origin/main" -> "origin")
        let remote_name = upstream_name
            .split('/')
            .next()
            .ok_or_else(|| anyhow!("Invalid upstream format"))?;

        // Fetch from remote
        self.fetch(remote_name)?;

        // Get the upstream commit
        let upstream_ref = upstream.get();
        let upstream_commit = upstream_ref.peel_to_commit()?;

        // Create annotated commit for merge analysis
        let fetch_head = self.repo.find_reference("FETCH_HEAD")?;
        let annotated = self.repo.reference_to_annotated_commit(&fetch_head)?;

        // Fast-forward merge
        let analysis = self.repo.merge_analysis(&[&annotated])?;

        if analysis.0.is_up_to_date() {
            return Ok(());
        }

        if analysis.0.is_fast_forward() {
            // Do fast-forward
            let refname = head.name().ok_or_else(|| anyhow!("Invalid HEAD ref"))?;
            self.repo
                .reference(refname, upstream_commit.id(), true, "pull: fast-forward")?;

            // Update working directory
            let mut checkout = CheckoutBuilder::new();
            checkout.force();
            self.repo.checkout_head(Some(&mut checkout))?;
        } else {
            return Err(anyhow!(
                "Cannot fast-forward. Please merge or rebase manually."
            ));
        }

        Ok(())
    }

    /// Get the remote tracking branch for a local branch
    pub fn get_tracking_remote(&self, branch_name: &str) -> Result<Option<String>> {
        let branch = match self.repo.find_branch(branch_name, BranchType::Local) {
            Ok(b) => b,
            Err(_) => return Ok(None),
        };

        match branch.upstream() {
            Ok(upstream) => {
                let name = upstream.name()?.map(String::from);
                Ok(name)
            }
            Err(_) => Ok(None),
        }
    }

    /// Create a local branch tracking a remote branch
    pub fn create_tracking_branch(&self, local_name: &str, remote_ref: &str) -> Result<()> {
        // Find the remote reference (e.g., "origin/main")
        let reference = self
            .repo
            .find_reference(&format!("refs/remotes/{}", remote_ref))
            .with_context(|| format!("Remote branch '{}' not found", remote_ref))?;

        let commit = reference.peel_to_commit()?;

        // Create local branch
        let mut branch = self.repo.branch(local_name, &commit, false)?;

        // Set upstream
        branch.set_upstream(Some(remote_ref))?;

        Ok(())
    }
}

#[derive(Debug, Clone)]
pub struct StashInfo {
    pub index: usize,
    pub message: String,
    pub oid: Oid,
}