Implement cleanup functions, including 'mailto'.
[whenjobs.git] / lib / whentools.ml
index 979124f..cac698a 100644 (file)
  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  *)
 
-open Big_int
 open Whenexpr
 
+open Big_int
+open Printf
+
 let set_variable name value =
   check_valid_variable_name name;
   Whenfile.set_variable name (T_string value)
@@ -36,3 +38,30 @@ let set_variable_string = set_variable
 let set_variable_float name value =
   check_valid_variable_name name;
   Whenfile.set_variable name (T_float value)
+
+type result = Whenexpr.result
+
+let mailto ?(only_on_failure = false) ?from email result =
+  if result.res_code <> 0 || not only_on_failure then (
+    let subject =
+      sprintf "%s: %s (return code %d)"
+        result.res_job_name
+        (if result.res_code = 0 then "successful" else "FAILED")
+        result.res_code in
+
+    let cmd = sprintf "%s -s %s -a %s"
+      Config.mailx
+      (Filename.quote subject)
+      (Filename.quote result.res_output) in
+
+    let cmd =
+      match from with
+      | None -> cmd
+      | Some from -> sprintf "%s -r %s" cmd from in
+
+    let cmd =
+      sprintf "%s %s </dev/null" cmd (Filename.quote email) in
+
+    if Sys.command cmd <> 0 then
+      failwith "Whentools.mailto: mailx command failed";
+  )