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