text
stringlengths 0
601k
|
---|
let is_active x = not ! disabled && ( ! current ) . active . ( number x ) |
let is_error x = not ! disabled && ( ! current ) . error . ( number x ) |
let alert_is_active { kind ; _ } = not ! disabled && let ( set , pos ) = ( ! current ) . alerts in Misc . Stdlib . String . Set . mem kind set = pos |
let alert_is_error { kind ; _ } = not ! disabled && let ( set , pos ) = ( ! current ) . alert_errors in Misc . Stdlib . String . Set . mem kind set = pos |
let mk_lazy f = let state = backup ( ) in lazy ( let prev = backup ( ) in restore state ; try let r = f ( ) in restore prev ; r with exn -> restore prev ; raise exn ) |
let set_alert ~ error ~ enable s = let upd = match s with | " all " -> ( Misc . Stdlib . String . Set . empty , not enable ) | s -> let ( set , pos ) = if error then ( ! current ) . alert_errors else ( ! current ) . alerts in let f = if enable = pos then Misc . Stdlib . String . Set . add else Misc . Stdlib . String . Set . remove in ( f s set , pos ) in if error then current := { ( ! current ) with alert_errors = upd } else current := { ( ! current ) with alerts = upd } |
let parse_alert_option s = let n = String . length s in let id_char = function | ' a ' . . ' z ' | ' A ' . . ' Z ' | ' _ ' | ' ' ' \ | ' 0 ' . . ' 9 ' -> true | _ -> false in let rec parse_id i = if i < n && id_char s . [ i ] then parse_id ( i + 1 ) else i in let rec scan i = if i = n then ( ) else if i + 1 = n then raise ( Arg . Bad " Ill - formed list of alert settings " ) else match s . [ i ] , s . [ i + 1 ] with | ' ' , + ' ' + -> id ( set_alert ~ error : true ~ enable : true ) ( i + 2 ) | ' ' , + _ -> id ( set_alert ~ error : false ~ enable : true ) ( i + 1 ) | ' ' , - ' ' - -> id ( set_alert ~ error : true ~ enable : false ) ( i + 2 ) | ' ' , - _ -> id ( set_alert ~ error : false ~ enable : false ) ( i + 1 ) | ' ' , @ _ -> id ( fun s -> set_alert ~ error : true ~ enable : true s ; set_alert ~ error : false ~ enable : true s ) ( i + 1 ) | _ -> raise ( Arg . Bad " Ill - formed list of alert settings " ) and id f i = let j = parse_id i in if j = i then raise ( Arg . Bad " Ill - formed list of alert settings " ) ; let id = String . sub s i ( j - i ) in f id ; scan j in scan 0 |
let parse_opt error active errflag s = let flags = if errflag then error else active in let set i = if i = 3 then set_alert ~ error : errflag ~ enable : true " deprecated " else flags . ( i ) <- true in let clear i = if i = 3 then set_alert ~ error : errflag ~ enable : false " deprecated " else flags . ( i ) <- false in let set_all i = if i = 3 then begin set_alert ~ error : false ~ enable : true " deprecated " ; set_alert ~ error : true ~ enable : true " deprecated " end else begin active . ( i ) <- true ; error . ( i ) <- true end in let error ( ) = raise ( Arg . Bad " Ill - formed list of warnings " ) in let rec get_num n i = if i >= String . length s then i , n else match s . [ i ] with | ' 0 ' . . ' 9 ' -> get_num ( 10 * n + Char . code s . [ i ] - Char . code ' 0 ' ) ( i + 1 ) | _ -> i , n in let get_range i = let i , n1 = get_num 0 i in if i + 2 < String . length s && s . [ i ] = ' . ' && s . [ i + 1 ] = ' . ' then let i , n2 = get_num 0 ( i + 2 ) in if n2 < n1 then error ( ) ; i , n1 , n2 else i , n1 , n1 in let rec loop i = if i >= String . length s then ( ) else match s . [ i ] with | ' A ' . . ' Z ' -> List . iter set ( letter ( Char . lowercase_ascii s . [ i ] ) ) ; loop ( i + 1 ) | ' a ' . . ' z ' -> List . iter clear ( letter s . [ i ] ) ; loop ( i + 1 ) | ' ' + -> loop_letter_num set ( i + 1 ) | ' ' - -> loop_letter_num clear ( i + 1 ) | ' ' @ -> loop_letter_num set_all ( i + 1 ) | _ -> error ( ) and loop_letter_num myset i = if i >= String . length s then error ( ) else match s . [ i ] with | ' 0 ' . . ' 9 ' -> let i , n1 , n2 = get_range i in for n = n1 to min n2 last_warning_number do myset n done ; loop i | ' A ' . . ' Z ' -> List . iter myset ( letter ( Char . lowercase_ascii s . [ i ] ) ) ; loop ( i + 1 ) | ' a ' . . ' z ' -> List . iter myset ( letter s . [ i ] ) ; loop ( i + 1 ) | _ -> error ( ) in loop 0 ; ; |
let parse_options errflag s = let error = Array . copy ( ! current ) . error in let active = Array . copy ( ! current ) . active in parse_opt error active errflag s ; current := { ( ! current ) with error ; active } |
let ( ) = parse_options false defaults_w ; ; |
let ( ) = parse_options true defaults_warn_error ; ; |
let ref_manual_explanation ( ) = let [ @ manual . ref " s : comp - warnings " ] chapter , section = 9 , 5 in Printf . sprintf " ( See manual section % d . % d ) " chapter section |
let message = function | Comment_start -> " this ` let sub_locs = if not alert . def . loc_ghost && not alert . use . loc_ghost then [ alert . def , " Definition " ; alert . use , " Expected signature " ; ] else [ ] in ` Active { id = alert . kind ; message ; is_error ; sub_locs ; } |
let reset_fatal ( ) = nerrors := 0 |
let check_fatal ( ) = if ! nerrors > 0 then begin nerrors := 0 ; raise Errors ; end ; ; ; |
let descriptions = [ 1 , " Suspicious - looking start - of - comment mark . " ; 2 , " Suspicious - looking end - of - comment mark . " ; 3 , " Deprecated synonym for the ' deprecated ' alert " ; 4 , " Fragile pattern matching : matching that will remain complete even \ n \ \ if additional constructors are added to one of the variant types \ n \ \ matched . " ; 5 , " Partially applied function : expression whose result has function \ n \ \ type and is ignored . " ; 6 , " Label omitted in function application . " ; 7 , " Method overridden . " ; 8 , " Partial match : missing cases in pattern - matching . " ; 9 , " Missing fields in a record pattern . " ; 10 , " Expression on the left - hand side of a sequence that doesn ' t have \ type \ n \ \ " \ unit " \ ( and that is not a function , see warning number 5 ) . " ; 11 , " Redundant case in a pattern matching ( unused match case ) . " ; 12 , " Redundant sub - pattern in a pattern - matching . " ; 13 , " Instance variable overridden . " ; 14 , " Illegal backslash escape in a string constant . " ; 15 , " Private method made public implicitly . " ; 16 , " Unerasable optional argument . " ; 17 , " Undeclared virtual method . " ; 18 , " Non - principal type . " ; 19 , " Type without principality . " ; 20 , " Unused function argument . " ; 21 , " Non - returning statement . " ; 22 , " Preprocessor warning . " ; 23 , " Useless record " \ with " \ clause . " ; 24 , " Bad module name : the source file name is not a valid OCaml module \ name . " ; 25 , " Deprecated : now part of warning 8 . " ; 26 , " Suspicious unused variable : unused variable that is bound \ n \ \ with " \ let " \ or " \ as " , \ and doesn ' t start with an underscore ( " \ _ " ) \\ n \ \ character . " ; 27 , " Innocuous unused variable : unused variable that is not bound with \ n \ \ " \ let " \ nor " \ as " , \ and doesn ' t start with an underscore ( " \ _ " ) \\ n \ \ character . " ; 28 , " Wildcard pattern given as argument to a constant constructor . " ; 29 , " Unescaped end - of - line in a string constant ( non - portable code ) . " ; 30 , " Two labels or constructors of the same name are defined in two \ n \ \ mutually recursive types . " ; 31 , " A module is linked twice in the same executable . " ; 32 , " Unused value declaration . " ; 33 , " Unused open statement . " ; 34 , " Unused type declaration . " ; 35 , " Unused for - loop index . " ; 36 , " Unused ancestor variable . " ; 37 , " Unused constructor . " ; 38 , " Unused extension constructor . " ; 39 , " Unused rec flag . " ; 40 , " Constructor or label name used out of scope . " ; 41 , " Ambiguous constructor or label name . " ; 42 , " Disambiguated constructor or label name ( compatibility warning ) . " ; 43 , " Nonoptional label applied as optional . " ; 44 , " Open statement shadows an already defined identifier . " ; 45 , " Open statement shadows an already defined label or constructor . " ; 46 , " Error in environment variable . " ; 47 , " Illegal attribute payload . " ; 48 , " Implicit elimination of optional arguments . " ; 49 , " Absent cmi file when looking up module alias . " ; 50 , " Unexpected documentation comment . " ; 51 , " Warning on non - tail calls if @ tailcall present . " ; 52 , " Fragile constant pattern . " ; 53 , " Attribute cannot appear in this context " ; 54 , " Attribute used more than once on an expression " ; 55 , " Inlining impossible " ; 56 , " Unreachable case in a pattern - matching ( based on type information ) . " ; 57 , " Ambiguous or - pattern variables under guard " ; 58 , " Missing cmx file " ; 59 , " Assignment to non - mutable value " ; 60 , " Unused module declaration " ; 61 , " Unboxable type in primitive declaration " ; 62 , " Type constraint on GADT type declaration " ; 63 , " Erroneous printed signature " ; 64 , " - unsafe used with a preprocessor returning a syntax tree " ; 65 , " Type declaration defining a new ' ( ) ' constructor " ; 66 , " Unused open ! statement " ; 67 , " Dependency on a module compiled without lto " ; ] ; ; |
let help_warnings ( ) = List . iter ( fun ( i , s ) -> Printf . printf " % 3i % s \ n " i s ) descriptions ; print_endline " A all warnings " ; for i = Char . code ' b ' to Char . code ' z ' do let c = Char . chr i in match letter c with | [ ] -> ( ) | [ n ] -> Printf . printf " % c Alias for warning % i . \ n " ( Char . uppercase_ascii c ) n | l -> Printf . printf " % c warnings % s . \ n " ( Char . uppercase_ascii c ) ( String . concat " , " ( List . map Int . to_string l ) ) done ; exit 0 ; ; |
let err = T . err Warp_error |
type resample_t = | Nearest_neighbor | Bilinear | Cubic | Cubic_spline | Lanczos |
let int_of_resample = function | Nearest_neighbor -> 0 | Bilinear -> 1 | Cubic -> 2 | Cubic_spline -> 3 | Lanczos -> 4 |
module Options = struct module Raw = struct type warp_options_t type t = warp_options_t structure ptr let t : warp_options_t structure typ = structure " GDALWarpOptions " let f n k = field t n k let warp_options = f " warp_options " ( ptr string_opt ) let memory_limit = f " memory_limit " double let resample_alg = f " resample_alg " int let data_type = f " data_type " int let src_ds = f " src_ds " Data_set . t let dst_ds = f " dst_ds " Data_set . t let band_count = f " band_count " int let src_bands = f " src_bands " ( ptr int ) let dst_bands = f " dst_bands " ( ptr int ) let _src_alpha_band = f " src_alpha_band " int let _dst_alpha_band = f " dst_alpha_band " int let src_no_data_real = f " src_no_data_real " ( ptr_opt double ) let src_no_data_imag = f " src_no_data_imag " ( ptr_opt double ) let dst_no_data_real = f " dst_no_data_real " ( ptr_opt double ) let dst_no_data_imag = f " dst_no_data_imag " ( ptr_opt double ) let _progress = f " progress " ( ptr void ) let _progress_arg = f " progress_arg " ( ptr void ) let transformer = f " transformer " ( Foreign . funptr ( Transform . transform_t ( ptr void ) ) ) let transformer_arg = f " transformer_arg " ( ptr void ) let _src_per_band_validity_mask_func = f " src_per_band_validity_mask_func " ( ptr void ) let _src_per_band_validity_mask_func_arg = f " src_per_band_validity_mask_func_arg " ( ptr ( ptr void ) ) let _src_validity_mask_func = f " src_validity_mask_func " ( ptr void ) let _src_validity_mask_func_arg = f " src_validity_mask_func_arg " ( ptr void ) let _src_density_mask_func = f " src_density_mask_func " ( ptr void ) let _src_density_mask_func_arg = f " src_density_mask_func_arg " ( ptr void ) let _dst_density_mask_func = f " dst_density_mask_func " ( ptr void ) let _dst_density_mask_func_arg = f " dst_density_mask_func_arg " ( ptr void ) let _dst_validity_mask_func = f " dst_validity_mask_func " ( ptr void ) let _dst_validity_mask_func_arg = f " dst_validity_mask_func_arg " ( ptr void ) let _pre_warp_chunk_processor = f " pre_warp_chunk_processor " ( ptr void ) let _pre_warp_chunk_processor_arg = f " pre_warp_chunk_processor_arg " ( ptr void ) let _post_warp_chunk_processor = f " post_warp_chunk_processor " ( ptr void ) let _post_warp_chunk_processor_arg = f " post_warp_chunk_processor_arg " ( ptr void ) let _cutline = f " cutline " ( ptr void ) let _cutline_blend_dist = f " cutline_blend_dist " double let ( ) = seal t let create = Lib . c " GDALCreateWarpOptions " ( void @-> returning ( ptr t ) ) let clone = Lib . c " GDALCloneWarpOptions " ( ptr t @-> returning ( ptr t ) ) let delete = Lib . c " free " ( ptr t @-> returning void ) let create ( ) = let o = create ( ) in Gc . finalise delete o ; o end exception Band_count_mismatch type ' a t = { o : Raw . t ; mutable options : string option Ctypes . CArray . t option ; mutable src_bands : ( int , Bigarray . int_elt , Bigarray . c_layout ) Bigarray . Array1 . t option ; mutable dst_bands : ( int , Bigarray . int_elt , Bigarray . c_layout ) Bigarray . Array1 . t option ; mutable src_no_data_real : ( float , Bigarray . float64_elt , Bigarray . c_layout ) Bigarray . Array1 . t option ; mutable src_no_data_imag : ( float , Bigarray . float64_elt , Bigarray . c_layout ) Bigarray . Array1 . t option ; mutable dst_no_data_real : ( float , Bigarray . float64_elt , Bigarray . c_layout ) Bigarray . Array1 . t option ; mutable dst_no_data_imag : ( float , Bigarray . float64_elt , Bigarray . c_layout ) Bigarray . Array1 . t option ; } let set_warp_options o options = let options = Lib . convert_creation_options options in setf ( !@ o . o ) Raw . warp_options ( Lib . creation_options_to_ptr options ) ; o . options <- options ; ( ) let set_memory_limit { o ; _ } l = setf !@ o Raw . memory_limit l ; ( ) let set_resample_alg { o ; _ } a = let i = int_of_resample a in setf !@ o Raw . resample_alg i ; ( ) let set_working_data_type { o ; _ } t = let i = Band . Data . to_int t in setf !@ o Raw . data_type i ; ( ) let set_src { o ; _ } ds = setf !@ o Raw . src_ds ds ; ( ) let set_dst { o ; _ } ds = setf !@ o Raw . dst_ds ds ; ( ) let set_bands o bands = let src = List . map fst bands |> Array . of_list in let dst = List . map snd bands |> Array . of_list in let open Bigarray in let src = Array1 . of_array int c_layout src in let dst = Array1 . of_array int c_layout dst in let n = Array1 . dim src in setf ( !@ o . o ) Raw . band_count n ; setf ( !@ o . o ) Raw . src_bands ( bigarray_start array1 src ) ; setf ( !@ o . o ) Raw . dst_bands ( bigarray_start array1 dst ) ; o . src_bands <- Some src ; o . dst_bands <- Some dst ; ( ) let ptr_opt_of_list = function | [ ] -> None | l -> let a = Array . of_list l |> Bigarray . ( Array1 . of_array float64 c_layout ) in Some a let set_band_dep o l f = let bands = getf ( !@ o . o ) Raw . band_count in let n = List . length l in if n > 0 && n <> bands then raise Band_count_mismatch ; match ptr_opt_of_list l with | None -> setf ( !@ o . o ) f None ; None | Some ca -> let p = bigarray_start array1 ca in setf ( !@ o . o ) f ( Some p ) ; Some ca let set_src_no_data_real o l = let ca = set_band_dep o l Raw . src_no_data_real in o . src_no_data_real <- ca let set_src_no_data_imag o l = let ca = set_band_dep o l Raw . src_no_data_imag in o . src_no_data_imag <- ca let set_dst_no_data_real o l = let ca = set_band_dep o l Raw . dst_no_data_real in o . dst_no_data_real <- ca let set_dst_no_data_imag o l = let ca = set_band_dep o l Raw . dst_no_data_imag in o . dst_no_data_imag <- ca let set_transformer { o ; _ } transform = let c = Transform . get_transform_c transform in let arg = Transform . get_transform_t transform in setf !@ o Raw . transformer c ; setf !@ o Raw . transformer_arg arg ; ( ) let may f o = match o with | None -> ( ) | Some x -> f x let create ( ) = let o = Raw . create ( ) in { o ; options = None ; src_bands = None ; dst_bands = None ; src_no_data_real = None ; src_no_data_imag = None ; dst_no_data_real = None ; dst_no_data_imag = None ; } let make ? warp_options ? memory_limit ? resample_alg ? working_data_type ? src ? dst ? bands ? src_no_data_real ? src_no_data_imag ? dst_no_data_real ? dst_no_data_imag ? transformer ( ) = let o = create ( ) in let mayo f x = may ( f o ) x in mayo set_warp_options warp_options ; mayo set_memory_limit memory_limit ; mayo set_resample_alg resample_alg ; mayo set_working_data_type working_data_type ; mayo set_src src ; mayo set_dst dst ; mayo set_bands bands ; mayo set_src_no_data_real src_no_data_real ; mayo set_src_no_data_imag src_no_data_imag ; mayo set_dst_no_data_real dst_no_data_real ; mayo set_dst_no_data_imag dst_no_data_imag ; mayo set_transformer transformer ; o let clone o = { o with o = Raw . clone o . o } end |
let reproject_image = Lib . c " GDALReprojectImage " ( Data_set . t @-> string_opt @-> Data_set . t @-> string_opt @-> int @-> double @-> double @-> ptr void @-> ptr void @-> ptr Options . Raw . t @-> returning err ) |
let reproject_image ( ? memory_limit = 0 . 0 ) ( ? max_error = 0 . 0 ) ? options ? src_wkt ? dst_wkt ~ src ~ dst alg = let options = match options with | None -> from_voidp Options . Raw . t null | Some { Options . o ; _ } -> o in reproject_image src src_wkt dst dst_wkt ( int_of_resample alg ) memory_limit max_error null null options |
let create_and_reproject_image = Lib . c " GDALCreateAndReprojectImage " ( Data_set . t @-> string_opt @-> string @-> string_opt @-> Driver . t @-> ptr string_opt @-> int @-> double @-> double @-> ptr void @-> ptr void @-> ptr Options . Raw . t @-> returning err ) |
let create_and_reproject_image ( ? memory_limit = 0 . 0 ) ( ? max_error = 0 . 0 ) ? options ? src_wkt ? dst_wkt ( ? create_options = [ ] ) src ~ filename driver alg = let options = match options with | None -> from_voidp Options . Raw . t null | Some { Options . o ; _ } -> o in let create_options = Lib . convert_creation_options create_options in create_and_reproject_image src src_wkt filename dst_wkt driver ( Lib . creation_options_to_ptr create_options ) ( int_of_resample alg ) memory_limit max_error null null options |
let auto_create_warped_vrt = Lib . c " GDALAutoCreateWarpedVRT " ( Data_set . t @-> string_opt @-> string_opt @-> int @-> float @-> ptr Options . Raw . t @-> returning Data_set . t_opt ) |
let auto_create_warped_vrt ? src_wkt ? dst_wkt ( ? max_error = 0 . 0 ) ? options src alg = let options = match options with | None -> from_voidp Options . Raw . t null | Some { Options . o ; _ } -> o in let result = auto_create_warped_vrt src src_wkt dst_wkt ( int_of_resample alg ) max_error options in match result with | Some ds -> ds | None -> raise Warp_error |
type warp_output_t = { geo_transform : Geo_transform . t ; dims : int * int ; } |
let suggested_warp_output arg = Lib . c " GDALSuggestedWarpOutput " ( Data_set . t @-> Foreign . funptr ( Transform . transform_t arg ) @-> arg @-> ptr double @-> ptr int @-> ptr int @-> returning err ) |
let suggested_warp_output ds transform = let transform_t = Transform . get_transform_t transform in let transform_f = Transform . get_transform_c transform in let geo_transform = Geo_transform . make ~ origin ( : 0 . 0 , 0 . 0 ) ~ pixel_size ( : 0 . 0 , 0 . 0 ) ~ rotation ( : 0 . 0 , 0 . 0 ) in let pixels = allocate_n int ~ count : 1 in let lines = allocate_n int ~ count : 1 in suggested_warp_output ( ptr void ) ds transform_f transform_t ( let open Bigarray in bigarray_start array1 ( geo_transform :> ( float , float64_elt , c_layout ) Array1 . t ) ) pixels lines ; { geo_transform ; dims = !@ pixels , !@ lines } |
module Operation = struct type raw_t = T . t let t = T . t type ' a t = { t : raw_t ; options : ' a Options . t ; } let create = Lib . c " GDALCreateWarpOperation " ( ptr Options . Raw . t @-> returning t ) let destroy = Lib . c " GDALDestroyWarpOperation " ( t @-> returning void ) let create options = let result = create Options . ( options . o ) in if result = null then raise Warp_error else ( Gc . finalise destroy result ; { t = result ; options } ) let chunk_and_warp_image = Lib . c " GDALChunkAndWarpImage " ( t @-> int @-> int @-> int @-> int @-> returning err ) let chunk_and_warp_image t ~ offset ~ size = chunk_and_warp_image t . t ( fst offset ) ( snd offset ) ( fst size ) ( snd size ) let chunk_and_warp_multi = Lib . c " GDALChunkAndWarpMulti " ( t @-> int @-> int @-> int @-> int @-> returning err ) let chunk_and_warp_multi t ~ offset ~ size = chunk_and_warp_multi t . t ( fst offset ) ( snd offset ) ( fst size ) ( snd size ) let warp_region = Lib . c " GDALWarpRegion " ( t @-> int @-> int @-> int @-> int @-> int @-> int @-> int @-> int @-> returning err ) let warp_region t ~ dst_offset ~ dst_size ~ src_offset ~ src_size = let dox , doy = dst_offset in let dsx , dsy = dst_size in let sox , soy = src_offset in let ssx , ssy = src_size in warp_region t . t dox doy dsx dsy sox soy ssx ssy let warp_region_to_buffer = Lib . c " GDALWarpRegionToBuffer " ( t @-> int @-> int @-> int @-> int @-> ptr void @-> int @-> int @-> int @-> int @-> int @-> returning err ) let warp_region_to_buffer ? buffer t dt ~ dst_offset ~ dst_size ~ src_offset ~ src_size = let open Bigarray in let dox , doy = dst_offset in let dsx , dsy = dst_size in let sox , soy = src_offset in let ssx , ssy = src_size in let buffer = match buffer with | Some b -> let rows = Array2 . dim1 b in let cols = Array2 . dim2 b in if cols < dox + dsx || rows < doy + dsy then invalid_arg " Buffer is too small " else b | None -> let kind = Band . Data . to_ba_kind dt in Array2 . create kind c_layout ( doy + dsy ) ( dox + dsx ) in let buffer_ptr = bigarray_start array2 buffer in let dt_i = Band . Data . to_int dt in warp_region_to_buffer t . t dox doy dsx dsy ( to_voidp buffer_ptr ) dt_i sox soy ssx ssy ; buffer let wrap ? offset ? size options f = let offset = match offset with | Some o -> o | None -> 0 , 0 in let size = match size with | Some s -> s | None -> let ds = getf !@ Options . ( options . o ) Options . Raw . dst_ds in Data_set . get_x_size ds , Data_set . get_y_size ds in let operation = create options in f operation ~ offset ~ size let warp ? offset ? size options = wrap ? offset ? size options chunk_and_warp_image let warp_multi ? offset ? size options = wrap ? offset ? size options chunk_and_warp_multi end |
let init ( ) = Gdal . Lib . init_dynamic ( ) ; Gdal . Lib . register_all ( ) ; ( ) |
let usage_and_exit ( ) = prerr_endline " Usage : warptut [ src ] [ dst ] " ; prerr_endline " [ src ] must exist " ; prerr_endline " [ dst ] must not exist " ; exit 1 |
let parse_args ( ) = try let s = Sys . argv . ( 1 ) in let d = Sys . argv . ( 2 ) in if Sys . file_exists s && not ( Sys . file_exists d ) then s , d else raise Exit with | _ -> usage_and_exit ( ) |
let ( ) = init ( ) ; let src_file , dst_file = parse_args ( ) in let src_ds = Gdal . Data_set . of_source_exn src_file in let dst_bands = Gdal . Data_set . get_count src_ds in let dst_dt = Gdal . Band . Data . Float32 in let driver = Gdal . Driver . get_by_name_exn " GTiff " in let dst_sr = Gdal . Spatial_reference . make ` name " WGS84 " in let dst_wkt = Gdal . Spatial_reference . to_wkt dst_sr in let transform = Gdal . Transform . make_gen_img @@ ` data_set_wkt ( src_ds , dst_wkt ) in let warp_suggestions = Gdal . Warp . suggested_warp_output src_ds transform in Gdal . Transform . set_dst_geo_transform transform warp_suggestions . Gdal . Warp . geo_transform ; let dst_ds = Gdal . Data_set . create_exn ~ bands ( : dst_bands , dst_dt ) driver dst_file warp_suggestions . Gdal . Warp . dims in Gdal . Data_set . set_projection dst_ds dst_wkt ; Gdal . Geo_transform . set dst_ds warp_suggestions . Gdal . Warp . geo_transform ; let bands = Array . init dst_bands ( fun i -> i + 1 , i + 1 ) |> Array . to_list in let warp_options = Gdal . Warp . Options . make ~ resample_alg : Gdal . Warp . Nearest_neighbor ~ src : src_ds ~ dst : dst_ds ~ bands ~ transformer : transform ( ) in Gdal . Warp . Operation . warp warp_options ; Gdal . Data_set . close src_ds ; Gdal . Data_set . close dst_ds ; ( ) |
let rec highest_timestamp ( ? highest = 0 . ) folders = match folders with | [ ] -> highest | file :: rest -> ( let is_dir = Sys . is_directory file in match is_dir with | ` Yes -> let inside_dirs = Sys . ls_dir file in let inside_dirs = List . map inside_dirs ~ f ( : fun x -> file ^ " " / ^ x ) in highest_timestamp ~ highest ( inside_dirs @ rest ) | _ -> let stat = Unix . stat file in let modif_time = stat . st_mtime in let highest = if Float . ( modif_time > highest ) then modif_time else highest in highest_timestamp ~ highest rest ) |
let rec has_changed ( last_change : float ) ( folders : string list ) : float option = match folders with | [ ] -> None | file :: rest -> ( let is_dir = Sys . is_directory file in match is_dir with | ` Yes -> let inside_dirs = Sys . ls_dir file in let inside_dirs = List . map inside_dirs ~ f ( : fun x -> file ^ " " / ^ x ) in has_changed last_change ( inside_dirs @ rest ) | _ -> let stat = Unix . stat file in let modif_time = stat . st_mtime in if Float . ( modif_time > last_change ) then Some modif_time else has_changed last_change rest ) |
let rec watch last_timestamp path ~ f = Unix . sleep 1 ; match has_changed last_timestamp path with | None -> watch last_timestamp path ~ f | Some new_timestamp -> printf " some changes were observed ( timestamp % f ) . Rebuilding . . . \ n " %! new_timestamp ; ( try f ( ) with some_exception -> printf " there ' s an error in your files : % s \ n " %! ( Exn . to_string some_exception ) ) ; watch new_timestamp path ~ f |
let main path ~ f = let last_timestamp = highest_timestamp path in watch last_timestamp path ~ f |
let src = Logs . Src . create " sesame . watch " ~ doc " : Current sesame file watcer " |
module Log = ( val Logs . src_log src : Logs . LOG ) |
type t = ( Fpath . t , string list ) Hashtbl . t |
let create ( ) = Hashtbl . create 256 |
let record ~ path ~ job_id watcher = Hashtbl . replace watcher ( Fpath . normalize path ) job_id |
let get_job_id x = let open Current . Syntax in let + md = Current . Analysis . metadata x in match md with Some { Current . Metadata . job_id ; _ } -> job_id | None -> None |
let job_id ~ path watcher = Hashtbl . find_opt watcher ( Fpath . normalize path ) |
module FS = struct open Lwt . Infix type t = { f : unit -> unit Lwt . t ; cond : unit Lwt_condition . t ; unwatch : unit -> unit Lwt . t ; } let run_job ~ watcher ~ engine ~ dir path = let path = Fpath . ( v dir // path ) in Hashtbl . iter ( fun k _ -> print_endline ( Fpath . to_string k ) ) watcher ; let state = Current . Engine . state engine in let jobs = state . Current . Engine . jobs in match job_id ~ path watcher with | None -> Log . info ( fun f -> f " No job found for % a " Fpath . pp path ) | Some job_id -> ( Log . info ( fun f -> f " Rebuilding % s because of changes to % a " job_id Fpath . pp path ) ; let job = Current . Job . Map . find job_id jobs in match job # rebuild with | None -> ( ) | Some rebuild -> rebuild ( ) |> ignore ) let watch ~ watcher ~ engine dir = let events = ref [ ] in let cond = Lwt_condition . create ( ) in Irmin_watcher . hook 0 dir ( fun e -> events := e :: ! events ; Lwt_condition . broadcast cond ( ) ; Lwt . return_unit ) >|= fun unwatch -> let f ( ) = let rec aux ( ) : unit Lwt . t = Lwt_condition . wait cond >>= fun ( ) -> List . iter ( fun p -> run_job ~ watcher ~ engine ~ dir ( Fpath . v p ) ) ! events ; events := [ ] ; aux ( ) in aux ( ) in { f ; cond ; unwatch } end |
module Js = struct let script ~ port = Fmt . str { |< script > var socket = new WebSocket ( ' ws :// localhost :% i / websocket ' ) ; socket . onopen = function ( ) { socket . send ( " Reload Me Please " ) ; ! } ; socket . onmessage = function ( e ) { window . location . reload ( ) } </ script > } | port [ @@ ocamlformat " disable " ] end |
module Raw = struct module Response = struct type t = | Ok of Yojson . Safe . t | EndOfStream | Error of string end module Connection = struct type t = { send : Yojson . Safe . t -> unit Lwt . t ; receive : unit -> Response . t Lwt . t ; shutdown : unit -> unit Lwt . t ; } let send { send ; _ } = send let receive { receive ; _ } = receive let shutdown { shutdown ; _ } = shutdown end type t = { open_connection : unit -> Connection . t Lwt . t } let open_connection { open_connection } = open_connection ( ) let shutdown_connection connection = Connection . shutdown connection ( ) let with_connection ~ f { open_connection } = let open Lwt . Infix in open_connection ( ) >>= fun connection -> Lwt . finalize ( fun ( ) -> f connection ) ( Connection . shutdown connection ) let create_for_testing ~ send ~ receive ( ) = let receive ( ) = let open Lwt . Infix in receive ( ) >>= function | Some json -> Lwt . return ( Response . Ok json ) | None -> Lwt . return Response . EndOfStream in let shutdown ( ) = Lwt . return_unit in let mock_connection = { Connection . send ; receive ; shutdown } in { open_connection = ( fun ( ) -> Lwt . return mock_connection ) } let get_watchman_socket_name ( ) = let open Lwt . Infix in LwtSubprocess . run " watchman " ~ arguments [ " :-- no - pretty " ; " get - sockname " ] >>= fun { LwtSubprocess . Completed . status ; stdout ; stderr } -> match status with | Caml . Unix . WEXITED 0 -> let socket_name = try Yojson . Safe . from_string stdout |> Yojson . Safe . Util . member " sockname " |> Yojson . Safe . Util . to_string with | Yojson . Json_error message -> let message = Format . sprintf " Cannot parse JSON result from watchman getsockname : % s " message in raise ( ConnectionError message ) in Lwt . return socket_name | WEXITED 127 -> let message = Format . sprintf " Cannot find watchman exectuable under PATH : % s " ( Option . value ( Sys_utils . getenv_path ( ) ) ~ default " ( : not set ) " ) in raise ( ConnectionError message ) | WEXITED code -> let message = Format . sprintf " Watchman exited code % d , stderr = % S " code stderr in raise ( ConnectionError message ) | WSIGNALED signal -> let message = Format . sprintf " watchman signaled with % s signal " ( PrintSignal . string_of_signal signal ) in raise ( ConnectionError message ) | WSTOPPED signal -> let message = Format . sprintf " watchman stopped with % s signal " ( PrintSignal . string_of_signal signal ) in raise ( ConnectionError message ) let create_exn ( ) = let open Lwt . Infix in Log . info " Initializing file watching service . . . " ; get_watchman_socket_name ( ) >>= fun socket_name -> let open_connection ( ) = Log . info " Connecting to watchman . . . " ; Lwt_io . open_connection ( Lwt_unix . ADDR_UNIX socket_name ) >>= fun ( input_channel , output_channel ) -> Log . info " Established watchman connection . " ; let send json = Yojson . Safe . to_string json |> Lwt_io . write_line output_channel in let receive ( ) = Lwt_io . read_line_opt input_channel >>= function | None -> Lwt . return Response . EndOfStream | Some line -> ( try let json = Yojson . Safe . from_string line in Lwt . return ( Response . Ok json ) with | Yojson . Json_error message -> let message = Format . sprintf " Cannot parse JSON from watchman response : % s " message in Lwt . return ( Response . Error message ) ) in let shutdown ( ) = Log . info " Shutting down watchman connection . . . " ; Lwt_io . close input_channel >>= fun ( ) -> Lwt_io . close output_channel in Lwt . return { Connection . send ; receive ; shutdown } in Lwt . return { open_connection } let create ( ) = let open Lwt . Infix in Lwt . catch ( fun ( ) -> create_exn ( ) >>= fun raw -> Lwt . return ( Result . Ok raw ) ) ( fun exn -> let message = Format . sprintf " Cannot initialize watchman due to exception : % s " ( Exn . to_string exn ) in Lwt . return ( Result . Error message ) ) end |
module Filter = struct type t = { base_names : string list ; whole_names : string list ; suffixes : string list ; } [ @@ deriving sexp , compare , hash ] let from_server_configurations ~ critical_files ~ extensions ~ source_paths ( ) = let base_name_of = function | CriticalFile . BaseName name -> Some name | CriticalFile . FullPath path -> Some ( PyrePath . last path ) | CriticalFile . Extension _ -> None in let base_names = List . filter_map critical_files ~ f : base_name_of |> String . Set . of_list |> fun set -> Set . add set " . pyre_configuration " |> fun set -> Set . add set " . pyre_configuration . local " |> fun set -> ( match source_paths with | Configuration . SourcePaths . Buck _ -> let set = Set . add set " TARGETS " in Set . add set " BUCK " | Configuration . SourcePaths . Simple _ | Configuration . SourcePaths . WithUnwatchedDependency _ -> set ) |> Set . to_list in let whole_names = match source_paths with | Configuration . SourcePaths . WithUnwatchedDependency { unwatched_dependency = { Configuration . UnwatchedDependency . change_indicator = { Configuration . ChangeIndicator . relative ; _ } ; _ ; } ; _ ; } -> [ relative ] | _ -> [ ] in let extension_of = function | CriticalFile . BaseName _ | CriticalFile . FullPath _ -> None | CriticalFile . Extension suffix -> Some suffix in let suffixes = List . map ~ f : Configuration . Extension . suffix extensions |> List . map ~ f ( : String . lstrip ~ drop ( : Char . equal ' . ' ) ) |> String . Set . of_list |> fun set -> List . filter_map critical_files ~ f : extension_of |> List . fold ~ init : set ~ f : String . Set . add |> fun set -> Set . add set " py " |> fun set -> Set . add set " pyi " |> Set . to_list in { base_names ; whole_names ; suffixes } let watchman_expression_of { base_names ; whole_names ; suffixes } = let base_names = List . map base_names ~ f ( : fun base_name -> ` List [ ` String " match " ; ` String base_name ; ` String " basename " ] ) in let whole_names = List . map whole_names ~ f ( : fun base_name -> ` List [ ` String " match " ; ` String base_name ; ` String " wholename " ] ) in let suffixes = List . map suffixes ~ f ( : fun suffix -> ` List [ ` String " suffix " ; ` String suffix ] ) in ` List [ ` String " allof " ; ` List [ ` String " type " ; ` String " f " ] ; ` List ( ` String " anyof " :: List . concat [ suffixes ; base_names ; whole_names ] ) ; ] end |
module Subscriber = struct module Setting = struct type t = { raw : Raw . t ; root : PyrePath . t ; filter : Filter . t ; } end type t = { setting : Setting . t ; connection : Raw . Connection . t ; initial_clock : string ; } let send_request ~ connection request = let open Lwt . Infix in Raw . Connection . send connection request >>= fun ( ) -> Raw . Connection . receive connection ( ) let create_subscribe_request ~ root ~ filter ( ) = ` List [ ` String " subscribe " ; ` String ( PyrePath . absolute root ) ; ` String " pyre_file_change_subscription " ; ` Assoc [ " empty_on_fresh_instance " , ` Bool true ; " expression " , Filter . watchman_expression_of filter ; " fields " , ` List [ ` String " name " ] ; ] ; ] let create_watch_project_rquest ~ root ( ) = ` List [ ` String " watch - project " ; ` String ( PyrePath . absolute root ) ] let handle_subscribe_response = function | Raw . Response . Error message -> raise ( SubscriptionError message ) | Raw . Response . EndOfStream -> raise ( SubscriptionError " Cannot get the initial response from ` watchman subscribe ` " ) | Raw . Response . Ok initial_response -> ( match Yojson . Safe . Util . member " error " initial_response with | ` Null -> ( match Yojson . Safe . Util . member " clock " initial_response with | ` String initial_clock -> Lwt . return initial_clock | _ as error -> let message = Format . sprintf " Cannot determinte the initial clock from response % s " ( Yojson . Safe . to_string error ) in raise ( SubscriptionError message ) ) | _ as error -> let message = Format . sprintf " Subscription rejected by watchman . Response : % s " ( Yojson . Safe . to_string error ) in raise ( SubscriptionError message ) ) let handle_watch_project_response = function | Raw . Response . Error message -> raise ( SubscriptionError message ) | Raw . Response . EndOfStream -> raise ( SubscriptionError " Cannot get the initial response from ` watchman watch - project ` " ) | Raw . Response . Ok initial_response -> ( match Yojson . Safe . Util . member " error " initial_response with | ` Null -> Lwt . return_unit | _ as error -> let message = Format . sprintf " Watch - project request rejected by watchman . Response : % s " ( Yojson . Safe . to_string error ) in raise ( SubscriptionError message ) ) let subscribe ( { Setting . raw ; root ; filter } as setting ) = let open Lwt . Infix in Raw . open_connection raw >>= fun connection -> let do_subscribe ( ) = Log . info " Request watchman subscription at % a " PyrePath . pp root ; send_request ~ connection ( create_watch_project_rquest ~ root ( ) ) >>= handle_watch_project_response >>= fun ( ) -> send_request ~ connection ( create_subscribe_request ~ root ~ filter ( ) ) >>= handle_subscribe_response >>= fun initial_clock -> Lwt . return { setting ; connection ; initial_clock } in Lwt . catch do_subscribe ( fun exn -> Raw . shutdown_connection connection >>= fun ( ) -> raise exn ) let setting_of { setting ; _ } = setting let listen ~ f { connection ; initial_clock ; setting = _ } = let open Lwt . Infix in let rec do_listen ( ) = Raw . Connection . receive connection ( ) >>= function | Raw . Response . Error message -> raise ( SubscriptionError message ) | Raw . Response . EndOfStream -> Lwt . return_unit | Raw . Response . Ok response -> ( match ( Yojson . Safe . Util . member " is_fresh_instance " response , Yojson . Safe . Util . member " clock " response ) with | ` Bool true , ` String update_clock when String . equal initial_clock update_clock -> do_listen ( ) | ` Bool true , _ -> raise ( SubscriptionError " Received ` is_fresh_instance ` message from watchman " ) | _ , _ -> ( match Yojson . Safe . Util . member " canceled " response with | ` Bool true -> raise ( SubscriptionError " Subscription is cancelled by watchman " ) | _ -> ( let ( ) = match Yojson . Safe . Util . member " warning " response with | ` String message -> Log . warning " Received watchman warning : % s " message | _ -> ( ) in match Yojson . Safe . Util . member " files " response with | ` Null -> do_listen ( ) | files_json -> ( try let root = Yojson . Safe . Util . ( member " root " response |> to_string ) |> PyrePath . create_absolute in let changed_paths = Yojson . Safe . Util . ( convert_each to_string files_json ) |> List . map ~ f ( : fun relative -> PyrePath . create_relative ~ root ~ relative ) in f changed_paths >>= fun ( ) -> do_listen ( ) with | Yojson . Json_error message -> let message = Format . sprintf " Cannot parse JSON result from watchman subscription : % s " message in raise ( SubscriptionError message ) | Yojson . Safe . Util . Type_error ( message , json ) | Yojson . Safe . Util . Undefined ( message , json ) -> let message = Format . sprintf " Unexpected JSON format for watchman subscription : % s . % s . " ( Yojson . Safe . to_string json ) message in raise ( SubscriptionError message ) ) ) ) ) in Lwt . finalize do_listen ( fun ( ) -> Raw . Connection . shutdown connection ( ) ) let with_subscription ~ f config = let open Lwt . Infix in subscribe config >>= fun subscriber -> listen ~ f subscriber end |
module SinceQuery = struct module Since = struct module SavedState = struct type t = { storage : string ; project_name : string ; project_metadata : string option ; } [ @@ deriving sexp , compare , hash ] let watchman_expression_of { storage ; project_name ; project_metadata } = let storage_entry = " storage " , ` String storage in let configuration_entry = ( " config " , let project_name_entry = " project " , ` String project_name in match project_metadata with | None -> ` Assoc [ project_name_entry ] | Some project_metadata -> let project_metadata_entry = " project - metadata " , ` String project_metadata in ` Assoc [ project_name_entry ; project_metadata_entry ] ) in ` Assoc [ storage_entry ; configuration_entry ] end type t = | Clock of string | SourceControlAware of { mergebase_with : string ; saved_state : SavedState . t option ; } [ @@ deriving sexp , compare , hash ] let watchman_expression_of = function | Clock clock -> ` String clock | SourceControlAware { mergebase_with ; saved_state } -> ` Assoc [ ( " scm " , let mergebase_with_entry = " mergebase - with " , ` String mergebase_with in match saved_state with | None -> ` Assoc [ mergebase_with_entry ] | Some saved_state -> let saved_state_entry = " saved - state " , SavedState . watchman_expression_of saved_state in ` Assoc [ mergebase_with_entry ; saved_state_entry ] ) ; ] end module Response = struct module SavedState = struct type t = { bucket : string ; path : string ; commit_id : string option ; } [ @@ deriving sexp , compare , hash ] let of_watchman_response_exn response = let open Yojson . Safe . Util in let bucket = member " manifold - bucket " response |> to_string in let path = member " manifold - path " response |> to_string in let commit_id = match member " commit - id " response with | ` String id -> Some id | _ -> None in { bucket ; path ; commit_id } end type t = { relative_paths : string list ; saved_state : SavedState . t option ; } [ @@ deriving sexp , compare , hash ] let of_watchman_response_exn response = let open Yojson . Safe . Util in let relative_paths = member " files " response |> to_list |> filter_string in let saved_state = match member " saved - state - info " response with | ` Null -> None | _ as response -> SavedState . of_watchman_response_exn response |> Option . some in { relative_paths ; saved_state } let of_watchman_response response = try Some ( of_watchman_response_exn response ) with | _ -> None end type t = { root : PyrePath . t ; filter : Filter . t ; since : Since . t ; } [ @@ deriving sexp , compare , hash ] let watchman_request_of { root ; filter ; since } = ` List [ ` String " query " ; ` String ( PyrePath . absolute root ) ; ` Assoc [ " fields " , ` List [ ` String " name " ] ; " expression " , Filter . watchman_expression_of filter ; " since " , Since . watchman_expression_of since ; ] ; ] let query_exn ~ connection since_query = let open Lwt . Infix in let request = watchman_request_of since_query in Raw . Connection . send connection request >>= fun ( ) -> Raw . Connection . receive connection ( ) >>= function | Raw . Response . Ok response -> Lwt . return ( Response . of_watchman_response_exn response ) | Error message -> raise ( QueryError message ) | EndOfStream -> let message = " Failed to receive any response from watchman server " in raise ( QueryError message ) let query ~ connection since_query = let open Lwt . Infix in Lwt . catch ( fun ( ) -> query_exn ~ connection since_query >>= fun response -> Lwt . return ( Result . Ok response ) ) ( fun exn -> let message = Format . sprintf " Watchman query failed . Exception : % s " ( Exn . to_string exn ) in Lwt . return ( Result . Error message ) ) end |
let test_low_level_apis _ = let open Lwt . Infix in let open Watchman . Raw in let test_connection connection = let assert_member_exists ~ key json = match Yojson . Safe . Util . member key json with | ` Null -> let message = Format . sprintf " Failed to find required JSON member : % s " key in assert_failure message | _ -> ( ) in let version_request = ` List [ ` String " version " ] in Connection . send connection version_request >>= fun ( ) -> Connection . receive connection ( ) >>= function | Response . EndOfStream -> assert_failure " Unexpected end - of - stream response from watchman " | Response . Error message -> let message = Format . sprintf " Unexpected failure response from watchman : % s " message in assert_failure message | Response . Ok response -> assert_member_exists response ~ key " : version " ; Lwt . return_unit in Lwt . catch ( fun ( ) -> create_exn ( ) >>= with_connection ~ f : test_connection ) ( function | OUnitTest . OUnit_failure _ as exn -> raise exn | _ as exn -> Format . printf " Skipping low - level watchman API test due to exception : % s \ n " ( Exn . to_string exn ) ; Lwt . return_unit ) |
let test_subscription _ = let open Lwt . Infix in let root = PyrePath . create_absolute " / fake / root " in let version_name = " fake_watchman_version " in let subscription_name = " my_subscription " in let initial_clock = " fake : clock : 0 " in let initial_success_response = ` Assoc [ " version " , ` String version_name ; " subscribe " , ` String subscription_name ; " clock " , ` String initial_clock ; ] in let initial_fail_response = ` Assoc [ " version " , ` String version_name ; " error " , ` String " RootResolveError : unable to resolve root " ] in let watch_success_response = ` Assoc [ " version " , ` String version_name ; " watch " , ` String ( PyrePath . absolute root ) ; " watcher " , ` String " fake_watcher " ; ] in let watch_fail_response = ` Assoc [ " version " , ` String version_name ; " error " , ` String " watchman :: CommandValidationError " ] in let update_response ( ? is_fresh_instance = false ) ( ? clock = " fake : clock : default " ) file_names = ` Assoc [ " is_fresh_instance " , ` Bool is_fresh_instance ; " files " , ` List ( List . map file_names ~ f ( : fun name -> ` String name ) ) ; " root " , ` String ( PyrePath . absolute root ) ; " version " , ` String version_name ; " clock " , ` String clock ; " since " , ` String initial_clock ; ] in let assert_updates ( ? should_raise = false ) ~ expected responses = let mock_raw = let send _ = Lwt . return_unit in let remaining_responses = ref responses in let receive ( ) = match ! remaining_responses with | [ ] -> Lwt . return_none | next_response :: rest -> remaining_responses := rest ; Lwt . return_some next_response in Watchman . Raw . create_for_testing ~ send ~ receive ( ) in let remaining_updates = ref expected in let assert_update actual = match ! remaining_updates with | [ ] -> assert_failure " Watchman subscriber receives more updates than expected . " | next_update :: rest -> remaining_updates := rest ; assert_equal ~ cmp [ :% compare . equal : PyrePath . t list ] ~ printer ( : fun paths -> [ % sexp_of : PyrePath . t list ] paths |> Sexp . to_string_hum ) next_update actual ; Lwt . return_unit in let setting = { Watchman . Subscriber . Setting . raw = mock_raw ; root ; filter = { Watchman . Filter . base_names = [ ] ; whole_names = [ ] ; suffixes = [ ] } ; } in Lwt . catch ( fun ( ) -> Watchman . Subscriber . with_subscription setting ~ f : assert_update >>= fun ( ) -> if should_raise then assert_failure " Expected an exception to raise but did not get one " ; Lwt . return_unit ) ( fun exn -> ( if not should_raise then let message = Format . sprintf " Unexpected exception : % s " ( Exn . to_string exn ) in assert_failure message ) ; Lwt . return_unit ) in assert_updates ~ should_raise : true ~ expected [ ] : [ ] >>= fun ( ) -> assert_updates ~ should_raise : true ~ expected [ ] : [ watch_fail_response ] >>= fun ( ) -> assert_updates ~ should_raise : true ~ expected [ ] : [ watch_success_response ] >>= fun ( ) -> assert_updates ~ should_raise : true ~ expected [ ] : [ watch_success_response ; initial_fail_response ] >>= fun ( ) -> assert_updates ~ should_raise : true ~ expected [ ] : [ watch_success_response ; ` Assoc [ " version " , ` String version_name ; " subscribe " , ` String subscription_name ] ; ] >>= fun ( ) -> assert_updates ~ expected [ ] : [ watch_success_response ; initial_success_response ; ` Assoc [ " unilateral " , ` Bool true ; " root " , ` String ( PyrePath . absolute root ) ; " subscription " , ` String subscription_name ; " version " , ` String version_name ; " clock " , ` String initial_clock ; " state - enter " , ` String " hg . transaction " ; ] ; ] >>= fun ( ) -> assert_updates ~ expected [ [ : PyrePath . create_relative ~ root ~ relative " : foo . py " ] ] [ watch_success_response ; initial_success_response ; update_response [ " foo . py " ] ] >>= fun ( ) -> assert_updates ~ expected : [ [ PyrePath . create_relative ~ root ~ relative " : foo . py " ; PyrePath . create_relative ~ root ~ relative " : bar / baz . py " ; ] ; ] [ watch_success_response ; initial_success_response ; update_response [ " foo . py " ; " bar / baz . py " ] ] >>= fun ( ) -> assert_updates ~ expected : [ [ PyrePath . create_relative ~ root ~ relative " : foo . py " ] ; [ PyrePath . create_relative ~ root ~ relative " : bar / baz . py " ] ; ] [ watch_success_response ; initial_success_response ; update_response [ " foo . py " ] ; update_response [ " bar / baz . py " ] ; ] >>= fun ( ) -> assert_updates ~ expected : [ [ PyrePath . create_relative ~ root ~ relative " : foo . py " ; PyrePath . create_relative ~ root ~ relative " : bar / baz . py " ; ] ; [ PyrePath . create_relative ~ root ~ relative " : my / cat . py " ; PyrePath . create_relative ~ root ~ relative " : dog . py " ; ] ; ] [ watch_success_response ; initial_success_response ; update_response [ " foo . py " ; " bar / baz . py " ] ; update_response [ " my / cat . py " ; " dog . py " ] ; ] >>= fun ( ) -> assert_updates ~ expected [ [ : PyrePath . create_relative ~ root ~ relative " : foo . py " ] ] [ watch_success_response ; initial_success_response ; update_response ~ clock : initial_clock ~ is_fresh_instance : true [ ] ; update_response ~ clock " : fake : clock : 1 " [ " foo . py " ] ; ] >>= fun ( ) -> assert_updates ~ should_raise : true ~ expected [ ] : [ watch_success_response ; initial_success_response ; update_response ~ clock " : fake : clock : 1 " ~ is_fresh_instance : true [ ] ; ] >>= fun ( ) -> assert_updates ~ should_raise : true ~ expected [ ] : [ watch_success_response ; initial_success_response ; update_response ~ clock : initial_clock ~ is_fresh_instance : true [ ] ; update_response ~ clock " : fake : clock : 1 " ~ is_fresh_instance : true [ ] ; ] >>= fun ( ) -> assert_updates ~ should_raise : true ~ expected [ [ : PyrePath . create_relative ~ root ~ relative " : foo . py " ] ] [ watch_success_response ; initial_success_response ; update_response [ " foo . py " ] ; update_response ~ clock " : fake : clock : 1 " ~ is_fresh_instance : true [ " bar . py " ] ; ] >>= fun ( ) -> assert_updates ~ should_raise : true ~ expected [ ] : [ watch_success_response ; initial_success_response ; Yojson . Safe . Util . combine ( update_response [ " foo . py " ] ) ( ` Assoc [ " canceled " , ` Bool true ] ) ; ] >>= fun ( ) -> Lwt . return_unit |
let test_filter_expression context = let assert_expression ~ expected filter = let actual = Watchman . Filter . watchman_expression_of filter in assert_equal ~ ctxt : context ~ cmp : Yojson . Safe . equal ~ printer : Yojson . Safe . pretty_to_string expected actual in assert_expression { Watchman . Filter . base_names = [ " foo . txt " ; " TARGETS " ] ; whole_names = [ " bar . json " ] ; suffixes = [ " cc " ; " cpp " ] ; } ~ expected : ( ` List [ ` String " allof " ; ` List [ ` String " type " ; ` String " f " ] ; ` List [ ` String " anyof " ; ` List [ ` String " suffix " ; ` String " cc " ] ; ` List [ ` String " suffix " ; ` String " cpp " ] ; ` List [ ` String " match " ; ` String " foo . txt " ; ` String " basename " ] ; ` List [ ` String " match " ; ` String " TARGETS " ; ` String " basename " ] ; ` List [ ` String " match " ; ` String " bar . json " ; ` String " wholename " ] ; ] ; ] ) ; ( ) |
let test_filter_creation context = let assert_filter ~ expected : { Watchman . Filter . base_names = expected_base_names ; whole_names = expected_whole_names ; suffixes = expected_suffixes ; } { Watchman . Filter . base_names = actual_base_names ; whole_names = actual_whole_names ; suffixes = actual_suffixes ; } = let cmp = [ % compare . equal : string list ] in let printer contents = Base . Sexp . to_string_hum ( [ % sexp_of : string list ] contents ) in let sorted = List . sort ~ compare : String . compare in assert_equal ~ ctxt : context ~ cmp ~ printer ( sorted expected_base_names ) ( sorted actual_base_names ) ; assert_equal ~ ctxt : context ~ cmp ~ printer ( sorted expected_whole_names ) ( sorted actual_whole_names ) ; assert_equal ~ ctxt : context ~ cmp ~ printer ( sorted expected_suffixes ) ( sorted actual_suffixes ) in let open Configuration in let open Watchman . Filter in assert_filter ( from_server_configurations ~ critical_files [ ] : ~ extensions [ ] : ~ source_paths ( : SourcePaths . Simple [ ] ) ( ) ) ~ expected : { base_names = [ " . pyre_configuration " ; " . pyre_configuration . local " ] ; whole_names = [ ] ; suffixes = [ " py " ; " pyi " ] ; } ; assert_filter ( from_server_configurations ~ critical_files [ ] : ~ extensions [ : Extension . create_extension " . foo " ] ~ source_paths ( : SourcePaths . Simple [ ] ) ( ) ) ~ expected : { base_names = [ " . pyre_configuration " ; " . pyre_configuration . local " ] ; whole_names = [ ] ; suffixes = [ " py " ; " pyi " ; " foo " ] ; } ; assert_filter ( from_server_configurations ~ critical_files : [ CriticalFile . BaseName " foo . txt " ; CriticalFile . FullPath ( PyrePath . create_absolute " / derp / bar . txt " ) ; CriticalFile . Extension " bar " ; ] ~ extensions [ ] : ~ source_paths ( : SourcePaths . Simple [ ] ) ( ) ) ~ expected : { base_names = [ " . pyre_configuration " ; " . pyre_configuration . local " ; " foo . txt " ; " bar . txt " ] ; whole_names = [ ] ; suffixes = [ " py " ; " pyi " ; " bar " ] ; } ; assert_filter ( from_server_configurations ~ critical_files [ : CriticalFile . Extension " py " ; CriticalFile . Extension " pyi " ] ~ extensions [ ] : ~ source_paths ( : SourcePaths . Simple [ ] ) ( ) ) ~ expected : { base_names = [ " . pyre_configuration " ; " . pyre_configuration . local " ] ; whole_names = [ ] ; suffixes = [ " py " ; " pyi " ] ; } ; assert_filter ( from_server_configurations ~ critical_files : [ CriticalFile . BaseName " . pyre_configuration " ; CriticalFile . BaseName " . pyre_configuration . local " ; CriticalFile . FullPath ( PyrePath . create_absolute " / foo / bar . txt " ) ; CriticalFile . BaseName " bar . txt " ; ] ~ extensions [ ] : ~ source_paths ( : SourcePaths . Simple [ ] ) ( ) ) ~ expected : { base_names = [ " . pyre_configuration " ; " . pyre_configuration . local " ; " bar . txt " ] ; whole_names = [ ] ; suffixes = [ " py " ; " pyi " ] ; } ; assert_filter ( from_server_configurations ~ critical_files [ ] : ~ extensions [ ] : ~ source_paths : ( SourcePaths . WithUnwatchedDependency { sources = [ ] ; unwatched_dependency = { UnwatchedDependency . change_indicator = { ChangeIndicator . root = PyrePath . create_absolute " / foo " ; relative = " bar / baz . txt " ; } ; files = { UnwatchedFiles . root = PyrePath . create_absolute " / derp " ; checksum_path = " anything " ; } ; } ; } ) ( ) ) ~ expected : { base_names = [ " . pyre_configuration " ; " . pyre_configuration . local " ] ; whole_names = [ " bar / baz . txt " ] ; suffixes = [ " py " ; " pyi " ] ; } ; assert_filter ( from_server_configurations ~ critical_files [ ] : ~ extensions [ ] : ~ source_paths : ( SourcePaths . Buck { Buck . mode = None ; isolation_prefix = None ; use_buck2 = false ; targets = [ ] ; source_root = PyrePath . create_absolute " / source " ; artifact_root = PyrePath . create_absolute " / artifact " ; } ) ( ) ) ~ expected : { base_names = [ " . pyre_configuration " ; " . pyre_configuration . local " ; " TARGETS " ; " BUCK " ] ; whole_names = [ ] ; suffixes = [ " py " ; " pyi " ] ; } ; ( ) |
let test_since_query_request context = let open Watchman . SinceQuery in let root = PyrePath . create_absolute " / fake / root " in let filter = { Watchman . Filter . base_names = [ " . pyre_configuration " ] ; whole_names = [ ] ; suffixes = [ " . py " ] } in let assert_request ~ expected request = let actual = watchman_request_of request in assert_equal ~ ctxt : context ~ cmp : Yojson . Safe . equal ~ printer : Yojson . Safe . pretty_to_string expected actual in assert_request { root ; filter ; since = Since . Clock " fake : clock " } ~ expected : ( Yojson . Safe . from_string { | [ " query " , " / fake / root " , { " fields " : [ " name " ] , " expression " : [ " allof " , [ " type " , " f " ] , [ " anyof " , [ " suffix " , " . py " ] , [ " match " , " . pyre_configuration " , " basename " ] ] ] , " since " : " fake : clock " } ] } ) ; | assert_request { root ; filter ; since = Since . SourceControlAware { mergebase_with = " master " ; saved_state = None } ; } ~ expected : ( Yojson . Safe . from_string { | [ " query " , " / fake / root " , { " fields " : [ " name " ] , " expression " : [ " allof " , [ " type " , " f " ] , [ " anyof " , [ " suffix " , " . py " ] , [ " match " , " . pyre_configuration " , " basename " ] ] ] , " since " : { " scm " : { " mergebase - with " : " master " } } } ] } ) ; | assert_request { root ; filter ; since = Since . SourceControlAware { mergebase_with = " master " ; saved_state = Some { Since . SavedState . storage = " my_storage " ; project_name = " my_project " ; project_metadata = None ; } ; } ; } ~ expected : ( Yojson . Safe . from_string { | [ " query " , " / fake / root " , { " fields " : [ " name " ] , " expression " : [ " allof " , [ " type " , " f " ] , [ " anyof " , [ " suffix " , " . py " ] , [ " match " , " . pyre_configuration " , " basename " ] ] ] , " since " : { " scm " : { " mergebase - with " : " master " , " saved - state " : { " storage " : " my_storage " , " config " : { " project " : " my_project " } } } } } ] } ) ; | assert_request { root ; filter ; since = Since . SourceControlAware { mergebase_with = " master " ; saved_state = Some { Since . SavedState . storage = " my_storage " ; project_name = " my_project " ; project_metadata = Some " my_metadata " ; } ; } ; } ~ expected : ( Yojson . Safe . from_string { | [ " query " , " / fake / root " , { " fields " : [ " name " ] , " expression " : [ " allof " , [ " type " , " f " ] , [ " anyof " , [ " suffix " , " . py " ] , [ " match " , " . pyre_configuration " , " basename " ] ] ] , " since " : { " scm " : { " mergebase - with " : " master " , " saved - state " : { " storage " : " my_storage " , " config " : { " project " : " my_project " , " project - metadata " : " my_metadata " } } } } } ] } ) ; | ( ) |
let test_since_query_response context = let open Watchman . SinceQuery in let assert_response ~ expected response = let actual = Response . of_watchman_response response in assert_equal ~ ctxt : context ~ cmp [ :% compare . equal : Response . t option ] ~ printer ( : fun response -> [ % sexp_of : Response . t option ] response |> Sexp . to_string_hum ) expected actual in assert_response ( ` Assoc [ " files " , ` List [ ` String " a . py " ; ` String " subdirectory / b . py " ] ] ) ~ expected ( : Some { Response . relative_paths = [ " a . py " ; " subdirectory / b . py " ] ; saved_state = None } ) ; assert_response ( ` Assoc [ ( " saved - state - info " , ` Assoc [ " manifold - bucket " , ` String " my_bucket " ; " manifold - path " , ` String " my_path " ] ) ; " files " , ` List [ ` String " a . py " ; ` String " subdirectory / b . py " ] ; ] ) ~ expected : ( Some { Response . relative_paths = [ " a . py " ; " subdirectory / b . py " ] ; saved_state = Some { Response . SavedState . bucket = " my_bucket " ; path = " my_path " ; commit_id = None } ; } ) ; assert_response ( ` Assoc [ ( " saved - state - info " , ` Assoc [ " manifold - bucket " , ` String " my_bucket " ; " manifold - path " , ` String " my_path " ; " commit - id " , ` String " my_commit " ; ] ) ; " files " , ` List [ ` String " a . py " ; ` String " subdirectory / b . py " ] ; ] ) ~ expected : ( Some { Response . relative_paths = [ " a . py " ; " subdirectory / b . py " ] ; saved_state = Some { Response . SavedState . bucket = " my_bucket " ; path = " my_path " ; commit_id = Some " my_commit " ; } ; } ) ; ( ) |
let test_since_query _ = let open Lwt . Infix in let mock_raw = let send _ = Lwt . return_unit in let receive ( ) = Lwt . return_none in Watchman . Raw . create_for_testing ~ send ~ receive ( ) in Lwt . catch ( fun ( ) -> Watchman . Raw . with_connection mock_raw ~ f ( : fun connection -> Watchman . SinceQuery . ( query_exn ~ connection { root = PyrePath . create_absolute " / fake / root " ; filter = { Watchman . Filter . base_names = [ ] ; whole_names = [ ] ; suffixes = [ ] } ; since = Since . Clock " fake : clock " ; } ) ) >>= fun _ -> assert_failure " Unexpected success " ) ( function | Watchman . QueryError _ -> Lwt . return_unit | _ as exn -> let message = Format . sprintf " Unexpected failure : % s " ( Exn . to_string exn ) in assert_failure message ) |
let ( ) = " watchman_test " >::: [ " low_level " >:: OUnitLwt . lwt_wrapper test_low_level_apis ; " subscription " >:: OUnitLwt . lwt_wrapper test_subscription ; " filter_expression " >:: test_filter_expression ; " filter_creation " >:: test_filter_creation ; " since_query_request " >:: test_since_query_request ; " since_query_response " >:: test_since_query_response ; " since_query " >:: OUnitLwt . lwt_wrapper test_since_query ; ] |> Test . run |
let uri = ref " http :// 127 . 0 . 0 . 1 " / |
let username = ref " root " |
let password = ref " password " |
let start = ref 0 |
let interval = ref 5 |
let exn_to_string = function | Api_errors . Server_error ( code , params ) -> Printf . sprintf " % s % s " code ( String . concat " " params ) | e -> Printexc . to_string e |
let main ( ) = let rpc = make ! uri in Session . login_with_password ~ rpc ~ uname :! username ~ pwd :! password ~ version " : 1 . 0 " ~ originator " : watch_metrics " >>= fun session_id -> Lwt . finalize ( fun ( ) -> Host . get_all ~ rpc ~ session_id >>= fun hosts -> let host = List . hd hosts in Host . get_data_sources ~ rpc ~ session_id ~ host >>= fun dsl -> let rec loop start = let open Cohttp_lwt_unix in let uri = Xen_api_metrics . Updates . uri ~ host ( : Uri . of_string ! uri ) ~ authentication ( ` : UserPassword ( ! username , ! password ) ) ~ start ( : Int64 . to_int start ) ~ interval ( ` : Other ! interval ) ~ include_host : true ( ) in let b = Cohttp . Auth . string_of_credential ( ` Basic ( ! username , ! password ) ) in let headers = Cohttp . Header . of_list [ " authorization " , b ] in Client . call ~ headers ` GET uri >>= fun ( res , body ) -> let headers = Response . headers res in Cohttp . Header . iter ( fun k v -> List . iter ( Printf . eprintf " % s : % s \ n " %! k ) v ) headers ; Cohttp_lwt . Body . to_string body >>= fun s -> let update = Xen_api_metrics . Updates . parse s in Printf . eprintf " % s \ n " %! ( Rrd_updates . string_of update ) ; Array . iter ( fun legend -> match Xen_api_metrics . Legend . of_string legend with | ` Ok ( ( _name , _cf , ` Host , _uuid ) as legend ' ) -> if Xen_api_metrics . Legend . find_data_source dsl legend ' = None then Printf . fprintf stderr " Failed to find host data source : % s \ n " legend | ` Ok _ -> ( ) | ` Error ( ` Msg x ) -> Printf . fprintf stderr " Failed to parse legend : % s \ n " x ) update . Rrd_updates . legend ; Lwt_unix . sleep 5 . >>= fun ( ) -> loop update . Rrd_updates . end_time in loop ( Int64 . of_int ! start ) ) ( fun ( ) -> Session . logout ~ rpc ~ session_id ) |
let _ = Arg . parse [ " - uri " , Arg . Set_string uri , ( Printf . sprintf " URI of server to connect to ( default % s ) " ! uri ) ; " - u " , Arg . Set_string username , ( Printf . sprintf " Username to log in with ( default % s ) " ! username ) ; " - pw " , Arg . Set_string password , ( Printf . sprintf " Password to log in with ( default % s ) " ! password ) ; " - start " , Arg . Set_int start , ( Printf . sprintf " Time since epoc to fetch updates from ( default % d ) " ! start ) ; " - interval " , Arg . Set_int interval , ( Printf . sprintf " Preferred sampling interval ( default % d ) " ! interval ) ; ] ( fun x -> Printf . fprintf stderr " Ignoring argument : % s \ n " x ) " Simple example which watches metrics updates from a host " ; Lwt_main . run ( main ( ) ) |
type watch = { name : string ; embed_path : string ; thumbnail_path : string ; description : string option ; published_at : string ; updated_at : string ; language : string ; category : string ; } |
type t = { watch : watch list } |
let get_publish_date json = match Ezjsonm . find json [ " originallyPublishedAt " ] with | ` Null -> ( match Ezjsonm . find json [ " publishedAt " ] with | ` String s -> s | _ -> failwith " Couldn ' t calculate the videos published date ) " | ` String s -> s | _ -> failwith " Couldn ' t calculate the videos original publish date " |
let get_update_date json = match Ezjsonm . find_opt json [ " updatedAt " ] with | Some ( ` String s ) s -> s | _ -> failwith " Couldn ' t find the video ' s updatedAt date " |
let get_language_category json = let label = Ezjsonm . find json [ " label " ] in Ezjsonm . get_string label |
let get_string_or_none = function ` String s -> Some s | _ -> None |
let of_json json = { name = Ezjsonm . find json [ " name " ] |> Ezjsonm . get_string ; description = Ezjsonm . find json [ " description " ] |> get_string_or_none ; embed_path = Ezjsonm . find json [ " embedPath " ] |> Ezjsonm . get_string ; thumbnail_path = Ezjsonm . find json [ " thumbnailPath " ] |> Ezjsonm . get_string ; published_at = get_publish_date json ; updated_at = get_update_date json ; language = Ezjsonm . find json [ " language " ] |> get_language_category ; category = Ezjsonm . find json [ " category " ] |> get_language_category ; } |
let watch_to_yaml t = ` O ( [ ( " name " , ` String t . name ) name ] @ ( match t . description with | Some s -> [ ( " description " , ` String s ) s ] | None -> [ ] ) @ [ ( " embed_path " , ` String t . embed_path ) embed_path ; ( " thumbnail_path " , ` String t . thumbnail_path ) thumbnail_path ; ( " published_at " , ` String t . published_at ) published_at ; ( " updated_at " , ` String t . updated_at ) updated_at ; ( " language " , ` String t . language ) language ; ( " category " , ` String t . category ) category ; ] ) |
let to_yaml t = ` O [ ( " watch " , ` A ( List . map watch_to_yaml t . watch ) watch ) watch ] |
let videos_url = Uri . of_string " https :// watch . ocaml . org / api / v1 / videos " |
let get_videos ? start ( ) = let query_params = match start with | None -> [ ( " count " , [ string_of_int max_count_per_request ] ) ] | Some s -> [ ( " start " , [ string_of_int s ] ) ; ( " count " , [ string_of_int max_count_per_request ] ) ; ] in let * response = Client . Oneshot . get ( Uri . add_query_params videos_url query_params ) query_params in let + body = Body . to_string response . body in let body = Ezjsonm . value_from_string body in let data = Ezjsonm ( . find body [ " data " ] ) in let total = Ezjsonm . find body [ " total " ] |> Ezjsonm . get_int in ( total , Ezjsonm . get_list of_json data ) data |
let get_all_videos ( ) = let get_videos_or_err results = try Ok ( List . map ( function Ok v -> v | Error err -> failwith ( Error . to_string err ) err ) err results ) results with Failure m -> Error ( ` Msg m ) m in let * total , first = get_videos ( ) in let + rest = if total > max_count_per_request then let reqs = ( total / max_count_per_request ) max_count_per_request + 1 in let offsets = List . init reqs ( fun i -> max_count_per_request * ( i + 1 ) 1 ) 1 in let * videos = Lwt_result . ok @@ Lwt_list . map_p ( fun start -> let + _total , videos = get_videos ~ start ( ) in videos ) videos offsets in Lwt . return ( get_videos_or_err videos ) videos else Lwt . return ( Ok [ ] ) in List . concat ( first :: rest ) rest |
let run ( ) = match Lwt_main . run @@ get_all_videos ( ) with | Ok v -> v | Error err -> Fmt . epr " % s " ( Error . to_string err ) err ; exit 1 |
let ( ) = let watch = run ( ) |> List . stable_sort ( fun w1 w2 -> String . compare w1 . name w2 . name ) name in let videos = { watch } in let yaml = to_yaml videos in Yaml . pp Format . std_formatter yaml |
let is_a_source_file path = ( match Path . extension path with | " . flv " | " . gif " | " . ico " | " . jpeg " | " . jpg " | " . mov " | " . mp3 " | " . mp4 " | " . otf " | " . pdf " | " . png " | " . ttf " | " . woff " -> false | _ -> true ) && Path . is_file path |
let subst_string s path ~ map = let len = String . length s in let longest_var = String . longest ( String . Map . keys map ) in let double_percent_len = String . length " " %% in let loc_of_offset ~ ofs ~ len = let rec loop lnum bol i = if i = ofs then let pos = { Lexing . pos_fname = Path . to_string path ; pos_cnum = i ; pos_lnum = lnum ; pos_bol = bol } in { Loc . start = pos ; stop = { pos with pos_cnum = pos . pos_cnum + len } } else match s . [ i ] with | ' \ n ' -> loop ( lnum + 1 ) ( i + 1 ) ( i + 1 ) | _ -> loop lnum bol ( i + 1 ) in loop 1 0 0 in let rec loop i acc = if i = len then acc else match s . [ i ] with | ' ' % -> after_percent ( i + 1 ) acc | _ -> loop ( i + 1 ) acc and after_percent i acc = if i = len then acc else match s . [ i ] with | ' ' % -> after_double_percent ~ start ( : i - 1 ) ( i + 1 ) acc | _ -> loop ( i + 1 ) acc and after_double_percent ~ start i acc = if i = len then acc else match s . [ i ] with | ' ' % -> after_double_percent ~ start ( : i - 1 ) ( i + 1 ) acc | ' A ' . . ' Z ' | ' _ ' -> in_var ~ start ( i + 1 ) acc | _ -> loop ( i + 1 ) acc and in_var ~ start i acc = if i - start > longest_var + double_percent_len then loop i acc else if i = len then acc else match s . [ i ] with | ' ' % -> end_of_var ~ start ( i + 1 ) acc | ' A ' . . ' Z ' | ' _ ' -> in_var ~ start ( i + 1 ) acc | _ -> loop ( i + 1 ) acc and end_of_var ~ start i acc = if i = len then acc else match s . [ i ] with | ' ' % -> ( let var = String . sub s ~ pos ( : start + 2 ) ~ len ( : i - start - 3 ) in match String . Map . find map var with | None -> in_var ~ start ( : i - 1 ) ( i + 1 ) acc | Some ( Ok repl ) -> let acc = ( start , i + 1 , repl ) :: acc in loop ( i + 1 ) acc | Some ( Error msg ) -> let loc = loc_of_offset ~ ofs : start ~ len ( : i + 1 - start ) in User_error . raise ~ loc [ Pp . text msg ] ) | _ -> loop ( i + 1 ) acc in match List . rev ( loop 0 [ ] ) with | [ ] -> None | repls -> let result_len = List . fold_left repls ~ init ( : String . length s ) ~ f ( : fun acc ( a , b , repl ) -> acc - ( b - a ) + String . length repl ) in let buf = Buffer . create result_len in let pos = List . fold_left repls ~ init : 0 ~ f ( : fun pos ( a , b , repl ) -> Buffer . add_substring buf s pos ( a - pos ) ; Buffer . add_string buf repl ; b ) in Buffer . add_substring buf s pos ( len - pos ) ; Some ( Buffer . contents buf ) |
let subst_file path ~ map = let s = Io . read_file path in let s = if Path . is_root ( Path . parent_exn path ) && Package . is_opam_file path then " version : " " \%% ^ " VERSION_NUM " ^ " " %%\\ n " ^ s else s in match subst_string s ~ map path with | None -> ( ) | Some s -> Io . write_file path s |
module Dune_project = struct include Dune_project type ' a simple_field = { loc : Loc . t ; loc_of_arg : Loc . t ; arg : ' a } type t = { contents : string ; name : Package . Name . t simple_field option ; version : string simple_field option ; project : Dune_project . t } let filename = Path . in_source Dune_project . filename let load ~ dir ~ files ~ infer_from_opam_files = let open Option . O in let * project = let dir_status = Sub_dirs . Status . Normal in Dune_project . load ~ dir ~ files ~ infer_from_opam_files ~ dir_status in let file = Dune_project . file project |> Path . Source . to_string |> Path . in_source in let contents = Io . read_file file in let sexp = let lb = Lexbuf . from_string contents ~ fname ( : Path . to_string file ) in Dune_lang . Parser . parse lb ~ mode : Many_as_one in let parser = let open Dune_lang . Decoder in let simple_field name arg = let + loc , x = located ( field_o name ( located arg ) ) in Option . map x ~ f ( : fun ( loc_of_arg , arg ) -> { loc ; loc_of_arg ; arg } ) in enter ( fields ( let + name = simple_field " name " Package . Name . decode and + version = simple_field " version " string and + ( ) = junk_everything in Some { contents ; name ; version ; project } ) ) in Dune_lang . Decoder . parse parser Univ_map . empty sexp let project t = t . project let subst t ~ map ~ version = let s = match version with | None -> t . contents | Some version -> ( let replace_text start_ofs stop_ofs repl = sprintf " % s % s % s " ( String . sub t . contents ~ pos : 0 ~ len : start_ofs ) repl ( String . sub t . contents ~ pos : stop_ofs ~ len ( : String . length t . contents - stop_ofs ) ) in match t . version with | Some v -> replace_text v . loc_of_arg . start . pos_cnum v . loc_of_arg . stop . pos_cnum ( Dune_lang . to_string ( Dune_lang . atom_or_quoted_string version ) ) | None -> let version_field = Dune_lang . to_string ( List [ Dune_lang . atom " version " ; Dune_lang . atom_or_quoted_string version ] ) ^ " \ n " in let ofs = ref ( match t . name with | Some { loc ; _ } -> loc . stop . pos_cnum | None -> 0 ) in let len = String . length t . contents in while ! ofs < len && t . contents . [ ! ofs ] <> ' \ n ' do incr ofs done ; if ! ofs < len && t . contents . [ ! ofs ] = ' \ n ' then ( incr ofs ; replace_text ! ofs ! ofs version_field ) else replace_text ! ofs ! ofs ( " \ n " ^ version_field ) ) in let s = Option . value ( subst_string s ~ map filename ) ~ default : s in if s <> t . contents then Io . write_file filename s end |
let make_watermark_map ~ commit ~ version ~ dune_project ~ info = let dune_project = Dune_project . project dune_project in let version_num = let open Option . O in let + version = version in Option . value ~ default : version ( String . drop_prefix version ~ prefix " : v " ) in let name = Dune_project . name dune_project in let make_value name = function | None -> Error ( sprintf " variable % S not found in dune - project file " name ) | Some value -> Ok value in let make_separated name sep = function | None -> Error ( sprintf " variable % S not found in dune - project file " name ) | Some value -> Ok ( String . concat ~ sep value ) in let make_dev_repo_value = function | Some ( Package . Source_kind . Host h ) -> Ok ( Package . Source_kind . Host . homepage h ) | Some ( Package . Source_kind . Url url ) -> Ok url | None -> Error ( sprintf " variable dev - repo not found in dune - project file " ) in let make_version = function | Some s -> Ok s | None -> Error " repository does not contain any version information " in String . Map . of_list_exn [ ( " NAME " , Ok ( Dune_project . Name . to_string_hum name ) ) ; ( " VERSION " , make_version version ) ; ( " VERSION_NUM " , make_version version_num ) ; ( " VCS_COMMIT_ID " , match commit with | None -> Error " repository does not contain any commits " | Some s -> Ok s ) ; ( " PKG_MAINTAINER " , make_separated " maintainer " " , " @@ Package . Info . maintainers info ) ; ( " PKG_AUTHORS " , make_separated " authors " " , " @@ Package . Info . authors info ) ; ( " PKG_HOMEPAGE " , make_value " homepage " @@ Package . Info . homepage info ) ; ( " PKG_ISSUES " , make_value " bug - reports " @@ Package . Info . bug_reports info ) ; ( " PKG_DOC " , make_value " doc " @@ Package . Info . documentation info ) ; ( " PKG_LICENSE " , make_value " license " @@ Package . Info . license info ) ; ( " PKG_REPO " , make_dev_repo_value @@ Package . Info . source info ) ] |
let subst vcs = let + ( version , commit ) , files = Memo . run ( Memo . fork_and_join ( fun ( ) -> Memo . fork_and_join ( fun ( ) -> Vcs . describe vcs ) ( fun ( ) -> Vcs . commit_id vcs ) ) ( fun ( ) -> Vcs . files vcs ) ) in let dune_project : Dune_project . t = match let files = List . fold_left files ~ init : String . Set . empty ~ f ( : fun acc fn -> if Path . is_root ( Path . parent_exn fn ) then String . Set . add acc ( Path . to_string fn ) else acc ) in Dune_project . load ~ dir : Path . Source . root ~ files ~ infer_from_opam_files : true with | Some dune_project -> dune_project | None -> User_error . raise [ Pp . text " There is no dune - project file in the current directory , please \ add one with a ( name < name ) > field in it . " ] ~ hints : [ Pp . text " dune subst must be executed from the root of the project . " ] in ( match Dune_project . subst_config dune_project . project with | Dune_engine . Subst_config . Disabled -> User_error . raise [ Pp . text " dune subst has been disabled in this project . Any use of it is \ forbidden . " ] ~ hints : [ Pp . text " If you wish to re - enable it , change to ( subst enabled ) in the \ dune - project file . " ] | Dune_engine . Subst_config . Enabled -> ( ) ) ; let info = let loc , name = match dune_project . name with | None -> User_error . raise [ Pp . textf " The project name is not defined , please add a ( name < name ) > \ field to your dune - project file . " ] | Some n -> ( n . loc_of_arg , n . arg ) in let package_named_after_project = let packages = Dune_project . packages dune_project . project in Package . Name . Map . find packages name in let metadata_from_dune_project ( ) = Dune_project . info dune_project . project in let metadata_from_matching_package ( ) = match package_named_after_project with | Some pkg -> Ok pkg . info | None -> Error ( User_error . make ~ loc [ Pp . textf " Package % s doesn ' t exist . " ( Package . Name . to_string name ) ] ) in let version = Dune_project . dune_version dune_project . project in let ok_exn = function | Ok s -> s | Error e -> raise ( User_error . E e ) in if version >= ( 3 , 0 ) then metadata_from_dune_project ( ) else if version >= ( 2 , 8 ) then match metadata_from_matching_package ( ) with | Ok p -> p | Error _ -> metadata_from_dune_project ( ) else ok_exn ( metadata_from_matching_package ( ) ) in let watermarks = make_watermark_map ~ commit ~ version ~ dune_project ~ info in Dune_project . subst ~ map : watermarks ~ version dune_project ; List . iter files ~ f ( : fun path -> if is_a_source_file path && not ( Path . equal path Dune_project . filename ) then subst_file path ~ map : watermarks ) |
let subst ( ) = match Sys . readdir " . " |> Array . to_list |> String . Set . of_list |> Vcs . Kind . of_dir_contents with | None -> Fiber . return ( ) | Some kind -> subst { kind ; root = Path . root } |
type exarray = { mutable len : int ; mutable data : t array ; } |
let make ( ) = { len = 0 ; data = [ ] ; || } |
let extend t = let len = Array . length t . data in t . data <- Array . init ( len + n ) ( fun i -> if i < len then t . data . ( i ) else empty ) |
let rec set a i v = if i >= Array . length a . data then begin extend a ; set a i v end else begin a . data . ( i ) <- v ; a . len <- max a . len ( i + 1 ) end |
let get a i = a . data . ( i ) |
let length a = a . len |
let data a = a . data |
type wave = { name : string ; nbits : int ; data : exarray ; } |
type waves = wave array |
let wrap sim = let ports p = List . map ( fun s -> { name = fst s ; nbits = B . width ( ! snd s ) ; data = make ( ) ; } ) p in let in_ports = ports sim . sim_in_ports in let out_ports = ports sim . sim_out_ports in let trace i x = List . iter2 ( fun a b -> set a . data i ( ! snd b ) ) x in let cycle = ref 0 in let sim_reset ( ) = sim . sim_reset ( ) ; trace ! cycle in_ports sim . sim_in_ports ; trace ! cycle out_ports sim . sim_out_ports ; incr cycle in let sim_cycle_seq ( ) = sim . sim_cycle_seq ( ) ; trace ! cycle in_ports sim . sim_in_ports ; trace ! cycle out_ports sim . sim_out_ports ; incr cycle in { sim with sim_reset = sim_reset ; sim_cycle_seq = sim_cycle_seq } , Array . of_list ( in_ports @ out_ports ) |
module Gui = struct module D = Dom_html let jstr = Js . string let jstri x = jstr ( string_of_int x ) let line ( ~ ctx : D . canvasRenderingContext2D Js . t ) ~ x0 ~ y0 ~ x1 ~ y1 = let f = float_of_int in ctx ( ## moveTo ( f x0 ) ( f y0 ) ) ; ctx ( ## lineTo ( f x1 ) ( f y1 ) ) let delta d = let len = Array . length d in let rec build ( prev , prev_idx ) i = if i = len then [ ] else if d . ( i ) = prev then build ( prev , prev_idx ) ( i + 1 ) else ( d . ( i ) , i ) :: build ( d . ( i ) , i ) ( i + 1 ) in if len = 0 then [ ] else ( d . ( 0 ) , 0 ) :: ( build ( d . ( 0 ) , 0 ) 1 ) let render_1 ( ox , oy ) ( sx , sy ) max_t ( ctx : D . canvasRenderingContext2D Js . t ) d = let d = Array . map to_int d in let d = delta d in let line x0 y0 x1 y1 = line ctx ( x0 * sx + ox ) ( y0 * sy + oy ) ( x1 * sx + ox ) ( y1 * sy + oy ) in let rec render first ( p_d , p_t ) next = match next with | [ ] -> render_elt first p_d p_t max_t | ( n_d , n_t ) :: tl -> if n_t < max_t then begin render_elt first p_d p_t n_t ; render false ( n_d , n_t ) tl end else render_elt first p_d p_t max_t and render_elt first p_d p_t n_t = line p_t ( 1 - p_d ) n_t ( 1 - p_d ) ; if not first then line p_t 0 p_t 1 in match d with | [ ] -> ( ) | h :: t -> render true h t let render_n to_str ( ox , oy ) ( sx , sy ) max_t ( ctx : D . canvasRenderingContext2D Js . t ) d = let d = delta d in let line x0 y0 x1 y1 = line ctx ( x0 * sx + ox ) ( y0 * sy + oy ) ( x1 * sx + ox ) ( y1 * sy + oy ) in let rec text dotted x str w = let jstr = if dotted then jstr ( str " . . " ) ^ else jstr str in let max_w = float ( w * sx - 4 ) in let w ' = ctx ( ## measureText jstr ) . ## width in if w ' > max_w then begin let len = String . length str in if len > 1 then begin text true x ( String . Sub . to_string @@ String . sub str ~ start : 0 ~ stop ( : len - 1 ) ) w end end else ctx ( ## fillText jstr ( float ( x * sx + ox + 2 ) ) ( float ( oy + 2 ) ) ) in let rec render first ( p_d , p_t ) next = match next with | [ ] -> render_elt first p_d p_t max_t | ( n_d , n_t ) :: tl -> if n_t < max_t then begin render_elt first p_d p_t n_t ; render false ( n_d , n_t ) tl end else render_elt first p_d p_t max_t and render_elt first p_d p_t n_t = line p_t 1 n_t 1 ; line p_t 0 n_t 0 ; if not first then line p_t 0 p_t 1 ; text false p_t ( to_str p_d ) ( n_t - p_t ) in match d with | [ ] -> ( ) | h :: t -> render true h t let vlines ( ctx : D . canvasRenderingContext2D Js . t ) width height n = let rec f i = line ctx ( i * width ) 0 ( i * width ) height ; if i = n then ( ) else f ( i + 1 ) in f 0 let mk_canvas width height = let d = D . document in let canvas = D . createCanvas d in let style = canvas . ## style in canvas . ## width := width ; canvas . ## height := height ; style . ## width := jstri width ; style . ## height := jstri height ; canvas let select ( d : exarray ) ofs n = let len = length d in Array . init n ( fun i -> if i + ofs < len then get d ( i + ofs ) else get d ( len - 1 ) ) let mk_wave_table par width height data = let margin = 2 in let w_width , w_height = ref 16 , height ( - 2 * margin ) in let n = ref ( width / ! w_width ) in let ofs = ref 0 in let set_w_width w = let w = max 1 ( min width w ) in w_width := w ; n := width / ! w_width ; in let set_ofs o = ofs := max 0 o in let d = D . document in let table = D . createTable d in let tbody = D . createTbody d in table . ## className := jstr " wave - table " ; Dom . appendChild table tbody ; let create_header ( ) = let trow = D . createTr d in let td = D . createTd d in td . ## className := jstr " wave - name " ; td . ## innerHTML := jstr " cycle " ; Dom . appendChild trow td ; let tdc = D . createTd d in tdc . ## className := jstr " wave - data " ; tdc . ## innerHTML := jstr " 0 " ; Dom . appendChild trow tdc ; let td = D . createTd d in let buttons = List . map ( fun ( title , url , id , margin ) -> let i = D . createInput ~ _type ( : jstr " image " ) d in let s = i . ## style in i . ## title := jstr title ; i . ## src := jstr url ; i . ## alt := jstr id ; s . ## marginLeft := jstr margin ; Dom . appendChild td i ; id , i ) [ " scroll one page backward " , " data : image / png ; base64 , iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAASpJREFUeNq8VksOgjAUbCuJW46AJ9ClO7mBHIGlnsIj6NaVHAGX7vAk4glkS + JvXvIwUmkjQp3kpSGFmfZ9kcICbzicY4lgISzQtnNYBkuvZbk3cUgD8QxL0kBqAonFEDrqG6qBfM0n + 5Zc8LsZf1vDQCPfYVmI3zFVnhfcb7f9hwCrdyGvMIGID5HDKwbs80z0i5BiUgmcWvr8q8BDYCQ5FVPhBpHiPBcuBULDZtHDzULP4PuChScwv2U9BLVnxOCh2QU2 / uW4 + G6l8ynhGJRFD4uLfEuMGn2uvy8tNVBw8XXJslxZKtjvIYUz5bDICKnzVlFlUezg9PGrXaO1nqnFUj / viXyD029r84D6Nw0Lrt4uSEC + bJxoNIk63mTzTv6XoS9d / 7Y8BRgAoCRp6va + RI4AAAAASUVORK5CYII " , = " page_backward " , " 5px " ; " step one cycle backward " , " data : image / png ; base64 , iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAUpJREFUeNq8Vj3OwjAMTUMk1u8GlBt0ZPu4AeUGZYONm8DK9HGEMrKVG3AD4AasSPw9IxdBaYoTymcpiiD1e67tPDdQFWaazR62GKuLFRaOt1gZVno8HBY2jMAC / IttXgJqMyJLQLQqHugS8AlHJgVX / GzGvk / WKID / YRsqf + toY8Lz6bR4IWD2T8Bzi0DyA5LlvQac80zVa12qSV6DudBp7UBww9TciqHQYexSeMLW3OdvwfG6A480xZov0TfAb3Uwb9JTBN9XNENZoGGAPF0sDiQBfWmoNhxd4bOvo1dNxVmCqNRjivC7Rf + 7EFCKNtI6eFzIrRY4JKxRPpYRQSp40JckzbVoI7zNJBWRND1IbTvvImnhIofok7tcQ1p3JLGk5zUp6RTRz57mAek3DQvHKG1dNyqdaDSJPnyT6SP4vwz94NufLVcBBgCMLnX3vQebUQAAAABJRU5ErkJggg " , == " step_backward " , " 5px " ; " step one cycle forward " , " data : image / png ; base64 , iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAUxJREFUeNq8VrsNwjAQtR1LtIwAG1DSkQ2gpAwdTMEI0FLBCKGkCxtkA2ADWiQCvIvOCEIcbCCcZDmSz +/ dne8TKSpENxp9bAOsEKtVON5jJVjx + XRa2zCkBbiHbVUCahMii0C0LR6oEvAZW + YKLlg34btPEhTAl9jG4nPpKq1blyxbvxAw + zfgRjogaYJkc38DjnkifishvYl5g5XHxdRRL8cMOBV9QjM0oXij10SoUsV57iVwfeTo9UBxEYmaSEJdke + 2Rz8 + kiDE9BnZ6kNC4WqxULp6w / VTSqJEzaIrrJra0g / eHVyszwsNCjvPvhOapvYOnJqg + rSCHcDzRCGCuCZwktj0Ip8wpQ5VnIcHoWybLIo8HOg46kX3do3WeqAWS / 38R9k5h / WLp3lA / ZuGhYeFoiKNJ6UTjSbRl57MH8H / MvRl3b8tNwEGAJsIdYLae8SOAAAAAElFTkSuQmCC " , " step_forward " , " 5px " ; " scroll one page forward " , " data : image / png ; base64 , iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAATFJREFUeNq8VrsNwjAUtE0k2owAE0BJBxuQEVLCFIwALRUZwZR0YQM2IEwALRK / e + iBiLERITYnPVmRkzv7fSPFB0TN5hBLAhvAWsZ2Acth + nQ8Ll0c0kHcx5JZSF0gsRRCa3NDWcinfLJvyQW / m / O3JTQM8gWWkfgdPRVFrcv5vHwTYPU65A90IRJDZPWMAfs8F34xoJg8BLYVff5V4CHQVpyKvsnvgSduxXkeConiIqoDDTu44iBxjaulaIoKAlSQG06S2Fa1V8Mmv1wD33Vge5NPicCIbH6DchWOnGNgdZH0UAOaEyW21YLyUMGJg / x + O8UnCAUdvlXwQxrg9OmzXaO17qjFUj / 3RD7D6eeleUD9m4YF9fOa5BnIx9aJRpOo5k1mr + R / Gfoy9G / LTYABAI8sa271ebkxAAAAAElFTkSuQmCC " , " page_forward " , " 5px " ; " zoom out " , " data : image / png ; base64 , iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAARFJREFUeNq8VkEOgjAQbGsTrj4Bf + DRm / xAnsBRX + ET5OpJngBHb / gS5Rkkou6ahQi2BKTrJJuGFGaWnbKLFD3QnreBJYQIIPzO9g0ih0jvZZnZOKSFeA1LYiC1AcUiELp0N5SB / ECZDSUXdG9Oz7Yw65CfYNmK37FSWvuPqsq + BEh9CnmNJYjMQeTceEA1z4VbBOhJLXAdWfNBxoPAQtFRdE3 + Nh65FZ1zLoSSqTxNmVDgadkca3pg / JJtAmCQHMNu41GCGbono70LAXaTFcMX3DooKJAyCqT8rYIuIobso6ZdQ2stsMViP3dEHkP2x9Y8wP6NwwL7 + UTyBMh3xomGk2jim8Sf5H8Z + pL7t + UlwABnxV9UzyoJYgAAAABJRU5ErkJggg " , == " zoom_out " , " 15px " ; " zoom in " , " data : image / png ; base64 , iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAATNJREFUeNq8lkEOgjAQRdvahK1H4Agu3dEbyBFc6inkBrJ1JUeApTu8CR6DRNQZMxioLSlC / UnTEOibdmY6A2cDkkGwgSmGoWCE2usKRgkjv9d1YWNwCziCKTNAbUJjWzB01V8IA / xIO3OFM / q2pLU9LTT4GaYd + 11rIWX4aJriywBZnwJvtQIjSzBy + cSAfF6yeaUwJm0MMocFGWWTGvE9k5SKLgGt2iyBNcol8MgWlOe + FAs6si8pOeCe0nCZ9Fvcg5ncxMFPTxMd / M3HbNXGEcyz5MCODrrLOlkUucZOkj9NcUgMz9eOvxOX1BYebnDv1Ggg92ggF9QsKg9wvPmF92L3LtdQWm9YYrGezwRPAX7q9QOs39gssJ5PhGcA3xs7GnaiiSdJu / C / NH3u + 7flJcAAN2ByK2 / IoW0AAAAASUVORK5CYII " , = " zoom_in " , " 5px " ; ] in Dom . appendChild trow td ; Dom . appendChild tbody trow ; tdc , buttons in let create_wave_row data = let trow = D . createTr d in let td = D . createTd d in td . ## className := jstr " wave - name " ; td . ## innerHTML := jstr ( if data . nbits = 1 then data . name else data . name ^ " [ " ^ string_of_int data . nbits ^ " ] " ) ; Dom . appendChild trow td ; let tdv = D . createTd d in tdv . ## className := jstr " wave - data " ; tdv . ## innerHTML := jstr " XXX " ; Dom . appendChild trow tdv ; let td = D . createTd d in let canvas = mk_canvas width height in let ctx = canvas ( ## getContext ( D . _2d_ ) ) in ctx . ## textBaseline := jstr " top " ; ctx . ## textAlign := jstr " left " ; ctx . ## font := jstr ( string_of_int ( w_height ( - 2 * margin ) ) ^ " px sans - serif " ) ; let clear ( ) = ctx . ## fillStyle := jstr " white " ; ctx ( ## fillRect ( 0 . ) ( 0 . ) ( float width ) ( float height ) ) ; in let grid ( ) = ctx ## beginPath ; ctx . ## strokeStyle := jstr " lightgray " ; vlines ctx ( ! w_width ) height ! n ; ctx ## stroke ; ctx ## closePath ; in let render ( ) = clear ( ) ; grid ( ) ; ctx . ## fillStyle := jstr " black " ; ctx ## beginPath ; ctx . ## strokeStyle := jstr " black " ; ctx . ## lineWidth := 1 . 5 ; ( if data . nbits = 1 then render_1 ( 0 , margin ) ( ! w_width , w_height ) ! n ctx ( select data . data ! ofs ! n ) else let str = B . to_string in render_n str ( 0 , margin ) ( ! w_width , w_height ) ! n ctx ( select data . data ! ofs ! n ) ) ; ctx ## stroke ; ctx ## closePath in Dom . appendChild td canvas ; Dom . appendChild trow td ; Dom . appendChild tbody trow ; tdv , canvas , render , data in let cycle , buttons = create_header ( ) in let waves = Array . map create_wave_row data in let render ( ) = Array . iter ( fun ( _ , _ , r , _ ) -> r ( ) ) waves in let set_values x = Array . iter ( fun ( v , _ , _ , d ) -> let l = length d . data in v . ## innerHTML := jstr ( B . to_string ( get d . data ( min ( l - 1 ) x ) ) ) ) waves in let onclick c = c . ## onclick := D . handler ( fun e -> let clientLeft = int_of_float ( ( Js . to_float c ## getBoundingClientRect . ## left ) . + 0 . 5 ) in let x = ( ( e . ## clientX - clientLeft ) / ! w_width ) + ! ofs in cycle . ## innerHTML := jstri x ; set_values x ; Js . _false ) in Array . iter ( fun ( _ , c , _ , _ ) -> onclick c ) waves ; Dom . appendChild par table ; let param_ev fn = D . handler ( fun _ -> fn ( ) ; render ( ) ; Js . _false ) in let events = [ " zoom_in " , param_ev ( fun ( ) -> set_w_width ( ! w_width * 2 ) ) ; " zoom_out " , param_ev ( fun ( ) -> set_w_width ( ! w_width / 2 ) ) ; " step_forward " , param_ev ( fun _ -> set_ofs ( ! ofs + 1 ) ) ; " step_backward " , param_ev ( fun _ -> set_ofs ( ! ofs - 1 ) ) ; " page_forward " , param_ev ( fun _ -> set_ofs ( ! ofs + ! n ) ) ; " page_backward " , param_ev ( fun _ -> set_ofs ( ! ofs - ! n ) ) ; ] in let rec myassoc a l = match l with | [ ] -> failwith " myassoc " | ( b , c ) :: t -> if a = b then c else myassoc a t in List . iter ( fun ( id , b ) -> let ev = myassoc id events in b . ## onclick := ev ) buttons ; set_values 0 ; render ( ) end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.