3 using Gee; // for array list?
5 static int main (string[] args) {
6 // A reference to our file
7 var file = File.new_for_path ("data.txt");
13 var Gio = imports.gi.Gio;
14 var GLib = imports.gi.GLib;
20 * Library to wrap GLib.spawn_async_with_pipes
24 * Spawn = import.Spawn;
27 * var output = Spawn.run({
29 * args : [ 'ls', '-l' ],
30 * env : [], // optional
32 output : function (line) { Seed.print(line); },
33 * stderr : function (line) {Seed.print("ERROR" + line); },
34 * input : function() { return 'xxx' },
43 * CRITICAL - needs this change to gir in GLib-2.0.gir g_spawn_async_with_pipes
44 * Fixed in Ubuntu 12.10
45 <parameter name="argv" transfer-ownership="none">
46 <array c:type="gchar**">
50 <parameter name="envp" transfer-ownership="none" allow-none="1">
51 <array c:type="gchar**">
56 * ALSO in GLib-2.0.gir
58 <method name="read_line"
59 c:identifier="g_io_channel_read_line"
61 <return-value transfer-ownership="none">
62 <type name="IOStatus" c:type="GIOStatus"/>
65 <parameter name="str_return" transfer-ownership="full" direction="out">
66 <type name="utf8" c:type="gchar**"/>
68 <parameter name="length" transfer-ownership="none" direction="out">
69 <type name="gsize" c:type="gsize*"/>
71 <parameter name="terminator_pos" transfer-ownership="none" direction="out">
72 <type name="gsize" c:type="gsize*"/>
77 * run g-ir-compile -o /usr/lib/girepostitory-1.0/GLib-2.0.typelib GLib-2.0.gir
85 * @param cfg {Object} settings - see properties.
87 * @arg cwd {String} working directory. (defaults to home directory)
88 * @arg args {Array} arguments eg. [ 'ls', '-l' ]
89 * @arg listeners {Object} (optional) handlers for output, stderr, input
90 * stderr/output both receive output line as argument
91 * input should return any standard input
92 * finish recieves result as argument.
93 * @arg env {Array} enviroment eg. [ 'GITDIR=/home/test' ]
94 * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
95 * @arg exceptions {Boolean} throw exception on failure (default no)
96 * @arg debug {Boolean} print out what's going on.. (default no)
104 this.listeners = this.listeners || {};
105 this.cwd = this.cwd || GLib.get_home_dir();
106 if (!this.args || !this.args.length) {
107 throw "No arguments";
115 ctx : false, // the mainloop ctx.
124 * @property output {String} resulting output
128 * @property stderr {String} resulting output from stderr
132 * @property result {Number} execution result.
136 * @property pid {Number} pid of child process (of false if it's not running)
140 * @property in_ch {GLib.IOChannel} input io channel
144 * @property out_ch {GLib.IOChannel} output io channel
148 * @property err_ch {GLib.IOChannel} stderr io channel
154 * Run the configured command.
155 * result is applied to object properties (eg. 'output' or 'stderr')
156 * @returns {Object} self.
168 print("cd " + this.cwd +";" + this.args.join(" "));
171 var gret = GLib.spawn_async_with_pipes(this.cwd, this.args, this.env,
172 GLib.SpawnFlags.DO_NOT_REAP_CHILD + GLib.SpawnFlags.SEARCH_PATH ,
176 if (typeof(Seed) == 'undefined') {
179 standard_input : gret[2],
180 standard_output: gret[3],
181 standard_error: gret[4]
186 //print(JSON.stringify(gret));
187 this.pid = ret.child_pid;
190 print("PID: " + this.pid);
195 GLib.child_watch_add(GLib.PRIORITY_DEFAULT, this.pid, function(pid, result) {
196 _this.result = result;
198 print("child_watch_add : result: " + result);
200 _this.read(_this.out_ch);
201 _this.read(_this.err_ch);
204 GLib.spawn_close_pid(_this.pid);
210 //print("DONE TIDYUP");
211 if (_this.listeners.finish) {
212 _this.listeners.finish.call(this, _this.result);
219 GLib.spawn_close_pid(_this.pid); // hopefully kills it..
222 if (_this.in_ch) _this.in_ch.close();
223 if (_this.out_ch) _this.out_ch.close();
224 if (_this.err_ch) _this.err_ch.close();
225 // blank out channels
227 _this.err_ch = false;
228 _this.out_ch = false;
229 // rmeove listeners !! important otherwise we kill the CPU
230 if (err_src !== false) GLib.source_remove(err_src);
231 if (out_src !== false) GLib.source_remove(out_src);
238 this.in_ch = new GLib.IOChannel.unix_new(ret.standard_input);
239 this.out_ch = new GLib.IOChannel.unix_new(ret.standard_output);
240 this.err_ch = new GLib.IOChannel.unix_new(ret.standard_error);
242 // make everything non-blocking!
246 // using NONBLOCKING only works if io_add_watch
247 //returns true/false in right conditions
248 this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
249 this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
250 this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
254 // add handlers for output and stderr.
255 out_src= GLib.io_add_watch(this.out_ch, GLib.PRIORITY_DEFAULT,
256 GLib.IOCondition.OUT + GLib.IOCondition.IN + GLib.IOCondition.PRI + GLib.IOCondition.HUP + GLib.IOCondition.ERR,
259 return _this.read(_this.out_ch);
263 err_src= GLib.io_add_watch(this.err_ch, GLib.PRIORITY_DEFAULT,
264 GLib.IOCondition.ERR + GLib.IOCondition.IN + GLib.IOCondition.PRI + GLib.IOCondition.OUT + GLib.IOCondition.HUP,
267 return _this.read(_this.err_ch);
274 if (this.pid !== false) {
275 // child can exit before 1we get this far..
276 if (this.listeners.input) {
277 print("Trying to call listeners");
279 this.write(this.listeners.input.call(this));
280 // this probably needs to be a bit smarter...
281 //but... let's close input now..
297 // async - if running - return..
298 if (this.async && this.pid) {
302 // start mainloop if not async..
304 if (this.pid !== false) {
306 print("starting main loop");
309 this.ctx = isSeed ? new GLib.MainLoop.c_new (null, false) : GLib.MainLoop.new (null, false);;
310 this.ctx.run(false); // wait fore exit?
312 //print("main_loop done!");
314 tidyup(); // tidyup get's called in main loop.
317 if (this.exceptions && this.result != 0) {
318 this.toString = function() { return this.stderr; };
319 throw this; // we throw self...
322 // finally throw, or return self..
328 * write to stdin of process
329 * @arg str {String} string to write to stdin of process
330 * @returns GLib.IOStatus (0 == error, 1= NORMAL)
332 write : function(str) // write a line to
335 return 0; // input is closed
337 //print("write: " + str);
338 // NEEDS GIR FIX! for return value.. let's ignore for the time being..
340 //var res = this.in_ch.write_chars(str, str.length, ret);
341 var res = this.in_ch.write_chars(str, str.length);
343 //print("write_char retunred:" + JSON.stringify(res) + ' ' +JSON.stringify(ret) );
345 if (res != GLib.IOStatus.NORMAL) {
346 throw "Write failed";
354 * read from pipe and call appropriate listerner and add to output or stderr string.
355 * @arg giochannel to read from.
360 var prop = ch == this.out_ch ? 'output' : 'stderr';
361 // print("prop: " + prop);
365 //print(JSON.stringify(ch, null,4));
369 var status = ch.read_line( x);
370 // print('status: ' +JSON.stringify(status));
371 // print(JSON.stringify(x));
373 case GLib.IOStatus.NORMAL:
376 if (this.listeners[prop]) {
377 this.listeners[prop].call(this, x.str_return);
379 _this[prop] += x.str_return;
381 print(prop + ':' + x.str_return.replace(/\n/, ''));
385 if (imports.gi.Gtk.events_pending()) {
386 imports.gi.Gtk.main_iteration();
393 //this.ctx.iteration(true);
395 case GLib.IOStatus.AGAIN:
396 //print("Should be called again.. waiting for more data..");
399 case GLib.IOStatus.ERROR:
400 case GLib.IOStatus.EOF:
408 //print("RETURNING");
409 return false; // allow it to be called again..
416 * simple run a process - returns result, or throws stderr result...
417 * @param cfg {Object} see spawn
418 * @return {string} stdout output.
421 cfg.exceptions = true;
423 var s = new Spawn(cfg);
431 args: ['ls', '/tmp'],
434 } catch (e) { print(JSON.stringify(e)); }
436 var secs = (new Date()).getSeconds()
440 args: ['/bin/touch', '/tmp/spawntest-' + secs ],
443 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }