|
| 1 | +require 'overcommit/os' |
| 2 | +require 'overcommit/subprocess' |
| 3 | + |
| 4 | +module Overcommit::Utils |
| 5 | + # Utility functions for file IO. |
| 6 | + module FileUtils |
| 7 | + class << self |
| 8 | + # When the host OS is Windows, uses the `mklink` command to create an |
| 9 | + # NTFS symbolic link from `new_name` to `old_name`. Otherwise delegates |
| 10 | + # to `File.symlink` |
| 11 | + def symlink(old_name, new_name) |
| 12 | + return File.symlink(old_name, new_name) unless Overcommit::OS.windows? |
| 13 | + |
| 14 | + result = win32_mklink_cmd(old_name, new_name) |
| 15 | + result.status |
| 16 | + end |
| 17 | + |
| 18 | + # When the host OS is Windows, uses the `dir` command to check whether |
| 19 | + # `file_name` is an NTFS symbolic link. Otherwise delegates to |
| 20 | + # `File.symlink`. |
| 21 | + def symlink?(file_name) |
| 22 | + return File.symlink?(file_name) unless Overcommit::OS.windows? |
| 23 | + |
| 24 | + result = win32_dir_cmd(file_name) |
| 25 | + win32_symlink?(result.stdout) |
| 26 | + end |
| 27 | + |
| 28 | + # When the host OS is Windows, uses the `dir` command to check whether |
| 29 | + # `link_name` is an NTFS symbolic link. If so, it parses the target from |
| 30 | + # the command output. Otherwise raises an `ArgumentError`. Delegates to |
| 31 | + # `File.readlink` if the host OS is not Windows. |
| 32 | + def readlink(link_name) |
| 33 | + return File.readlink(link_name) unless Overcommit::OS.windows? |
| 34 | + |
| 35 | + result = win32_dir_cmd(link_name) |
| 36 | + |
| 37 | + unless win32_symlink?(result.stdout) |
| 38 | + raise ArgumentError, "#{link_name} is not a symlink" |
| 39 | + end |
| 40 | + |
| 41 | + # Extract symlink target from output, which looks like: |
| 42 | + # 11/13/2012 12:53 AM <SYMLINK> mysymlink [C:\Windows\Temp\somefile.txt] |
| 43 | + result.stdout[/\[(.+)\]/, 1] |
| 44 | + end |
| 45 | + |
| 46 | + private |
| 47 | + |
| 48 | + def win32_dir_cmd(file_name) |
| 49 | + Overcommit::Subprocess.spawn( |
| 50 | + %W[dir #{win32_fix_pathsep(file_name)}] |
| 51 | + ) |
| 52 | + end |
| 53 | + |
| 54 | + def win32_mklink_cmd(old_name, new_name) |
| 55 | + Overcommit::Subprocess.spawn( |
| 56 | + %W[mklink #{win32_fix_pathsep(new_name)} #{win32_fix_pathsep(old_name)}] |
| 57 | + ) |
| 58 | + end |
| 59 | + |
| 60 | + def win32_fix_pathsep(path) |
| 61 | + path.gsub('/', '\\') |
| 62 | + end |
| 63 | + |
| 64 | + def win32_symlink?(dir_output) |
| 65 | + !(dir_output =~ /<SYMLINK>/).nil? |
| 66 | + end |
| 67 | + end |
| 68 | + end |
| 69 | +end |
0 commit comments