Skip to content

Commit 2b6d383

Browse files
Worktree add&remove
1 parent e0fb3f6 commit 2b6d383

File tree

4 files changed

+46
-3
lines changed

4 files changed

+46
-3
lines changed

lib/git/base/factory.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,12 @@ def branch(branch_name = 'master')
1414
def branches
1515
Git::Branches.new(self)
1616
end
17-
17+
18+
# returns a Git::Worktree object for dir, commitish
19+
def worktree(dir, commitish = nil)
20+
Git::Worktree.new(self, dir, commitish)
21+
end
22+
1823
# returns a Git::worktrees object of all the Git::Worktrees
1924
# objects for this repo
2025
def worktrees

lib/git/lib.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,15 @@ def worktrees_all
328328
arr
329329
end
330330

331+
def worktree_add(dir, commitish = nil)
332+
return command('worktree', ['add', dir, commitish]) if !commitish.nil?
333+
command('worktree', ['add', dir])
334+
end
335+
336+
def worktree_remove(dir)
337+
command('worktree', ['remove', dir])
338+
end
339+
331340
def list_files(ref_dir)
332341
dir = File.join(@git_dir, 'refs', ref_dir)
333342
files = []

lib/git/worktree.rb

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@ class Worktree < Path
66

77
attr_accessor :full, :dir, :gcommit
88

9-
def initialize(base, dir, gcommit)
10-
@full = dir + ' ' + gcommit
9+
def initialize(base, dir, gcommit = nil)
10+
@full = dir
11+
@full += ' ' + gcommit if !gcommit.nil?
1112
@base = base
1213
@dir = dir
1314
@gcommit = gcommit
@@ -18,6 +19,14 @@ def gcommit
1819
@gcommit
1920
end
2021

22+
def add
23+
@base.lib.worktree_add(@dir, @gcommit)
24+
end
25+
26+
def remove
27+
@base.lib.worktree_remove(@dir)
28+
end
29+
2130
def to_a
2231
[@full]
2332
end

tests/units/test_worktree.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,24 @@ def test_worktrees_single
2727
assert_equal(worktree.dir, @git.dir.to_s)
2828
assert_equal(worktree.gcommit, SAMPLE_LAST_COMMIT)
2929
end
30+
31+
def test_worktree_add_and_remove
32+
assert_equal(@git.worktrees.size, 2)
33+
34+
@git.worktree('/tmp/pp1').add
35+
assert_equal(@git.worktrees.size, 3)
36+
@git.worktree('/tmp/pp1').remove
37+
assert_equal(@git.worktrees.size, 2)
38+
39+
@git.worktree('/tmp/pp2', 'gitsearch1').add
40+
@git.worktree('/tmp/pp2').remove
41+
42+
@git.worktree('/tmp/pp3', '34a566d193dc4702f03149969a2aad1443231560').add
43+
@git.worktree('/tmp/pp3').remove
44+
45+
@git.worktree('/tmp/pp4', 'test_object').add
46+
@git.worktree('/tmp/pp4').remove
47+
48+
assert_equal(@git.worktrees.size, 2)
49+
end
3050
end

0 commit comments

Comments
 (0)