Skip to content

Commit

Permalink
Fixes agiledivider#141: Check for newlines before writing hosts file.
Browse files Browse the repository at this point in the history
  • Loading branch information
danepowell committed Jun 28, 2018
1 parent bdfa1c7 commit 5d27a1d
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions lib/vagrant-hostsupdater/HostsUpdater.rb
Original file line number Diff line number Diff line change
Expand Up @@ -137,14 +137,7 @@ def addToHosts(entries)

@ui.info "[vagrant-hostsupdater] Writing the following entries to (#@@hosts_path)"
@ui.info "[vagrant-hostsupdater] " + entries.join("\n[vagrant-hostsupdater] ")
if !File.writable_real?(@@hosts_path)
@ui.info "[vagrant-hostsupdater] This operation requires administrative access. You may " +
"skip it by manually adding equivalent entries to the hosts file."
if !sudo(%Q(sh -c 'echo "#{content}" >> #@@hosts_path'))
@ui.error "[vagrant-hostsupdater] Failed to add hosts, could not use sudo"
adviseOnSudo
end
elsif Vagrant::Util::Platform.windows?
if Vagrant::Util::Platform.windows?
require 'tmpdir'
uuid = @machine.id || @machine.config.hostsupdater.id
tmpPath = File.join(Dir.tmpdir, 'hosts-' + uuid + '.cmd')
Expand All @@ -154,10 +147,22 @@ def addToHosts(entries)
sudo(tmpPath)
File.delete(tmpPath)
else
content = "\n" + content + "\n"
hostsFile = File.open(@@hosts_path, "a")
hostsFile.write(content)
hostsFile.close()
# Check if the file is missing a newline before writing to it.
if !system("tail -c1 #@@hosts_path | read -r _")
content = "\n" + content
end
if !File.writable_real?(@@hosts_path)
@ui.info "[vagrant-hostsupdater] This operation requires administrative access. You may " +
"skip it by manually adding equivalent entries to the hosts file."
if !sudo(%Q(sh -c 'echo "#{content}" >> #@@hosts_path'))
@ui.error "[vagrant-hostsupdater] Failed to add hosts, could not use sudo"
adviseOnSudo
end
else
hostsFile = File.open(@@hosts_path, "a")
hostsFile.write(content)
hostsFile.close()
end
end
end

Expand Down

0 comments on commit 5d27a1d

Please sign in to comment.