text
stringlengths 12
786k
|
---|
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 |
type buffer = { data : Buffer . t ; mutable index : int ; size : int } |
let get ( buffer : buffer ) : char = let c = Buffer . nth buffer . data buffer . index in buffer . index <- buffer . index + 1 ; c |
let get_int ( buffer : buffer ) : int32 = Int32 . of_int ( Char . code ( get buffer ) ) |
let shift_or ( b1 : int32 ) ( b2 : int32 ) : int32 = Int32 . logor ( Int32 . shift_left b2 8 ) b1 |
let read2 ( buffer : buffer ) : int32 = let b1 = get_int buffer in let b2 = get_int buffer in shift_or b1 b2 |
let read3 ( buffer : buffer ) : int32 = let b1 = get_int buffer in let b2 = get_int buffer in let b3 = get_int buffer in b3 |> shift_or b2 |> shift_or b1 |
let read4 ( buffer : buffer ) : int32 = let b1 = get_int buffer in let b2 = get_int buffer in let b3 = get_int buffer in let b4 = get_int buffer in b4 |> shift_or b3 |> shift_or b2 |> shift_or b1 |
let read4_chars ( buffer : buffer ) : string = let c1 = get buffer in let c2 = get buffer in let c3 = get buffer in let c4 = get buffer in let result = Bytes . create 4 in Bytes . set result 0 c1 ; Bytes . set result 1 c2 ; Bytes . set result 2 c3 ; Bytes . set result 3 c4 ; Bytes . to_string result |
let searchData ( buffer : buffer ) : bool = let rec skipData n = if n = 0 then ( ) else let _ = get buffer in skipData ( n - 1 ) in let rec loop ( ) = if read4_chars buffer = " data " then true else let size = read4 buffer |> Int32 . to_int in let ( ) = skipData size in loop ( ) in match loop ( ) with | found -> found | exception Invalid_argument _ -> false |
let max_16 = ( 2 . 0 ** 16 . 0 ) . / 2 . 0 |
let sign_16 = Int32 . shift_left Int32 . one 15 |
let mask_16 = Int32 . shift_left Int32 . minus_one 15 |
let readSample16 ( buffer : buffer ) : float = let v = read2 buffer in if Int32 . logand sign_16 v <> Int32 . zero then Int32 . to_float ( Int32 . logor mask_16 v ) . / max_16 else Int32 . to_float v . / max_16 |
let max_24 = ( 2 . 0 ** 24 . 0 ) . / 2 . 0 |
let sign_24 = Int32 . shift_left Int32 . one 23 |
let mask_24 = Int32 . shift_left Int32 . minus_one 23 |
let readSample24 ( buffer : buffer ) : float = let v = read2 buffer in if Int32 . logand sign_24 v <> Int32 . zero then Int32 . to_float ( Int32 . logor mask_24 v ) . / max_24 else Int32 . to_float v . / max_24 |
let getReadSampleFunction ( bits : int32 ) : ( buffer -> float , string ) result = match Int32 . to_int bits with | 16 -> Ok readSample16 | 24 -> Ok readSample24 | _ -> Error ( " Wave file encoded in an unsupported bits per sample : " ^ string_of_int ( Int32 . to_int bits ) ) |
let readSamples ( buffer : buffer ) ( channels : int ) ( size : int ) ( data : float array array ) ( read_fn : buffer -> float ) : int = let rec loop_channels index channel = if channel >= channels then true else try let value = read_fn buffer in let channel_data = data . ( channel ) in let ( ) = channel_data . ( index ) <- value in loop_channels index ( channel + 1 ) with | Invalid_argument _ -> false in let rec loop_samples index = if index >= size then size else if loop_channels index 0 then loop_samples ( index + 1 ) else index - 1 in loop_samples 0 |
let checkFormat ( buffer : buffer ) = if not ( read4_chars buffer = " RIFF " ) then Error " Not a valid file " else let chunk_size = read4 buffer in if chunk_size < Int32 . of_int 4 then Error " Invalid chunk size " else if not ( read4_chars buffer = " WAVE " ) then Error " Not a supported wav file " else if not ( read4_chars buffer = " fmt " ) then Error " Not a supported wav file " else let sub_chunk_size = read4 buffer in let audio_format = read2 buffer in if sub_chunk_size <> Int32 . of_int 16 || audio_format <> Int32 . one then Error " Input file is not in PCM format " else Ok ( ) |
type wave = { channels : int ; samples : int ; data : float array array } |
let read ( file : string ) : ( wave , string ) result = match FileIO . read_bytes file with | None -> Error " failed to open the file " | Some data -> let buffer = { index = 0 ; size = Buffer . length data ; data } in ( match checkFormat buffer with | Error _ as error -> error | Ok ( ) -> let channels = read2 buffer |> Int32 . to_int in let _sample_rate = read4 buffer in let _byte_rate = read4 buffer in let _block_align = read2 buffer in let bits_per_sample = read2 buffer in ( match getReadSampleFunction bits_per_sample with | Error _ as e -> e | Ok sample_fn -> if not ( searchData buffer ) then Error " the file does not contain data " else let size = read4 buffer |> Int32 . to_int in let no_samples = size / channels / ( Int32 . to_int bits_per_sample / 8 ) in let data = Array . init channels ( fun _ -> Array . make no_samples 0 . 0 ) in let samples = readSamples buffer channels no_samples data sample_fn in Ok { channels ; samples ; data } ) ) |
let callback fn = object inherit [ _ ] Wayland_client . Wl_callback . v1 method on_done ~ callback_data = fn callback_data end |
let chars = ref 0 |
type state = Inside_word | Outside_word |
let count_channel in_channel = let rec count status = let c = input_char in_channel in incr chars ; match c with ' \ n ' -> incr lines ; count Outside_word | ' ' | ' \ t ' -> count Outside_word | _ -> if status = Outside_word then begin incr words ; ( ) end ; count Inside_word in try count Outside_word with End_of_file -> ( ) |
let count_file name = let ic = open_in name in count_channel ic ; close_in ic |
let print_result ( ) = print_int ! chars ; print_string " characters , " ; print_int ! words ; print_string " words , " ; print_int ! lines ; print_string " lines " ; print_newline ( ) |
let count name = count_file name ; print_result ( ) |
let _ = try if Array . length Sys . argv <= 1 then count_channel stdin else for i = 1 to Array . length Sys . argv - 1 do count_file Sys . argv . ( i ) done ; print_result ( ) print_string " I / O error : " ; print_string s ; print_newline ( ) |
type structured_code = { functions : func_block IMap . t ; } and func_block = { scope : cfg_scope ; block : block ; } and block = { loop_label : int option ; instructions : instruction array ; break_label : int option ; } and instruction = | Block of block | Label of int | Simple of I . instruction | Trap of { trylabel : int ; catchlabel : int ; poplabel : int option } | TryReturn | NextMain of int and cfg_scope = { cfg_letrec_label : int option ; cfg_func_label : int ; cfg_try_labels : int list ; cfg_main : bool ; } |
type trap_info = | Trap_push of int * int option | Trap_pop of int * int |
type try_info = | Try_entry of int | Try_exit |
type cfg_node = { cfg_scope : cfg_scope ; cfg_node_label : int ; cfg_try : try_info option ; cfg_trap : trap_info option ; mutable cfg_loops : int list ; cfg_succ : int list ; cfg_length : int ; cfg_final : I . instruction option ; cfg_next_main : int option ; } |
type cfg = { mutable nodes : cfg_node IMap . t ; mutable code : I . instruction array ; mutable labels : ISet . t ; } |
let string_of_scope s = sprintf " [ letrec =% s , func =% d , try =% s ] " ( match s . cfg_letrec_label with | None -> " none " | Some l -> string_of_int l ) s . cfg_func_label ( List . map string_of_int s . cfg_try_labels |> String . concat " , " ) |
let detect_loops ctx = let visited = ref ISet . empty in let trails = ref IMap . empty in let rec recurse exectrail label = let node = try IMap . find label ctx . nodes with Not_found -> assert false in if not ( ISet . mem label ! visited ) then ( visited := ISet . add label ! visited ; trails := IMap . add label exectrail ! trails ; let exectrail ' = ISet . add label exectrail in List . iter ( recurse exectrail ' ) node . cfg_succ ) else ( let loop_label_opt = if ISet . mem label exectrail then Some label else ( match node . cfg_loops with | [ ] -> None | l :: _ -> assert ( ISet . mem l exectrail ) ; Some l ) in match loop_label_opt with | Some loop_label -> let old_trail = try IMap . find loop_label ! trails with Not_found -> assert false in let loops = if node . cfg_loops = [ ] || List . hd node . cfg_loops <> loop_label then loop_label :: node . cfg_loops else node . cfg_loops in ISet . iter ( fun lab -> let n = try IMap . find lab ctx . nodes with Not_found -> assert false in if not ( List . mem loop_label n . cfg_loops ) then n . cfg_loops <- loops ) ( ISet . diff exectrail old_trail ) | None -> ( ) ) in IMap . iter ( fun label node -> let is_entry = label = node . cfg_scope . cfg_func_label || match node . cfg_try with | Some ( Try_entry _ ) -> true | _ -> false in if is_entry then recurse ISet . empty label ) ctx . nodes |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.