1 ///<script type="text/javascript">
3 var Gio = imports.gi.Gio;
4 var GLib = imports.gi.GLib;
10 * Library to wrap GLib.spawn_async_with_pipes
14 * Spawn = import.Spawn;
17 * var output = Spawn.run({
19 * args : [ 'ls', '-l' ],
20 * env : [], // optional
22 output : function (line) { Seed.print(line); },
23 * stderr : function (line) {Seed.print("ERROR" + line); },
24 * input : function() { return 'xxx' },
33 * CRITICAL - needs this change to gir in GLib-2.0.gir g_spawn_async_with_pipes
34 * Fixed in Ubuntu 12.10
35 <parameter name="argv" transfer-ownership="none">
36 <array c:type="gchar**">
40 <parameter name="envp" transfer-ownership="none" allow-none="1">
41 <array c:type="gchar**">
46 * ALSO in GLib-2.0.gir
48 <method name="read_line"
49 c:identifier="g_io_channel_read_line"
51 <return-value transfer-ownership="none">
52 <type name="IOStatus" c:type="GIOStatus"/>
55 <parameter name="str_return" transfer-ownership="full" direction="out">
56 <type name="utf8" c:type="gchar**"/>
58 <parameter name="length" transfer-ownership="none" direction="out">
59 <type name="gsize" c:type="gsize*"/>
61 <parameter name="terminator_pos" transfer-ownership="none" direction="out">
62 <type name="gsize" c:type="gsize*"/>
67 * run g-ir-compile -o /usr/lib/girepostitory-1.0/GLib-2.0.typelib GLib-2.0.gir
75 * @param cfg {Object} settings - see properties.
77 * @arg cwd {String} working directory. (defaults to home directory)
78 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
79 * @arg listeners {Object} (optional) handlers for output, stderr, input
80 * stderr/output both receive output line as argument
81 * input should return any standard input
82 * finish recieves result as argument.
83 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
84 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
85 * @arg exceptions {Boolean} throw exception on failure (default no)
86 * @arg debug {Boolean} print out what's going on.. (default no)
94 this.listeners = this.listeners || {};
95 this.cwd = this.cwd || GLib.get_home_dir();
96 if (!this.args || !this.args.length) {
105 ctx : false, // the mainloop ctx.
114 * @property output {String} resulting output
118 * @property stderr {String} resulting output from stderr
122 * @property result {Number} execution result.
126 * @property pid {Number} pid of child process (of false if it's not running)
130 * @property in_ch {GLib.IOChannel} input io channel
134 * @property out_ch {GLib.IOChannel} output io channel
138 * @property err_ch {GLib.IOChannel} stderr io channel
144 * Run the configured command.
145 * result is applied to object properties (eg. 'output' or 'stderr')
146 * @returns {Object} self.
158 print("cd " + this.cwd +";" + this.args.join(" "));
161 GLib.spawn_async_with_pipes(this.cwd, this.args, this.env,
162 GLib.SpawnFlags.DO_NOT_REAP_CHILD + GLib.SpawnFlags.SEARCH_PATH ,
165 //print(JSON.stringify(ret));
166 this.pid = ret.child_pid;
169 print("PID: " + this.pid);
174 GLib.child_watch_add(GLib.PRIORITY_DEFAULT, this.pid, function(pid, result) {
175 _this.result = result;
177 print("child_watch_add : result: " + result);
179 _this.read(_this.out_ch);
180 _this.read(_this.err_ch);
182 GLib.spawn_close_pid(_this.pid);
188 //print("DONE TIDYUP");
189 if (_this.listeners.finish) {
190 _this.listeners.finish.call(this, _this.result);
197 GLib.spawn_close_pid(_this.pid); // hopefully kills it..
200 if (_this.in_ch) _this.in_ch.close();
201 if (_this.out_ch) _this.out_ch.close();
202 if (_this.err_ch) _this.err_ch.close();
203 // blank out channels
205 _this.err_ch = false;
206 _this.out_ch = false;
207 // rmeove listeners !! important otherwise we kill the CPU
208 if (err_src !== false) GLib.source_remove(err_src);
209 if (out_src !== false) GLib.source_remove(out_src);
216 this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
217 this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
218 this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
220 // make everything non-blocking!
224 // using NONBLOCKING only works if io_add_watch
225 //returns true/false in right conditions
226 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
227 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
228 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
232 // add handlers for output and stderr.
233 out_src= GLib.io_add_watch(this.out_ch, GLib.PRIORITY_DEFAULT,
234 GLib.IOCondition.OUT + GLib.IOCondition.IN + GLib.IOCondition.PRI + GLib.IOCondition.HUP + GLib.IOCondition.ERR,
237 return _this.read(_this.out_ch);
241 err_src= GLib.io_add_watch(this.err_ch, GLib.PRIORITY_DEFAULT,
242 GLib.IOCondition.ERR + GLib.IOCondition.IN + GLib.IOCondition.PRI + GLib.IOCondition.OUT + GLib.IOCondition.HUP,
245 return _this.read(_this.err_ch);
252 if (this.pid !== false) {
253 // child can exit before we get this far..
254 if (this.listeners.input) {
255 print("Trying to call listeners");
257 this.write(this.listeners.input.call(this));
258 // this probably needs to be a bit smarter...
259 //but... let's close input now..
275 // async - if running - return..
276 if (this.async && this.pid) {
281 // start mainloop if not async..
283 if (this.pid !== false) {
285 print("starting main loop");
288 this.ctx = new GLib.MainLoop.c_new (null, false);
289 this.ctx.run(false); // wait fore exit?
291 //print("main_loop done!");
293 tidyup(); // tidyup get's called in main loop.
296 if (this.exceptions && this.result != 0) {
297 this.toString = function() { return this.stderr; };
298 throw this; // we throw self...
301 // finally throw, or return self..
307 * write to stdin of process
308 * @arg str {String} string to write to stdin of process
309 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
311 write : function(str) // write a line to
314 return 0; // input is closed
316 //print("write: " + str);
317 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
319 //var res = this.in_ch.write_chars(str, str.length, ret);
320 var res = this.in_ch.write_chars(str, str.length);
322 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
324 if (res != GLib.IOStatus.NORMAL) {
325 throw "Write failed";
333 * read from pipe and call appropriate listerner and add to output or stderr string.
334 * @arg giochannel to read from.
339 var prop = ch == this.out_ch ? 'output' : 'stderr';
340 // print("prop: " + prop);
344 //print(JSON.stringify(ch, null,4));
348 var status = ch.read_line( x);
349 // print('status: ' +JSON.stringify(status));
350 // print(JSON.stringify(x));
352 case GLib.IOStatus.NORMAL:
355 if (this.listeners[prop]) {
356 this.listeners[prop].call(this, x.str_return);
358 _this[prop] += x.str_return;
360 print(prop + ':' + x.str_return.replace(/\n/, ''));
364 if (imports.gi.Gtk.events_pending()) {
365 imports.gi.Gtk.main_iteration();
372 //this.ctx.iteration(true);
374 case GLib.IOStatus.AGAIN:
375 //print("Should be called again.. waiting for more data..");
378 case GLib.IOStatus.ERROR:
379 case GLib.IOStatus.EOF:
387 //print("RETURNING");
388 return false; // allow it to be called again..
395 * simple run a process - returns result, or throws stderr result...
396 * @param cfg {Object} see spawn
397 * @return {string} stdout output.
400 cfg.exceptions = true;
402 var s = new Spawn(cfg);
410 args: ['ls', '/tmp'],
413 } catch (e) { print(JSON.stringify(e)); }
415 var secs = (new Date()).getSeconds()
419 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
422 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }