Process.hx 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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.spawn(_shell, opt, function(code:Int, signal:Signal) {
  82. _code = code;
  83. if (!_handle.is_closing()){
  84. _handle.close();
  85. }
  86. _stdin.shutdown(()->_stdin.close());
  87. _stderr.shutdown(()->_stderr.close());
  88. _stdout.shutdown(()->_stdout.close());
  89. });
  90. _handle = p.handle;
  91. if (p.handle == null)
  92. throw p.pid;
  93. _pid = p.pid;
  94. }
  95. public function getPid():Int {
  96. return _pid;
  97. }
  98. public function close():Void {
  99. if (!_handle.is_closing()){
  100. _handle.close();
  101. }
  102. }
  103. public function exitCode(block:Bool = true):Null<Int> {
  104. if (!block)
  105. return _code;
  106. while (_handle.is_active()) {
  107. Loop.run(); // process io until the handle closes (emulate blocking)
  108. }
  109. return _code;
  110. }
  111. public function kill():Void {
  112. _handle.kill("sigterm");
  113. }
  114. }
  115. private class ProcessInput extends haxe.io.Input {
  116. var b:Pipe;
  117. var buf:String;
  118. var idx:Int;
  119. var _eof:Bool;
  120. public function new(pipe:Pipe) {
  121. b = pipe;
  122. _eof = false;
  123. }
  124. inline public function eof():Bool {
  125. return _eof;
  126. }
  127. override function readBytes(s:Bytes, pos:Int, len:Int):Int {
  128. if (eof())
  129. throw new haxe.io.Eof();
  130. return super.readBytes(s, pos, len);
  131. }
  132. override public function readByte() {
  133. var err_str = null;
  134. if (buf == null || idx >= NativeStringTools.len(buf)) {
  135. buf = null;
  136. idx = 0;
  137. var pending = true;
  138. b.read_start(function(err, chunk) {
  139. if (chunk != null) {
  140. if (buf != null) {
  141. buf = buf + chunk;
  142. } else {
  143. buf = chunk;
  144. }
  145. }
  146. if (err != null)
  147. err_str = err;
  148. pending = false;
  149. });
  150. // process io until we read our input (emulate blocking)
  151. while (pending)
  152. Loop.run();
  153. }
  154. if (buf == null) {
  155. _eof = true;
  156. throw new haxe.io.Eof();
  157. }
  158. if (err_str != null)
  159. throw err_str;
  160. var code = NativeStringTools.byte(buf, ++idx);
  161. return code;
  162. }
  163. override public function readAll(?bufsize:Int):Bytes {
  164. if (bufsize == null)
  165. bufsize = (1 << 14); // 16 Ko
  166. var buf = Bytes.alloc(bufsize);
  167. var total = new haxe.io.BytesBuffer();
  168. try {
  169. while (true) {
  170. var len = readBytes(buf, 0, bufsize);
  171. // don't throw blocked error here
  172. if (len != 0)
  173. total.addBytes(buf, 0, len);
  174. if (len < bufsize)
  175. break;
  176. }
  177. } catch (e:Eof) {
  178. _eof = true;
  179. }
  180. return total.getBytes();
  181. }
  182. override public function close() {
  183. b.close();
  184. }
  185. }
  186. private class ProcessOutput extends haxe.io.Output {
  187. var b:Pipe;
  188. public function new(pipe:Pipe) {
  189. b = pipe;
  190. set_bigEndian(Boot.platformBigEndian);
  191. }
  192. override public function writeByte(c:Int):Void {
  193. b.write(NativeStringTools.char(c));
  194. }
  195. override public function close() {
  196. b.close();
  197. }
  198. }