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 var gret = GLib.spawn_async_with_pipes(this.cwd, this.args, this.env,
162 GLib.SpawnFlags.DO_NOT_REAP_CHILD + GLib.SpawnFlags.SEARCH_PATH ,
166 if (typeof(Seed) == 'undefined') {
169 standard_input : gret[2],
170 standard_output: gret[3],
171 standard_error: gret[4]
176 //print(JSON.stringify(gret));
177 this.pid = ret.child_pid;
180 print("PID: " + this.pid);
185 GLib.child_watch_add(GLib.PRIORITY_DEFAULT, this.pid, function(pid, result) {
186 _this.result = result;
188 print("child_watch_add : result: " + result);
190 _this.read(_this.out_ch);
191 _this.read(_this.err_ch);
194 GLib.spawn_close_pid(_this.pid);
200 //print("DONE TIDYUP");
201 if (_this.listeners.finish) {
202 _this.listeners.finish.call(this, _this.result);
209 GLib.spawn_close_pid(_this.pid); // hopefully kills it..
212 if (_this.in_ch) _this.in_ch.close();
213 if (_this.out_ch) _this.out_ch.close();
214 if (_this.err_ch) _this.err_ch.close();
215 // blank out channels
217 _this.err_ch = false;
218 _this.out_ch = false;
219 // rmeove listeners !! important otherwise we kill the CPU
220 if (err_src !== false) GLib.source_remove(err_src);
221 if (out_src !== false) GLib.source_remove(out_src);
228 this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
229 this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
230 this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
232 // make everything non-blocking!
236 // using NONBLOCKING only works if io_add_watch
237 //returns true/false in right conditions
238 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
239 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
240 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
244 // add handlers for output and stderr.
245 out_src= GLib.io_add_watch(this.out_ch, GLib.PRIORITY_DEFAULT,
246 GLib.IOCondition.OUT + GLib.IOCondition.IN + GLib.IOCondition.PRI + GLib.IOCondition.HUP + GLib.IOCondition.ERR,
249 return _this.read(_this.out_ch);
253 err_src= GLib.io_add_watch(this.err_ch, GLib.PRIORITY_DEFAULT,
254 GLib.IOCondition.ERR + GLib.IOCondition.IN + GLib.IOCondition.PRI + GLib.IOCondition.OUT + GLib.IOCondition.HUP,
257 return _this.read(_this.err_ch);
264 if (this.pid !== false) {
265 // child can exit before 1we get this far..
266 if (this.listeners.input) {
267 print("Trying to call listeners");
269 this.write(this.listeners.input.call(this));
270 // this probably needs to be a bit smarter...
271 //but... let's close input now..
287 // async - if running - return..
288 if (this.async && this.pid) {
292 // start mainloop if not async..
294 if (this.pid !== false) {
296 print("starting main loop");
299 this.ctx = isSeed ? new GLib.MainLoop.c_new (null, false) : GLib.MainLoop.new (null, false);;
300 this.ctx.run(false); // wait fore exit?
302 //print("main_loop done!");
304 tidyup(); // tidyup get's called in main loop.
307 if (this.exceptions && this.result != 0) {
310 this.toString = function() { return this.stderr; };
311 throw this; // we throw self...
314 // finally throw, or return self..
320 * write to stdin of process
321 * @arg str {String} string to write to stdin of process
322 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
324 write : function(str) // write a line to
327 return 0; // input is closed
329 //print("write: " + str);
330 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
332 //var res = this.in_ch.write_chars(str, str.length, ret);
333 var res = this.in_ch.write_chars(str, str.length);
335 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
337 if (res != GLib.IOStatus.NORMAL) {
338 throw "Write failed";
346 * read from pipe and call appropriate listerner and add to output or stderr string.
347 * @arg giochannel to read from.
352 var prop = ch == this.out_ch ? 'output' : 'stderr';
353 // print("prop: " + prop);
357 //print(JSON.stringify(ch, null,4));
361 var status = ch.read_line( x);
362 // print('status: ' +JSON.stringify(status));
363 // print(JSON.stringify(x));
365 case GLib.IOStatus.NORMAL:
368 if (this.listeners[prop]) {
369 this.listeners[prop].call(this, x.str_return);
371 _this[prop] += x.str_return;
373 print(prop + ':' + x.str_return.replace(/\n/, ''));
377 if (imports.gi.Gtk.events_pending()) {
378 imports.gi.Gtk.main_iteration();
385 //this.ctx.iteration(true);
387 case GLib.IOStatus.AGAIN:
388 //print("Should be called again.. waiting for more data..");
391 case GLib.IOStatus.ERROR:
392 case GLib.IOStatus.EOF:
400 //print("RETURNING");
401 return false; // allow it to be called again..
408 * simple run a process - returns result, or throws stderr result...
409 * @param cfg {Object} see spawn
410 * @return {string} stdout output.
413 cfg.exceptions = true;
415 var s = new Spawn(cfg);
423 args: ['ls', '/tmp'],
426 } catch (e) { print(JSON.stringify(e)); }
428 var secs = (new Date()).getSeconds()
432 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
435 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }