Implement // and quote.
[goaljobs.git] / goaljobs.ml
1 (* goaljobs
2  * Copyright (C) 2013 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 open Unix
20 open Printf
21
22 open Goaljobs_config
23
24 let (//) = Filename.concat
25 let quote = Filename.quote
26
27 type goal_result_t = Goal_OK | Goal_failed of string
28 exception Goal_result of goal_result_t
29
30 let goal_failed msg = raise (Goal_result (Goal_failed msg))
31
32 let target v =
33   if v then raise (Goal_result Goal_OK)
34 let target_all vs = target (List.fold_left (&&) true vs)
35 let target_exists vs = target (List.fold_left (||) false vs)
36 let require () = ()
37
38 let file_exists = Sys.file_exists
39
40 let file_newer_than f1 f2 =
41   let stat f =
42     try Some (stat f)
43     with
44     | Unix_error (ENOENT, _, _) -> None
45     | Unix_error (err, _, _) ->
46       let msg = sprintf "file_newer_than: %s: %s" f (error_message err) in
47       goal_failed msg
48   in
49   let s1 = stat f1 and s2 = stat f2 in
50   match s1 with
51   | None -> false
52   | Some s1 ->
53     match s2 with
54     | None ->
55       let msg = sprintf "file_newer_than: %s: file does not exist" f2 in
56       goal_failed msg
57     | Some s2 ->
58       s1.st_mtime >= s2.st_mtime
59
60 let more_recent objs srcs =
61   if not (List.for_all file_exists objs) then false
62   else (
63     List.for_all (
64       fun obj -> List.for_all (file_newer_than obj) srcs
65     ) objs
66   )
67
68 let url_exists url =
69   (* http://stackoverflow.com/questions/12199059/how-to-check-if-an-url-exists-with-the-shell-and-probably-curl *)
70   let cmd =
71     sprintf "curl --output /dev/null --silent --head --fail %s" (quote url) in
72   match Sys.command cmd with
73   | 0 -> true
74   | 1 -> false
75   | r ->
76     let msg = sprintf "curl error testing '%s' (exit code %d)" url r in
77     goal_failed msg
78
79 let file_contains_string filename str =
80   let cmd = sprintf "grep -q %s %s" (quote str) (quote filename) in
81   match Sys.command cmd with
82   | 0 -> true
83   | 1 -> false
84   | r ->
85     let msg = sprintf "grep error testing for '%s' in '%s' (exit code %d)"
86       str filename r in
87     goal_failed msg
88
89 let url_contains_string url str =
90   let tmp = Filename.temp_file "goaljobsurl" "" in
91   let cmd =
92     sprintf "curl --output %s --silent --fail %s" (quote tmp) (quote url) in
93   (match Sys.command cmd with
94   | 0 -> ()
95   | 1 ->
96     let msg = sprintf "curl failed to download URL '%s'" url in
97     goal_failed msg
98   | r ->
99     let msg = sprintf "curl error testing '%s' (exit code %d)" url r in
100     goal_failed msg
101   );
102   let r = file_contains_string tmp str in
103   unlink tmp;
104   r
105
106
107 let sh fs =
108   let do_sh cmd =
109     let cmd = "set -e\nset -x\n\n" ^ cmd in
110     let r = Sys.command cmd in
111     if r <> 0 then (
112       let msg = sprintf "external command failed with code %d" r in
113       goal_failed msg
114     )
115   in
116   ksprintf do_sh fs
117
118 let do_shlines cmd =
119   let cmd = "set -e\nset -x\n\n" ^ cmd in
120   let chan = open_process_in cmd in
121   let lines = ref [] in
122   let rec loop () =
123     let line = input_line chan in
124     lines := line :: !lines;
125     loop ()
126   in
127   (try loop () with End_of_file -> ());
128   let r = close_process_in chan in
129   match r with
130   | WEXITED 0 -> List.rev !lines
131   | WEXITED i ->
132     let msg = sprintf "external command failed with code %d" i in
133     goal_failed msg
134   | WSIGNALED i ->
135     let msg = sprintf "external command was killed by signal %d" i in
136     goal_failed msg
137   | WSTOPPED i ->
138     let msg = sprintf "external command was stopped by signal %d" i in
139     goal_failed msg
140 let shlines fs = ksprintf do_shlines fs
141
142 let do_shout cmd =
143   let lines = do_shlines cmd in
144   String.concat "\n" lines
145 let shout fs = ksprintf do_shout fs
146
147 (*
148 val shell : string ref
149 *)
150
151 (*
152 val replace_substring : string -> string -> string -> string
153 *)
154
155 let change_file_extension ext filename =
156   let i =
157     try String.rindex filename '.'
158     with Not_found -> String.length filename in
159   String.sub filename 0 i ^ "." ^ ext
160
161 (*
162 val filter_file_extension : string -> string list -> string
163 *)
164
165 (* XXX The Memory is not actually persistent yet. *)
166 let memory = Hashtbl.create 13
167
168 let memory_exists = Hashtbl.mem memory
169 let memory_set = Hashtbl.replace memory
170 let memory_get k = try Some (Hashtbl.find memory k) with Not_found -> None
171 let memory_delete = Hashtbl.remove memory
172
173 let published_goals = ref []
174 let publish name fn = published_goals := (name, fn) :: !published_goals
175 let get_goal name =
176   try Some (List.assoc name !published_goals) with Not_found -> None
177
178 let goal_file_exists filename =
179   if not (file_exists filename) then (
180     let msg = sprintf "file '%s' required but not found" filename in
181     goal_failed msg
182   )
183 let goal_file_newer_than f1 f2 =
184   if not (file_newer_than f1 f2) then (
185     let msg = sprintf "file %s is required to be newer than %s" f1 f2 in
186     goal_failed msg
187   )
188 let goal_more_recent objs srcs =
189   if not (more_recent objs srcs) then (
190     let msg = sprintf "object(s) %s are required to be newer than source(s) %s"
191       (String.concat " " objs) (String.concat " " srcs) in
192     goal_failed msg
193   )
194 let goal_url_exists url =
195   if not (url_exists url) then (
196     let msg = sprintf "url_exists: URL '%s' required but does not exist" url in
197     goal_failed msg
198   )
199 let goal_file_contains_string filename str =
200   if not (file_contains_string filename str) then (
201     let msg = sprintf "file_contains_string: file '%s' is required to contain string '%s'" filename str in
202     goal_failed msg
203   )
204 let goal_url_contains_string url str =
205   if not (url_contains_string url str) then (
206     let msg = sprintf "url_contains_string: URL '%s' is required to contain string '%s'" url str in
207     goal_failed msg
208   )
209 let goal_memory_exists k =
210   if not (memory_exists k) then (
211     let msg = sprintf "memory_exists: key '%s' required but does not exist" k in
212     goal_failed msg
213   )
214
215 (* Run the program. *)
216 let init () =
217   let prog = Sys.executable_name in
218   let prog = Filename.basename prog in
219
220   let args = ref [] in
221
222   let display_version () =
223     printf "%s %s\n" package_name package_version;
224     exit 0
225   in
226
227   let list_goals () =
228     let names = !published_goals in
229     let names = List.map fst names in
230     let names = List.sort compare names in
231     List.iter print_endline names
232   in
233
234   let argspec = Arg.align [
235     "--goals", Arg.Unit list_goals, " List all goals";
236     "-l", Arg.Unit list_goals, " List all goals";
237     "-V", Arg.Unit display_version, " Display version number and exit";
238     "--version", Arg.Unit display_version, " Display version number and exit";
239   ] in
240   let anon_fun str = args := str :: !args in
241   let usage_msg = sprintf "\
242 %s: a script generated by goaljobs
243
244 List all goals:                %s -l
245 Run a single goal like this:   %s <name-of-goal> [<goal-args ...>]
246
247 For more information see the goaljobs(1) man page.
248
249 Options:
250 " prog prog prog in
251
252   Arg.parse argspec anon_fun usage_msg;
253
254   let args = List.rev !args in
255
256   (* Was a goal named on the command line? *)
257   match args with
258   | name :: args ->
259     (match get_goal name with
260     | Some fn -> fn args
261     | None ->
262       eprintf "error: no goal called '%s' was found.\n" name;
263       eprintf "Use %s -l to list all published goals in this script.\n" name;
264       exit 1
265     )
266   | [] ->
267     (* Does a published 'all' goal exist? *)
268     match get_goal "all" with
269     | Some fn -> fn []
270     | None ->
271       (* No published 'all' goal.  This is only a warning, because
272        * other top-level code may exist in the script.
273        *)
274       eprintf "warning: no 'all' goal found.\n"