sync
[gitlive] / Spawn.vala
1
2 /// # valac  --pkg gio-2.0 --pkg gtk+-3.0  --pkg posix Spawn.vala -o /tmp/Spawn
3
4 using GLib;
5 using Gtk;
6 // compile valac 
7
8
9
10 ///using Gee; // for array list?
11
12 static int main (string[] args) {
13     // A reference to our file
14     
15     var cfg = new SpawnConfig("", { "ls" } , { "" });
16     cfg.setHandlers(
17             (line) => {
18                     stdout.printf("%s\n", line);
19             },
20             null,null,null );
21     cfg.setOptions(
22         false, // async
23         false, // exceptions?? needed??
24         false  // debug???
25     );
26     try {
27         new Spawn(cfg);
28        
29     } catch (Error e) {
30         stdout.printf("Error %s", e.message);
31     }
32     
33     return 0;
34
35 }
36
37 //var Gio      = imports.gi.Gio;
38 //var GLib      = imports.gi.GLib;
39
40
41 /**
42 * @namespace Spawn
43
44 * Library to wrap GLib.spawn_async_with_pipes
45
46 * usage:
47 * v 
48 *
49 *var output = new Spawn( SpawnConfig() {
50     cwd = "/home",  // empty string to default to homedirectory.
51     args = {"ls", "-l" },
52     evn = {},
53     ouput  = (line) => { stdout.printf("%d\n", line); }
54     stderr  = (line) => { stdout.printf("%d\n", line); }
55     input  = () => { return "xxx"; }
56 };
57 *
58 *
59 */
60 public delegate void SpawnOutput(string line);
61 public delegate void SpawnErr(string line);
62 public delegate string SpawnInput();
63 public delegate void SpawnFinish(int result);
64  
65
66 public class  SpawnConfig {
67     public string cwd;
68     public string[] args;
69     public string[]  env;
70     public bool async;
71     public bool exceptions; // fire exceptions.
72     public bool debug; // fire exceptions.
73     
74     public SpawnOutput output;
75     public SpawnErr stderr;
76     public SpawnInput input;
77     public SpawnFinish finish;
78     // defaults..
79     public SpawnConfig(string cwd,
80             string[] args,
81             string[] env
82         ) {
83         this.cwd = cwd;
84         this.args = args;
85         this.env = env;
86          
87         async = false;
88         exceptions = false;
89         debug = false;
90         
91         output = null;
92         stderr = null;
93         input = null;
94         
95     }
96     
97     public void setOptions(
98             bool async,
99             bool exceptions,
100             bool debug
101         ) {
102         this.async = async;
103         this.exceptions = exceptions;
104         this.debug = debug;
105     }
106     public void setHandlers(
107             SpawnOutput? output,
108             SpawnErr? stderr,
109             SpawnInput? input,
110             SpawnFinish? finish
111          ) {
112         this.output = output;
113         this.stderr = stderr;
114         this.input = input;
115         this.finish = finish;
116     }
117     
118     
119 }
120
121 public errordomain SpawnError {
122     NO_ARGS,
123     WRITE_ERROR
124
125 }
126
127 /**
128  * @class Spawn
129  * @param cfg {SpawnConfig} settings - see properties.
130  * 
131  * @arg cwd {String}            working directory. (defaults to home directory)
132  * @arg args {Array}            arguments eg. [ 'ls', '-l' ]
133  * @arg listeners {Object} (optional) handlers for output, stderr, input
134  *     stderr/output both receive output line as argument
135  *     input should return any standard input
136  *     finish recieves result as argument.
137  * @arg env {Array}             enviroment eg. [ 'GITDIR=/home/test' ]
138  * @arg async {Boolean} (optional)return instantly, or wait for exit. (default no)
139  * @arg exceptions {Boolean}    throw exception on failure (default no)
140  * @arg debug {Boolean}    print out what's going on.. (default no)
141  * 
142  */
143
144
145 public class Spawn : Object
146 {
147
148     SpawnConfig cfg;
149
150     public Spawn(SpawnConfig cfg) throws Error
151     {
152        
153      
154         this.cfg = cfg;
155      
156     
157         this.cfg.cwd =  this.cfg.cwd.length  < 1 ? GLib.Environment.get_home_dir() : this.cfg.cwd;
158         if (this.cfg.args.length < 0) {
159             throw new SpawnError.NO_ARGS("No arguments");
160         }
161         this.run();
162     
163     }
164
165     
166     MainLoop ctx = null; // the mainloop ctx.
167     
168     /**
169      * @property output {String} resulting output
170      */
171     string output  = "";
172     /**
173      * @property stderr {String} resulting output from stderr
174      */
175     string stderr  = "";
176      /**
177      * @property result {Number} execution result.
178      */
179     int result= 0;
180     /**
181      * @property pid {Number} pid of child process (of false if it's not running)
182      */
183     int  pid = -1;
184     /**
185      * @property in_ch {GLib.IOChannel} input io channel
186      */
187     IOChannel in_ch = null;
188     /**
189      * @property out_ch {GLib.IOChannel} output io channel
190      */
191     IOChannel out_ch = null;
192     /**
193      * @property err_ch {GLib.IOChannel} stderr io channel
194      */
195     IOChannel err_ch = null;
196     /**
197      * @property err_src {int} the watch for errors
198      */
199     
200     int err_src = -1;
201       /**
202      * @property err_src {int} the watch for output
203      */
204     int out_src = -1;
205     
206     /**
207      * 
208      * @method run
209      * Run the configured command.
210      * result is applied to object properties (eg. '?' or 'stderr')
211      * @returns {Object} self.
212      */
213     public void run() throws SpawnError, GLib.SpawnError, GLib.IOChannelError
214     {
215         
216          
217         err_src = -1;
218         out_src = -1;
219         int standard_input;
220         int standard_output;
221         int standard_error;
222
223
224         
225         if (this.cfg.debug) {
226            stdout.printf("cd %s; %s" , this.cfg.cwd , string.joinv(" ", this.cfg.args));
227         }
228         
229         Process.spawn_async_with_pipes (
230                 this.cfg.cwd,
231                 this.cfg.args,
232                 this.cfg.env,
233                 SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
234                 null,
235                 out this.pid,
236                 out standard_input,
237                 out standard_output,
238                         out standard_error);
239
240                 // stdout:
241         
242                 
243         //print(JSON.stringify(gret));    
244          
245         if (this.cfg.debug) {
246             
247             stdout.printf("PID: %d" ,this.pid);
248         }
249          
250         ChildWatch.add (this.pid, (w_pid, result) => {
251             
252             this.result = result;
253             if (this.cfg.debug) {
254                 stdout.printf("child_watch_add : result:%d ", result);
255             }
256            
257             this.read(this.out_ch);
258             this.read(this.err_ch);
259             
260             
261             Process.close_pid(this.pid);
262             this.pid = -1;
263             if (this.ctx != null) {
264                 this.ctx.quit();
265                 this.ctx = null;
266             }
267             this.tidyup();
268         //print("DONE TIDYUP");
269             if (this.cfg.finish != null) {
270                 this.cfg.finish(this.result);
271             }
272         });
273             
274                           
275         
276         
277         this.in_ch = new GLib.IOChannel.unix_new(standard_input);
278         this.out_ch = new GLib.IOChannel.unix_new(standard_output);
279         this.err_ch = new GLib.IOChannel.unix_new(standard_error);
280         
281         // make everything non-blocking!
282         
283         
284             
285                   // using NONBLOCKING only works if io_add_watch
286           //returns true/false in right conditions
287           this.in_ch.set_flags (GLib.IOFlags.NONBLOCK);
288           this.out_ch.set_flags (GLib.IOFlags.NONBLOCK);
289           this.err_ch.set_flags (GLib.IOFlags.NONBLOCK);
290                    
291       
292             
293             // add handlers for output and stderr.
294         
295         this.out_src = (int) this.out_ch.add_watch (
296             IOCondition.OUT | IOCondition.IN  | IOCondition.PRI |  IOCondition.HUP |  IOCondition.ERR  ,
297             (channel, condition) => {
298                return this.read(this.out_ch);
299             }
300         );
301         this.err_src = (int) this.err_ch.add_watch (
302             IOCondition.OUT | IOCondition.IN  | IOCondition.PRI |  IOCondition.HUP |  IOCondition.ERR  ,
303             (channel, condition) => {
304                return this.read(this.err_ch);
305             }
306         );
307               
308         
309         // call input.. 
310         if (this.pid > -1) {
311             // child can exit before we get this far..
312             if (this.cfg.input != null) {
313                         if (this.cfg.debug) print("Trying to call listeners");
314                 try {
315                     this.write(this.cfg.input());
316                      // this probably needs to be a bit smarter...
317                     //but... let's close input now..
318                     this.in_ch.shutdown(true);
319                     this.in_ch = null;
320                      
321                     
322                 } catch (Error e) {
323                     this.tidyup();
324                     return;
325                   //  throw e;
326                     
327                 }
328                 
329             }
330             
331         }
332                 // async - if running - return..
333         if (this.cfg.async && this.pid > -1) {
334             return;
335         }
336          
337         // start mainloop if not async..
338         
339         if (this.pid > -1) {
340             if (this.cfg.debug) {
341                 print("starting main loop");
342             }
343                 this.ctx = new MainLoop ();
344             this.ctx.run(); // wait fore exit?
345             
346             //print("main_loop done!");
347         } else {
348             this.tidyup(); // tidyup get's called in main loop. 
349         }
350         
351         if (this.cfg.exceptions && this.result != 0) {
352             //this.toString = function() { return this.stderr; };
353             ///throw new Exception this; // we throw self...
354         }
355         
356         // finally throw, or return self..
357         
358         return;
359     
360     }
361     
362     
363
364     private void tidyup()
365     {
366         if (this.pid > -1) {
367             Process.close_pid(this.pid); // hopefully kills it..
368             this.pid = -1;
369         }
370         try {
371             if (this.in_ch != null)  this.in_ch.shutdown(true);
372             if (this.out_ch != null)  this.out_ch.shutdown(true);
373             if (this.err_ch != null)  this.err_ch.shutdown(true);
374         } catch (Error e) {
375             // error shutting donw.
376         }
377         // blank out channels
378         this.in_ch = null;
379         this.err_ch = null;
380         this.out_ch = null;
381         // rmeove listeners !! important otherwise we kill the CPU
382         //if (this.err_src > -1 ) GLib.source_remove(this.err_src);
383         //if (this.out_src > -1 ) GLib.source_remove(this.out_src);
384         this.err_src = -1;
385         this.out_src = -1;
386         
387     }
388     
389     
390     /**
391      * write to stdin of process
392      * @arg str {String} string to write to stdin of process
393      * @returns GLib.IOStatus (0 == error, 1= NORMAL)
394      */
395     private int write(string str) throws Error // write a line to 
396     {
397         if (this.in_ch == null) {
398             return 0; // input is closed
399         }
400         //print("write: " + str);
401         // NEEDS GIR FIX! for return value.. let's ignore for the time being..
402         //var ret = {};
403         size_t written;
404         var res = this.in_ch.write_chars(str.to_utf8(), out written);
405         
406         //print("write_char retunred:" + JSON.stringify(res) +  ' ' +JSON.stringify(ret)  );
407         
408         if (res != GLib.IOStatus.NORMAL) {
409             throw new SpawnError.WRITE_ERROR("Write failed");
410         }
411         //return ret.value;
412         return str.length;
413         
414     }
415     
416     /**
417      * read from pipe and call appropriate listerner and add to output or stderr string.
418      * @arg giochannel to read from.
419      * @returns none
420      */
421     private bool read(IOChannel ch) 
422     {
423         string prop = (ch == this.out_ch) ? "output" : "stderr";
424        // print("prop: " + prop);
425
426         
427         //print(JSON.stringify(ch, null,4));
428         while (true) {
429             string buffer;
430             size_t term_pos;
431             size_t len;
432             IOStatus status;
433             try {
434                 status = ch.read_line( out buffer,  out len,  out term_pos );
435             } catch (Error e) {
436                 //FIXme
437                 break; // ??
438                 
439             }
440
441             // print('status: '  +JSON.stringify(status));
442             // print(JSON.stringify(x));
443              switch(status) {
444                 case GLib.IOStatus.NORMAL:
445                 
446                     //write(fn, x.str);
447                     
448                     //if (this.listeners[prop]) {
449                     //    this.listeners[prop].call(this, x.str_return);
450                     //}
451                     if (ch == this.out_ch) {
452                         this.output += buffer;
453                         this.cfg.output(  buffer);                  
454                     } else {
455                         this.stderr += buffer;
456                     }
457                     //_this[prop] += x.str_return;
458                     if (this.cfg.debug) {
459                         stdout.printf("%s : %s", prop , buffer);
460                     }
461                     if (this.cfg.async) {
462                          
463                         if ( Gtk.events_pending()) {
464                              Gtk.main_iteration();
465                         }
466                          
467                     }
468                     
469                     //this.ctx.iteration(true);
470                    continue;
471                 case GLib.IOStatus.AGAIN:
472                     //print("Should be called again.. waiting for more data..");
473                             return true;
474                     //break;
475                 case GLib.IOStatus.ERROR:    
476                 case GLib.IOStatus.EOF:
477                             return false;
478                     //break;
479                 
480             }
481             break;
482         }
483        
484         //print("RETURNING");
485          return false; // allow it to be called again..
486     }
487     
488 }
489   /*
490 // test
491 try { 
492     Seed.print(run({
493         args: ['ls', '/tmp'],
494         debug : true
495     }));
496 } catch (e) { print(JSON.stringify(e)); }
497  
498 var secs = (new Date()).getSeconds() 
499
500 try {      
501 Seed.print(run({
502     args: ['/bin/touch', '/tmp/spawntest-' + secs ],
503     debug : true
504 }));
505 } catch (e) { print( 'Error: ' + JSON.stringify(e)); }
506
507  
508  */
509