|
| 1 | +package git |
| 2 | + |
| 3 | +/* |
| 4 | +#include <git2.h> |
| 5 | +
|
| 6 | +extern int _go_git_worktree_add(git_worktree **out, git_repository *repo, const char *name, const char *worktree); |
| 7 | +
|
| 8 | +*/ |
| 9 | +import "C" |
| 10 | +import ( |
| 11 | + "runtime" |
| 12 | + "unsafe" |
| 13 | +) |
| 14 | + |
| 15 | +type Worktree struct { |
| 16 | + ptr *C.git_worktree |
| 17 | + repo *Repository |
| 18 | +} |
| 19 | + |
| 20 | +func newWorktreeFromC(ptr *C.git_worktree, repo *Repository) *Worktree { |
| 21 | + idx := &Worktree{ptr, repo} |
| 22 | + runtime.SetFinalizer(idx, (*Worktree).Free) |
| 23 | + return idx |
| 24 | +} |
| 25 | + |
| 26 | +func ExistingWorktree(repo *Repository) (*Worktree, error) { |
| 27 | + var ptr *C.git_worktree |
| 28 | + |
| 29 | + runtime.LockOSThread() |
| 30 | + defer runtime.UnlockOSThread() |
| 31 | + |
| 32 | + if err := C.git_worktree_open_from_repository(&ptr, repo.ptr); err < 0 { |
| 33 | + return nil, MakeGitError(err) |
| 34 | + } |
| 35 | + |
| 36 | + return newWorktreeFromC(ptr, repo), nil |
| 37 | +} |
| 38 | + |
| 39 | +func AddWorktree(repo *Repository, name string, worktree string) (*Worktree, error) { |
| 40 | + var ptr *C.git_worktree |
| 41 | + |
| 42 | + runtime.LockOSThread() |
| 43 | + defer runtime.UnlockOSThread() |
| 44 | + |
| 45 | + cname := C.CString(name) |
| 46 | + defer C.free(unsafe.Pointer(cname)) |
| 47 | + |
| 48 | + cworktree := C.CString(worktree) |
| 49 | + defer C.free(unsafe.Pointer(cworktree)) |
| 50 | + |
| 51 | + err := C._go_git_worktree_add(&ptr, repo.ptr, cname, cworktree) |
| 52 | + if err < 0 { |
| 53 | + return nil, MakeGitError(err) |
| 54 | + } |
| 55 | + return newWorktreeFromC(ptr, repo), nil |
| 56 | +} |
| 57 | + |
| 58 | +// Path returns the worktree's path on disk or an empty string if it |
| 59 | +// exists only in memory. |
| 60 | +func (v *Worktree) Path() string { |
| 61 | + ret := C.GoString(C.git_worktree_path(v.ptr)) |
| 62 | + runtime.KeepAlive(v) |
| 63 | + return ret |
| 64 | +} |
| 65 | + |
| 66 | +func (v *Worktree) Free() { |
| 67 | + runtime.SetFinalizer(v, nil) |
| 68 | + C.git_worktree_free(v.ptr) |
| 69 | +} |
0 commit comments