From 1c650a7fb89436fd070f28648c925caa8c71a7b9 Mon Sep 17 00:00:00 2001 From: Chris Roberts Date: Mon, 11 Mar 2019 17:08:13 -0700 Subject: [PATCH] Remove whitespace from id file on load If the id file includes whitespace, remove it. If the content of the id file is empty, do not set the machine id. Fixes: #10722 --- lib/vagrant/machine.rb | 5 ++- test/unit/vagrant/machine_test.rb | 58 +++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/lib/vagrant/machine.rb b/lib/vagrant/machine.rb index 993de2b50..0b1ca1b65 100644 --- a/lib/vagrant/machine.rb +++ b/lib/vagrant/machine.rb @@ -399,7 +399,10 @@ module Vagrant # Read the id file from the data directory if it exists as the # ID for the pre-existing physical representation of this machine. id_file = @data_dir.join("id") - @id = id_file.read.chomp if id_file.file? + id_content = id_file.read.strip if id_file.file? + if !id_content.to_s.empty? + @id = id_content + end end if @id != old_id && @provider diff --git a/test/unit/vagrant/machine_test.rb b/test/unit/vagrant/machine_test.rb index c542402c1..9665f48f9 100644 --- a/test/unit/vagrant/machine_test.rb +++ b/test/unit/vagrant/machine_test.rb @@ -912,4 +912,62 @@ describe Vagrant::Machine do expect(subject.ui).to_not equal(ui) end end + + describe "#reload" do + context "when ID is unset and id file does not exist" do + it "should remain nil" do + expect(subject.id).to be_nil + instance.reload + expect(subject.id).to be_nil + end + end + + context "when id file is set" do + let(:id_content) { "test-machine-id" } + + before do + id_file = subject.data_dir.join("id") + File.write(id_file.to_s, id_content) + end + + it "should update the machine id" do + expect(subject.id).to be_nil + instance.reload + expect(subject.id).to eq(id_content) + end + + it "should notify of the id change when provider is set" do + expect(provider).to receive(:machine_id_changed) + instance.reload + end + + context "when id file content includes whitespace" do + let(:id_content) { " test-machine-id\n" } + + it "should remove all whitespace" do + instance.reload + expect(instance.id).to eq("test-machine-id") + end + end + + context "when id file content is all whitespace" do + let(:id_content) { "\0\0\0\0\0\0" } + + it "should not update the id" do + expect(instance.id).to be_nil + instance.reload + expect(instance.id).to be_nil + end + end + + context "when id is already set to value in id file" do + it "should not notify of id change" do + instance.instance_variable_set(:@id, id_content) + expect(provider).not_to receive(:machine_id_changed) + instance.reload + expect(instance.id).to eq(id_content) + end + end + end + end end