Class: SourceWindowsBatch

Inherits:
Object
  • Object
show all
Defined in:
lib/source_win_bat.rb

Constant Summary collapse

VERSION =
"0.3.0"

Instance Method Summary collapse

Instance Method Details

#main(argv) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/source_win_bat.rb', line 11

def main(argv)
  options = parse_args!(argv)

  unless [:cygwin, :msys, :wsl].include? UnixCompatEnv.compat_env
    raise "You're in an unsupported UNIX compatible environment"
  end

  env = prepare_env_vars
  env_tmp_file_in = mk_tmpname(".env")
  macro_tmp_file_in = mk_tmpname(".doskey")
  cwd_tmp_file_in = mk_tmpname(".cwd")
  win_cmd = argv[3..-1].map {|v| "#{v}"}.join(" ")
  win_cmd += " & call set SW_EXITSTATUS=%^ERRORLEVEL% "
  win_cmd = concat_envdump(win_cmd, env_tmp_file_in)
  win_cmd = concat_macrodump(win_cmd, macro_tmp_file_in)
  win_cmd = concat_cwddump(win_cmd, cwd_tmp_file_in)
  win_cmd += " & call exit %^SW_EXITSTATUS%"
  if options[:show_cmd]
    STDERR.puts "SW: " + win_cmd
  end
  Signal.trap(:INT, "SIG_IGN")
  if UnixCompatEnv.compat_env == :wsl
    # * Skip winpty, assuming the system's WSL supports ConPTY
    # * Use an absolute path since EC overwrites PATH with Windows-style PATH in WSL
    pid = Process.spawn(env,
                        UnixCompatEnv.to_compat_path('C:\\Windows\\System32\\cmd.exe'),
                        '/C', win_cmd, :in => 0, :out => 1, :err => 2)
  elsif !STDOUT.isatty
    pid = Process.spawn(env, 'cmd.exe', '/C', win_cmd, :in => 0, :out => 1, :err => 2)
  else
    pid = Process.spawn(env, 'winpty', '--', 'cmd.exe', '/C', win_cmd, :in => 0, :out => 1, :err => 2)
  end
  Signal.trap(:INT) do
    Process.signal("-KILL", pid)
  end
  status = nil
  loop do
    _, status = Process.wait2(pid)
    break if status.exited?
  end
  
  begin
    codepage = detect_ansi_codepage
    conv_setenv_stmts(env_tmp_file_in, argv[0], :bash, codepage)
    conv_doskey_stmts(macro_tmp_file_in, argv[1], :bash, codepage)
    gen_chdir_cmds(cwd_tmp_file_in, argv[2], :bash, codepage)
    if !options[:preserve_dump]
      [env_tmp_file_in, macro_tmp_file_in, cwd_tmp_file_in].each do |f|
        File.delete f
      end
    end
  rescue Errno::ENOENT
    # ignore
  end

  exit(status.exitstatus)
end