Source file import.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
(*******************************************************************************)
(*  Volgo - a Versatile OCaml Library for Git Operations                       *)
(*  Copyright (C) 2024-2025 Mathieu Barbin <mathieu.barbin@gmail.com>          *)
(*                                                                             *)
(*  This file is part of Volgo.                                                *)
(*                                                                             *)
(*  Volgo is free software; you can redistribute it and/or modify it under     *)
(*  the terms of the GNU Lesser General Public License as published by the     *)
(*  Free Software Foundation either version 3 of the License, or any later     *)
(*  version, with the LGPL-3.0 Linking Exception.                              *)
(*                                                                             *)
(*  Volgo is distributed in the hope that it will be useful, but WITHOUT ANY   *)
(*  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS  *)
(*  FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License and    *)
(*  the file `NOTICE.md` at the root of this repository for more details.      *)
(*                                                                             *)
(*  You should have received a copy of the GNU Lesser General Public License   *)
(*  and the LGPL-3.0 Linking Exception along with this library. If not, see    *)
(*  <http://www.gnu.org/licenses/> and <https://spdx.org>, respectively.       *)
(*******************************************************************************)

open! Stdlib_compat

module Array = struct
  include ArrayLabels

  let create ~len a = make len a

  let filter_mapi t ~f =
    let out_count = ref 0 in
    let out = ref [] in
    iteri t ~f:(fun i a ->
      match f i a with
      | None -> ()
      | Some e ->
        incr out_count;
        out := e :: !out);
    match !out with
    | [] -> [||]
    | hd :: _ ->
      let out_count = !out_count in
      let res = create ~len:out_count hd in
      List.iteri (fun i a -> res.(out_count - 1 - i) <- a) !out;
      res
  ;;

  let rev a =
    let len = length a in
    let res = create ~len a.(0) in
    iteri a ~f:(fun i x -> res.(len - 1 - i) <- x);
    res
  ;;

  let sort t ~compare = sort t ~cmp:compare
end

module Char = struct
  include Char

  let is_alphanum = function
    | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' -> true
    | _ -> false
  ;;

  let is_whitespace = function
    | '\t' | '\n' | '\011' (* vertical tab *) | '\012' (* form feed *) | '\r' | ' ' ->
      true
    | _ -> false
  ;;
end

module Hashtbl = struct
  include (
    MoreLabels.Hashtbl :
      module type of MoreLabels.Hashtbl with module Make := MoreLabels.Hashtbl.Make)

  module type S_extended = sig
    include MoreLabels.Hashtbl.S

    val add_exn : 'a t -> key:key -> data:'a -> unit
    val add_multi : 'a list t -> key:key -> data:'a -> unit
    val find : 'a t -> key -> 'a option
    val set : 'a t -> key:key -> data:'a -> unit
  end

  exception E of Sexp.t

  let () =
    Sexplib0.Sexp_conv.Exn_converter.add [%extension_constructor E] (function
      | E sexp -> sexp
      | _ -> assert false)
  ;;

  module Make (H : sig
      include Hashtbl.HashedType

      val sexp_of_t : t -> Sexp.t
    end) =
  struct
    include MoreLabels.Hashtbl.Make (H)

    let add_exn t ~key ~data =
      if mem t key
      then raise (E [%sexp "Hashtbl.add_exn: key already present", { key : H.t }])
      else add t ~key ~data
    ;;

    let add_multi t ~key ~data =
      let data =
        match find_opt t key with
        | None -> [ data ]
        | Some l -> data :: l
      in
      replace t ~key ~data
    ;;

    let find = find_opt
    let set = replace
  end
end

module Int = struct
  include Int

  let incr = incr
  let max_value = max_int

  let of_string s =
    try int_of_string s with
    | _ -> failwith (Printf.sprintf "Int.of_string: %S" s)
  ;;

  let of_string_opt = int_of_string_opt

  let to_string_hum n =
    let s = string_of_int n in
    let len = String.length s in
    let is_negative = n < 0 in
    let sign_count = if is_negative then 1 else 0 in
    let absolute_digit_count = if is_negative then len - 1 else len in
    let separator_count = absolute_digit_count / 3 in
    let initial_skip_count =
      let digit_skip = absolute_digit_count mod 3 in
      sign_count + if digit_skip > 0 then digit_skip else 3
    in
    let buffer = Buffer.create (len + separator_count) in
    let rec aux i count =
      if i < len
      then
        if count = 0
        then (
          Buffer.add_char buffer '_';
          aux i 3)
        else (
          Buffer.add_char buffer s.[i];
          aux (i + 1) (count - 1))
    in
    aux 0 initial_skip_count;
    Buffer.contents buffer
  ;;
end

module List = struct
  include ListLabels

  let dedup_and_sort t ~compare = sort_uniq t ~cmp:compare

  let hd = function
    | [] -> None
    | hd :: _ -> Some hd
  ;;

  let filter_opt t = filter_map t ~f:Fun.id
  let find t ~f = find_opt t ~f
  let fold t ~init ~f = fold_left ~f ~init t
  let sort t ~compare = sort t ~cmp:compare
end

module Option = struct
  include Option

  let map t ~f = map f t
  let some_if cond a = if cond then Some a else None
end

module Ordering = struct
  type t =
    | Less
    | Equal
    | Greater

  let of_int i = if i < 0 then Less else if i = 0 then Equal else Greater
end

module Queue = struct
  include Queue

  let enqueue t a = push a t
  let to_list t = t |> to_seq |> List.of_seq
end

module Result = struct
  type ('a, 'b) t = ('a, 'b) Result.t =
    | Ok of 'a
    | Error of 'b
  [@@deriving sexp_of]

  include (Result : module type of Result with type ('a, 'b) t := ('a, 'b) t)

  module Monad_syntax = struct
    let ( let* ) = Result.bind
  end

  let map t ~f = map f t
  let map_error t ~f = map_error f t

  let of_option t ~error =
    match t with
    | Some v -> Ok v
    | None -> Error error
  ;;

  let return = ok
end

module String = struct
  include StringLabels

  let to_string t = t

  let chop_prefix t ~prefix =
    if Astring.String.is_prefix t ~affix:prefix
    then Some (Astring.String.with_index_range t ~first:(String.length prefix))
    else None
  ;;

  let chop_suffix t ~suffix =
    if Astring.String.is_suffix t ~affix:suffix
    then
      Some
        (Astring.String.with_index_range
           t
           ~last:(String.length t - String.length suffix - 1))
    else None
  ;;

  let init len ~f = String.init len f
  let is_empty = Astring.String.is_empty
  let lsplit2 t ~on = Astring.String.cut ~sep:(String.make 1 on) t
  let rsplit2 t ~on = Astring.String.cut ~sep:(String.make 1 on) t ~rev:true

  (* The function [split_lines] below was copied from [Base.String0.split_lines]
     version [v0.17] which is released under MIT and may be found at
     [https://github.com/janestreet/base].

     The changes we made were minimal:

     - Changed references to [Char0] to [Char].

     See Base's LICENSE below:

     ----------------------------------------------------------------------------

     The MIT License

     Copyright (c) 2016--2024 Jane Street Group, LLC <opensource-contacts@janestreet.com>

     Permission is hereby granted, free of charge, to any person obtaining a copy
     of this software and associated documentation files (the "Software"), to deal
     in the Software without restriction, including without limitation the rights
     to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     copies of the Software, and to permit persons to whom the Software is
     furnished to do so, subject to the following conditions:

     The above copyright notice and this permission notice shall be included in all
     copies or substantial portions of the Software.

     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
     SOFTWARE. *)

  let split_lines =
    let back_up_at_newline ~t ~pos ~eol =
      pos := !pos - if !pos > 0 && Char.equal t.[!pos - 1] '\r' then 2 else 1;
      eol := !pos + 1
    in
    fun t ->
      let n = length t in
      if n = 0
      then []
      else (
        (* Invariant: [-1 <= pos < eol]. *)
        let pos = ref (n - 1) in
        let eol = ref n in
        let ac = ref [] in
        (* We treat the end of the string specially, because if the string ends with a
           newline, we don't want an extra empty string at the end of the output. *)
        if Char.equal t.[!pos] '\n' then back_up_at_newline ~t ~pos ~eol;
        while !pos >= 0 do
          if not (Char.equal t.[!pos] '\n')
          then decr pos
          else (
            (* Because [pos < eol], we know that [start <= eol]. *)
            let start = !pos + 1 in
            ac := sub t ~pos:start ~len:(!eol - start) :: !ac;
            back_up_at_newline ~t ~pos ~eol)
        done;
        sub t ~pos:0 ~len:!eol :: !ac)
  ;;

  (* ---------------------------------------------------------------------------- *)

  let split t ~on = split_on_char ~sep:on t
  let strip = trim
  let uncapitalize = uncapitalize_ascii
end

let compare_bool = Bool.compare
let compare_int = Int.compare
let compare_string = String.compare
let equal_bool = Bool.equal
let equal_int = Int.equal
let equal_string = String.equal
let equal_list eq a b = List.equal ~eq a b
let hash_string = String.hash