text
stringlengths
12
786k
type vcf_info_meta = Info of vcf_number * vcf_info_type * vcf_description
type vcf_filter_meta = Filter of vcf_description
type vcf_format_meta = Format of vcf_number * vcf_format_type * vcf_description
type vcf_alt_meta = Alt of vcf_description
type vcf_meta = { vcfm_version : string ; vcfm_id_cache : vcf_id Set . Poly . t ; vcfm_info : ( vcf_id , vcf_info_meta ) vcf_info_meta Hashtbl . t ; vcfm_filters : ( vcf_id * vcf_filter_meta ) vcf_filter_meta list ; vcfm_format : ( vcf_id , vcf_format_meta ) vcf_format_meta Hashtbl . t ; vcfm_alt : ( string , vcf_alt_meta ) vcf_alt_meta Hashtbl . t ; vcfm_arbitrary : ( string , string ) string Hashtbl . t ; vcfm_header : string list ; vcfm_samples : string list }
type vcf_format = [ ` integer of int | ` float of float | ` character of char | ` string of string | ` missing ]
type vcf_info = [ vcf_format | ` flag of string ]
type vcf_row = { vcfr_chrom : string ; vcfr_pos : int ; vcfr_ids : string list ; vcfr_ref : string ; vcfr_alts : string list ; vcfr_qual : float option ; vcfr_filter : vcf_id list ; vcfr_info : ( vcf_id , vcf_info list ) list Hashtbl . t ; vcfr_samples : ( vcf_id , ( vcf_id * vcf_format list ) list list ) list Hashtbl . t }
type vcf_parse_row_error = [ Safe . error | ` info_type_coersion_failure of vcf_info_type * string | ` format_type_coersion_failure of vcf_format_type * string | ` invalid_dna of string | ` unknown_info of vcf_id | ` unknown_filter of vcf_id | ` unknown_alt of string | ` duplicate_ids of vcf_id list | ` invalid_arguments_length of vcf_id * int * int | ` invalid_row_length of int * int | ` malformed_sample of string | ` unknown_format of vcf_id ]
type vcf_parse_error = [ ` malformed_meta of Pos . t * string | ` malformed_row of Pos . t * vcf_parse_row_error * string | ` malformed_header of Pos . t * string | ` incomplete_input of Pos . t * string list * string option | ` not_ready ]
let string_to_vcf_number = function | " A " -> OnePerAllele | " G " -> OnePerGenotype | " . " -> Unknown | arity -> Number ( int_of_string arity ) arity
let string_to_vcf_format_type s = match String . lowercase s with | " integer " -> ` integer_value | " float " -> ` float_value | " character " -> ` character_value | " string " -> ` string_value | v -> failwith ( " string_to_vcf_format_type : invalid format : " ^ v ) v
let vcf_format_type_to_string = function | ` integer_value -> " integer " | ` float_value -> " float " | ` character_value -> " character " | ` string_value -> " string "
let coerce_to_vcf_format_type t s = if String . equal s " . " then Ok ` missing else match t with | ` integer_value -> Result . map ( Safe . int_of_string s ) s ~ f ( : fun x -> ` integer x ) x | ` float_value -> Result . map ( Safe . float_of_string s ) s ~ f ( : fun x -> ` float x ) x | ` character_value when String . length s = 1 -> Ok ( ` character s [ . 0 ] 0 ) 0 | ` string_value -> Ok ( ` string s ) s | _ -> Error ( ` format_type_coersion_failure ( t , s ) s ) s
let coerce_n ~ f key n s = let open Result . Monad_infix in let res = lazy ( Result . all ( List . map ~ f ( String . split ~ on : ' , ' s ) s ) s ) s in match n with | Number n -> Lazy . force res >>= fun values -> if List . length values = n then Ok values else Error ( ` invalid_arguments_length ( key , List . length values , n ) n ) n | Unknown | OnePerAllele | OnePerGenotype -> Lazy . force res
let string_to_vcf_info_type s = match String . lowercase s with | " flag " -> ` flag_value | s -> string_to_vcf_format_type s
let vcf_info_type_to_string = function | ` flag_value -> " flag " | # vcf_format_type as t -> vcf_format_type_to_string t
let coerce_to_vcf_info_type t s = let res = match t with | ` flag_value -> Ok ( ` flag s ) s | # vcf_format_type -> coerce_to_vcf_format_type t s in Result . map_error res ~ f ( : fun _exn -> ` info_type_coersion_failure ( t , s ) s ) s
let parse_row_error_to_string = function | ` invalid_int s -> sprintf " invalid_integer ( % s ) s " s | ` invalid_float s -> sprintf " invalid_float ( % s ) s " s | ` info_type_coersion_failure ( t , s ) s -> sprintf " info_type_coersion_failure ( % s , % S ) S " ( vcf_info_type_to_string t ) t s | ` format_type_coersion_failure ( t , s ) s -> sprintf " format_type_coersion_failure ( % s , % S ) S " ( vcf_format_type_to_string t ) t s | ` invalid_dna s -> sprintf " invalid_dna ( % s ) s " s | ` unknown_info s -> sprintf " unknown_info ( % s ) s " s | ` unknown_filter f -> sprintf " unknown_filter ( % s ) s " f | ` unknown_alt s -> sprintf " unknown_alt ( % s ) s " s | ` duplicate_ids ids -> sprintf " duplicate_ids ( % s ) s " ( String . concat ~ sep " , : " ids ) ids | ` invalid_arguments_length ( key , got , expected ) expected -> sprintf " invalid_arguments_length ( % s , % i , % i ) i " key got expected | ` invalid_row_length ( got , expected ) expected -> sprintf " invalid_row_length ( % i , % i ) i " got expected | ` malformed_sample s -> sprintf " malformed_sample ( % s ) s " s | ` unknown_format f -> sprintf " unknown_formar ( % s ) s " f
let parse_error_to_string = let pos ( ) a = Pos . to_string a in function | ` malformed_meta ( p , s ) s -> sprintf " malformed_meta ( % a , % S ) S " pos p s | ` malformed_row ( p , err , s ) s -> sprintf " malformed_row ( % s , % a , % S ) S " ( parse_row_error_to_string err ) err pos p s | ` malformed_header ( p , s ) s -> sprintf " malformed_header ( % a , % s ) s " pos p s | _ -> sprintf " unknown_error "
let reserved_info = Hashtbl . Poly . of_alist_exn [ ( " AA " , ` string_value ) string_value ; ( " AC " , ` integer_value ) integer_value ; ( " AF " , ` float_value ) float_value ; ( " AN " , ` integer_value ) integer_value ; ( " BQ " , ` float_value ) float_value ; ( " CIGAR " , ` string_value ) string_value ; ( " DB " , ` flag_value ) flag_value ; ( " DP " , ` integer_value ) integer_value ; ( " H2 " , ` flag_value ) flag_value ; ( " MQ " , ` float_value ) float_value ; ( " MQ0 " , ` integer_value ) integer_value ; ( " NS " , ` integer_value ) integer_value ; ( " SB " , ` string_value ) string_value ; ( " SOMATIC " , ` flag_value ) flag_value ; ( " VALIDATED " , ` flag_value ) flag_value ; ( " IMPRECISE " , ` flag_value ) flag_value ; ( " NOVEL " , ` flag_value ) flag_value ; ( " END " , ` integer_value ) integer_value ; ( " SVTYPE " , ` string_value ) string_value ; ( " CIPOS " , ` integer_value ) integer_value ; ( " CIEND " , ` integer_value ) integer_value ; ( " HOMLEN " , ` integer_value ) integer_value ; ( " HOMSEQ " , ` integer_value ) integer_value ; ( " BKPTID " , ` string_value ) string_value ; ( " MEINFO " , ` string_value ) string_value ; ( " METRANS " , ` string_value ) string_value ; ( " DGVID " , ` string_value ) string_value ; ( " DBVARID " , ` string_value ) string_value ; ( " MATEID " , ` string_value ) string_value ; ( " PARID " , ` string_value ) string_value ; ( " EVENT " , ` string_value ) string_value ; ( " CILEN " , ` integer_value ) integer_value ; ( " CN " , ` integer_value ) integer_value ; ( " CNADJ " , ` integer_value ) integer_value ; ( " CICN " , ` integer_value ) integer_value ; ( " CICNADJ " , ` integer_value ) integer_value ] ( " GT " , ` string_value ) string_value ; ( " DP " , ` integer_value ) integer_value ; ( " FT " , ` string_value ) string_value ; ( " GL " , ` float_value ) float_value ; ( " GQ " , ` float_value ) float_value ; ( " HQ " , ` float_value ) float_value ; ( " CN " , ` integer_value ) integer_value ; ( " CNQ " , ` float_value ) float_value ; ( " CNL " , ` float_value ) float_value ; ( " NQ " , ` integer_value ) integer_value ; ( " HAP " , ` integer_value ) integer_value ; ( " AHAP " , ` integer_value ) integer_value ] ( " DEL " , Alt " Deletion relative to the reference ) " ; ( " INS " , Alt " Insertion of novel sequence relative to the reference ) " ; ( " DUP " , Alt " Region of elevated copy number relative to the reference ) " ; ( " INV " , Alt " Inversion of reference sequence ) " ; ( " CNV " , Alt " Copy number variable region ) " ; ( " DUP : TANDEM " , Alt " TANDEM Tandem duplication ) " ; ( " DEL : ME " , Alt " ME Deletion of mobile element relative to the reference ) " ; ( " INS : ME " , Alt " ME Insertion of a mobile element relative to the reference ) " ; ]
let default_meta = { vcfm_version = " < unknown " ; > vcfm_id_cache = Set . Poly . empty ; vcfm_info = Hashtbl . Poly . create ( ) ; vcfm_filters = [ ] ; vcfm_format = Hashtbl . Poly . create ( ) ; vcfm_alt = reserved_alt ; vcfm_arbitrary = Hashtbl . Poly . create ( ) ; vcfm_header = [ ] ; vcfm_samples = [ ] }
let string_to_vcfr_ref s = let s = String . uppercase s in if is_valid_dna s then Ok s else Error ( ` invalid_dna s ) s
let string_to_vcfr_info { vcfm_info ; _ } s = let go values = List . map ( String . split ~ on : ' ; ' s ) s ~ f ( : fun chunk -> let ( key , raw_value ) raw_value = Option . value ~ default ( : chunk , ) " " ( String . lsplit2 ~ on : ' = ' chunk ) chunk in let chunk_values = match Hashtbl . find vcfm_info key with | Some ( Info ( _t , ` flag_value , _description ) _description ) _description when String . equal raw_value " " -> Ok [ ` flag key ] key | Some ( Info ( n , t , _description ) _description ) _description -> coerce_n ~ f ( : coerce_to_vcf_info_type t ) t key n raw_value | None -> Error ( ` unknown_info key ) key in Result . map chunk_values ~ f ( : fun data -> Hashtbl . set values ~ key ~ data ) data ) data and values = Hashtbl . Poly . create ( ) in Result ( . map ( all_unit ( go values ) values ) values ~ f ( : Fn . const values ) values ) values
let string_to_vcfr_filter { vcfm_filters ; _ } s = match String . split ~ on : ' ; ' s with | [ " PASS ] " -> Ok [ ] | chunks -> match List . find chunks ~ f ( : fun chunk -> not ( List . Assoc . mem ~ equal : String . equal vcfm_filters chunk ) chunk ) chunk with | Some unknown_filter -> Error ( ` unknown_filter unknown_filter ) unknown_filter | None -> Ok chunks
let string_to_vcfr_ids { vcfm_id_cache ; _ } s = match String . split ~ on : ' ; ' s with | [ ] " . " -> Ok [ ] | chunks -> let duplicate_ids = List . filter chunks ~ f ( : Set . mem vcfm_id_cache ) vcfm_id_cache in if List . is_empty duplicate_ids then Ok chunks else Error ( ` duplicate_ids duplicate_ids ) duplicate_ids
let string_to_vcfr_alts { vcfm_alt ; _ } s = match String . split ~ on : ' , ' s with | [ ] " . " -> Ok [ ] | chunks -> let res = List . map chunks ~ f ( : fun chunk -> let n = String . length chunk in match Char ( . chunk [ . 0 ] 0 = ' < ' && chunk [ . n - 1 ] 1 = ' > ' , is_valid_dna chunk ) chunk with | ( true , _ ) _ -> if Hashtbl . mem vcfm_alt ( String . sub ~ pos : 1 ~ len ( : n - 2 ) 2 chunk ) chunk then Ok chunk else Error ( ` unknown_alt chunk ) chunk | ( false , true ) true -> Ok chunk | ( false , false ) false -> Error ( ` invalid_dna chunk ) chunk ) chunk in Result . all res
let list_to_vcfr_samples { vcfm_format ; vcfm_samples ; _ } chunks = let open Result . Monad_infix in let samples = Hashtbl . Poly . create ( ) in let go sample_keys id raw_sample = let sample_chunks = String . split ~ on : ' : ' raw_sample in if List ( . length sample_keys <> length sample_chunks ) sample_chunks then Error ( ` malformed_sample raw_sample ) raw_sample else let res = List . map2_exn sample_keys sample_chunks ~ f ( : fun key raw_value -> match Hashtbl . find vcfm_format key with | Some ( Format ( n , t , _description ) _description ) _description -> coerce_n ~ f ( : coerce_to_vcf_format_type t ) t key n raw_value >>= fun value -> Ok ( key , value ) value | None -> Error ( ` unknown_format key ) key ) key in Result ( . map ( all res ) res ~ f ( : fun data -> Hashtbl . set samples ~ key : id ~ data ) data ) data in match chunks with | raw_sample_keys :: raw_samples -> let sample_keys = String . split ~ on : ' : ' raw_sample_keys in let res = List . map2_exn vcfm_samples raw_samples ~ f ( : go sample_keys ) sample_keys in Result . map ( Result . all_unit res ) res ~ f ( : Fn . const samples ) samples | [ ] -> Ok samples
let list_to_vcf_row meta chunks = let open Result . Monad_infix in let n_chunks = List . length chunks and n_columns = List ( . length meta . vcfm_header + length meta . vcfm_samples ) vcfm_samples in match chunks with | vcfr_chrom :: raw_pos :: raw_id :: raw_ref :: raw_alt :: raw_qual :: raw_filter :: raw_info :: raw_samples when n_chunks = n_columns -> Safe . int_of_string raw_pos >>= fun vcfr_pos -> string_to_vcfr_ids meta raw_id >>= fun vcfr_ids -> string_to_vcfr_ref raw_ref >>= fun vcfr_ref -> string_to_vcfr_alts meta raw_alt >>= fun vcfr_alts -> string_to_vcfr_info meta raw_info >>= fun vcfr_info -> string_to_vcfr_filter meta raw_filter >>= fun vcfr_filter -> list_to_vcfr_samples meta raw_samples >>= fun vcfr_samples -> let row = { vcfr_chrom ; vcfr_pos ; vcfr_ids ; vcfr_ref ; vcfr_alts ; vcfr_qual = Result . ok ( Safe . float_of_string raw_qual ) raw_qual ; vcfr_filter ; vcfr_info ; vcfr_samples } in Ok row | _ -> Error ( ` invalid_row_length ( n_chunks , n_columns ) n_columns ) n_columns
module Transform = struct let next_vcf_header meta p = let open Lines . Buffer in let { vcfm_info ; vcfm_format ; _ } = meta in let l = Option . value_exn ( next_line p :> string option ) option in let chunks = List . filter ~ f : String ( . fun s -> s <> ) " " ( String . split ~ on : ' \ t ' l ) l in begin match chunks with | " # CHROM " :: " POS " :: " ID " :: " REF " :: " ALT " :: " QUAL " :: " FILTER " :: " INFO " :: rest -> begin match rest with | " FORMAT " :: ( ( _ :: _ ) _ as samples ) samples | ( [ ] as samples ) samples -> let merge_with_reserved ~ c = Hashtbl . merge ~ f ( : fun ~ key : _ v -> match v with | ` Left t -> Some ( c Unknown t " < reserved ) " > | ` Right parsed -> Some parsed | ` Both ( _t , parsed ) parsed -> Some parsed ) parsed in let vcfm_info = merge_with_reserved reserved_info vcfm_info ~ c ( : fun n t description -> Info ( n , t , description ) description ) description ; and vcfm_format = merge_with_reserved reserved_format vcfm_format ~ c ( : fun n t description -> Format ( n , t , description ) description ) description ; and ( vcfm_header , vcfm_samples ) vcfm_samples = if List . is_empty samples then ( chunks , samples ) samples else List . split_n chunks List ( . length chunks - length samples ) samples in Ok ( ` complete { meta with vcfm_info ; vcfm_format ; vcfm_header ; vcfm_samples } ) | _ :: _ -> Error ( ` malformed_header ( current_position p , l ) l ) l end | _ -> Error ( ` malformed_header ( current_position p , l ) l ) l end let next_vcf_meta meta p = let open Lines . Buffer in let { vcfm_info ; vcfm_filters ; vcfm_format ; vcfm_alt ; _ } = meta in match ( peek_line p :> string option ) option with | Some l when String . is_prefix l ~ prefix " " :## -> let _l = next_line p in let s = String . suffix l ( String . length l - 2 ) 2 in begin match String . lsplit2 s ~ on : ' = ' with | Some ( " fileformat " , v ) v -> Ok ( ` partial { meta with vcfm_version = v } ) | Some ( " INFO " , v ) v -> Scanf . sscanf v " < ID =% s , @ Number =% s , @ Type =% s , @ Description =% S " > ( fun id n t description -> let info_meta = Info ( string_to_vcf_number n , string_to_vcf_info_type t , description ) description in Hashtbl . set vcfm_info ~ key : id ~ data : info_meta ) info_meta ; Ok ( ` partial meta ) meta | Some ( " FILTER " , v ) v -> Scanf . sscanf v " < ID =% s , @ Description =% S " > ( fun id description -> let filter_meta = Filter description in let meta = { meta with vcfm_filters = ( id , filter_meta ) filter_meta :: vcfm_filters } in Ok ( ` partial meta ) meta ) meta | Some ( " FORMAT " , v ) v -> Scanf . sscanf v " < ID =% s , @ Number =% s , @ Type =% s , @ Description =% S " > ( fun id n t description -> let format_meta = Format ( string_to_vcf_number n , string_to_vcf_format_type t , description ) description in Hashtbl . set vcfm_format ~ key : id ~ data : format_meta ) format_meta ; Ok ( ` partial meta ) meta | Some ( " ALT " , v ) v -> Scanf . sscanf v " < ID =% s , @ Description =% S " > ( fun id description -> let alt_meta = Alt description in Hashtbl . set vcfm_alt ~ key : id ~ data : alt_meta ) alt_meta ; Ok ( ` partial meta ) meta | Some ( k , v ) v -> begin Hashtbl . set meta . vcfm_arbitrary ~ key : k ~ data : v ; Ok ( ` partial meta ) meta end | None -> Error ( ` malformed_meta ( current_position p , s ) s ) s end | Some _l -> next_vcf_header meta p | None -> Error ` not_ready let next_vcf_row meta p = let open Lines . Buffer in match ( next_line p :> string option ) option with | Some l when not ( String . is_empty l ) l -> let chunks = List . filter ~ f : String ( . fun s -> s <> ) " " ( String . split ~ on : ' \ t ' l ) l in begin match list_to_vcf_row meta chunks with | Ok row -> ` output ( Ok row ) row | Error err -> ` output ( Error ( ` malformed_row ( current_position p , err , l ) l ) l ) l end | Some _ | None -> ` not_ready let next meta_ref p = match ! meta_ref with | ` complete meta -> next_vcf_row meta p | ` partial meta -> begin match next_vcf_meta meta p with | Ok meta -> meta_ref := meta ; ` not_ready | Error ` not_ready -> ` not_ready | Error err -> ` output ( Error err ) err end let string_to_item ? filename ( ) = let name = sprintf " vcf_parser :% s " Option ( . value ~ default " " :<> filename ) filename in let meta_ref = ref ( ` partial default_meta ) default_meta in Lines . Transform . make_merge_error ~ name ? filename ~ next ( : next meta_ref ) meta_ref ( ) end
module type Cohttp_IO_S = sig type + ' a t val ( ) >>= : ' a t -> ( ' a -> ' b t ) t -> ' b t val return : ' a -> ' a t type ic type oc val iter : ( ' a -> unit t ) t -> ' a list -> unit t val read_line : ic -> string option t val read : ic -> int -> string t val read_exactly : ic -> int -> string option t val write : oc -> string -> unit t val flush : oc -> unit t end
module IO = struct type ' a t = ' a Lwt . t let ( >>= ) = Lwt ( . >>= ) let return = Lwt . return type ic = Lwt_io . input_channel type oc = Lwt_io . output_channel let iter = Lwt_list . iter_s let read_line = Lwt_io . read_line_opt let read ic count = Lwt . catch ( fun ( ) -> Lwt_io . read ~ count ic ) ic ( function End_of_file -> return " " | e -> Lwt . fail e ) e let read_exactly ic buf off len = Lwt . catch ( fun ( ) -> Lwt_io . read_into_exactly ic buf off len >>= fun ( ) -> return true ) true ( function End_of_file -> return false | e -> Lwt . fail e ) e let read_exactly ic len = let buf = Bytes . create len in read_exactly ic buf 0 len >>= function | true -> return ( Some ( Bytes . to_string buf ) buf ) buf | false -> return None let write = Lwt_io . write let flush = Lwt_io . flush end
let reader t = let frag = ref ( Cstruct . create 0 ) 0 in let rec aux buf ofs len = if len = 0 then return 0 else let available = Cstruct . length ! frag in if available = 0 then begin M . read t >>= function | Ok ` Eof -> return 0 | Ok ( ` Data b ) b -> frag := b ; aux buf ofs len | Error e -> Fmt . kstr Lwt . fail_with " % a " M . pp_error e end else begin let n = min available len in Cstruct . blit ! frag 0 ( Cstruct . of_bigarray buf ) buf ofs n ; frag := Cstruct . shift ! frag n ; return n end in aux
let writer t ( buf : Lwt_bytes . t ) t ( ofs : int ) int ( len : int ) int = let b = Cstruct . sub ( Cstruct . of_bigarray buf ) buf ofs len in M . write t b >>= function | Ok ( ) -> return len | Error ` Closed -> return 0 | Error e -> Fmt . kstr Lwt . fail_with " % a " M . pp_write_error e
let open_client ~ domid ~ port ( ? buffer_size = 1024 ) 1024 ( ) = M . client ~ domid ~ port ( ) >>= fun t -> let close ( ) = M . close t in let in_buffer = Lwt_bytes . create buffer_size in let ic = Lwt_io . make ~ buffer : in_buffer ~ mode : Lwt_io . input ~ close ( reader t ) t in let out_buffer = Lwt_bytes . create buffer_size in let oc = Lwt_io . make ~ buffer : out_buffer ~ mode : Lwt_io . output ( writer t ) t in return ( ic , oc ) oc
let open_server ~ domid ~ port ( ? buffer_size = 1024 ) 1024 ( ) = M . server ~ domid ~ port ~ read_size : buffer_size ~ write_size : buffer_size ( ) >>= fun t -> let close ( ) = M . close t in let in_buffer = Lwt_bytes . create buffer_size in let ic = Lwt_io . make ~ buffer : in_buffer ~ mode : Lwt_io . input ~ close ( reader t ) t in let out_buffer = Lwt_bytes . create buffer_size in let oc = Lwt_io . make ~ buffer : out_buffer ~ mode : Lwt_io . output ( writer t ) t in return ( ic , oc ) oc
module Kind = struct type t = | Git | Hg let of_dir_contents files = if String . Set . mem files " . git " then Some Git else if String . Set . mem files " . hg " then Some Hg else None let to_dyn t = Dyn . Variant ( ( match t with | Git -> " Git " | Hg -> " Hg " ) , [ ] ) let equal = ( = ) end
module T = struct type t = { root : Path . t ; kind : Kind . t } let to_dyn { root ; kind } = Dyn . record [ ( " root " , Path . to_dyn root ) ; ( " kind " , Kind . to_dyn kind ) ] let equal { root = ra ; kind = ka } { root = rb ; kind = kb } = Path . equal ra rb && Kind . equal ka kb let hash t = Path . hash t . root end
let git , hg = let get prog = lazy ( match Bin . which ~ path ( : Env . path Env . initial ) prog with | Some x -> x | None -> Utils . program_not_found prog ~ loc : None ) in ( get " git " , get " hg " )
let select git hg t = Memo . of_non_reproducible_fiber ( match t . kind with | Git -> git t | Hg -> hg t )
let prog t = Lazy . force ( match t . kind with | Git -> git | Hg -> hg )
let run t args = let open Fiber . O in let + s = Process . run_capture Strict ( prog t ) args ~ dir : t . root ~ env : Env . initial in String . trim s
let git_accept ( ) = Process . Accept ( Predicate_lang . union [ Element 0 ; Element 128 ] )
let run_git t args = let res = Process . run_capture ( git_accept ( ) ) ( prog t ) args ~ dir : t . root ~ env : Env . initial ~ stderr_to ( : Process . Io . file Config . dev_null Out ) in let open Fiber . O in let + res = res in match res with | Ok s -> Some ( String . trim s ) | Error 128 -> None | Error _ -> assert false
let hg_describe t = let open Fiber . O in let * s = run t [ " log " ; " -- rev " ; " . " ; " - T " ; " { latesttag } { latesttagdistance } " ] in let + id = run t [ " id " ; " - i " ] in let id , dirty_suffix = match String . drop_suffix id ~ suffix " " :+ with | Some id -> ( id , " - dirty " ) | None -> ( id , " " ) in let s = let s , dist = Option . value_exn ( String . rsplit2 s ~ on ' : ' ) in match s with | " null " -> id | _ -> ( match int_of_string dist with | 1 -> s | n -> sprintf " % s -% d -% s " s ( n - 1 ) id | exception _ -> sprintf " % s -% s -% s " s dist id ) in s ^ dirty_suffix
let make_fun name ~ git ~ hg = let memo = Memo . create name ~ input ( : module T ) ( select git hg ) in Staged . stage ( Memo . exec memo )
let describe = Staged . unstage @@ make_fun " vcs - describe " ~ git ( : fun t -> run_git t [ " describe " ; " -- always " ; " -- dirty " ; " -- abbrev = 7 " ] ) ~ hg ( : fun x -> let open Fiber . O in let + res = hg_describe x in Some res )
let commit_id = Staged . unstage @@ make_fun " vcs - commit - id " ~ git ( : fun t -> run_git t [ " rev - parse " ; " HEAD " ] ) ~ hg ( : fun t -> let open Fiber . O in let + res = run t [ " id " ; " - i " ] in Some res )
let files = let run_zero_separated_hg t args = Process . run_capture_zero_separated Strict ( prog t ) args ~ dir : t . root ~ env : Env . initial in let run_zero_separated_git t args = let open Fiber . O in let + res = Process . run_capture_zero_separated ( git_accept ( ) ) ( prog t ) args ~ dir : t . root ~ env : Env . initial in match res with | Ok s -> s | Error 128 -> [ ] | Error _ -> assert false in let f run args t = let open Fiber . O in let + l = run t args in List . map l ~ f : Path . in_source in Staged . unstage @@ make_fun " vcs - files " ~ git : ( f run_zero_separated_git [ " ls - tree " ; " - z " ; " - r " ; " -- name - only " ; " HEAD " ] ) ~ hg ( : f run_zero_separated_hg [ " files " ; " - 0 " ] )
let ( ) = init ( )
let temp_dir = lazy ( Path . of_string " vcs - tests " )
let ( ) = at_exit ( fun ( ) -> Path . rm_rf ( Lazy . force temp_dir ) )
let has_hg = match Lazy . force Vcs . hg with | ( _ : Path . t ) -> true | exception _ -> false
let run ( vcs : Vcs . t ) args = let prog , prog_str , real_args = match vcs . kind with | Git -> ( Vcs . git , " git " , args ) | Hg -> ( if has_hg then ( Vcs . hg , " hg " , args ) else ( Vcs . git , " hg " , match args with | [ " tag " ; s ; " - u " ; _ ] -> [ " tag " ; " - a " ; s ; " - m " ; s ] | [ " commit " ; " - m " ; msg ; " - u " ; _ ] -> [ " commit " ; " - m " ; msg ] | _ -> args ) ) in printf " $ % s \ n " ( List . map ( prog_str :: args ) ~ f : String . quote_for_shell |> String . concat ~ sep " : " ) ; Process . run Strict ( Lazy . force prog ) real_args ~ env : ( Env . add Env . initial ~ var " : GIT_DIR " ~ value ( : Filename . concat ( Path . to_absolute_filename vcs . root ) " . git " ) ) ~ dir : vcs . root ~ stdout_to ( : Process . Io . file Config . dev_null Process . Io . Out )
type action = | Init | Add of string | Write of string * string | Commit | Tag of string | Describe of string
let run_action ( vcs : Vcs . t ) action = match action with | Init -> run vcs [ " init " ; " - q " ] | Add fn -> run vcs [ " add " ; fn ] | Commit -> ( match vcs . kind with | Git -> run vcs [ " commit " ; " - m " ; " commit message " ] | Hg -> run vcs [ " commit " ; " - m " ; " commit message " ; " - u " ; " toto " ] ) | Write ( fn , s ) -> printf " $ echo % S > % s \ n " s fn ; Io . write_file ( Path . relative ( Lazy . force temp_dir ) fn ) s ; Fiber . return ( ) | Describe expected -> printf " $ % s describe [ . . . ] \ n " ( match vcs . kind with | Git -> " git " | Hg -> " hg " ) ; Memo . reset ( Memo . Invalidation . clear_caches ~ reason : Test ) ; let vcs = match vcs . kind with | Hg when not has_hg -> { vcs with kind = Git } | _ -> vcs in let + s = Memo . run ( Vcs . describe vcs ) in let s = Option . value s ~ default " : n / a " in let processed = String . split s ~ on ' ' :- |> List . map ~ f ( : fun s -> match s with | " " | " dirty " -> s | s when String . length s = 1 && String . for_all s ~ f ( : function | ' 0 ' . . ' 9 ' -> true | _ -> false ) -> s | _ when String . for_all s ~ f ( : function | ' 0 ' . . ' 9 ' | ' a ' . . ' z ' -> true | _ -> false ) -> " < commit - id " > | _ -> s ) |> String . concat ~ sep " " :- in printf " % s \ n " processed ; if processed <> expected then printf " Expected : % s \ nOriginal : % s \ n " expected s ; printf " \ n " | Tag s -> ( match vcs . kind with | Git -> run vcs [ " tag " ; " - a " ; s ; " - m " ; s ] | Hg -> run vcs [ " tag " ; s ; " - u " ; " toto " ] )
let run kind script = let ( lazy temp_dir ) = temp_dir in Path . rm_rf temp_dir ; Path . mkdir_p temp_dir ; let vcs = { Vcs . kind ; root = temp_dir } in let config = { Scheduler . Config . concurrency = 1 ; display = { verbosity = Short ; status_line = false } ; rpc = None ; stats = None } in Scheduler . Run . go ~ on_event ( : fun _ _ -> ( ) ) config ( fun ( ) -> Fiber . sequential_iter script ~ f ( : run_action vcs ) )
let script = [ Init ; Write ( " a " , " " ) - ; Add " a " ; Commit ; Describe " < commit - id " > ; Write ( " b " , " " ) - ; Add " b " ; Describe " < commit - id >- dirty " ; Commit ; Describe " < commit - id " > ; Tag " 1 . 0 " ; Describe " 1 . 0 " ; Write ( " c " , " " ) - ; Add " c " ; Describe " 1 . 0 - dirty " ; Commit ; Describe " 1 . 0 - 1 -< commit - id " > ; Write ( " d " , " " ) - ; Add " d " ; Describe " 1 . 0 - 1 -< commit - id >- dirty " ; Commit ; Describe " 1 . 0 - 2 -< commit - id " > ] run Git script ; [ % expect { | < commit - id > < commit - id >- dirty < commit - id > 1 . 0 1 . 0 - dirty 1 . 0 - 1 -< commit - id > 1 . 0 - 1 -< commit - id >- dirty 1 . 0 - 2 -< commit - id > } ] | run Hg script ; [ % expect { | < commit - id > < commit - id >- dirty < commit - id > 1 . 0 1 . 0 - dirty 1 . 0 - 1 -< commit - id > 1 . 0 - 1 -< commit - id >- dirty 1 . 0 - 2 -< commit - id > } ] |
type ' msg applicationCallbacks = { enqueue : ' msg -> unit ; }
type ' msg eventHandler = | EventHandlerCallback of string * ( Web . Node . event -> ' msg option ) | EventHandlerMsg of ' msg
type ' msg eventCache = { handler : Web . Node . event_cb ; cb : ( Web . Node . event -> ' msg option ) ref }
type ' msg property = | NoProp | RawProp of string * string | Attribute of string * string * string | Data of string * string | Event of string * ' msg eventHandler * ' msg eventCache option ref | Style of ( string * string ) list
type ' msg properties = ' msg property list
type ' msg t = | CommentNode of string | Text of string | Node of string * string * string * string * ' msg properties * ' msg t list | LazyGen of string * ( unit -> ' msg t ) * ' msg t ref | Tagger of ( ' msg applicationCallbacks ref -> ' msg applicationCallbacks ref ) * ' msg t
let noNode = CommentNode " "
let comment s = CommentNode s
let text s = Text s
let fullnode namespace tagName key unique props vdoms = Node ( namespace , tagName , key , unique , props , vdoms )
let node ( ? namespace " " ) = tagName ( ? key " " ) = ( ? unique " " ) = props vdoms = fullnode namespace tagName key unique props vdoms
let lazyGen key fn = LazyGen ( key , fn , ref noNode )
let prop key value = RawProp ( key , value )
let onCB name key cb = Event ( name , EventHandlerCallback ( key , cb ) , ref None )
let onMsg name msg = Event ( name , EventHandlerMsg msg , ref None )
let attribute namespace key value = Attribute ( namespace , key , value )
let data key value = Data ( key , value )
let style key value = Style [ ( key , value ) ]
let styles s = Style s
let rec renderToHtmlString = function | CommentNode s -> " <!-- " ^ s ^ " " --> | Text s -> s | Node ( namespace , tagName , _key , _unique , props , vdoms ) -> let renderProp = function | NoProp -> " " | RawProp ( k , v ) -> String . concat " " [ " " ; k ; " " " ; =\ v ; " " " ] \ | Attribute ( _namespace , k , v ) -> String . concat " " [ " " ; k ; " " " ; =\ v ; " " " ] \ | Data ( k , v ) -> String . concat " " [ " data " ; - k ; " " " ; =\ v ; " " " ] \ | Event ( _ , _ , _ ) -> " " | Style s -> String . concat " " [ " style " " ; =\ String . concat " ; " ( List . map ( fun ( k , v ) -> String . concat " " [ k ; " " ; : v ; " ; " ] ) s ) ; " " " ] \ in String . concat " " [ " " < ; namespace ; if namespace = " " then " " else " " : ; tagName ; String . concat " " ( List . map ( fun p -> renderProp p ) props ) ; " " > ; String . concat " " ( List . map ( fun v -> renderToHtmlString v ) vdoms ) ; " " </ ; tagName ; " " > ] | LazyGen ( _key , gen , _cache ) -> let vdom = gen ( ) in renderToHtmlString vdom | Tagger ( _tagger , vdom ) -> renderToHtmlString vdom
let emptyEventHandler : Web . Node . event_cb = fun [ @ bs ] _ev -> ( )
let emptyEventCB = fun _ev -> None
let eventHandler callbacks cb : Web . Node . event_cb = fun [ @ bs ] ev -> match ! cb ev with | None -> ( ) | Some msg -> ! callbacks . enqueue msg
let eventHandler_GetCB = function | EventHandlerCallback ( _ , cb ) -> cb | EventHandlerMsg msg -> fun _ev -> Some msg
let compareEventHandlerTypes left = function | EventHandlerCallback ( cb , _ ) -> ( match left with | EventHandlerCallback ( lcb , _ ) when cb = lcb -> true | _ -> false ) | EventHandlerMsg msg -> ( match left with | EventHandlerMsg lmsg when msg = lmsg -> true | _ -> false )
let eventHandler_Register callbacks elem name handlerType = let cb = ref ( eventHandler_GetCB handlerType ) in let handler = eventHandler callbacks cb in let ( ) = Web . Node . addEventListener elem name handler false in Some { handler ; cb }
let eventHandler_Unregister elem name = function | None -> None | Some cache -> let ( ) = Web . Node . removeEventListener elem name cache . handler false in None
let eventHandler_Mutate callbacks elem ( oldName : string ) ( newName : string ) oldHandlerType newHandlerType oldCache newCache = match ! oldCache with | None -> newCache := eventHandler_Register callbacks elem newName newHandlerType | Some oldcache -> if oldName = newName then let ( ) = newCache := ! oldCache in if compareEventHandlerTypes oldHandlerType newHandlerType then ( ) else let cb = eventHandler_GetCB newHandlerType in let ( ) = oldcache . cb := cb in ( ) else let ( ) = oldCache := eventHandler_Unregister elem oldName ! oldCache in let ( ) = newCache := eventHandler_Register callbacks elem newName newHandlerType in ( )
let patchVNodesOnElems_PropertiesApply_Add callbacks elem _idx = function | NoProp -> ( ) | RawProp ( k , v ) -> Web . Node . setProp elem k v | Attribute ( namespace , k , v ) -> Web . Node . setAttributeNsOptional elem namespace k v | Data ( k , v ) -> Js . log ( " TODO : Add Data Unhandled " , k , v ) ; failwith " TODO : Add Data Unhandled " | Event ( name , handlerType , cache ) -> cache := eventHandler_Register callbacks elem name handlerType | Style s -> List . fold_left ( fun ( ) ( k , v ) -> Web . Node . setStyleProperty elem k ( Js . Null . return v ) ) ( ) s
let patchVNodesOnElems_PropertiesApply_Remove _callbacks elem _idx = function | NoProp -> ( ) | RawProp ( k , _v ) -> Web . Node . setProp elem k Js . Undefined . empty | Attribute ( namespace , k , _v ) -> Web . Node . removeAttributeNsOptional elem namespace k | Data ( k , v ) -> Js . log ( " TODO : Remove Data Unhandled " , k , v ) ; failwith " TODO : Remove Data Unhandled " | Event ( name , _ , cache ) -> cache := eventHandler_Unregister elem name ! cache | Style s -> List . fold_left ( fun ( ) ( k , _v ) -> Web . Node . setStyleProperty elem k Js . Null . empty ) ( ) s
let patchVNodesOnElems_PropertiesApply_RemoveAdd callbacks elem idx oldProp newProp = let ( ) = patchVNodesOnElems_PropertiesApply_Remove callbacks elem idx oldProp in let ( ) = patchVNodesOnElems_PropertiesApply_Add callbacks elem idx newProp in ( )
let patchVNodesOnElems_PropertiesApply_Mutate _callbacks elem _idx oldProp = function | NoProp as _newProp -> failwith " This should never be called as all entries through NoProp are gated . " | RawProp ( k , v ) as _newProp -> Web . Node . setProp elem k v | Attribute ( namespace , k , v ) as _newProp -> Web . Node . setAttributeNsOptional elem namespace k v | Data ( k , v ) as _newProp -> Js . log ( " TODO : Mutate Data Unhandled " , k , v ) ; failwith " TODO : Mutate Data Unhandled " | Event ( _newName , _newHandlerType , _newCache ) as _newProp -> failwith " This will never be called because it is gated " | Style s as _newProp -> match [ @ ocaml . warning " - 4 " ] oldProp with | Style oldS -> List . fold_left2 ( fun ( ) ( ok , ov ) ( nk , nv ) -> if ok = nk then if ov = nv then ( ) else Web . Node . setStyleProperty elem nk ( Js . Null . return nv ) else let ( ) = Web . Node . setStyleProperty elem ok Js . Null . empty in Web . Node . setStyleProperty elem nk ( Js . Null . return nv ) ) ( ) oldS s | _ -> failwith " Passed a non - Style to a new Style as a Mutations while the old Style is not actually a style " !
let rec patchVNodesOnElems_PropertiesApply callbacks elem idx oldProperties newProperties = match [ @ ocaml . warning " - 4 " ] oldProperties , newProperties with | [ ] , [ ] -> true | [ ] , _newProp :: _newRest -> false | _oldProp :: _oldRest , [ ] -> false | NoProp :: oldRest , NoProp :: newRest -> patchVNodesOnElems_PropertiesApply callbacks elem ( idx + 1 ) oldRest newRest | ( RawProp ( oldK , oldV ) as oldProp ) :: oldRest , ( RawProp ( newK , newV ) as newProp ) :: newRest -> let ( ) = if oldK = newK && oldV = newV then ( ) else patchVNodesOnElems_PropertiesApply_Mutate callbacks elem idx oldProp newProp in patchVNodesOnElems_PropertiesApply callbacks elem ( idx + 1 ) oldRest newRest | ( Attribute ( oldNS , oldK , oldV ) as oldProp ) :: oldRest , ( Attribute ( newNS , newK , newV ) as newProp ) :: newRest -> let ( ) = if oldNS = newNS && oldK = newK && oldV = newV then ( ) else patchVNodesOnElems_PropertiesApply_Mutate callbacks elem idx oldProp newProp in patchVNodesOnElems_PropertiesApply callbacks elem ( idx + 1 ) oldRest newRest | ( Data ( oldK , oldV ) as oldProp ) :: oldRest , ( Data ( newK , newV ) as newProp ) :: newRest -> let ( ) = if oldK = newK && oldV = newV then ( ) else patchVNodesOnElems_PropertiesApply_Mutate callbacks elem idx oldProp newProp in patchVNodesOnElems_PropertiesApply callbacks elem ( idx + 1 ) oldRest newRest | ( Event ( oldName , oldHandlerType , oldCache ) as _oldProp ) :: oldRest , ( Event ( newName , newHandlerType , newCache ) as _newProp ) :: newRest -> let ( ) = eventHandler_Mutate callbacks elem oldName newName oldHandlerType newHandlerType oldCache newCache in patchVNodesOnElems_PropertiesApply callbacks elem ( idx + 1 ) oldRest newRest | ( Style oldS as oldProp ) :: oldRest , ( Style newS as newProp ) :: newRest -> let ( ) = if oldS = newS then ( ) else patchVNodesOnElems_PropertiesApply_Mutate callbacks elem idx oldProp newProp in patchVNodesOnElems_PropertiesApply callbacks elem ( idx + 1 ) oldRest newRest | oldProp :: oldRest , newProp :: newRest -> let ( ) = patchVNodesOnElems_PropertiesApply_RemoveAdd callbacks elem idx oldProp newProp in patchVNodesOnElems_PropertiesApply callbacks elem ( idx + 1 ) oldRest newRest
let patchVNodesOnElems_Properties callbacks elem oldProperties newProperties = patchVNodesOnElems_PropertiesApply callbacks elem 0 oldProperties newProperties
let genEmptyProps length = let rec aux lst = function | 0 -> lst | len -> aux ( noProp :: lst ) ( len - 1 ) in aux [ ] length
let mapEmptyProps props = List . map ( fun _ -> noProp ) props
let rec patchVNodesOnElems_ReplaceNode callbacks elem elems idx = function [ @ ocaml . warning " - 4 " ] | ( Node ( newNamespace , newTagName , _newKey , _newUnique , newProperties , newChildren ) ) -> let oldChild = elems . ( idx ) in let newChild = Web . Document . createElementNsOptional newNamespace newTagName in let [ @ ocaml . warning " - 8 " ] true = patchVNodesOnElems_Properties callbacks newChild ( mapEmptyProps newProperties ) newProperties in let childChildren = Web . Node . childNodes newChild in let ( ) = patchVNodesOnElems callbacks newChild childChildren 0 [ ] newChildren in let _attachedChild = Web . Node . insertBefore elem newChild oldChild in let _removedChild = Web . Node . removeChild elem oldChild in ( ) | _ -> failwith " Node replacement should never be passed anything but a node itself " | CommentNode s -> Web . Document . createComment s | Text text -> Web . Document . createTextNode text | Node ( newNamespace , newTagName , _newKey , _unique , newProperties , newChildren ) -> let newChild = Web . Document . createElementNsOptional newNamespace newTagName in let [ @ ocaml . warning " - 8 " ] true = patchVNodesOnElems_Properties callbacks newChild ( mapEmptyProps newProperties ) newProperties in let childChildren = Web . Node . childNodes newChild in let ( ) = patchVNodesOnElems callbacks newChild childChildren 0 [ ] newChildren in newChild | LazyGen ( _newKey , newGen , newCache ) -> let vdom = newGen ( ) in let ( ) = newCache := vdom in patchVNodesOnElems_CreateElement callbacks vdom | Tagger ( tagger , vdom ) -> patchVNodesOnElems_CreateElement ( tagger callbacks ) vdom match ( oldNode , newNode ) with | ( ( Node ( _oldNamespace , oldTagName , _oldKey , oldUnique , oldProperties , oldChildren ) as _oldNode ) , ( Node ( _newNamespace , newTagName , _newKey , newUnique , newProperties , newChildren ) as newNode ) ) -> if oldUnique <> newUnique || oldTagName <> newTagName then patchVNodesOnElems_ReplaceNode callbacks elem elems idx newNode else let child = elems . ( idx ) in let childChildren = Web . Node . childNodes child in let ( ) = if patchVNodesOnElems_Properties callbacks child oldProperties newProperties then ( ) else let ( ) = Js . log " VDom : Failed swapping properties because the property list length changed , use ` noProp ` to swap properties instead , not by altering the list structure . This is a massive inefficiency until this issue is resolved . " in patchVNodesOnElems_ReplaceNode callbacks elem elems idx newNode in patchVNodesOnElems callbacks child childChildren 0 oldChildren newChildren | _ -> failwith " Non - node passed to patchVNodesOnElems_MutateNode " match [ @ ocaml . warning " - 4 " ] oldVNodes , newVNodes with | Tagger ( _oldTagger , oldVdom ) :: oldRest , _ -> patchVNodesOnElems callbacks elem elems idx ( oldVdom :: oldRest ) newVNodes | oldNode :: oldRest , Tagger ( newTagger , newVdom ) :: newRest -> let ( ) = patchVNodesOnElems ( newTagger callbacks ) elem elems idx [ oldNode ] [ newVdom ] in patchVNodesOnElems callbacks elem elems ( idx + 1 ) oldRest newRest | [ ] , [ ] -> ( ) | [ ] , newNode :: newRest -> let newChild = patchVNodesOnElems_CreateElement callbacks newNode in let _attachedChild = Web . Node . appendChild elem newChild in patchVNodesOnElems callbacks elem elems ( idx + 1 ) [ ] newRest | _oldVnode :: oldRest , [ ] -> let child = elems . ( idx ) in let _removedChild = Web . Node . removeChild elem child in patchVNodesOnElems callbacks elem elems idx oldRest [ ] | CommentNode oldS :: oldRest , CommentNode newS :: newRest when oldS = newS -> patchVNodesOnElems callbacks elem elems ( idx + 1 ) oldRest newRest | Text oldText :: oldRest , Text newText :: newRest -> let ( ) = if oldText = newText then ( ) else let child = elems . ( idx ) in Web . Node . set_nodeValue child newText in patchVNodesOnElems callbacks elem elems ( idx + 1 ) oldRest newRest | LazyGen ( oldKey , _oldGen , oldCache ) :: oldRest , LazyGen ( newKey , newGen , newCache ) :: newRest -> if oldKey = newKey then let ( ) = newCache := ! oldCache in patchVNodesOnElems callbacks elem elems ( idx + 1 ) oldRest newRest else ( match oldRest , newRest with | LazyGen ( olderKey , _olderGen , _olderCache ) :: olderRest , LazyGen ( newerKey , _newerGen , _newerCache ) :: newerRest when olderKey = newKey && oldKey = newerKey -> let firstChild = elems . ( idx ) in let secondChild = elems . ( idx + 1 ) in let _removedChild = Web . Node . removeChild elem secondChild in let _attachedChild = Web . Node . insertBefore elem secondChild firstChild in patchVNodesOnElems callbacks elem elems ( idx + 2 ) olderRest newerRest | LazyGen ( olderKey , _olderGen , olderCache ) :: olderRest , _ when olderKey = newKey -> let oldChild = elems . ( idx ) in let _removedChild = Web . Node . removeChild elem oldChild in let oldVdom = ! olderCache in let ( ) = newCache := oldVdom in patchVNodesOnElems callbacks elem elems ( idx + 1 ) olderRest newRest | _ , LazyGen ( newerKey , _newerGen , _newerCache ) :: _newerRest when newerKey = oldKey -> let oldChild = elems . ( idx ) in let newVdom = newGen ( ) in let ( ) = newCache := newVdom in let newChild = patchVNodesOnElems_CreateElement callbacks newVdom in let _attachedChild = Web . Node . insertBefore elem newChild oldChild in patchVNodesOnElems callbacks elem elems ( idx + 1 ) oldVNodes newRest | _ -> let oldVdom = ! oldCache in let newVdom = newGen ( ) in let ( ) = newCache := newVdom in patchVNodesOnElems callbacks elem elems idx ( oldVdom :: oldRest ) ( newVdom :: newRest ) ) | ( Node ( oldNamespace , oldTagName , oldKey , _oldUnique , _oldProperties , _oldChildren ) as oldNode ) :: oldRest , ( Node ( newNamespace , newTagName , newKey , _newUnique , _newProperties , _newChildren ) as newNode ) :: newRest -> if oldKey = newKey && oldKey <> " " then patchVNodesOnElems callbacks elem elems ( idx + 1 ) oldRest newRest else if oldKey = " " || newKey = " " then let ( ) = patchVNodesOnElems_MutateNode callbacks elem elems idx oldNode newNode in patchVNodesOnElems callbacks elem elems ( idx + 1 ) oldRest newRest else ( match oldRest , newRest with | Node ( olderNamespace , olderTagName , olderKey , _olderUnique , _olderProperties , _olderChildren ) :: olderRest , Node ( newerNamespace , newerTagName , newerKey , _newerUnique , _newerProperties , _newerChildren ) :: newerRest when olderNamespace = newNamespace && olderTagName = newTagName && olderKey = newKey && oldNamespace = newerNamespace && oldTagName = newerTagName && oldKey = newerKey -> let firstChild = elems . ( idx ) in let secondChild = elems . ( idx + 1 ) in let _removedChild = Web . Node . removeChild elem secondChild in let _attachedChild = Web . Node . insertBefore elem secondChild firstChild in patchVNodesOnElems callbacks elem elems ( idx + 2 ) olderRest newerRest | Node ( olderNamespace , olderTagName , olderKey , _olderUnique , _olderProperties , _olderChildren ) :: olderRest , _ when olderNamespace = newNamespace && olderTagName = newTagName && olderKey = newKey -> let oldChild = elems . ( idx ) in let _removedChild = Web . Node . removeChild elem oldChild in patchVNodesOnElems callbacks elem elems ( idx + 1 ) olderRest newRest | _ , Node ( newerNamespace , newerTagName , newerKey , _newerUnique , _newerProperties , _newerChildren ) :: _newerRest when oldNamespace = newerNamespace && oldTagName = newerTagName && oldKey = newerKey -> let oldChild = elems . ( idx ) in let newChild = patchVNodesOnElems_CreateElement callbacks newNode in let _attachedChild = Web . Node . insertBefore elem newChild oldChild in patchVNodesOnElems callbacks elem elems ( idx + 1 ) oldVNodes newRest | _ -> let ( ) = patchVNodesOnElems_MutateNode callbacks elem elems idx oldNode newNode in patchVNodesOnElems callbacks elem elems ( idx + 1 ) oldRest newRest ) | _oldVnode :: oldRest , newNode :: newRest -> let oldChild = elems . ( idx ) in let newChild = patchVNodesOnElems_CreateElement callbacks newNode in let _attachedChild = Web . Node . insertBefore elem newChild oldChild in let _removedChild = Web . Node . removeChild elem oldChild in patchVNodesOnElems callbacks elem elems ( idx + 1 ) oldRest newRest
let patchVNodesIntoElement callbacks elem oldVNodes newVNodes = let elems = Web . Node . childNodes elem in let ( ) = patchVNodesOnElems callbacks elem elems 0 oldVNodes newVNodes in newVNodes
let patchVNodeIntoElement callbacks elem oldVNode newVNode = patchVNodesIntoElement callbacks elem [ oldVNode ] [ newVNode ]
let wrapCallbacks func callbacks = ref { enqueue = ( fun msg -> ! callbacks . enqueue ( func msg ) ) }
let map : ( ' a -> ' b ) -> ' a t -> ' b t = fun func vdom -> let tagger callbacks = ref { enqueue = ( fun msg -> ! callbacks . enqueue ( func msg ) ) } in Tagger ( Obj . magic tagger , Obj . magic vdom )
module Cmd = struct type ' msg ctx = { send_msg : ( ' msg -> unit ) unit ; } let send_msg ctx = ctx . send_msg type handler = { f : ' msg . ' msg ctx -> ' msg Vdom . Cmd . t -> bool } bool let rec run : type t . handler list -> ( t -> unit ) unit -> t Cmd . t -> unit = fun h p -> function | Cmd . Echo msg -> p msg | Cmd . Batch l -> List . iter ( run h p ) p l | Cmd . Map ( f , cmd ) cmd -> run h ( fun x -> p ( f x ) x ) x cmd | x -> let ctx = { send_msg = p } p in let rec loop = function | [ ] -> failwith ( Printf . sprintf " No command handler found ! ( % s ) s " ( Obj . Extension_constructor . name ( Obj . Extension_constructor . of_val x ) x ) x ) x | hd :: tl -> if hd . f ctx x then ( ) else loop tl in loop h end