@@ -55,13 +55,34 @@ def update_host
55
55
# copy and modify hosts file on host with Vagrant-managed entries
56
56
file = @global_env . tmp_path . join ( 'hosts.local' )
57
57
58
- if WindowsSupport . windows?
58
+ if WindowsSupport . windows? || WindowsSupport . wsl?
59
59
# lazily include windows Module
60
60
class << self
61
61
include WindowsSupport unless include? WindowsSupport
62
62
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
65
86
line_endings = "crlf"
66
87
else
67
88
hosts_location = '/etc/hosts'
@@ -70,6 +91,9 @@ class << self
70
91
end
71
92
72
93
FileUtils . cp ( hosts_location , file )
94
+ if WindowsSupport . wsl?
95
+ FileUtils . chmod ( "+w" , file )
96
+ end
73
97
74
98
if update_file ( file , nil , true , line_endings )
75
99
copy_proc . call
@@ -183,6 +207,10 @@ def self.windows?
183
207
RbConfig ::CONFIG [ 'host_os' ] =~ /mswin|mingw|cygwin/
184
208
end
185
209
210
+ def self . wsl?
211
+ defined? ( ENV [ 'WSLENV' ] )
212
+ end
213
+
186
214
require 'win32ole' if windows?
187
215
188
216
def windows_copy_file ( source , dest )
@@ -195,6 +223,16 @@ def windows_copy_file(source, dest)
195
223
end
196
224
end
197
225
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
+
198
236
private
199
237
200
238
def windows_copy_file_elevated ( source , dest )
0 commit comments