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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
(* src/package_manager/update_manager.ml *)
(* Handles dependency updates: regenerate flake.nix from TOML, then lock *)

open Package_types
open Release_manager

module String_set = Set.Make (String)

type remote_tag_update = {
  dependency_name : string;
  current_tag : string;
  latest_tag : string;
}

(** Extract the nixpkgs date from an existing flake.nix by looking for
    the pattern "rstats-on-nix/nixpkgs/YYYY-MM-DD" *)
let extract_nixpkgs_date flake_content =
  let prefix = "rstats-on-nix/nixpkgs/" in
  let plen = String.length prefix in
  let rec search i =
    if i + plen + 10 > String.length flake_content then None
    else if String.sub flake_content i plen = prefix then
      let date = String.sub flake_content (i + plen) 10 in
      (* Basic sanity check: YYYY-MM-DD *)
      if String.length date = 10 && date.[4] = '-' && date.[7] = '-' then
        Some date
      else
        search (i + 1)
    else
      search (i + 1)
  in
  search 0

(** Read a file's contents *)
let read_file path =
  try
    let ch = open_in path in
    let content = really_input_string ch (in_channel_length ch) in
    close_in ch;
    Ok content
  with Sys_error msg -> Error msg

let parse_remote_tag_refs output =
  let prefix = "refs/tags/" in
  let prefix_len = String.length prefix in
  output
  |> String.split_on_char '\n'
  |> List.fold_left
       (fun acc line ->
         match String.split_on_char '\t' (String.trim line) with
         | [_sha; refname] when String.starts_with ~prefix refname ->
             let tag = String.sub refname prefix_len (String.length refname - prefix_len) in
             if String.ends_with ~suffix:"^{}" tag then
               acc
             else
               tag :: acc
         | _ -> acc)
       []
  |> List.rev

let latest_semver_tag tags =
  let versioned_tags =
    List.fold_left
      (fun acc tag ->
        match Scaffold.parse_semver tag with
        | Some semver -> (semver, tag) :: acc
        | None -> acc)
      []
      tags
  in
  match versioned_tags with
  | [] -> None
  | (semver, tag) :: rest ->
      let _, latest_tag =
        List.fold_left
          (fun (best_semver, best_tag) (candidate_semver, candidate_tag) ->
            if Scaffold.compare_semver candidate_semver best_semver > 0 then
              (candidate_semver, candidate_tag)
            else
              (best_semver, best_tag))
          (semver, tag)
          rest
      in
      Some latest_tag

type loaded_dependency_source =
  | Project_config of string * project_config
  | Package_config of string * package_config

type project_dependency_counts = {
  t_dependencies : int;
  r_dependencies : int;
  python_dependencies : int;
  additional_tools : int;
  latex_packages : int;
}

let project_dependency_counts cfg =
  {
    t_dependencies = List.length cfg.proj_dependencies;
    r_dependencies = List.length cfg.proj_r_dependencies;
    python_dependencies = List.length cfg.proj_py_dependencies;
    additional_tools = List.length cfg.proj_additional_tools;
    latex_packages = List.length cfg.proj_latex_packages;
  }

let pluralize count singular plural =
  if count = 1 then singular else plural

let format_labeled_count count label singular plural =
  Printf.sprintf "%d %s %s" count label (pluralize count singular plural)

let optional_labeled_count count label singular plural =
  if count > 0 then
    Some (format_labeled_count count label singular plural)
  else
    None

let project_dependency_count_segments counts =
  let base_segments =
    [
      format_labeled_count counts.t_dependencies "T" "dependency" "dependencies";
      format_labeled_count counts.r_dependencies "R" "dependency" "dependencies";
      format_labeled_count
        counts.python_dependencies
        "Python"
        "dependency"
        "dependencies";
    ]
  in
  let extra_segments =
    List.filter_map
      (fun segment -> segment)
      [
        optional_labeled_count
          counts.additional_tools
          "additional"
          "tool"
          "tools";
        optional_labeled_count
          counts.latex_packages
          "LaTeX"
          "package"
          "packages";
      ]
  in
  base_segments @ extra_segments

let format_count_segments segments =
  match segments with
  | [] -> ""
  | [segment] -> segment
  | [first; second] -> first ^ " and " ^ second
  | _ ->
      let reversed = List.rev segments in
      (match reversed with
      | last :: rest_rev ->
          String.concat ", " (List.rev rest_rev) ^ " and " ^ last
      | [] -> "")

let format_project_sync_message cfg =
  let counts = project_dependency_counts cfg in
  Printf.sprintf
    "Syncing %s from tproject.toml → flake.nix...\n"
    (format_count_segments (project_dependency_count_segments counts))

let format_no_t_project_dependencies_message config_name cfg =
  let counts = project_dependency_counts cfg in
  let non_t_segments =
    List.filter_map
      (fun segment -> segment)
      [
        optional_labeled_count counts.r_dependencies "R" "dependency" "dependencies";
        optional_labeled_count
          counts.python_dependencies
          "Python"
          "dependency"
          "dependencies";
        optional_labeled_count
          counts.additional_tools
          "additional"
          "tool"
          "tools";
        optional_labeled_count
          counts.latex_packages
          "LaTeX"
          "package"
          "packages";
      ]
  in
  if non_t_segments = [] then
    Printf.sprintf "No T package dependencies declared in %s.\n" config_name
  else
    Printf.sprintf
      "No T package dependencies declared in %s; project defines %s.\n"
      config_name
      (format_count_segments non_t_segments)

let load_current_dependency_source () =
  let dir = Sys.getcwd () in
  let tproject_path = Filename.concat dir "tproject.toml" in
  let description_path = Filename.concat dir "DESCRIPTION.toml" in
  if Sys.file_exists tproject_path then
    match read_file tproject_path with
    | Error msg -> Error (Printf.sprintf "Cannot read tproject.toml: %s" msg)
    | Ok content ->
        (match Toml_parser.parse_tproject_toml content with
        | Error msg -> Error (Printf.sprintf "Cannot parse tproject.toml: %s" msg)
        | Ok cfg -> Ok (Project_config ("tproject.toml", cfg)))
  else if Sys.file_exists description_path then
    match read_file description_path with
    | Error msg -> Error (Printf.sprintf "Cannot read DESCRIPTION.toml: %s" msg)
    | Ok content ->
        (match Toml_parser.parse_description_toml content with
        | Error msg -> Error (Printf.sprintf "Cannot parse DESCRIPTION.toml: %s" msg)
        | Ok cfg -> Ok (Package_config ("DESCRIPTION.toml", cfg)))
  else
    Error "No tproject.toml or DESCRIPTION.toml found in the current directory."

let is_safe_git_location url =
  let len = String.length url in
  let rec check i =
    if i >= len then
      true
    else
      match url.[i] with
      | '\000' | '\n' | '\r' -> false
      | _ -> check (i + 1)
  in
  len > 0 && url.[0] <> '-' && check 0

let run_git_ls_remote_tags url =
  if not (is_safe_git_location url) then
    Error "invalid repository location"
  else
    try
      let argv = [| "git"; "ls-remote"; "--tags"; url |] in
      let ch_in, ch_out, ch_err =
        Unix.open_process_args_full "git" argv (Unix.environment ())
      in
      close_out ch_out;
      let out_buf = Buffer.create 1024 in
      let err_buf = Buffer.create 1024 in
      let buf = Bytes.create 4096 in
      let fd_out = Unix.descr_of_in_channel ch_in in
      let fd_err = Unix.descr_of_in_channel ch_err in
      let rec drain out_open err_open =
        if not out_open && not err_open then
          ()
        else
          let read_fds =
            [] |> (fun acc -> if out_open then fd_out :: acc else acc)
               |> (fun acc -> if err_open then fd_err :: acc else acc)
          in
          let ready, _, _ = Unix.select read_fds [] [] (-1.) in
          let out_open =
            if out_open && List.mem fd_out ready then (
              let n =
                try input ch_in buf 0 (Bytes.length buf) with
                | End_of_file -> 0
              in
              if n = 0 then
                false
              else (
                Buffer.add_subbytes out_buf buf 0 n;
                true
              )
            ) else out_open
          in
          let err_open =
            if err_open && List.mem fd_err ready then (
              let n =
                try input ch_err buf 0 (Bytes.length buf) with
                | End_of_file -> 0
              in
              if n = 0 then
                false
              else (
                Buffer.add_subbytes err_buf buf 0 n;
                true
              )
            ) else err_open
          in
          drain out_open err_open
      in
      drain true true;
      let status = Unix.close_process_full (ch_in, ch_out, ch_err) in
      match status with
      | Unix.WEXITED 0 -> Ok (String.trim (Buffer.contents out_buf))
      | Unix.WEXITED _ ->
          let err_output = String.trim (Buffer.contents err_buf) in
          let lower_err = String.lowercase_ascii err_output in
          if err_output = "" then
            Error "git ls-remote failed"
          else if String.starts_with ~prefix:"fatal" lower_err then
            Error "repository access failed"
          else
            Error "git ls-remote reported an error"
      | Unix.WSIGNALED _ | Unix.WSTOPPED _ -> Error "git ls-remote terminated unexpectedly"
    with _ -> Error "git ls-remote invocation failed"

let remote_tag_warning_message dep_name reason =
  match reason with
  | "invalid repository location" ->
      Printf.sprintf
        "Warning: Failed to check remote tags for `%s`. Verify the dependency git location in your TOML file.\n%!"
        dep_name
  | "repository access failed" ->
      Printf.sprintf
        "Warning: Failed to check remote tags for `%s`. Verify the repository URL and your access to it.\n%!"
        dep_name
  | _ ->
      Printf.sprintf
        "Warning: Failed to check remote tags for `%s`. Verify git is available and try again.\n%!"
        dep_name

let check_dependency_remote_tag dep =
  match Scaffold.parse_semver dep.tag with
  | None -> None
  | Some current_semver ->
      match run_git_ls_remote_tags dep.git_url with
      | Error msg ->
          Printf.eprintf "%s" (remote_tag_warning_message dep.dep_name msg);
          None
      | Ok output ->
          match latest_semver_tag (parse_remote_tag_refs output) with
          | None -> None
          | Some latest_tag ->
              (match Scaffold.parse_semver latest_tag with
              | Some latest_semver when Scaffold.compare_semver latest_semver current_semver > 0 ->
                  Some
                    {
                      dependency_name = dep.dep_name;
                      current_tag = dep.tag;
                      latest_tag;
                    }
              | _ -> None)

let check_remote_tags () =
  match load_current_dependency_source () with
  | Error msg -> Error msg
  | Ok source ->
      let config_name, deps, no_deps_message =
        match source with
        | Project_config (config_name, cfg) ->
            ( config_name,
              cfg.proj_dependencies,
              format_no_t_project_dependencies_message config_name cfg )
        | Package_config (config_name, cfg) ->
            ( config_name,
              cfg.dependencies,
              Printf.sprintf "No T package dependencies declared in %s.\n" config_name )
      in
      if deps = [] then begin
        Printf.printf "%s" no_deps_message;
        flush stdout;
        Ok []
      end else
        let updates =
          List.fold_left
            (fun acc dep ->
              match check_dependency_remote_tag dep with
              | Some update -> update :: acc
              | None -> acc)
            []
            deps
          |> List.rev
        in
        if updates = [] then
          Printf.printf "All pinned dependency tags in %s are up to date.\n" config_name
        else begin
          Printf.printf
            "Newer tagged releases are available in %s:\n"
            config_name;
          List.iter
            (fun update ->
              Printf.printf "  - %s: %s -> %s\n"
                update.dependency_name
                update.current_tag
                update.latest_tag)
            updates
        end;
        flush stdout;
        Ok updates

let validate_update_prerequisites () =
  let in_ci =
    match Sys.getenv_opt "CI" with
    | Some s when String.trim s <> "" -> true
    | _ -> false
  in
  if in_ci then Ok ()
  else
    match validate_git_remote () with
    | Error _ as err -> err
    | Ok () -> validate_clean_git ()

type lock_section =
  | Locked
  | Original

type flake_lock_node_snapshot = {
  name : string;
  locked_fields : (string * string) list;
  original_fields : (string * string) list;
}

type flake_lock_parse_state = {
  inside_nodes : bool;
  current_node : string option;
  current_section : lock_section option;
  current_locked : (string * string) list;
  current_original : (string * string) list;
  nodes : flake_lock_node_snapshot list;
}

(** Remove the trailing JSON comma from a pretty-printed flake.lock field value. *)
let trim_trailing_comma value =
  let value = String.trim value in
  let len = String.length value in
  if len > 0 && value.[len - 1] = ',' then
    String.sub value 0 (len - 1)
  else
    value

(** Normalize a pretty-printed flake.lock field value by trimming commas and quotes. *)
let normalize_json_value value =
  let trimmed = trim_trailing_comma value in
  let len = String.length trimmed in
  if len >= 2 && trimmed.[0] = '"' && trimmed.[len - 1] = '"' then
    String.sub trimmed 1 (len - 2)
  else
    trimmed

let finalize_current_node state =
  match state.current_node with
  | None -> state
  | Some name ->
      {
        state with
        current_node = None;
        current_locked = [];
        current_original = [];
        nodes =
          {
            name;
            locked_fields = List.rev state.current_locked;
            original_fields = List.rev state.current_original;
          }
          :: state.nodes;
      }

(** Parse the top-level nodes from flake.lock's standard pretty-printed JSON output.
    This expects nix's usual indentation for nodes and locked/original sections
    (2/4/6/8 spaces respectively). *)
let parse_flake_lock_nodes content =
  let lines = String.split_on_char '\n' content in
  let nodes_start_re = Str.regexp {|^  "nodes": {$|} in
  let node_re = Str.regexp {|^    "\([^"]+\)": {$|} in
  let subsection_re = Str.regexp {|^      "\(locked\|original\)": {$|} in
  let field_re = Str.regexp {|^        "\([^"]+\)": \(.*\)$|} in
  let initial_state =
    {
      inside_nodes = false;
      current_node = None;
      current_section = None;
      current_locked = [];
      current_original = [];
      nodes = [];
    }
  in
  let final_state =
    List.fold_left
      (fun state line ->
        if (not state.inside_nodes) && Str.string_match nodes_start_re line 0 then
          { state with inside_nodes = true }
        else if state.inside_nodes then
          match state.current_node, state.current_section with
          | None, _ when line = "  }," || line = "  }" ->
              { state with inside_nodes = false }
          | Some _, Some _ when line = "      }," || line = "      }" ->
              { state with current_section = None }
          | Some _, None when line = "    }," || line = "    }" ->
              finalize_current_node state
          | None, _ when Str.string_match node_re line 0 ->
              {
                state with
                current_node = Some (Str.matched_group 1 line);
                current_section = None;
                current_locked = [];
                current_original = [];
              }
          | Some _, None when Str.string_match subsection_re line 0 ->
              let section_name = Str.matched_group 1 line in
              let current_section =
                if section_name = "locked" then Some Locked else Some Original
              in
              { state with current_section }
          | Some _, Some section when Str.string_match field_re line 0 ->
              let key = Str.matched_group 1 line in
              let value = normalize_json_value (Str.matched_group 2 line) in
              (match section with
              | Locked ->
                  { state with current_locked = (key, value) :: state.current_locked }
              | Original ->
                  {
                    state with
                    current_original = (key, value) :: state.current_original;
                  })
          | _ -> state
        else
          state)
      initial_state
      lines
  in
  let final_state = finalize_current_node final_state in
  List.rev final_state.nodes

let find_flake_lock_node name nodes =
  List.find_opt (fun node -> node.name = name) nodes

let field_value fields key = List.assoc_opt key fields

(** Collect unique projected string values from multiple lists while preserving
    first-seen order across the input lists. *)
let collect_unique_ordered_by project lists =
  let _, reversed =
    List.fold_left
      (fun (seen, acc) items ->
        List.fold_left
          (fun (seen, acc) item ->
            let value = project item in
            if String_set.mem value seen then
              (seen, acc)
            else
              (String_set.add value seen, value :: acc))
          (seen, acc)
          items)
      (String_set.empty, [])
      lists
  in
  List.rev reversed

let summarize_flake_lock_changes before_content after_content =
  match before_content, after_content with
  | None, None -> []
  | None, Some _ -> [ "  - flake.lock created." ]
  | Some before, Some after when before = after -> []
  | Some before, Some after ->
      let before_nodes = parse_flake_lock_nodes before in
      let after_nodes = parse_flake_lock_nodes after in
      let node_names = collect_unique_ordered_by (fun node -> node.name) [before_nodes; after_nodes] in
      let describe_field_changes section_name before_fields after_fields =
        let field_names = collect_unique_ordered_by fst [before_fields; after_fields] in
        List.fold_left
          (fun acc field_name ->
            match field_value before_fields field_name, field_value after_fields field_name with
            | Some before_value, Some after_value when before_value <> after_value ->
                Printf.sprintf
                  "      %s.%s: %s -> %s"
                  section_name
                  field_name
                  before_value
                  after_value
                :: acc
            | None, Some after_value ->
                Printf.sprintf
                  "      %s.%s: (missing) -> %s"
                  section_name
                  field_name
                  after_value
                :: acc
            | Some before_value, None ->
                Printf.sprintf
                  "      %s.%s: %s -> (missing)"
                  section_name
                  field_name
                  before_value
                :: acc
            | _ -> acc)
          []
          field_names
        |> List.rev
      in
      let lines =
        List.fold_left
          (fun acc node_name ->
            match find_flake_lock_node node_name before_nodes, find_flake_lock_node node_name after_nodes with
            | None, Some _ -> Printf.sprintf "  - %s: added to flake.lock" node_name :: acc
            | Some _, None -> Printf.sprintf "  - %s: removed from flake.lock" node_name :: acc
            | Some before_node, Some after_node ->
                let node_changes =
                  describe_field_changes "original" before_node.original_fields after_node.original_fields
                  @ describe_field_changes "locked" before_node.locked_fields after_node.locked_fields
                in
                if node_changes = [] then
                  acc
                else
                  List.rev_append (Printf.sprintf "  - %s" node_name :: node_changes) acc
            | None, None -> acc)
          []
          node_names
        |> List.rev
      in
      if lines = [] then [ "  - flake.lock changed." ] else lines
  | Some _, None -> [ "  - flake.lock was removed." ]

let report_flake_lock_changes before_content after_content =
  let summary_lines = summarize_flake_lock_changes before_content after_content in
  if summary_lines = [] then
    Printf.printf "flake.lock is already up to date.\n"
  else begin
    Printf.printf "flake.lock changes:\n";
    List.iter (fun line -> Printf.printf "%s\n" line) summary_lines
  end;
  flush stdout

(*
--# Update Dependencies
--#
--# Regenerates the `flake.nix` file from the current TOML configuration and runs `nix flake update`
--# to lock dependencies to their latest versions within the specified tags.
--#
--# @name update_flake_lock
--# @return :: Result[Unit] Ok(()) or an error message.
--# @family package_manager
--# @export
*)
let update_flake_lock () =
  let dir = Sys.getcwd () in
  let tproject_path = Filename.concat dir "tproject.toml" in
  let description_path = Filename.concat dir "DESCRIPTION.toml" in
  let flake_path = Filename.concat dir "flake.nix" in
  let flake_lock_path = Filename.concat dir "flake.lock" in
  (* Read existing flake.nix to extract nixpkgs_date *)
  let nixpkgs_date =
    match read_file flake_path with
    | Ok content ->
      (match extract_nixpkgs_date content with
       | Some date -> date
       | None -> Nixpkgs_date.date) (* Changed fallback to static rstats-on-nix date *)
     | Error _ -> Nixpkgs_date.date
   in
  let in_ci = (match Sys.getenv_opt "CI" with Some s when String.trim s <> "" -> true | _ -> false) in
  (* On CI, we want to pinned to the versions being tested: specifically the nixpkgs date
     from the current T source, and the T-lang flake pointing to the repo/SHA under test. *)
  let nixpkgs_date = if in_ci then Nixpkgs_date.date else nixpkgs_date in
  (if in_ci then (
     match Sys.getenv_opt "TLANG_REPO", Sys.getenv_opt "TLANG_SHA" with
     | Some repo, Some sha ->
         Unix.putenv "TLANG_FLAKE_URL" (Printf.sprintf "github:%s/%s" repo sha)
     | _ -> ()
  ));
  let flake_lock_before =
    if Sys.file_exists flake_lock_path then
      match read_file flake_lock_path with
      | Ok content -> Some content
      | Error _ -> None
    else
      None
  in
  match check_remote_tags () with
  | Error msg -> Error msg
  | Ok _ ->
      match validate_update_prerequisites () with
      | Error msg -> Error msg
      | Ok () ->
          let regen_result =
            if Sys.file_exists tproject_path then begin
              match read_file tproject_path with
              | Error msg -> Error (Printf.sprintf "Cannot read tproject.toml: %s" msg)
              | Ok content ->
                  match Toml_parser.parse_tproject_toml content with
                  | Error msg -> Error (Printf.sprintf "Cannot parse tproject.toml: %s" msg)
                  | Ok cfg ->
                      Printf.printf "%s" (format_project_sync_message cfg);
                      flush stdout;
                      match Nix_generator.install_flake
                              ~kind:Project
                              ~name:cfg.proj_name
                              ~version:"0.0.0"
                              ~nixpkgs_date:(if cfg.proj_nixpkgs_date <> "" then cfg.proj_nixpkgs_date else nixpkgs_date)
                              ~t_version:cfg.proj_min_t_version
                              ~deps:cfg.proj_dependencies
                              ~r_deps:cfg.proj_r_dependencies
                              ~py_deps:cfg.proj_py_dependencies
                              ~py_version:cfg.proj_py_version
                              ~additional_tools:cfg.proj_additional_tools
                              ~latex_pkgs:cfg.proj_latex_packages
                              ~dir
                              ~dry_run:false
                              ()
                      with
                      | Ok _ -> Ok ()
                      | Error msg -> Error msg
            end
            else if Sys.file_exists description_path then begin
              match read_file description_path with
              | Error msg -> Error (Printf.sprintf "Cannot read DESCRIPTION.toml: %s" msg)
              | Ok content ->
                  match Toml_parser.parse_description_toml content with
                  | Error msg -> Error (Printf.sprintf "Cannot parse DESCRIPTION.toml: %s" msg)
                  | Ok cfg ->
                      Printf.printf "Syncing %d dependency(ies) from DESCRIPTION.toml → flake.nix...\n"
                        (List.length cfg.dependencies);
                      flush stdout;
                      match Nix_generator.install_flake
                              ~kind:Package
                              ~name:cfg.name
                              ~version:cfg.version
                              ~nixpkgs_date:nixpkgs_date
                              ~t_version:cfg.min_t_version
                              ~deps:cfg.dependencies
                              ~additional_tools:cfg.additional_tools
                              ~latex_pkgs:cfg.latex_packages
                              ~dir
                              ~dry_run:false
                              ()
                      with
                      | Ok _ -> Ok ()
                      | Error msg -> Error msg
            end
            else
              Error "No tproject.toml or DESCRIPTION.toml found in the current directory."
          in
          match regen_result with
          | Error msg -> Error msg
          | Ok () ->
              Printf.printf "Running nix flake update...\n";
              flush stdout;
              let in_ci = (match Sys.getenv_opt "CI" with Some s when String.trim s <> "" -> true | _ -> false) in
              (if in_ci then ignore (run_command "git add -N flake.nix 2>/dev/null || true"));
              let update_cmd = if in_ci then "nix flake lock --accept-flake-config" else "nix flake update --accept-flake-config" in
              match run_command update_cmd with
              | Ok _ ->
                  let flake_lock_after =
                    if Sys.file_exists flake_lock_path then
                      match read_file flake_lock_path with
                      | Ok content -> Some content
                      | Error _ -> None
                    else
                      None
                  in
                  report_flake_lock_changes flake_lock_before flake_lock_after;
                  Ok ()
              | Error msg -> Error ("Failed to update dependencies: " ^ msg)

(** Upgrade the current project to the latest T version and today's nixpkgs date *)
let cmd_upgrade () =
  let dir = Sys.getcwd () in
  let tproject_path = Filename.concat dir "tproject.toml" in
  if not (Sys.file_exists tproject_path) then
    Error "tproject.toml not found. Upgrade is only supported for projects."
  else
    match read_file tproject_path with
    | Error msg -> Error (Printf.sprintf "Cannot read tproject.toml: %s" msg)
    | Ok content ->
        match Toml_parser.parse_tproject_toml content with
        | Error msg -> Error (Printf.sprintf "Cannot parse tproject.toml: %s" msg)
        | Ok cfg ->
            Printf.printf "Checking for new T releases...\n";
            flush stdout;
            let latest_tag = Scaffold.latest_tlang_tag () in
            let latest_version = Scaffold.strip_v_prefix latest_tag in
            
            let t = Unix.gmtime (Unix.gettimeofday ()) in
            let today = Printf.sprintf "%04d-%02d-%02d" (1900 + t.Unix.tm_year) (t.Unix.tm_mon + 1) t.Unix.tm_mday in
            
            if cfg.proj_min_t_version = latest_version && cfg.proj_nixpkgs_date = today then (
              Printf.printf "Project is already up to date (T %s, nixpkgs %s).\n" latest_version today;
              Ok ()
            ) else (
              Printf.printf "Upgrading project to T %s and nixpkgs date %s...\n" latest_version today;
              flush stdout;
              let new_cfg = { cfg with proj_min_t_version = latest_version; proj_nixpkgs_date = today } in
              let new_content = Toml_parser.serialize_tproject_toml new_cfg in
              (try
                 let oc = open_out tproject_path in
                 output_string oc new_content;
                 close_out oc;
                 Printf.printf "Regenerating flake.nix and updating dependencies...\n";
                 flush stdout;
                 update_flake_lock ()
               with e -> Error (Printf.sprintf "Failed to update tproject.toml: %s" (Printexc.to_string e)))
            )