Skip to content

Commit bde7c53

Browse files
Add support for nested as (#558)
This PR adds support for nested as : ```ruby as :root do as :other_user do execute :cat, 'file', :strip => false end end ```
1 parent 7395c33 commit bde7c53

File tree

2 files changed

+57
-2
lines changed

2 files changed

+57
-2
lines changed

lib/sshkit/backends/abstract.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ def with(environment, &_block)
103103
end
104104

105105
def as(who, &_block)
106+
who_old = [@user, @group]
106107
if who.is_a? Hash
107108
@user = who[:user] || who["user"]
108109
@group = who[:group] || who["group"]
@@ -118,8 +119,7 @@ def as(who, &_block)
118119
EOTEST
119120
yield
120121
ensure
121-
remove_instance_variable(:@user)
122-
remove_instance_variable(:@group)
122+
@user, @group = *who_old
123123
end
124124

125125
class << self

test/unit/backends/test_abstract.rb

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,61 @@ def test_within_home
111111
assert_equal 'cd ~/foo && /usr/bin/env cat file', backend.executed_command.to_command
112112
end
113113

114+
def test_as_properly_clears
115+
backend = ExampleBackend.new do
116+
as :root do
117+
execute :cat, 'file', :strip => false
118+
end
119+
120+
execute :cat, 'file', :strip => false
121+
end
122+
123+
backend.run
124+
125+
assert_equal '/usr/bin/env cat file', backend.executed_command.to_command
126+
end
127+
128+
def test_as_root
129+
backend = ExampleBackend.new do
130+
as :root do
131+
execute :cat, 'file', :strip => false
132+
end
133+
end
134+
135+
backend.run
136+
137+
assert_equal 'sudo -u root -- sh -c /usr/bin/env\\ cat\\ file', backend.executed_command.to_command
138+
end
139+
140+
def test_nested_as
141+
backend = ExampleBackend.new do
142+
as :root do
143+
as :other_user do
144+
execute :cat, 'file', :strip => false
145+
end
146+
end
147+
end
148+
149+
backend.run
150+
151+
assert_equal 'sudo -u other_user -- sh -c /usr/bin/env\\ cat\\ file', backend.executed_command.to_command
152+
end
153+
154+
def test_nested_as_properly_clears
155+
backend = ExampleBackend.new do
156+
as :root do
157+
as :other_user do
158+
execute :cat, 'file', :strip => false
159+
end
160+
execute :cat, 'file', :strip => false
161+
end
162+
end
163+
164+
backend.run
165+
166+
assert_equal 'sudo -u root -- sh -c /usr/bin/env\\ cat\\ file', backend.executed_command.to_command
167+
end
168+
114169
def test_background_logs_deprecation_warnings
115170
deprecation_out = +''
116171
SSHKit.config.deprecation_output = deprecation_out

0 commit comments

Comments
 (0)