Process.hx 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. /*
  2. * Copyright (C)2005-2019 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package sys.io;
  23. import lua.Io;
  24. import lua.lib.luv.Pipe;
  25. import lua.lib.luv.Signal;
  26. import lua.lib.luv.Loop;
  27. import lua.Boot;
  28. import lua.Table;
  29. import lua.NativeStringTools;
  30. import haxe.SysTools;
  31. import haxe.io.Bytes;
  32. import haxe.io.Error;
  33. import haxe.io.Eof;
  34. @:coreApi
  35. class Process {
  36. var _pid:Int;
  37. var _handle:lua.lib.luv.Process;
  38. var _code:Int;
  39. var closef:Int->Signal->Void;
  40. public var stdout(default, null):haxe.io.Input;
  41. public var stderr(default, null):haxe.io.Input;
  42. public var stdin(default, null):haxe.io.Output;
  43. static var argQuote = Sys.systemName() == "Windows" ? function(x) return SysTools.quoteWinArg(x, true) : SysTools.quoteUnixArg;
  44. static var _shell = Sys.systemName() == "Windows" ? 'cmd.exe' : '/bin/sh';
  45. /**
  46. Sets the args for the shell, which will include the cmd to be executed
  47. by the shell.
  48. **/
  49. static function setArgs(cmd:String, ?args:Array<String>):Table<Int, String> {
  50. var pargs = lua.Table.create();
  51. var idx = 1;
  52. if (sys.FileSystem.exists(cmd))
  53. cmd = '"$cmd"'; // escape simple paths
  54. var all = [cmd];
  55. if (args != null) {
  56. for (a in args) {
  57. all.push(argQuote(a));
  58. }
  59. }
  60. if (Sys.systemName() == "Windows") {
  61. pargs[idx++] = '/s';
  62. pargs[idx++] = '/c';
  63. pargs[idx++] = all.join(" ");
  64. } else {
  65. pargs[idx++] = "-c";
  66. pargs[idx++] = all.join(" ");
  67. }
  68. return pargs;
  69. }
  70. public function new(cmd:String, ?args:Array<String>, ?detached:Bool) {
  71. if (detached)
  72. throw "Detached process is not supported on this platform";
  73. var _stdout = new Pipe(false);
  74. var _stderr = new Pipe(false);
  75. var _stdin = new Pipe(false);
  76. stdout = new ProcessInput(_stdout);
  77. stderr = new ProcessInput(_stderr);
  78. stdin = new ProcessOutput(_stdin);
  79. var stdio = untyped __lua_table__([_stdin, _stdout, _stderr]);
  80. var opt = {args: setArgs(cmd, args), stdio: stdio};
  81. var p:lua.lib.luv.Process.LuvSpawn;
  82. p = lua.lib.luv.Process.spawn(_shell, opt, function(code:Int, signal:Signal) {
  83. _code = code;
  84. });
  85. if (p.handle == null)
  86. throw p.pid;
  87. _pid = p.pid;
  88. _handle = p.handle;
  89. }
  90. public function getPid():Int {
  91. return _pid;
  92. }
  93. public function close():Void {
  94. stdout.close();
  95. stdin.close();
  96. stderr.close();
  97. _handle.close();
  98. }
  99. public function exitCode(block:Bool = true):Null<Int> {
  100. if (!block)
  101. return _code;
  102. while (_handle.is_active()) {
  103. Loop.run(); // process io until the handle closes (emulate blocking)
  104. }
  105. return _code;
  106. }
  107. public function kill():Void {
  108. _handle.kill("sigterm");
  109. }
  110. }
  111. private class ProcessInput extends haxe.io.Input {
  112. var b:Pipe;
  113. var buf:String;
  114. var idx:Int;
  115. var _eof:Bool;
  116. public function new(pipe:Pipe) {
  117. b = pipe;
  118. _eof = false;
  119. }
  120. inline public function eof():Bool {
  121. return _eof;
  122. }
  123. override function readBytes(s:Bytes, pos:Int, len:Int):Int {
  124. if (eof())
  125. throw new haxe.io.Eof();
  126. return super.readBytes(s, pos, len);
  127. }
  128. override public function readByte() {
  129. var err_str = null;
  130. if (buf == null || idx >= NativeStringTools.len(buf)) {
  131. buf = null;
  132. idx = 0;
  133. var pending = true;
  134. b.read_start(function(err, chunk) {
  135. if (chunk != null) {
  136. if (buf != null) {
  137. buf = buf + chunk;
  138. } else {
  139. buf = chunk;
  140. }
  141. }
  142. if (err != null)
  143. err_str = err;
  144. pending = false;
  145. });
  146. // process io until we read our input (emulate blocking)
  147. while (pending)
  148. Loop.run();
  149. }
  150. if (buf == null) {
  151. _eof = true;
  152. throw new haxe.io.Eof();
  153. }
  154. if (err_str != null)
  155. throw err_str;
  156. var code = NativeStringTools.byte(buf, ++idx);
  157. return code;
  158. }
  159. override public function readAll(?bufsize:Int):Bytes {
  160. if (bufsize == null)
  161. bufsize = (1 << 14); // 16 Ko
  162. var buf = Bytes.alloc(bufsize);
  163. var total = new haxe.io.BytesBuffer();
  164. try {
  165. while (true) {
  166. var len = readBytes(buf, 0, bufsize);
  167. // don't throw blocked error here
  168. if (len != 0)
  169. total.addBytes(buf, 0, len);
  170. if (len < bufsize)
  171. break;
  172. }
  173. } catch (e:Eof) {
  174. _eof = true;
  175. }
  176. return total.getBytes();
  177. }
  178. override public function close() {
  179. b.close();
  180. }
  181. }
  182. private class ProcessOutput extends haxe.io.Output {
  183. var b:Pipe;
  184. public function new(pipe:Pipe) {
  185. b = pipe;
  186. set_bigEndian(Boot.platformBigEndian);
  187. }
  188. override public function writeByte(c:Int):Void {
  189. b.write(NativeStringTools.char(c));
  190. }
  191. override public function close() {
  192. b.close();
  193. }
  194. }