Add TODO note for better abstractions
[dups.git] / dups.ml
diff --git a/dups.ml b/dups.ml
index a1dca83..c627369 100644 (file)
--- a/dups.ml
+++ b/dups.ml
@@ -2,6 +2,8 @@ open Printf
 
 module Array = ArrayLabels
 module List  = ListLabels
+module StrSet = Set.Make(String)
+module Unix  = UnixLabels
 
 module Stream : sig
   type 'a t
@@ -9,17 +11,58 @@ module Stream : sig
   val create : (unit -> 'a option) -> 'a t
 
   val iter : 'a t -> f:('a -> unit) -> unit
+
+  val map : 'a t -> f:('a -> 'b) -> 'b t
+
+  val filter : 'a t -> f:('a -> bool) -> 'a t
+
+  val concat : ('a t) list -> 'a t
 end = struct
   module S = Stream
 
   type 'a t =
-    'a S.t
+    {mutable streams : ('a S.t) list}
 
   let create f =
-    S.from (fun _ -> f ())
+    {streams = [S.from (fun _ -> f ())]}
+
+  let rec next t =
+    match t.streams with
+    | [] ->
+        None
+    | s :: streams ->
+        (match S.next s with
+        | exception Stream.Failure ->
+            t.streams <- streams;
+            next t
+        | x ->
+            Some x
+        )
+
+  let map t ~f =
+    create (fun () ->
+      match next t with
+      | None   -> None
+      | Some x -> Some (f x)
+    )
+
+  let filter t ~f =
+    let rec filter () =
+      match next t with
+      | None ->
+          None
+      | Some x when f x ->
+          Some x
+      | Some _ ->
+          filter ()
+    in
+    create filter
 
   let iter t ~f =
-    S.iter f t
+    List.iter t.streams ~f:(S.iter f)
+
+  let concat ts =
+    {streams = List.concat (List.map ts ~f:(fun {streams} -> streams))}
 end
 
 module In_channel : sig
@@ -35,19 +78,45 @@ end = struct
     )
 end
 
-module Directory : sig
-  val find_files : string -> string Stream.t
+module File : sig
+  type t =
+    { path : string
+    ; size : int
+    }
+
+  val find : string -> t Stream.t
+  (** Find all files in the directory tree, starting from the given root path *)
+
+  val lookup : string Stream.t -> t Stream.t
+  (** Lookup file info for given paths *)
+
+  module Set : sig include Set.S with type elt := t end
 end = struct
-  let find_files root =
+  type t =
+    { path : string
+    ; size : int
+    }
+
+  let compare {path=p1; _} {path=p2; _} =
+    Stdlib.compare p1 p2
+
+  let lookup paths =
+    Stream.map paths ~f:(fun path ->
+      let {Unix.st_size = size; _} = Unix.lstat path in
+      {path; size}
+    )
+
+  let find root =
     let dirs  = Queue.create () in
     let files = Queue.create () in
     let explore parent =
       Array.iter (Sys.readdir parent) ~f:(fun child ->
         let path = Filename.concat parent child in
-        let {Unix.st_kind = file_kind; _} = Unix.lstat path in
+        let {Unix.st_kind = file_kind; st_size; _} = Unix.lstat path in
         match file_kind with
         | Unix.S_REG ->
-            Queue.add path files
+            let file = {path; size = st_size} in
+            Queue.add file files
         | Unix.S_DIR ->
             Queue.add path dirs
         | Unix.S_CHR
@@ -58,75 +127,249 @@ end = struct
             ()
       )
     in
-    let next_dir () =
-      match Queue.take dirs with
-      | exception Queue.Empty ->
-          ()
-      | dir ->
-          explore dir
-    in
-    let next_file () =
-      match Queue.take files with
-      | exception Queue.Empty ->
-          None
-      | file_path ->
-          Some file_path
-    in
     explore root;
-    Stream.create (fun () ->
-      next_dir ();
-      next_file ()
-    )
+    let rec next () =
+      match Queue.is_empty files, Queue.is_empty dirs with
+      | false, _     -> Some (Queue.take files)
+      | true , true  -> None
+      | true , false ->
+          explore (Queue.take dirs);
+          next ()
+    in
+    Stream.create next
+
+  module Set = Set.Make(struct
+    type elt = t
+    type t = elt
+    let compare = compare
+  end)
 end
 
 type input =
-  | Root_path of string
-  | Paths_on_stdin
+  | Stdin
+  | Directories of string list
+
+type output =
+  | Stdout
+  | Directory of string
+
+type opt =
+  { input  : input
+  ; output : output
+  ; ignore : Str.regexp option
+  ; sample : int
+  }
+
+type count =
+  { considered  : int ref
+  ; empty       : int ref
+  ; ignored     : int ref
+  ; unique_size : int ref
+  ; unique_sample : int ref
+  ; hashed      : int ref
+  }
 
-let main input =
-  let paths =
+let make_input_stream input ignore count =
+  let input =
     match input with
-    | Paths_on_stdin -> In_channel.lines stdin
-    | Root_path root -> Directory.find_files root
+    | Stdin ->
+        File.lookup (In_channel.lines stdin)
+    | Directories paths ->
+        let paths = StrSet.elements (StrSet.of_list paths) in
+        Stream.concat (List.map paths ~f:File.find)
   in
-  let paths_by_digest = Hashtbl.create 1_000_000 in
-  let path_count = ref 0 in
+  Stream.filter input ~f:(fun {File.path; size} ->
+    incr count.considered;
+    let empty = size = 0 in
+    let ignored =
+      match ignore with
+      | Some regexp when (Str.string_match regexp path 0) ->
+          true
+      | Some _ | None ->
+          false
+    in
+    if empty   then incr count.empty;
+    if ignored then incr count.ignored;
+    (not empty) && (not ignored)
+  )
+
+let make_output_fun = function
+  | Stdout ->
+      fun digest n_files files ->
+        printf "%s %d\n%!" (Digest.to_hex digest) n_files;
+        List.iter (File.Set.elements files) ~f:(fun {File.path; _} ->
+          printf "    %S\n%!" path
+        )
+  | Directory dir ->
+      fun digest _ files ->
+        let digest = Digest.to_hex digest in
+        let dir = Filename.concat dir (String.sub digest 0 2) in
+        Unix.mkdir dir ~perm:0o700;
+        let oc = open_out (Filename.concat dir digest) in
+        List.iter (File.Set.elements files) ~f:(fun {File.path; _} ->
+          output_string oc (sprintf "%S\n%!" path)
+        );
+        close_out oc
+
+let sample path ~len =
+  let buf = Bytes.make len ' ' in
+  let ic = open_in_bin path in
+  let rec read pos len =
+    assert (len >= 0);
+    if len = 0 then
+      ()
+    else begin
+      let chunk_size = input ic buf pos len in
+      if chunk_size = 0 then (* EOF *)
+        ()
+      else
+        read (pos + chunk_size) (len - chunk_size)
+    end
+  in
+  read 0 len;
+  close_in ic;
+  Bytes.to_string buf
+
+let main {input; output; ignore; sample = sample_len} =
   let t0 = Sys.time () in
-  Stream.iter paths ~f:(fun path ->
-    incr path_count;
-    try
-      let digest = Digest.file path in
-      let paths =
-        match Hashtbl.find_opt paths_by_digest digest with
-        | None ->
-            []
-        | Some paths ->
-            paths
-      in
-      Hashtbl.replace paths_by_digest digest (path :: paths)
-    with Sys_error e ->
-      eprintf "WARNING: Failed to process %S: %S\n%!" path e
+  let count =
+    { considered  = ref 0
+    ; empty       = ref 0
+    ; ignored     = ref 0
+    ; unique_size = ref 0
+    ; hashed      = ref 0
+    ; unique_sample     = ref 0
+    }
+  in
+  let output = make_output_fun  output in
+  let input  = make_input_stream input ignore count in
+  let files_by_size = Hashtbl.create 1_000_000 in
+  let files_by_sample = Hashtbl.create 1_000_000 in
+  let files_by_digest = Hashtbl.create 1_000_000 in
+  let process tbl ~group ~file =
+    let count, files =
+      match Hashtbl.find_opt tbl group with
+      | None ->
+          (0, File.Set.empty)
+      | Some (n, files) ->
+          (n, files)
+    in
+    Hashtbl.replace tbl group (count + 1, File.Set.add file files)
+  in
+  (* TODO: Make a nice(r) abstraction to re-assemble pieces in the pipeline:
+   *
+   * from input           to files_by_size
+   * from files_by_size   to files_by_sample
+   * from files_by_sample to files_by_digest
+   * from files_by_digest to output
+   *
+   * input |> files_by_size |> files_by_sample |> files_by_digest |> output
+   *)
+  Stream.iter input ~f:(fun ({File.size; _} as file) ->
+    process files_by_size ~group:size ~file
   );
   Hashtbl.iter
-    (fun digest paths ->
-      let n_paths = List.length paths in
-      if n_paths > 1 then begin
-        printf "%s %d\n%!" (Digest.to_hex digest) n_paths;
-        List.iter paths ~f:(fun path -> printf "    %s\n%!" path)
-      end
+    (fun _ (n, files) ->
+      (* Skip files with unique sizes *)
+      if n > 1 then
+        File.Set.iter
+          (fun ({File.path; _} as file) ->
+            process
+              files_by_sample
+              ~group:(sample path ~len:sample_len)
+              ~file
+          )
+          files
+      else
+        incr count.unique_size;
+    )
+    files_by_size;
+  Hashtbl.iter
+    (fun _ (n, files) ->
+      (* Skip files with unique samples *)
+      if n > 1 then
+        File.Set.iter
+          (fun ({File.path; _} as file) ->
+            incr count.hashed;
+            process files_by_digest ~group:(Digest.file path) ~file
+          )
+          files
+      else
+        incr count.unique_sample;
+    )
+    files_by_sample;
+  Hashtbl.iter
+    (fun d (n, files) ->
+      if n > 1 then
+        output d n files
     )
-    paths_by_digest;
+    files_by_digest;
   let t1 = Sys.time () in
-  eprintf "Processed %d files in %f seconds.\n%!" !path_count (t1 -. t0)
+  eprintf "Time                       : %f seconds\n%!" (t1 -. t0);
+  eprintf "Considered                 : %d\n%!" !(count.considered);
+  eprintf "Hashed                     : %d\n%!" !(count.hashed);
+  eprintf "Skipped due to 0      size : %d\n%!" !(count.empty);
+  eprintf "Skipped due to unique size : %d\n%!" !(count.unique_size);
+  eprintf "Skipped due to unique sample : %d\n%!" !(count.unique_sample);
+  eprintf "Ignored due to regex match : %d\n%!" !(count.ignored)
 
-let () =
-  let input = ref Paths_on_stdin in
-  Arg.parse [] (fun path ->
-    if Sys.file_exists path then
-      input := Root_path path
-    else begin
-      eprintf "File does not exist: %S\n%!" path;
+let get_opt () : opt =
+  let assert_ test x msg =
+    if not (test x) then begin
+      eprintf "%s\n%!" msg;
       exit 1
     end
-  ) "";
-  main !input
+  in
+  let assert_file_exists path =
+    assert_ Sys.file_exists path (sprintf "File does not exist: %S" path)
+  in
+  let assert_file_is_dir path =
+    assert_ Sys.is_directory path (sprintf "File is not a directory: %S" path)
+  in
+  let input  = ref Stdin in
+  let output = ref Stdout in
+  let ignore = ref None in
+  let sample = ref 256 in
+  let spec =
+    [ ( "-out"
+      , Arg.String (fun path ->
+          assert_file_exists path;
+          assert_file_is_dir path;
+          output := Directory path
+        )
+      , " Output to this directory instead of stdout."
+      )
+    ; ( "-ignore"
+      , Arg.String (fun regexp -> ignore := Some (Str.regexp regexp))
+      , " Ignore file paths which match this regexp pattern (see Str module)."
+      )
+    ; ( "-sample"
+      , Arg.Set_int sample
+      , (sprintf " Byte size of file samples to use. Default: %d" !sample)
+      )
+    ]
+  in
+  Arg.parse
+    (Arg.align spec)
+    (fun path ->
+      assert_file_exists path;
+      assert_file_is_dir path;
+      match !input with
+      | Stdin ->
+          input := Directories [path]
+      | Directories paths ->
+          input := Directories (path :: paths)
+    )
+    "";
+  assert_
+    (fun x -> x > 0)
+    !sample
+    (sprintf "Sample size cannot be negative: %d" !sample);
+  { input  = !input
+  ; output = !output
+  ; ignore = !ignore
+  ; sample = !sample
+  }
+
+let () =
+  main (get_opt ())
This page took 0.025614 seconds and 4 git commands to generate.