guests/darwin: Configure hostname in a single command

This commit is contained in:
Seth Vargo 2016-05-31 01:10:48 -04:00
parent 249cda879d
commit 5683a3b8ca
No known key found for this signature in database
GPG Key ID: 905A90C2949E8787
2 changed files with 65 additions and 7 deletions

View File

@ -3,13 +3,31 @@ module VagrantPlugins
module Cap
class ChangeHostName
def self.change_host_name(machine, name)
if !machine.communicate.test("hostname -f | grep '^#{name}$' || hostname -s | grep '^#{name}$'")
machine.communicate.sudo("scutil --set ComputerName #{name}")
machine.communicate.sudo("scutil --set HostName #{name}")
# LocalHostName shouldn't contain dots.
# It is used by Bonjour and visible through file sharing services.
machine.communicate.sudo("scutil --set LocalHostName #{name.gsub(/\.+/, '')}")
machine.communicate.sudo("hostname #{name}")
comm = machine.communicate
if !comm.test("hostname -f | grep -w '#{name}' || hostname -s | grep -w '#{name}'")
basename = name.split(".", 2)[0]
comm.sudo <<-EOH.gsub(/^ {14}/, '')
scutil --set ComputerName '#{name}'
scutil --set HostName '#{name}'
# LocalHostName should not contain dots - it is used by Bonjour and
# visible through file sharing services.
scutil --set LocalHostName '#{basename}'
hostname '#{name}'
# Remove comments and blank lines from /etc/hosts
sed -i'' -e 's/#.*$//' /etc/hosts
sed -i'' -e '/^$/d' /etc/hosts
# Prepend ourselves to /etc/hosts - sed on bsd is sad
grep -w '#{name}' /etc/hosts || {
echo -e '127.0.0.1\\t#{name}\\t#{basename}' | cat - /etc/hosts > /tmp/tmp-hosts
mv /tmp/tmp-hosts /etc/hosts
}
EOH
end
end
end

View File

@ -0,0 +1,40 @@
require_relative "../../../../base"
describe "VagrantPlugins::GuestDarwin::Cap::ChangeHostName" do
let(:described_class) do
VagrantPlugins::GuestDarwin::Plugin
.components
.guest_capabilities[:darwin]
.get(:change_host_name)
end
let(:machine) { double("machine") }
let(:comm) { VagrantTests::DummyCommunicator::Communicator.new(machine) }
before do
allow(machine).to receive(:communicate).and_return(comm)
end
after do
comm.verify_expectations!
end
describe ".change_host_name" do
let(:hostname) { "banana-rama.example.com" }
it "sets the hostname" do
comm.stub_command("hostname -f | grep -w '#{hostname}' || hostname -s | grep -w '#{hostname}'", exit_code: 1)
described_class.change_host_name(machine, hostname)
expect(comm.received_commands[1]).to match(/scutil --set ComputerName 'banana-rama.example.com'/)
expect(comm.received_commands[1]).to match(/scutil --set HostName 'banana-rama.example.com'/)
expect(comm.received_commands[1]).to match(/scutil --set LocalHostName 'banana-rama'/)
expect(comm.received_commands[1]).to match(/hostname 'banana-rama.example.com'/)
end
it "does not change the hostname if already set" do
comm.stub_command("hostname -f | grep -w '#{hostname}' || hostname -s | grep -w '#{hostname}'", exit_code: 0)
described_class.change_host_name(machine, hostname)
expect(comm.received_commands.size).to eq(1)
end
end
end