From c69d45533518a8528e821f7eb5c643c22cd115de Mon Sep 17 00:00:00 2001 From: Thomas <1258170+ThomasSevestre@users.noreply.github.com> Date: Tue, 2 Dec 2025 12:59:05 +0100 Subject: [PATCH] add support for nested as --- lib/sshkit/backends/abstract.rb | 4 +-- test/unit/backends/test_abstract.rb | 55 +++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/lib/sshkit/backends/abstract.rb b/lib/sshkit/backends/abstract.rb index 592f7b08..62bf3ea1 100644 --- a/lib/sshkit/backends/abstract.rb +++ b/lib/sshkit/backends/abstract.rb @@ -103,6 +103,7 @@ def with(environment, &_block) end def as(who, &_block) + who_old = [@user, @group] if who.is_a? Hash @user = who[:user] || who["user"] @group = who[:group] || who["group"] @@ -118,8 +119,7 @@ def as(who, &_block) EOTEST yield ensure - remove_instance_variable(:@user) - remove_instance_variable(:@group) + @user, @group = *who_old end class << self diff --git a/test/unit/backends/test_abstract.rb b/test/unit/backends/test_abstract.rb index e7afac83..1f2b33aa 100644 --- a/test/unit/backends/test_abstract.rb +++ b/test/unit/backends/test_abstract.rb @@ -111,6 +111,61 @@ def test_within_home assert_equal 'cd ~/foo && /usr/bin/env cat file', backend.executed_command.to_command end + def test_as_properly_clears + backend = ExampleBackend.new do + as :root do + execute :cat, 'file', :strip => false + end + + execute :cat, 'file', :strip => false + end + + backend.run + + assert_equal '/usr/bin/env cat file', backend.executed_command.to_command + end + + def test_as_root + backend = ExampleBackend.new do + as :root do + execute :cat, 'file', :strip => false + end + end + + backend.run + + assert_equal 'sudo -u root -- sh -c /usr/bin/env\\ cat\\ file', backend.executed_command.to_command + end + + def test_nested_as + backend = ExampleBackend.new do + as :root do + as :other_user do + execute :cat, 'file', :strip => false + end + end + end + + backend.run + + assert_equal 'sudo -u other_user -- sh -c /usr/bin/env\\ cat\\ file', backend.executed_command.to_command + end + + def test_nested_as_properly_clears + backend = ExampleBackend.new do + as :root do + as :other_user do + execute :cat, 'file', :strip => false + end + execute :cat, 'file', :strip => false + end + end + + backend.run + + assert_equal 'sudo -u root -- sh -c /usr/bin/env\\ cat\\ file', backend.executed_command.to_command + end + def test_background_logs_deprecation_warnings deprecation_out = +'' SSHKit.config.deprecation_output = deprecation_out