Add commands to list, cancel, start jobs.
[whenjobs.git] / lib / pa_when.ml
1 (* whenjobs
2  * Copyright (C) 2012 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  *)
18
19 (* For general information about camlp4, see:
20  * http://brion.inria.fr/gallium/index.php/Camlp4
21  *
22  * For information about quotations, see:
23  * http://brion.inria.fr/gallium/index.php/Quotation
24  *)
25
26 open Printf
27
28 open Camlp4.PreCast
29 open Syntax
30 open Ast
31
32 let unique = let i = ref 0 in fun () -> incr i; !i
33
34 let unique_job_name () = sprintf "job$%d" (unique ())
35
36 let rec find s sub =
37   let len = String.length s in
38   let sublen = String.length sub in
39   let rec loop i =
40     if i <= len-sublen then (
41       let rec loop2 j =
42         if j < sublen then (
43           if s.[i+j] = sub.[j] then loop2 (j+1)
44           else -1
45         ) else
46           i (* found *)
47       in
48       let r = loop2 0 in
49       if r = -1 then loop (i+1) else r
50     ) else
51       -1 (* not found *)
52   in
53   loop 0
54
55 let rec replace_str s s1 s2 =
56   let len = String.length s in
57   let sublen = String.length s1 in
58   let i = find s s1 in
59   if i = -1 then s
60   else (
61     let s' = String.sub s 0 i in
62     let s'' = String.sub s (i+sublen) (len-i-sublen) in
63     s' ^ s2 ^ replace_str s'' s1 s2
64   )
65
66 (* Convert a _loc to an AST. *)
67 let expr_of_loc _loc loc =
68   let file_name,
69     start_line, start_bol, start_off,
70     stop_line, stop_bol, stop_off,
71     ghost = Loc.to_tuple loc in
72   <:expr< Camlp4.PreCast.Loc.of_tuple
73     ($str:file_name$,
74      $`int:start_line$, $`int:start_bol$, $`int:start_off$,
75      $`int:stop_line$, $`int:stop_bol$, $`int:stop_off$,
76      $`bool:ghost$) >>
77
78 (* Convert 'expr option' to an expression that contains the option inside. *)
79 let expr_of_option _loc = function
80   | None -> <:expr< None >>
81   | Some e -> <:expr< Some $e$ >>
82
83 (* "Lift" an expression, turning it from an expression into an OCaml
84  * abstract syntax tree in the output.  This is pretty obscure.
85  * http://caml.inria.fr/pub/ml-archives/caml-list/2008/09/591f7c4a8df9295d675a5adcb6802748.en.html
86  *)
87 module M = Ast.Meta.Make (Ast.Meta.MetaGhostLoc)
88 let lift_expr = M.Expr.meta_expr
89
90 (* Handle a top level statement. *)
91 let rec call_stmt name cleanup (_loc, stmt, sh) =
92   let name =
93     match name with
94     | None -> let name = unique_job_name () in <:expr< $str:name$ >>
95     | Some name -> name in
96   let cleanup = expr_of_option _loc cleanup in
97   match stmt with
98   | `When e -> when_stmt _loc name cleanup e sh
99   | `Every p -> every_stmt _loc name cleanup p sh
100
101 (* Handle a top level "when" statement.
102  * e -> when expression
103  * sh -> the shell script to run
104  * Returns a top level statement (str_item) which when executed just
105  * adds the statement to a global list.
106  *)
107 and when_stmt _loc name cleanup e sh =
108   let loc = expr_of_loc _loc _loc in
109   let e = lift_expr _loc e in
110   <:str_item<
111     open Camlp4.PreCast
112     Whenfile.add_when_job $loc$ $name$ $cleanup$ $e$ $sh$
113   >>
114
115 (* Handle a top level "every" statement. *)
116 and every_stmt _loc name cleanup period sh =
117   let loc = expr_of_loc _loc _loc in
118   <:str_item<
119     open Camlp4.PreCast
120     Whenfile.add_every_job $loc$ $name$ $cleanup$ $period$ $sh$
121   >>
122
123 let () =
124   (* Quotation expander for shell script. *)
125   let sh_quotation_expander _loc _ sh =
126     let loc = expr_of_loc _loc _loc in
127
128     (* Convert ">\>" to ">>" in code. *)
129     let sh = replace_str sh ">\\>" ">>" in
130
131     <:expr< { Whenexpr.sh_loc = $loc$;
132               sh_script = $str:sh$ } >>
133   in
134   Quotation.add "sh" Quotation.DynAst.expr_tag sh_quotation_expander;
135
136   (* Default quotation expander (<< .. >>) should be shell script ("sh"). *)
137   Quotation.default := "sh"
138
139 (* For period expressions "<NN> (secs|mins|hours|...)" we cannot use
140  * the ordinary camlp4 parser since it only looks ahead by 1 symbol, so
141  * it gets "stuck" on the integer.  Write a custom parser instead.
142  *
143  * Note the EXTEND macro implicitly reserves KEYWORDs.
144  *)
145 let period_parser =
146   Gram.Entry.of_parser "period"
147     (fun stream ->
148       match Stream.peek stream with
149       | Some (INT (_, i), info) ->
150         let i = int_of_string i in
151         let _loc = Gram.token_location info in
152         Stream.junk stream;
153         (match Stream.next stream with
154         | KEYWORD ("sec"|"secs"|"second"|"seconds"), _ ->
155           <:expr< Whenexpr.Every_seconds $`int:i$ >>
156         | KEYWORD ("min"|"mins"|"minute"|"minutes"), _ ->
157           let i = 60 * i in
158           <:expr< Whenexpr.Every_seconds $`int:i$ >>
159         | KEYWORD ("hour"|"hours"), _ ->
160           let i = 3600 * i in
161           <:expr< Whenexpr.Every_seconds $`int:i$ >>
162         | KEYWORD ("day"|"days"), _ ->
163           <:expr< Whenexpr.Every_days $`int:i$ >>
164         | KEYWORD ("week"|"weeks"), _ ->
165           let i = 7 * i in
166           <:expr< Whenexpr.Every_days $`int:i$ >>
167         | KEYWORD ("month"|"months"), _ ->
168           <:expr< Whenexpr.Every_months $`int:i$ >>
169         | KEYWORD ("year"|"years"), _ ->
170           <:expr< Whenexpr.Every_years $`int:i$ >>
171         | KEYWORD ("decade"|"decades"), _ ->
172           let i = 10 * i in
173           <:expr< Whenexpr.Every_years $`int:i$ >>
174         | KEYWORD ("century"|"centuries"|"centurys"), _ ->
175           let i = 100 * i in
176           <:expr< Whenexpr.Every_years $`int:i$ >>
177         | KEYWORD ("millenium"|"millenia"|"milleniums"), _ ->
178           let i = 1000 * i in
179           <:expr< Whenexpr.Every_years $`int:i$ >>
180         | (KEYWORD s | LIDENT s), _ ->
181           eprintf "period: failed to parse %d %s\n%!" i s;
182           raise Stream.Failure
183         | _ ->
184           raise Stream.Failure
185         )
186       | _ -> raise Stream.Failure
187     )
188 ;;
189
190 EXTEND Gram
191   GLOBAL: str_item;
192
193   (* A period expression (used in "every"). *)
194   periodexpr: [
195     [ ["sec"|"secs"|"second"|"seconds"] ->
196       <:expr< Whenexpr.Every_seconds 1 >> ]
197   | [ ["min"|"mins"|"minute"|"minutes"] ->
198       <:expr< Whenexpr.Every_seconds 60 >> ]
199   | [ ["hour"|"hours"] -> <:expr< Whenexpr.Every_seconds 3600 >> ]
200   | [ ["day"|"days"] -> <:expr< Whenexpr.Every_days 1 >> ]
201   | [ ["week"|"weeks"] -> <:expr< Whenexpr.Every_days 7 >> ]
202   | [ ["month"|"months"] -> <:expr< Whenexpr.Every_months 1 >> ]
203   | [ ["year"|"years"] -> <:expr< Whenexpr.Every_years 1 >> ]
204   | [ ["decade"|"decades"] -> <:expr< Whenexpr.Every_years 10 >> ]
205   | [ ["century"|"centuries"|"centurys"] ->
206       <:expr< Whenexpr.Every_years 100 >> ]
207   | [ ["millenium"|"millenia"|"milleniums"] ->
208       <:expr< Whenexpr.Every_years 1000 >> ]
209   | [ e = period_parser -> e ]
210   ];
211
212   (* Cleanup function. *)
213   cleanup: [
214     [ "cleanup"; f = expr -> f ]
215   ];
216
217   (* Top level statements. *)
218   statement: [
219     [ "when"; e = expr; ":"; sh = expr ->
220       (_loc, `When e, sh) ]
221   | [ "every"; p = periodexpr; ":"; sh = expr ->
222       (_loc, `Every p, sh) ]
223   ];
224
225   (* "str_item" is a top level statement in an OCaml program. *)
226   str_item: LEVEL "top" [
227     [ s = statement -> call_stmt None None s ]
228   | [ "job"; name = expr;
229       cleanup = OPT cleanup;
230       s = statement ->
231         call_stmt (Some name) cleanup s ]
232   ];
233
234 END