text
stringlengths
12
786k
module Parser = struct let header_size = 16 let xenstore_payload_max = 4096 let allow_oversize_packets = ref true type state = | Unknown_operation of int32 | Parser_failed of string | Need_more_data of int | Packet of t type parse = | ReadingHeader of int * string | ReadingBody of t | Finished of state let start ( ) = ReadingHeader ( 0 , String . make header_size ' \ 000 ' ) let state = function | ReadingHeader ( got_already , _ ) -> Need_more_data ( header_size - got_already ) | ReadingBody pkt -> Need_more_data ( pkt . len - ( Buffer . length pkt . data ) ) | Finished r -> r let parse_header str = let header = Cstruct . create sizeof_header in Cstruct . blit_from_string str 0 header 0 sizeof_header ; let ty = get_header_ty header in let rid = get_header_rid header in let tid = get_header_tid header in let len = get_header_len header in let len = Int32 . to_int len in let len = if ! allow_oversize_packets then len else max 0 ( min xenstore_payload_max len ) in begin match Op . of_int32 ty with | Some ty -> let t = { tid = tid ; rid = rid ; ty = ty ; len = len ; data = Buffer . create len ; } in if len = 0 then Finished ( Packet t ) else ReadingBody t | None -> Finished ( Unknown_operation ty ) end let input state bytes = match state with | ReadingHeader ( got_already , str ) -> String . blit bytes 0 str got_already ( String . length bytes ) ; let got_already = got_already + ( String . length bytes ) in if got_already < header_size then ReadingHeader ( got_already , str ) else parse_header str | ReadingBody x -> Buffer . add_string x . data bytes ; let needed = x . len - ( Buffer . length x . data ) in if needed > 0 then ReadingBody x else Finished ( Packet x ) | Finished f -> Finished f end
module type IO = sig type ' a t val return : ' a -> ' a t val ( >>= ) : ' a t -> ( ' a -> ' b t ) -> ' b t type channel val read : channel -> string -> int -> int -> int t val write : channel -> string -> int -> int -> unit t end
type ( ' a , ' b ) result =
module PacketStream = functor ( IO : IO ) -> struct let ( >>= ) = IO . ( >>= ) let return = IO . return type stream = { channel : IO . channel ; mutable incoming_pkt : Parser . parse ; } let make t = { channel = t ; incoming_pkt = Parser . start ( ) ; } let rec recv t = let open Parser in match Parser . state t . incoming_pkt with | Packet pkt -> t . incoming_pkt <- start ( ) ; return ( Ok pkt ) | Need_more_data x -> let buf = String . make x ' \ 000 ' in IO . read t . channel buf 0 x >>= ( function | 0 -> return ( Exception EOF ) | n -> let fragment = String . sub buf 0 n in | Unknown_operation x -> return ( Exception ( Unknown_xenstore_operation x ) ) | Parser_failed x -> return ( Exception ( Response_parser_failed x ) ) let send t request = let req = to_string request in end
let is_valid_path path = let result = ref true in let bad = " " // in for offset = 0 to String . length path - ( String . length bad ) do if String . sub path offset ( String . length bad ) = bad then result := false done ; if path <> " " / && path <> " " && path . [ String . length path - 1 ] = ' ' / then result := false ; ! result
let is_valid_watch_path path = ( path <> " " && path . [ 0 ] = ' ' ) @ || ( is_valid_path path )
module Token = struct type t = string let to_user_string x = Scanf . sscanf x " % d :% s " ( fun _ x -> x ) let to_debug_string x = x let of_string x = x let to_string x = x end
let data_concat ls = ( String . concat " \ 000 " ls ) ^ " \ 000 "
let create tid rid ty data = let len = String . length data in let b = Buffer . create len in Buffer . add_string b data ; { tid = tid ; rid = rid ; ty = ty ; len = len ; data = b ; }
let set_data pkt ( data : string ) = let len = String . length data in let b = Buffer . create len in Buffer . add_string b data ; { pkt with len = len ; data = b }
module Response = struct type payload = | Read of string | Directory of string list | Getperms of ACL . t | Getdomainpath of string | Transaction_start of int32 | Write | Mkdir | Rm | Setperms | Watch | Unwatch | Transaction_end | Debug of string list | Introduce | Resume | Release | Set_target | Restrict | Isintroduced of bool | Error of string | Watchevent of string * string let prettyprint_payload = let open Printf in function | Read x -> sprintf " Read % s " x | Directory xs -> sprintf " Directory [ % s ] " ( String . concat " ; " xs ) | Getperms acl -> sprintf " Getperms % s " ( ACL . to_string acl ) | Getdomainpath p -> sprintf " Getdomainpath % s " p | Transaction_start x -> sprintf " Transaction_start % ld " x | Write -> " Write " | Mkdir -> " Mkdir " | Rm -> " Rm " | Setperms -> " Setperms " | Watch -> " Watch " | Unwatch -> " Unwatch " | Transaction_end -> " Transaction_end " | Debug xs -> sprintf " Debug [ % s ] " ( String . concat " ; " xs ) | Introduce -> " Introduce " | Resume -> " Resume " | Release -> " Release " | Set_target -> " Set_target " | Restrict -> " Restrict " | Isintroduced x -> sprintf " Isintroduced % b " x | Error x -> sprintf " Error % s " x | Watchevent ( x , y ) -> sprintf " Watchevent % s % s " x y let ty_of_payload = function | Read _ -> Op . Read | Directory _ -> Op . Directory | Getperms perms -> Op . Getperms | Getdomainpath _ -> Op . Getdomainpath | Transaction_start _ -> Op . Transaction_start | Debug _ -> Op . Debug | Isintroduced _ -> Op . Isintroduced | Watchevent ( _ , _ ) -> Op . Watchevent | Error _ -> Op . Error | Write -> Op . Write | Mkdir -> Op . Mkdir | Rm -> Op . Rm | Setperms -> Op . Setperms | Watch -> Op . Watch | Unwatch -> Op . Unwatch | Transaction_end -> Op . Transaction_end | Introduce -> Op . Introduce | Resume -> Op . Resume | Release -> Op . Release | Set_target -> Op . Set_target | Restrict -> Op . Restrict let ok = " OK \ 000 " let data_of_payload = function | Read x -> x | Directory ls -> if ls = [ ] then " " else data_concat ls | Getperms perms -> data_concat [ ACL . to_string perms ] | Getdomainpath x -> data_concat [ x ] | Transaction_start tid -> data_concat [ Int32 . to_string tid ] | Debug items -> data_concat items | Isintroduced b -> data_concat [ if b then " T " else " F " ] | Watchevent ( path , token ) -> data_concat [ path ; token ] | Error x -> data_concat [ x ] | _ -> ok let print x tid rid = create tid rid ( ty_of_payload x ) ( data_of_payload x ) end
module Request = struct do done ; ! v end try ] create rid end
module Unmarshal = struct let some x = Some x let int_of_string_opt x = try Some ( int_of_string x ) with _ -> None let int32_of_string_opt x = try Some ( Int32 . of_string x ) with _ -> None let unit_of_string_opt x = if x = " " then Some ( ) else None let ok x = if x = " OK " then Some ( ) else None let string = some ++ get_data let list = some ++ split_string ' \ 000 ' ++ get_data let acl = ACL . of_string ++ get_data let int = int_of_string_opt ++ get_data let int32 = int32_of_string_opt ++ get_data let unit = unit_of_string_opt ++ get_data let ok = ok ++ get_data end
let response hint sent received f = match get_ty sent , get_ty received with | _ , Op . Error -> begin match get_data received with | " ENOENT " -> raise ( Enoent hint ) | " EAGAIN " -> raise Eagain | " EINVAL " -> raise Invalid | " EEXIST " -> raise Eexist | s -> raise ( Error s ) end | x , y when x = y -> begin match f received with | None -> raise ( Error ( Printf . sprintf " failed to parse response ( hint :% s ) ( payload :% s ) " hint ( get_data received ) ) ) | Some z -> z end | x , y -> raise ( Error ( Printf . sprintf " unexpected packet : expected % s ; got % s " ( Op . to_string x ) ( Op . to_string y ) ) )
let ( |> ) a b = b a
let ( ++ ) f g x = f ( g x )
let debug fmt = Logging . debug " xs_server " fmt
let error fmt = Logging . error " xs_server " fmt
let store = List . iter store
module type TRANSPORT = sig type ' a t = ' a Lwt . t val return : ' a -> ' a Lwt . t val ( >>= ) : ' a t -> ( ' a -> ' b Lwt . t ) -> ' b Lwt . t type server val listen : unit -> server Lwt . t type channel val read : channel -> string -> int -> int -> int Lwt . t val write : channel -> string -> int -> int -> unit Lwt . t val destroy : channel -> unit Lwt . t val address_of : channel -> Xs_protocol . address Lwt . t val namespace_of : channel -> ( module Namespace . IO ) option val accept_forever : server -> ( channel -> unit Lwt . t ) -> ' a Lwt . t end
module Server = functor ( T : TRANSPORT ) -> struct Lwt_list . iter_s ) try_lwt ) end
let ( |> ) a b = b a
let id x = x
let op_ids _ = let open Xs_protocol . Op in for i = 0 to 100 do let i ' = Int32 . of_int i in match of_int32 i ' with | None -> ( ) | Some x -> assert ( to_int32 x = i ' ) done
let example_acl = { owner = 5 ; other = READ ; acl = [ 2 , WRITE ; 3 , RDWR ] }
let acl_parser _ = let open Xs_protocol . ACL in let ts = [ { owner = 5 ; other = READ ; acl = [ 2 , WRITE ; 3 , RDWR ] } ; { owner = 1 ; other = WRITE ; acl = [ ] } ; ] in let ss = List . map to_string ts in let ts ' = List . map of_string ss in let printer = function | None -> " None " | Some x -> " Some " ^ to_string x in List . iter ( fun ( x , y ) -> assert_equal ~ msg " : acl " ~ printer x y ) ( List . combine ( List . map ( fun x -> Some x ) ts ) ts ' )
let test_packet_parser choose pkt ( ) = let open Xs_protocol in let p = ref ( Parser . start ( ) ) in let s = to_string pkt in let i = ref 0 in let finished = ref false in while not ! finished do match Parser . state ! p with done
let test _ = let t = return ( ) in Lwt_main . run t
type example_packet = { }
let make_example_request op payload tid wire_fmt = { }
let example_request_packets = " \ x01 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x05 \ x00 \ x00 \ x00 \ x13 \ x00 \ x00 \ x00 \ x2f \ x77 \ x68 \ x61 \ x74 \ x65 \ x76 \ x65 \ x72 \ x2f \ x77 \ x68 \ x65 \ x6e \ x65 \ x76 \ x65 \ x72 \ x00 " ; " \ x02 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x06 \ x00 \ x00 \ x00 \ x07 \ x00 \ x00 \ x00 \ x2f \ x61 \ x2f \ x62 \ x2f \ x63 \ x00 " ; " \ x03 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x07 \ x00 \ x00 \ x00 \ x05 \ x00 \ x00 \ x00 \ x2f \ x61 \ x2f \ x62 \ x00 " ; " \ x0d \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x02 \ x00 \ x00 \ x00 \ x2f \ x00 " ; " \ x0e \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x01 \ x00 \ x00 \ x00 \ x0b \ x00 \ x00 \ x00 \ x2f \ x00 \ x72 \ x35 \ x00 \ x77 \ x32 \ x00 \ x62 \ x33 \ x00 " ; " \ x0b \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x01 \ x00 \ x00 \ x00 \ x0a \ x00 \ x00 \ x00 \ x2f \ x6b \ x65 \ x79 \ x00 \ x76 \ x61 \ x6c \ x75 \ x65 " ; " \ x0c \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x04 \ x00 \ x00 \ x02 \ x00 \ x00 \ x00 \ x2f \ x00 " ; " \ x06 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x01 \ x00 \ x00 \ x00 \ x00 " ; " \ x07 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x01 \ x00 \ x00 \ x00 \ x02 \ x00 \ x00 \ x00 \ x54 \ x00 " ; " \ x08 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x06 \ x00 \ x00 \ x00 \ x34 \ x00 \ x35 \ x00 \ x31 \ x00 " ; " \ x09 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x02 \ x00 \ x00 \ x00 \ x32 \ x00 " ; " \ x12 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x02 \ x00 \ x00 \ x00 \ x33 \ x00 " ; " \ x0a \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x02 \ x00 \ x00 \ x00 \ x33 \ x00 " ; " \ x04 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x13 \ x00 \ x00 \ x00 \ x2f \ x66 \ x6f \ x6f \ x2f \ x62 \ x61 \ x72 \ x00 \ x73 \ x6f \ x6d \ x65 \ x74 \ x68 \ x69 \ x6e \ x67 \ x00 " ; " \ x05 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x16 \ x00 \ x00 \ x00 \ x2f \ x66 \ x6f \ x6f \ x2f \ x62 \ x61 \ x72 \ x00 \ x73 \ x6f \ x6d \ x65 \ x74 \ x68 \ x69 \ x6e \ x67 \ x6c \ x73 \ x65 \ x00 " ; " \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x0e \ x00 \ x00 \ x00 \ x61 \ x00 \ x62 \ x00 \ x73 \ x6f \ x6d \ x65 \ x74 \ x68 \ x69 \ x6e \ x67 \ x00 " ]
let make_example_response op response wire_fmt = }
let example_response_packets = " \ x02 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x06 \ x00 \ x00 \ x00 \ x09 \ x00 \ x00 \ x00 \ x74 \ x68 \ x65 \ x72 \ x65 \ x73 \ x75 \ x6c \ x74 " ; " \ x02 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x06 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 " ; " \ x03 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x07 \ x00 \ x00 \ x00 \ x06 \ x00 \ x00 \ x00 \ x72 \ x32 \ x00 \ x6e \ x34 \ x00 " ; " \ x0a \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x10 \ x00 \ x00 \ x00 \ x2f \ x6c \ x6f \ x63 \ x61 \ x6c \ x2f \ x64 \ x6f \ x6d \ x61 \ x69 \ x6e \ x2f \ x34 \ x00 " ; " \ x06 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x02 \ x00 \ x00 \ x00 \ x33 \ x00 " ; " \ x01 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x05 \ x00 \ x00 \ x00 \ x15 \ x00 \ x00 \ x00 \ x61 \ x00 \ x62 \ x00 \ x63 \ x00 \ x61 \ x73 \ x65 \ x61 \ x73 \ x79 \ x61 \ x73 \ x00 \ x31 \ x00 \ x32 \ x00 \ x33 \ x00 " ; " \ x0b \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x01 \ x00 \ x00 \ x00 \ x03 \ x00 \ x00 \ x00 \ x4f \ x4b \ x00 " ; " \ x0c \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x04 \ x00 \ x00 \ x03 \ x00 \ x00 \ x00 \ x4f \ x4b \ x00 " ; " \ x0d \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x03 \ x00 \ x00 \ x00 \ x4f \ x4b \ x00 " ; " \ x0e \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x01 \ x00 \ x00 \ x00 \ x03 \ x00 \ x00 \ x00 \ x4f \ x4b \ x00 " ; " \ x04 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x03 \ x00 \ x00 \ x00 \ x4f \ x4b \ x00 " ; " \ x05 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x03 \ x00 \ x00 \ x00 \ x4f \ x4b \ x00 " ; " \ x07 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x01 \ x00 \ x00 \ x00 \ x03 \ x00 \ x00 \ x00 \ x4f \ x4b \ x00 " ; { " \ x10 \ x00 \ x00 \ x00 \ x10 \ x00 \ x00 \ x00 \ x02 \ x00 \ x00 \ x00 \ x14 \ x00 \ x00 \ x00 \ x77 \ x68 \ x61 \ x74 \ x79 \ x6f \ x75 \ x74 \ x61 \ x6c \ x6b \ x69 \ x6e \ x67 \ x61 \ x62 \ x6f \ x75 \ x74 \ x00 " } ]
let example_packets = example_request_packets @ example_response_packets
let rec ints first last =
let hexstring x = " " " ; \ " " " ; \ ] )
let _ = let verbose = ref false in Arg . parse [ " - verbose " , Arg . Unit ( fun _ -> verbose := true ) , " Run in verbose mode " ; ] ( fun x -> Printf . fprintf stderr " Ignoring argument : % s " x ) " Test xenstore protocol code " ; let packet_parsing choose = let f = test_packet_parser choose in " packet_parsing " >::: let packet_printing = let suite = " xenstore " >::: [ " op_ids " >:: op_ids ; " acl_parser " >:: acl_parser ; packet_parsing id ; packet_parsing ( fun _ -> 1 ) ; " test " >:: test ; ] in run_test_tt ~ verbose :! verbose suite
let create ( ) = ( match Xs_transport . choose_xenstore_path ( ) with | None -> Printf . fprintf stderr " Failed to find xenstore socket . I tried the following :\ n " ; List . iter ( fun x -> Printf . fprintf stderr " % s \ n " x ) ( Xs_transport . get_xenstore_paths ( ) ) ; Printf . fprintf stderr " \ nOn linux you might not have xenfs mounted :\ n " ; Printf . fprintf stderr " sudo mount - t xenfs xenfs / proc / xen \ n " ; Printf . fprintf stderr " Or perhaps you just need to set the XENSTORED_PATH environment variable . \ n " ; fail Xs_transport . Could_not_find_xenstore | Some x -> return x ) >>= fun path -> Lwt_unix . stat path >>= fun stats -> match stats . Lwt_unix . st_kind with | Lwt_unix . S_SOCK -> let sockaddr = Lwt_unix . ADDR_UNIX ( path ) in let fd = Lwt_unix . socket Lwt_unix . PF_UNIX Lwt_unix . SOCK_STREAM 0 in Lwt . catch ( fun ( ) -> Lwt_unix . connect fd sockaddr ) ( fun e -> Lwt_unix . close fd >>= fun ( ) -> Lwt . fail e ) >>= fun ( ) -> return fd | _ -> let fd = Unix . openfile path [ Lwt_unix . O_RDWR ] 0o0 in return ( Lwt_unix . of_unix_file_descr ~ blocking : false fd )
let write fd bufs ofs len = Lwt_unix . write fd bufs ofs len >>= fun n -> if n <> len then fail End_of_file else return ( )
type ' a t = ' a Lwt . t
let ( >>= ) = Lwt . bind
type backend = [ ` unix | ` xen ]
let create ( ) = let path = match Xs_transport . choose_xenstore_path ( ) with | None -> Printf . fprintf stderr " Failed to find xenstore socket . I tried the following :\ n " ; List . iter ( fun x -> Printf . fprintf stderr " % s \ n " x ) ( Xs_transport . get_xenstore_paths ( ) ) ; Printf . fprintf stderr " \ nOn linux you might not have xenfs mounted :\ n " ; Printf . fprintf stderr " sudo mount - t xenfs xenfs / proc / xen \ n " ; Printf . fprintf stderr " Or perhaps you just need to set the XENSTORED_PATH environment variable . \ n " ; raise Xs_transport . Could_not_find_xenstore | Some path -> path in let stats = Unix . stat path in match stats . Unix . st_kind with | Unix . S_SOCK -> begin let sockaddr = Unix . ADDR_UNIX ( path ) in let fd = Unix . socket Unix . PF_UNIX Unix . SOCK_STREAM 0 in try Unix . connect fd sockaddr ; fd with e -> Unix . close fd ; raise e end | _ -> Unix . openfile path [ Lwt_unix . O_RDWR ] 0o0
let destroy fd = Unix . close fd
let read fd = Unix . read fd
let write fd bufs ofs len = let n = Unix . write fd bufs ofs len in if n <> len then begin raise End_of_file end
type ' a t = ' a
let return x = x
let ( >>= ) x f = f x
type backend = [ ` unix | ` xen ]
type t = | Test of ( unit -> unit ) | Labeled of string * t | List of t list
let fun_ f = Test f
let label s t = Labeled ( s , t )
let list ts = List ts
module Config = struct type arg = | Do of Pcre . regexp | Dont of Pcre . regexp type t = { args : arg list ; show_tests : bool ; default_go : bool ; } let rev_args = ref [ ] let show_tests = ref false let from_args default_go = { args = List . rev ! rev_args ; show_tests = ! show_tests ; default_go = default_go ; } let is_go conf label = let s = String . concat " " / label in match List . find_map_opt ( function | Do rex when Pcre . pmatch ~ rex s -> Some true | Dont rex when Pcre . pmatch ~ rex s -> Some false | _ -> None ) conf . args with | Some b -> b | None -> conf . default_go end
let arg_specs = let open Arg in let open Config in [ " -- test " , String ( fun s -> rev_args +::= Do ( Pcre . regexp s ) ) , " < string >: Perform tests match with the string " ; " -- no - test " , String ( fun s -> rev_args +::= Dont ( Pcre . regexp s ) ) , " < string >: Skip tests match with the string " ; " -- show - tests " , Set show_tests , " : List all the tests " ; ]
module State = struct type t = { rev_label : string list ; config : Config . t ; } let add_label l st = { st with rev_label = l :: st . rev_label } let labels st = List . rev st . rev_label let is_go t = Config . is_go t . config & List . rev t . rev_label let from_args default_go = { rev_label = [ ] ; config = Config . from_args default_go ; } end
let rec iter st go prim = function | Test t -> prim st t | Labeled ( l , t ) -> let st = State . add_label l st in go st ( fun ( ) -> iter st go prim t ) | List ts -> List . iter ( iter st go prim ) ts
let show st t = let go _st f = f ( ) in let prim st _ = !!% " % s : % s . " @ ( String . concat " " / ( State . labels st ) ) ( if State . is_go st then " go " else " skip " ) in iter st go prim t ; exit 0
let run ' st = let go _st f = f ( ) in let prim st t = if State . is_go st then begin let name = String . concat " " / ( State . labels st ) in !!% " Testing % s . . . . " @ name ; begin try t ( ) with | e -> !!% " Error : % s : % s . " @ ( String . concat " . " ( State . labels st ) ) ( Exn . to_string e ) ; raise e end ; !!% " Done % s . " @ name ; end in iter st go prim
let run default_go t = let st = State . from_args default_go in if st . State . config . Config . show_tests then show st t else run ' st t
let sourceDirs = Node . Path . join [ " | lib " ; " bs " ; " . sourcedirs . json ] " |
let lock = Xwatcher_util . makeLock ( )
let events = Xwatcher_util . makeEventObj ( )
let watchers : watcher array = [ ] ||
let source_dirname = Js . Option . getExn [ % external __dirname ] __dirname
let bsb = Node . Path . join [ | source_dirname ; bsb_exe ] |
let rec onChange = fun eventType fileName -> Js . log { j | Event $ eventType $ fileName | j } j ; events ## push ( eventType , fileName ) fileName ; build bsb events lock ( fun [ @ bs ] bs ( ) -> idle ( ) ) let watchFiles = getWatchFiles sourceDirs in watchers |> Js . Vector . filterInPlace ( fun [ @ bs ] bs { dir ; watcher } watcher -> if dir = bsconfig || Js . Vector . memByRef dir watchFiles then true else begin Js . log { j | $ dir is no longer watched | j } j ; Node . Fs . Watch . close watcher ; false end ) ; watchFiles |> Js . Array . forEach ( fun dir -> if not ( Js . Array . some ( fun { dir = watcher_dir } watcher_dir -> watcher_dir = dir ) dir watchers ) watchers then begin Js . log { j | watching dir $ dir now | j } j ; Js . Vector . pushBack ( makeWatcher dir ( fun [ @ bs ] bs x y -> onChange x y ) ) watchers end )
let ( ) = Node . Process . putEnvVar " BS_VSCODE " " 1 " ; Js . Vector . pushBack ( makeWatcher bsconfig ( fun [ @ bs ] bs x y -> onChange x y ) y ) y watchers ; build bsb events lock ( fun [ @ bs ] bs ( ) -> idle ( ) )
let source_dirname = Js . Option . getExn [ % external __dirname ] __dirname
let cwd = Node . Process . cwd ( )
let root = if Node . Fs . existsSync ( Node . Path . join [ | cwd ; bsconfig ] ) | then cwd else Xwatcher_util . findFile ~ prev : cwd ~ cwd ( : Node . Path . dirname cwd ) cwd bsconfig
let jscomp = Js . log { j | Root : $ root | j } j ; Node . Path . join [ | root ; " jscomp " ] |
let lock = Xwatcher_util . makeLock ( )
let events = Xwatcher_util . makeEventObj ( )
let exec ( ) = buildWithShell command events lock ( fun [ @ bs ] bs ( ) -> ( ) )
let watch dir = makeWatcher dir ( fun [ @ bs ] bs _event fileName -> if Js . String . endsWith " . ml " fileName || Js . String . endsWith " . mli " fileName || Js . String . endsWith " . cppo " fileName || Js . String . endsWith " . js " fileName || fileName = " Makefile " || fileName = " Makefile . shared " then exec ( ) )
let ( ) = Node . Process . putEnvVar " BS_VSCODE " " 1 " ; match Js . Array . sliceFrom 2 Node . Process . argv with | [ " |- build ] " | -> Xwatcher_util . spawnInheritIgnore command | _ -> begin Js . Vector . iter ( fun [ @ bs ] bs x -> ignore @@ watch ( Node . Path . join [ | jscomp ; x ] ) | ) [ | " core " ; " syntax " ; " ext " ; " depends " ; " others " ; " ounit " ; " ounit_tests " ; " test " ; " runtime " ; " xwatcher " ; " bsb " ; " common " ; " super_errors " ; " . " ] ; | exec ( ) end
let getWatchFiles file = if Fs . existsSync file then Js . String . split " \ n " ( Fs . readFileAsUtf8Sync file ) |> Js . Array . filter ( fun x -> String . length ( Js . String . trim x ) x <> 0 ) 0 else [ ] || method empty : unit -> unit method needRebuild : unit -> bool method push : string * string -> unit method currentEvents : unit -> ( string * string ) string array
type eventObj = _eventObj Js . t
let rec findFile ~ prev ~ cwd f = if String . length prev = String . length cwd then Js . Exn . raiseError { j | $ f not found | j } j else if Fs . existsSync ( Node . Path . join [ | cwd ; f ] ) | then cwd else findFile cwd ( Node . Path . dirname cwd ) f
let makeEventObj ( ) : eventObj = object ( self ) self val events : ( string * string ) string array = [ ] || method empty ( ) = Js . Vector . empty self ## events method push a = Js . Vector . pushBack a self ## events method needRebuild ( ) = Array . length self ## events <> 0 method currentEvents ( ) = self ## events end [ @ bs ] bs
type t ( _ [ @ bs . as { json | [ ] | json } json ] json ) json -> ( _ [ @ bs . as { json | { " stdio " : " inherit " } | json } json ] json ) json -> t = " spawn " [ @@ bs . module " child_process ] " ( _ [ @ bs . as { json | [ ] | json } json ] json ) json -> ( _ [ @ bs . as { json | { " stdio " : " inherit " , " shell " : true } | json } json ] json ) json -> t = " spawn " [ @@ bs . module " child_process ] " ( _ [ @ bs . as { json | [ ] | json } json ] json ) json -> ( _ [ @ bs . as { json | { " stdio " : " inherit " , " shell " : true } | json } json ] json ) json -> unit = " spawn " [ @@ bs . module " child_process ] " method acquire : unit -> bool method release : unit -> unit
type lock = _lock Js . t
let makeLock ( ) : lock = object ( objectself ) objectself val mutable isBuilding = false method acquire ( ) = if self ## isBuilding then false else begin self ## isBuilding #= true ; true end method release ( ) = self ## isBuilding #= false end [ @ bs ] bs
let rec build cmd ( event : eventObj ) eventObj ( lock : lock ) idle = if lock ## acquire ( ) then begin Js . log " >>>> Start compiling " ; let events = event ## currentEvents ( ) in Js . log { j | Rebuilding since $ events | j } j ; event ## empty ( ) ; spawnInheritNoShell cmd |> onExit ( fun ( ) -> Js . log " >>>> Finish compiling " ; lock ## release ( ) ; if event ## needRebuild ( ) then build cmd event lock idle else idle ( ) [ @ bs ] bs ) end
let rec buildWithShell cmd ( event : eventObj ) eventObj ( lock : lock ) idle = if lock ## acquire ( ) then begin Js . log " >>>> Start compiling " ; let events = event ## currentEvents ( ) in Js . log { j | Rebuilding since $ events | j } j ; event ## empty ( ) ; spawnInherit cmd |> onExit ( fun ( ) -> Js . log " >>>> Finish compiling " ; lock ## release ( ) ; if event ## needRebuild ( ) then build cmd event lock idle else idle ( ) [ @ bs ] bs ) end
type watcher = { dir : string ; watcher : Fs . Watch . t } string -> ( string -> string -> unit [ @ bs ] bs ) bs -> Node . Fs . Watch . t = " watch " [ @@ bs . module " fs ] "
let makeWatcher file onChange = { watcher = watchOnChange file onChange ; dir = file }
let make_printable i_char = match i_char with n when ( ( ( Char . code n ) < 32 ) or ( ( Char . code n ) > 126 ) ) -> ' . ' | _ -> i_char ; ;
let make_hex chr = Printf . sprintf " . % 2x " ( Char . code chr ) ; ;
let conditional_add_st bffr ch = match bffr with n when ( ( Buffer . length bffr ) = 0 ) -> Buffer . add_string bffr ch | n when ( ( Buffer . length bffr ) = 4 ) -> Buffer . add_string bffr ( " " ^ ch ) | n when ( ( ( Buffer . length bffr ) mod 5 ) = 4 ) -> Buffer . add_string bffr ( " " ^ ch ) | _ -> Buffer . add_string bffr ch ; ;
let string_map str fnc = let rec strmap st acc = match st with " " -> List . rev acc | _ -> strmap ( String . sub st 1 ( ( String . length st ) - 1 ) ) ( ( fnc st . [ 0 ] ) :: acc ) in strmap str [ ] ; ;
let rec output_lines fle f_buf s_buf curpos = let str_buf = String . create 16 in
let res = input fle str_buf 0 16 in ( if ( res < 16 ) then ( List . iter ( conditional_add_st f_buf ) List . iter ( Buffer . add_char s_buf ) else ( List . iter ( conditional_add_st f_buf ) ( string_map str_buf make_hex ) ; List . iter ( Buffer . add_char s_buf ) ( string_map str_buf make_printable ) ) ) ; Printf . printf " % 0 . 7x : %- 40s % s \ n " curpos ( Buffer . contents f_buf ) ( Buffer . contents s_buf ) ; if ( res < 16 ) then exit ( 0 ) else Buffer . clear f_buf ; Buffer . clear s_buf ; output_lines fle f_buf s_buf ( curpos + res ) ; ;
let output_file fname = let fo = open_in_bin fname in
let res = output_lines fo ( Buffer . create 16 ) ( Buffer . create 16 ) 0 in close_in fo ; res ; ;
let rec build_char_list sb acc = let nval = try Some ( Scanf . bscanf sb " % 2x " ( fun x -> Char . chr x ) ) with End_of_file -> None in match nval with Some n -> build_char_list sb ( n :: acc ) | None -> List . rev acc ; ;
let rec input_lines source_chan dest_chan = let write_line sc dc = try let istr = String . sub ( input_line sc ) 9 39 in let buf = Buffer . create 32 in with End_of_file -> false in let do_more = write_line source_chan dest_chan in match do_more with | false -> ( ) ; ;
let input_file source_file dest_file = let ic = open_in source_file in