@@ -55,13 +55,34 @@ def update_host
5555 # copy and modify hosts file on host with Vagrant-managed entries
5656 file = @global_env . tmp_path . join ( 'hosts.local' )
5757
58- if WindowsSupport . windows?
58+ if WindowsSupport . windows? || WindowsSupport . wsl?
5959 # lazily include windows Module
6060 class << self
6161 include WindowsSupport unless include? WindowsSupport
6262 end
63- hosts_location = "#{ ENV [ 'WINDIR' ] } \\ System32\\ drivers\\ etc\\ hosts"
64- copy_proc = Proc . new { windows_copy_file ( file , hosts_location ) }
63+ windir = ENV [ 'WINDIR' ]
64+ if WindowsSupport . wsl?
65+ Dir . chdir ( '/mnt/c' ) {
66+ windir = `cmd.exe /c echo %WINDIR%` . strip
67+ }
68+ # convert wsl path to windows path
69+ if file . to_s =~ /\/ mnt\/ [a-z]\/ /
70+ win_file = file . to_s . sub ( /^\/ mnt\/ ([a-z])\/ / , '\1:\\' ) . gsub ( '/' , '\\' )
71+ else
72+ win_file = "\\ \\ wsl\$ \\ #{ ENV [ 'WSL_DISTRO_NAME' ] } " + file . to_s . gsub ( '/' , '\\' )
73+ end
74+ win_hosts_location = "#{ windir } \\ System32\\ drivers\\ etc\\ hosts"
75+ hosts_location = "/mnt/" + windir [ 0 ] . downcase + "/" + windir [ 3 ..-1 ] + "/System32/drivers/etc/hosts"
76+
77+ # add to both, windows host and wsl machine
78+ copy_proc = Proc . new {
79+ wsl_copy_file ( file , hosts_location , win_file , win_hosts_location )
80+ `[ -w "/etc/hosts" ] && cat "#{ file } " > "/etc/hosts" || sudo cp "#{ file } " "/etc/hosts"`
81+ }
82+ else
83+ hosts_location = "#{ windir } \\ System32\\ drivers\\ etc\\ hosts"
84+ copy_proc = Proc . new { windows_copy_file ( file , hosts_location ) }
85+ end
6586 line_endings = "crlf"
6687 else
6788 hosts_location = '/etc/hosts'
@@ -70,6 +91,9 @@ class << self
7091 end
7192
7293 FileUtils . cp ( hosts_location , file )
94+ if WindowsSupport . wsl?
95+ FileUtils . chmod ( "+w" , file )
96+ end
7397
7498 if update_file ( file , nil , true , line_endings )
7599 copy_proc . call
@@ -183,6 +207,10 @@ def self.windows?
183207 RbConfig ::CONFIG [ 'host_os' ] =~ /mswin|mingw|cygwin/
184208 end
185209
210+ def self . wsl?
211+ defined? ( ENV [ 'WSLENV' ] )
212+ end
213+
186214 require 'win32ole' if windows?
187215
188216 def windows_copy_file ( source , dest )
@@ -195,6 +223,16 @@ def windows_copy_file(source, dest)
195223 end
196224 end
197225
226+ def wsl_copy_file ( source , dest , win_source , win_dest )
227+ begin
228+ # First, try Ruby copy
229+ FileUtils . cp ( source , dest )
230+ rescue Errno ::EACCES
231+ # Access denied, try with elevated privileges
232+ system ( 'powershell.exe' , 'Start-Process -Verb Runas -FilePath cmd.exe -Argumentlist "/C","copy","' + win_source + '","' + win_dest + '"' )
233+ end
234+ end
235+
198236 private
199237
200238 def windows_copy_file_elevated ( source , dest )
0 commit comments