package cascade

  1. Overview
  2. Docs

Source file browser.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
let ( // ) = Filename.concat

let getenv name =
  match Sys.getenv_opt name with Some "" | None -> None | Some v -> Some v

(* Windows has no execute bit: a program is a file with an extension [PATHEXT]
   lists, and a command is found on [PATH] under each of those extensions. *)
let program_extensions () =
  Option.value ~default:".COM;.EXE;.BAT;.CMD" (getenv "PATHEXT")
  |> String.split_on_char ';'
  |> List.filter_map (function
    | "" -> None
    | e -> Some (String.lowercase_ascii e))

let program_extension path =
  List.mem
    (String.lowercase_ascii (Filename.extension path))
    (program_extensions ())

let executable path =
  (try Sys.file_exists path && not (Sys.is_directory path)
   with Sys_error _ -> false)
  &&
  if Sys.win32 then program_extension path
  else
    try
      Unix.access path [ Unix.X_OK ];
      true
    with Unix.Unix_error _ | Sys_error _ -> false

let on_path name =
  let dirs =
    String.split_on_char
      (if Sys.win32 then ';' else ':')
      (Option.value ~default:"" (getenv "PATH"))
  in
  let names =
    if Sys.win32 then
      name
      :: List.map
           (fun e -> String.concat "" [ name; e ])
           (program_extensions ())
    else [ name ]
  in
  List.find_map
    (fun d ->
      if d = "" then None
      else
        List.find_map
          (fun n ->
            let p = d // n in
            if executable p then Some p else None)
          names)
    dirs

(* The name a program answers to: on Windows, its file name less the extension
   that makes it one. *)
let program_name file =
  if Sys.win32 && program_extension file then Filename.remove_extension file
  else file

(* The browser caches keep one directory per version, so the largest path is the
   newest build. *)
let rec search_tree root names depth acc =
  if depth <= 0 then acc
  else
    match Sys.readdir root with
    | exception Sys_error _ -> acc
    | entries ->
        Array.fold_left
          (fun acc entry ->
            let p = root // entry in
            if try Sys.is_directory p with Sys_error _ -> false then
              search_tree p names (depth - 1) acc
            else if List.mem (program_name entry) names && executable p then
              p :: acc
            else acc)
          acc entries

(* A browser installed for the machine or the user rather than cached by a test
   tool: Chrome and Chromium on Windows, then the macOS bundle. *)
let installed_chrome () =
  let windows =
    List.concat_map
      (fun var ->
        match getenv var with
        | None -> []
        | Some root ->
            [
              root // "Google" // "Chrome" // "Application";
              root // "Chromium" // "Application";
            ])
      [ "PROGRAMFILES"; "PROGRAMFILES(X86)"; "LOCALAPPDATA" ]
  in
  match
    List.find_map
      (fun dir ->
        match search_tree dir [ "chrome" ] 1 [] with
        | [] -> None
        | c :: _ -> Some c)
      windows
  with
  | Some c -> Some c
  | None ->
      let app =
        "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
      in
      if executable app then Some app else None

let chrome_binary () =
  match getenv "CHROME" with
  | Some c when executable c -> Some c
  | Some _ | None -> (
      let names =
        [
          "chromium";
          "chromium-browser";
          "google-chrome";
          "google-chrome-stable";
        ]
      in
      match List.find_map on_path names with
      | Some c -> Some c
      | None -> (
          (* Windows has no HOME: puppeteer's cache is under USERPROFILE and
             playwright's under LOCALAPPDATA. *)
          let home =
            match getenv "HOME" with
            | Some h -> Some h
            | None -> getenv "USERPROFILE"
          in
          let under var path =
            Option.map (fun root -> List.fold_left ( // ) root path) var
          in
          let caches =
            List.filter_map Fun.id
              [
                under home [ ".cache"; "puppeteer" ];
                under home [ "Library"; "Caches"; "ms-playwright" ];
                under home [ ".cache"; "ms-playwright" ];
                under (getenv "LOCALAPPDATA") [ "ms-playwright" ];
              ]
          in
          let binaries =
            [
              "chrome-headless-shell";
              "headless_shell";
              "Chromium";
              "Google Chrome for Testing";
            ]
          in
          let found =
            List.concat_map (fun c -> search_tree c binaries 6 []) caches
          in
          match List.sort compare found with
          | [] -> installed_chrome ()
          | l -> Some (List.nth l (List.length l - 1))))

let node_binary () =
  match getenv "NODE" with
  | Some n when executable n -> Some n
  | Some _ | None -> on_path "node"

let read_lines ic =
  let rec loop acc =
    match input_line ic with
    | line -> loop (line :: acc)
    | exception End_of_file -> List.rev acc
  in
  loop []

let run ?(env = []) ?stderr prog args =
  let set binding (name, _) =
    String.starts_with ~prefix:(String.concat "" [ name; "=" ]) binding
  in
  let inherited =
    List.filter
      (fun binding -> not (List.exists (set binding) env))
      (Array.to_list (Unix.environment ()))
  in
  let environment =
    Array.of_list
      (List.map (fun (name, v) -> String.concat "" [ name; "="; v ]) env
      @ inherited)
  in
  (* Where the spawn forks before it execs (OpenBSD), a missing program is a
     child exiting 127, not an error: settle that here, before any spawn. *)
  if (not (String.equal (Filename.basename prog) prog)) && not (executable prog)
  then raise (Unix.Unix_error (Unix.ENOENT, "create_process", prog));
  let null = Unix.openfile Filename.null [ Unix.O_RDWR; Unix.O_CLOEXEC ] 0 in
  let err =
    match stderr with
    | None -> null
    | Some file ->
        Unix.openfile file
          [ Unix.O_WRONLY; Unix.O_CREAT; Unix.O_TRUNC; Unix.O_CLOEXEC ]
          0o644
  in
  let out, child_out = Unix.pipe ~cloexec:true () in
  let spawn () =
    Unix.create_process_env prog
      (Array.of_list (prog :: args))
      environment null child_out err
  in
  let close_child_ends () =
    Unix.close child_out;
    if Option.is_some stderr then Unix.close err;
    Unix.close null
  in
  match Fun.protect ~finally:close_child_ends spawn with
  | exception e ->
      Unix.close out;
      raise e
  | pid ->
      let ic = Unix.in_channel_of_descr out in
      set_binary_mode_in ic false;
      let lines =
        Fun.protect ~finally:(fun () -> close_in ic) (fun () -> read_lines ic)
      in
      let _, status = Unix.waitpid [] pid in
      (lines, status)

let drive ~node ~chrome ~stderr script args =
  match run ~env:[ ("CHROME", chrome) ] ~stderr node (script :: args) with
  | exception Unix.Unix_error (e, _, _) ->
      Error
        (String.concat ""
           [ "the browser driver did not start: "; Unix.error_message e ])
  | lines, Unix.WEXITED 0 -> Ok lines
  | _, (Unix.WEXITED _ | Unix.WSIGNALED _ | Unix.WSTOPPED _) ->
      let text =
        try In_channel.with_open_bin stderr In_channel.input_all
        with Sys_error _ -> ""
      in
      Error
        (String.concat "" [ "the browser driver failed:\n"; String.trim text ])

let chrome_version chrome =
  (* A binary that cannot be started prints no banner. *)
  let lines =
    match run chrome [ "--version" ] with
    | exception Unix.Unix_error _ -> []
    | lines, _ -> lines
  in
  let leading_int s =
    let n = String.length s in
    let rec upto i =
      if i < n && s.[i] >= '0' && s.[i] <= '9' then upto (i + 1) else i
    in
    let stop = upto 0 in
    if stop = 0 then None else int_of_string_opt (String.sub s 0 stop)
  in
  let of_word w =
    match String.split_on_char '.' w with
    | major :: minor :: _ -> (
        match (leading_int major, leading_int minor) with
        | Some a, Some b -> Some (a, b)
        | _ -> None)
    | _ -> None
  in
  List.fold_left
    (fun found line ->
      match found with
      | Some _ -> found
      | None ->
          List.fold_left
            (fun found word ->
              match found with Some _ -> found | None -> of_word word)
            None
            (String.split_on_char ' ' line))
    None lines

let skip harness reason =
  print_endline (String.concat "" [ "SKIP: "; harness; " ("; reason; ")" ]);
  exit 0

(* Setting CASCADE_NO_BROWSER silences a gate, and a gate that did not run is
   not a pass: only the value below, which names the run for what it is, exits
   0. A machine with no browser still skips, because there is nothing there to
   silence. *)
let acknowledged = "unchecked"

let suppressed harness =
  match getenv "CASCADE_NO_BROWSER" with
  | None -> ()
  | Some v when String.equal v acknowledged ->
      print_endline
        (String.concat ""
           [
             "SKIP: ";
             harness;
             " (CASCADE_NO_BROWSER=";
             acknowledged;
             ", so this run checks nothing)";
           ]);
      exit 0
  | Some v ->
      prerr_endline
        (String.concat ""
           [
             "FAIL: ";
             harness;
             " is suppressed by CASCADE_NO_BROWSER=";
             v;
             "; a gate that did not run is not a pass. Set CASCADE_NO_BROWSER=";
             acknowledged;
             " to exit 0 and say so.";
           ]);
      exit 1