Improve vim's 'gf' for BUILD.gn files

If vim-maktaba is installed, vim will use it during the 'gf' command in
GN files.

If maktaba is not installed, the plugin uses a fallback approach,
however this is easily broken with the 'autochdir' setting.

BUG=

Review-Url: https://codereview.chromium.org/2657853004
Cr-Original-Commit-Position: refs/heads/master@{#446447}
Cr-Mirrored-From: https://chromium.googlesource.com/chromium/src
Cr-Mirrored-Commit: e46620f101019c220a303e6cc82c57c928a677bd
diff --git a/tools/gn/misc/vim/autoload/gn.vim b/tools/gn/misc/vim/autoload/gn.vim
index c1df012..5573efc 100644
--- a/tools/gn/misc/vim/autoload/gn.vim
+++ b/tools/gn/misc/vim/autoload/gn.vim
@@ -10,8 +10,17 @@
   let l:new_path = substitute(l:new_path, '\v:.*$', '', '')
 
   " Append 'BUILD.gn', only if this is a directory and not a file
-  if isdirectory(l:new_path)
-    let l:new_path = substitute(l:new_path, '\v/?$', '/BUILD.gn', '')
+  " Prefer using maktaba if it's available, but fallback to an alternative
+  if exists('*maktaba#path#Basename')
+    " Check if the last part of the path appears to be a file
+    if maktaba#path#Basename(l:new_path) !~# '\V.'
+      let l:new_path = maktaba#path#Join([l:new_path, 'BUILD.gn'])
+    endif
+  else
+    " This will break if 'autochdir' is enabled
+    if isdirectory(l:new_path)
+      let l:new_path = substitute(l:new_path, '\v/?$', '/BUILD.gn', '')
+    endif
   endif
   return l:new_path
 endfunction