aboutsummaryrefslogtreecommitdiffstats
path: root/import_issues.py
blob: 106c613aa6810efd80438d94f73cc54efa561eba (plain) (blame)
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
#!/usr/bin/env python3

# Copyright 2024 Bryan Gardiner <bog@khumba.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.


# Imports issues from an exported Gitlab project into a Sourcehut tracker.
#
# Reads *.ndjson files from an exported Gitlab project, and recreates tickets
# and their histories in a new, empty Sourcehut tracker.  Preserves notes
# attached to each issue; generally this includes comments, status changes,
# labels, milestones, and anything else that is included in as a plain text
# note, but definitely doesn't include all available metadata.
#
# Tickets are created in sr.ht via SMTP, so a working mail setup is required.
# Surely using Sourcehut's API would be better.
#
# There are a few caveats:
#
# 1. If all issue IDs from 1 to the max ID are available in your export, and the
# tracker you import into is a new tracker, then your Gitlab and Sourcehut issue
# IDs will match up one-to-one, and mentions of one ticket from another will
# work.  If not, you need to decide how you want to handle this.  You can choose
# to create empty Sourcehut tickets for the missing Gitlab issues so that IDs
# still match, by passing --create-missing-issues.  Blank issues will be created
# then closed.  Alternatively, you can pass --skip-missing-issues to not create
# any extra Sourcehut tickets, but IDs will not line up.  If one of these issues
# is needed, this program will tell you.
#
# 2. Because emails are used to create tickets, we also assume that emails are
# processed in the order that they are sent, so that tickets don't get created
# out of order.  This program has no way of knowing if that happens, however,
# there is a configurable delay between sending each email, for this reason.
#
# 3. Gitlab project exports are missing some crucial information, in particular
# they don't include ticket author names or label IDs.  For best results,
# appropriate mappings for your project can be provided manually in CSV files to
# --labels-file and --users-file.  These CSV files should be headerless, and
# each row should contain a label or user ID, followed by the name for that
# entity.  If you want to skip these, then --skip-labels and --skip-users must
# be passed.  Some label and user info will still be included, but label
# references in comments and issue creator names will be missing.  You can run
# with incomplete files by passing --skip-unknown-labels or
# --skip-unknown-users.
#
# 4. If your project has confidential issues or comments in it, then you will
# need to decide to exclude them with --skip-confidential, or include them all
# with --include-confidential.  If there are confidential items and you don't
# pass either of these options, then an exception will be thrown.  If you need
# more fine-grained control over confidential items, edit issues.ndjson by hand.
#
# 5. The projects I have tested this on are small, and don't make use of many of
# Gitlab's features.  This may bork on more complex projects.


# Still here?  Here's how to use this:
#
# First take an export of your Gitlab project from its settings area, then
# extract the archive.  The important files are tree/project/*.ndjson.
#
# Let's generate a report of all the emails that would be sent.  Preview the
# output to make sure things look right, and ensure that the command completes
# without error:
#
# touch labels.csv users.csv    # First create these empty files.
#
# ./import_issues.py \
#     --srht-owner=MY_SRHT_USER \
#     --srht-tracker=MY_SRHT_TRACKER \
#     --gitlab-project-url=https://gitlab.com/ME/PROJECT/ \
#     --from='Moi <me@email.com>' \
#     --labels-file=labels.csv \
#     --users-file=users.csv \
#     .../gitlab-export/tree/project \
#     >issue-emails.txt
#
# You may get errors if you are missing label or user mappings, and you haven't
# disabled these; add them to the labels.csv or users.csv until you get no more
# errors:
#
#   labels.csv:
#     123456,Bug
#     232323,Feature
#     ...
#
#   users.csv:
#     1234000,John Joe (@jdoe)
#     ...
#
# If the issue-emails.txt file looks correct, then you can proceed with sending
# emails.  Double-check that your tracket is empty to start with, then rerun the
# command with "--mode=send" and with your SMTP parameters.  SMTP options can be
# specified either via parameters --smtp-{host,port,user,password} or the
# equivalent SMTP_{HOST,PORT,USER,PASSWORD} environment variables.  Pass
# --smtp-ssl to enable SSL.  Also by default there is a five-second delay
# between sending emails, that you may wish to change with --delay.
#
# ./import_issues.py \
#     --srht-owner=MY_SRHT_USER \
#     --srht-tracker=MY_SRHT_TRACKER \
#     --gitlab-project-url=https://gitlab.com/ME/PROJECT/ \
#     --from='Moi <me@email.com>' \
#     --labels-file=labels.csv \
#     --users-file=users.csv \
#     --smtp-host=SMTP_HOSTNAME \
#     --smtp-ssl \
#     --smtp-user=SMTP_USERNAME \
#     --smtp-password=SMTP_PASSWORD \
#     .../gitlab-export/tree/project


import argparse
import csv
import json
import logging
import os
import re
import smtplib
import subprocess
import sys
import time
from datetime import datetime, timezone
from email.message import EmailMessage
from email.utils import format_datetime, make_msgid
from pathlib import Path
from typing import Any, Optional

logging.basicConfig(
    format="%(levelname)s:%(funcName)s:%(message)s",
    level=logging.DEBUG,
    stream=sys.stdout,
)

ID_RE = re.compile(r"^[0-9]+$")

# todo.sr.ht seems to be limited to less than 16k comments
# to be sure, we will do just 12k
MAX_SIZE_COMMENT = 12 * 1024


def split_long_str(in_str: str, max_len: int = MAX_SIZE_COMMENT) -> list[str]:
    out = []
    tmp_str = ""
    for line in in_str.splitlines(keepends=True):
        if len(tmp_str + line) < max_len:
            tmp_str += line
        else:
            out.append(tmp_str)
            tmp_str = line
    if len(tmp_str) > 0:
        out.append(tmp_str)
    return out


label_cache: dict[str, list[dict[str, str]]] = {}


def get_labels(tracker: str) -> list[dict[str, str]]:
    """
    collects labels for your named tracker

    param: tracker: name of the tracker
    return: list of all labels in the tracker
    """
    global label_cache

    result: list[dict[str, str]]

    if tracker in label_cache:
        result = label_cache[tracker]
    else:
        query = (
            'query { me { tracker(name: "'
            + tracker
            + '") { labels { results { id, name, foregroundColor, backgroundColor, created } } } }}'
        )

        try:
            ret = subprocess.run(
                ["hut", "graphql", "todo", "--stdin"],
                input=query,
                text=True,
                check=True,
                capture_output=True,
            )
        except subprocess.CalledProcessError as ex:
            raise RuntimeError(
                f"hut failed with exitcode {ex.returncode}\n\nstdout:\n{ex.stdout}\n\nand stderr:\n{ex.stderr}"
            ) from ex
        data = json.loads(ret.stdout)
        result = data["me"]["tracker"]["labels"]["results"]
        label_cache[tracker] = result

    return result


log = logging.getLogger()

email_count = 0
issue_count = 0


def read_id_map_file(file_path: Path) -> dict[int, str]:
    """Reads a CSV file with ID,NAME mappings and returns the resulting dict."""
    result: dict[int, str] = {}

    with open(file_path, newline="") as fh:
        reader = csv.reader(fh)
        line_num = 0
        for row in reader:
            line_num += 1
            assert (
                len(row) == 2 and ID_RE.search(row[0]) and row[1]
            ), f"Row {line_num} of {file_path} is not in the form <ID>,<NAME>: {row!r}"
            new_id = int(row[0])
            assert (
                new_id not in result
            ), f"ID {new_id} appears multiple times in {file_path}."
            result[new_id] = row[1]

    return result


def do_mail(
    *,
    smtp,
    delay: float,
    mode: str,
    frm: str,
    to: str,
    body: str,
    subject: Optional[str] = None,
):
    global email_count
    email_count += 1

    if mode == "print":
        verb = "Printing"
    elif mode == "send":
        verb = "Sending"
    else:
        raise ValueError(f"Unhandled mode {mode!r}.")

    log.info("%s email #%d.", verb, email_count)

    date = format_datetime(datetime.now(timezone.utc))
    msg_id = make_msgid()
    indent = "  "

    if mode == "print":
        print(f"{indent}From: {frm}")
        print(f"{indent}To: {to}")
        print(f"{indent}Date: {date}")
        if subject:
            print(f"{indent}Subject: {subject}")
        print(f"{indent}Message-ID: {msg_id}")
        print()
        print(indent + re.sub("\n", f"\n{indent}", body))
        print()

    elif mode == "send":
        msg = EmailMessage()
        msg.set_content(body)
        msg["From"] = frm
        msg["To"] = to
        msg["Date"] = date
        if subject:
            msg["Subject"] = subject

        # Message-ID is required, unless you want this error message from the
        # sr.ht mail server:
        #
        # 500 Error: (AttributeError) 'NoneType' object has no attribute
        # 'removeprefix' (in reply to end of DATA command)
        msg["Message-ID"] = msg_id

        smtp.send_message(msg)

        time.sleep(delay)

    else:
        raise RuntimeError(f"Unknown mode: {mode!r}")


def run_hut(
    cmds, tracker, msg, args=[], *, delay: float
) -> subprocess.CompletedProcess:
    log.debug(
        "cmds = %s, tracker = %s, args = %s\n\nmsg:\n%s", cmds, tracker, args, msg
    )
    if args is None:
        args = []
    try:
        if msg is None:
            res = subprocess.run(
                ["hut", "todo"] + cmds + ["-t", tracker] + args,
                check=True,
                encoding="utf-8",
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
        else:
            res = subprocess.run(
                ["hut", "todo"] + cmds + ["-t", tracker, "--stdin"] + args,
                check=True,
                encoding="utf-8",
                input=msg,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
    except subprocess.CalledProcessError as ex:
        raise RuntimeError(
            f"hut failed with exitcode {ex.returncode}\n\nstdout:\n{ex.stdout}\n\nand stderr:\n{ex.stderr}"
        ) from ex

    time.sleep(delay)

    return res


def open_ticket_by_email(
    *,
    smtp,
    delay: float,
    mode: str,
    tracker: str,
    frm: str,
    title: str,
    body: str,
    created_by: Optional[str],
    created_at: str,
    closed_at: Optional[str],
    is_closed: bool,
    is_confidential: bool,
    labels: list[dict[str, Any]],
    milestone_name: Optional[str],
    gitlab_ticket_url: str,
):
    # This is presently the ID of the issue we are going to create, following
    # along with e.g. any skipped confidential issues.  Unfortunately, unlike
    # calling 'hut', we don't get a response after sending the email to create
    # the ticket that tells us what the ticket ID actually is, so we have to
    # assume it's the next one in sequence.  It should be, unless ticket
    # creation fails for some reason (again, we don't know if that happens, we
    # can't see email responses).
    global issue_count

    lines = []
    pheaders = []

    pheaders.append(f"Migrated from: {gitlab_ticket_url}")

    if created_by:
        pheaders.append(f"Created by: {created_by}")
    pheaders.append(f"Created at: {created_at}")

    if closed_at is not None:
        pheaders.append(f"Closed at: {closed_at}")
    elif is_closed:
        pheaders.append("State: closed")

    if milestone_name:
        pheaders.append(f"Milestone: {milestone_name}")

    if labels:
        pheaders.append(
            "Labels: "
            + ", ".join(
                [
                    x["label"]["title"]
                    for x in sorted(labels, key=lambda x: x["label"]["title"])
                ]
            )
        )

    if is_confidential:
        pheaders.append("Confidential: true")

    lines.append(" \\\n".join(pheaders))
    lines.append("")
    lines.append(body)

    body_split = split_long_str("\n".join(lines))

    # First create the ticket
    do_mail(
        smtp=smtp,
        delay=delay,
        mode=mode,
        frm=frm,
        to=f"{tracker}@todo.sr.ht",
        subject=title,
        body=body_split[0],
    )

    # then add remaining parts of the description as comments
    if len(body_split) > 1:
        for part in body_split[1:]:
            do_mail(
                smtp=smtp,
                delay=delay,
                mode=mode,
                frm=frm,
                to=f"{tracker}/{issue_count}@todo.sr.ht",
                body=part,
            )


def open_ticket_by_hut(
    *,
    delay: float,
    tracker: str,
    title: str,
    body: str,
    created_by: Optional[str],
    created_at: str,
    closed_at: Optional[str],
    is_closed: bool,
    is_confidential: bool,
    labels: list[dict[str, Any]],
    milestone_name: Optional[str],
    gitlab_ticket_url: str,
):
    lines = []
    pheaders = []

    pheaders.append(f"Migrated from: {gitlab_ticket_url}")

    if created_by:
        pheaders.append(f"Created by: {created_by}")
    pheaders.append(f"Created at: {created_at}")

    if closed_at is not None:
        pheaders.append(f"Closed at: {closed_at}")
    elif is_closed:
        pheaders.append("State: closed")

    if milestone_name:
        pheaders.append(f"Milestone: {milestone_name}")

    if is_confidential:
        pheaders.append("Confidential: true")

    lines.append(" \\\n".join(pheaders))
    lines.append("")
    lines.append(body)

    msg = title
    if len(lines):
        msg += "\n" + "\n".join(lines)
    msg_split = split_long_str(msg)

    out = run_hut(["ticket", "create"], tracker, msg_split[0], delay=delay)
    stderr_msg = out.stderr.strip()
    expected_prefix = "Created new ticket #"
    assert stderr_msg.startswith(
        expected_prefix
    ), f"Expected stderr to start with {expected_prefix!r}, stderr = {stderr_msg!r}"
    issue_id = int(stderr_msg[len(expected_prefix) :])

    for label in sorted(labels, key=lambda x: x["label"]["title"]):
        # {"target_type":"Issue",
        #  "created_at":"2023-11-03T22:10:29.419Z",
        #  "updated_at":"2023-11-03T22:10:29.419Z",
        #  "label":{"title":"smime",
        #           "color":"#00b140",
        #           "project_id":346279,
        #           "created_at":"2023-02-02T10:49:17.779Z",
        #           "updated_at":"2023-02-02T10:49:17.779Z",
        #           "template":false,
        #           "description":null,
        #           "group_id":null,
        #           "type":"ProjectLabel",
        #           "priorities":[]}}
        label_name = label["label"]["title"]
        label_color = label["label"]["color"]
        ensure_label(tracker, label_name, label_color, delay=delay)
        run_hut(
            ["ticket", "label"],
            tracker,
            None,
            [str(issue_id), "-l", label_name],
            delay=delay,
        )

    # then add remaining parts of the description as comments
    if len(msg_split) > 1:
        for part in msg_split[1:]:
            run_hut(["ticket", "comment"], tracker, part, [str(issue_id)], delay=delay)


def open_ticket(
    *,
    smtp,
    delay: float,
    mode: str,
    tracker: str,
    frm: str,
    title: str,
    body: str,
    created_by: Optional[str],
    created_at: str,
    closed_at: Optional[str],
    is_closed: bool,
    is_confidential: bool,
    labels: list[dict[str, Any]],
    milestone_name: Optional[str],
    gitlab_ticket_url: str,
) -> int:
    global issue_count

    # Proactively increment this so that open_ticket_by_email() can use it for
    # the current issue ID.
    issue_count += 1

    if mode in ("send", "print"):
        open_ticket_by_email(
            smtp=smtp,
            delay=delay,
            mode=mode,
            tracker=tracker,
            frm=frm,
            title=title,
            body=body,
            created_by=created_by,
            created_at=created_at,
            closed_at=closed_at,
            is_closed=is_closed,
            is_confidential=is_confidential,
            labels=labels,
            milestone_name=milestone_name,
            gitlab_ticket_url=gitlab_ticket_url,
        )
    elif mode == "hut":
        open_ticket_by_hut(
            delay=delay,
            tracker=tracker,
            title=title,
            body=body,
            created_by=created_by,
            created_at=created_at,
            closed_at=closed_at,
            is_closed=is_closed,
            is_confidential=is_confidential,
            labels=labels,
            milestone_name=milestone_name,
            gitlab_ticket_url=gitlab_ticket_url,
        )

    return issue_count


def file_missing_ticket(
    *,
    smtp,
    delay: float,
    mode: str,
    tracker: str,
    frm: str,
    issue_id: int,
    tickets_to_be_closed: list[tuple[Any, float, str, str, str, int]],
):
    global issue_count

    if mode in ["send", "print"]:
        do_mail(
            smtp=smtp,
            delay=delay,
            mode=mode,
            frm=frm,
            to=f"{tracker}@todo.sr.ht",
            subject="Missing issue",
            body=f"Issue {issue_id} is not known.",
        )
    elif mode == "hut":
        msg = f"Missing issue\n\nIssue {issue_id} is not known."
        run_hut(["ticket", "create"], tracker, msg, delay=delay)

    issue_count += 1

    tickets_to_be_closed.append(
        (
            smtp,
            delay,
            mode,
            tracker,
            frm,
            issue_count,
        )
    )


def send_comment(
    *,
    smtp,
    delay: float,
    mode: str,
    tracker: str,
    frm: str,
    issue_id: int,
    body: str,
    author_name: str,
    created_at: str,
    last_edited_at: str,
    is_system: bool,
    is_confidential: bool,
):
    lines = []
    pheaders = []

    # Pseudo-headers, if any.
    if is_confidential:
        pheaders.append("Confidential: true")

    if pheaders:
        lines.append(" \\\n".join(pheaders))
        lines.append("")

    # Authorship note for a regular comment.
    if is_system:
        lines.append(f"Changed on {created_at} by {author_name}:")
    else:
        lines.append(f"On {created_at}, {author_name} wrote:")

    lines.append("")
    lines.append(body)

    if last_edited_at and last_edited_at != created_at:
        lines.append("")
        lines.append(f"(Last edited at {last_edited_at}.)")

    body = "\n".join(lines)

    body_split = split_long_str(body)

    for part in body_split:
        if mode in ["send", "print"]:
            do_mail(
                smtp=smtp,
                delay=delay,
                mode=mode,
                frm=frm,
                to=f"{tracker}/{issue_id}@todo.sr.ht",
                body=part,
            )
        elif mode == "hut":
            run_hut(["ticket", "comment"], tracker, part, [str(issue_id)], delay=delay)


def close_ticket(
    *,
    smtp,
    delay: float,
    mode: str,
    tracker: str,
    frm: str,
    issue_id: int,
    closed_at: Optional[str],
    is_closed: bool,
):
    lines = []

    if closed_at is not None:
        # (Skipping pseudoheaders array here, only have one.)
        lines.append(f"Closed at: {closed_at}")
    elif is_closed:
        lines.append("Ticket closed.")

    if mode in ["send", "print"]:
        lines.append("")
        lines.append("!resolve fixed")

        do_mail(
            smtp=smtp,
            delay=delay,
            mode=mode,
            frm=frm,
            to=f"{tracker}/{issue_id}@todo.sr.ht",
            body="\n".join(lines),
        )

    elif mode == "hut":
        run_hut(
            ["ticket", "update-status"],
            tracker,
            None,
            [str(issue_id), "--resolution", "fixed", "--status", "resolved"],
            delay=delay,
        )


def ensure_label(
    tracker: str,
    name: str,
    bg_color: str,
    fg_color: str = "#FFFFFF",
    *,
    delay: float,
):
    global label_cache

    labels = get_labels(tracker.split("/", 1)[1])
    if not any(x["name"] == name for x in labels):
        run_hut(
            ["label", "create"],
            tracker,
            None,
            ["--background", bg_color, "--foreground", fg_color, name],
            delay=delay,
        )

        label_cache.pop(tracker, None)  # The label cache is now invalid.


def run(
    *,
    smtp,
    delay: float,
    mode: str,
    tracker: str,
    frm: str,
    export_dir_path: Path,
    gitlab_project_url: str,
    labels_file_path: Optional[Path],
    skip_unknown_labels: bool,
    users_file_path: Optional[Path],
    skip_unknown_users: bool,
    skip_missing_issues: bool,
    create_missing_issues: bool,
    include_confidential: bool,
    skip_confidential: bool,
):
    label_ids_to_names: Optional[dict[int, str]] = (
        read_id_map_file(labels_file_path) if labels_file_path else None
    )
    user_ids_to_names: Optional[dict[int, str]] = (
        read_id_map_file(users_file_path) if users_file_path else None
    )
    # TODO Might be able to automatically map note.events.author_id to
    # note.author.name for a subset of relevant users.

    milestone_jsons = []
    milestones_file_path = export_dir_path / "milestones.ndjson"
    # This file may not exist if the project has no milestones.
    if milestones_file_path.exists():
        with open(milestones_file_path) as milestones_file:
            for line in milestones_file:
                milestone_jsons.append(json.loads(line))

    milestone_ids_to_titles = {}
    for milestone_json in milestone_jsons:
        milestone_ids_to_titles[milestone_json["iid"]] = milestone_json["title"]

    issue_jsons = []
    with open(export_dir_path / "issues.ndjson") as issues_file:
        for line in issues_file:
            issue_jsons.append(json.loads(line))

    if skip_confidential:
        issue_jsons = [x for x in issue_jsons if not x.get("confidential")]
        for issue_json in issue_jsons:
            issue_json["notes"] = [
                n for n in issue_json["notes"] if not n.get("confidential")
            ]

    elif not include_confidential:
        have_confidential_issues = any(x.get("confidential") for x in issue_jsons)
        have_confidential_notes = any(
            n.get("confidential") for x in issue_jsons for n in x["notes"]
        )
        confidential_types = []
        if have_confidential_issues:
            confidential_types.append("issues")
        if have_confidential_notes:
            confidential_types.append("notes")
        assert not (have_confidential_issues or have_confidential_notes), (
            f"Found confidential {' and '.join(confidential_types)}; please "
            f"decide whether these should all be included, then pass either "
            f"--include-confidential or --skip-confidential, or edit "
            f"issues.ndjson for more fine-grained control."
        )

    issue_jsons.sort(key=lambda x: x["iid"])

    max_issue_id = max(x["iid"] for x in issue_jsons)
    present_issue_id_set = {x["iid"] for x in issue_jsons}
    missing_issue_ids = set(range(1, max_issue_id + 1)) - present_issue_id_set
    if missing_issue_ids and not (skip_missing_issues or create_missing_issues):
        if skip_confidential:
            because_confidential_msg = (
                " (possibly because some confidential issues were excluded)"
            )
        else:
            because_confidential_msg = ""

        raise RuntimeError(
            f"Don't have all issues from 1 to {max_issue_id}{because_confidential_msg}, "
            f"please pass --create-missing-issues or --skip-missing-issues to proceed."
        )

    issues_by_id = {}
    for issue_json in issue_jsons:
        issues_by_id[issue_json["iid"]] = issue_json

    # Need to sort notes by date, they seem to come unsorted.
    for issue_json in issue_jsons:
        issue_json["notes"].sort(key=lambda x: x["created_at"])

    log.info("Creating tickets.")

    issue_id_map: dict[int, int] = {}
    tickets_to_be_closed: list[tuple[Any, float, str, str, str, int]] = []

    # While we're creating tickets, we can't just loop over the sorted
    # issue_jsons.  We have to loop over potential issue IDs and handle any that
    # are missing as well.
    for gitlab_issue_id in range(1, max_issue_id + 1):
        if gitlab_issue_id not in issues_by_id:
            if create_missing_issues:
                file_missing_ticket(
                    smtp=smtp,
                    delay=delay,
                    mode=mode,
                    tracker=tracker,
                    frm=frm,
                    issue_id=gitlab_issue_id,
                    tickets_to_be_closed=tickets_to_be_closed,
                )
            elif not skip_missing_issues:
                raise RuntimeError(
                    f"Internal error, don't know what to do with missing "
                    f"issue ID {gitlab_issue_id}."
                )

            continue

        issue_json = issues_by_id[gitlab_issue_id]

        author_id = issue_json["author_id"]
        created_by: Optional[str]
        if user_ids_to_names is None:
            created_by = None
        elif author_id in user_ids_to_names:
            created_by = user_ids_to_names[author_id]
        else:
            assert skip_unknown_users, (
                f"Unknown author #{author_id} of ticket #{gitlab_issue_id}, "
                f"please add to the users file."
            )
            created_by = None

        srht_issue_id = open_ticket(
            smtp=smtp,
            delay=delay,
            mode=mode,
            tracker=tracker,
            frm=frm,
            title=issue_json["title"],
            body=issue_json["description"],
            created_by=created_by,
            created_at=issue_json["created_at"],
            closed_at=issue_json["closed_at"],
            is_closed=(issue_json["state"] == "closed"),
            is_confidential=(issue_json.get("confidential") is True),
            labels=list(issue_json["label_links"]),
            milestone_name=issue_json.get("milestone", {}).get("title") or None,
            gitlab_ticket_url=f"{gitlab_project_url}/-/issues/{gitlab_issue_id}",
        )

        if not skip_missing_issues:
            assert srht_issue_id == gitlab_issue_id, (
                f"Internal error, srht_issue_id {srht_issue_id} != "
                f"gitlab_issue_id {gitlab_issue_id} "
                f"(skip_missing_issues={skip_missing_issues}, "
                f"create_missing_issues={create_missing_issues})."
            )

        issue_id_map[gitlab_issue_id] = srht_issue_id

    log.info("Creating comments.")

    for issue_json in issue_jsons:
        for note_json in issue_json["notes"]:
            system_action = note_json.get("system_note_metadata", {}).get(
                "action", None
            )

            body = note_json["note"]

            # The "Removed" part is a guess here, don't know if that actually shows up.
            if label_ids_to_names is not None and (
                system_action == "label"
                or re.search(r"^(Added|Removed) ~[0-9]+ label", body)
            ):

                def expand_label(ref):
                    ref_num = int(ref.group(1))
                    if ref_num in label_ids_to_names:
                        return label_ids_to_names[ref_num]
                    assert (
                        skip_unknown_labels
                    ), f"Unknown label #{ref_num}, please add to the labels file."
                    return ref.group(0)  # Return the original "~id" string.

                body = re.sub(r"~([0-9]+)", expand_label, body)

            if system_action == "milestone" or re.search(
                r"^Milestone changed to %[0-9]+$", body
            ):

                def expand_milestone(ref):
                    ref_num = int(ref.group(1))
                    assert (
                        ref_num in milestone_ids_to_titles
                    ), f"Unknown milestone #{ref_num}."
                    return milestone_ids_to_titles[ref_num]

                body = re.sub(r"%([0-9]+)", expand_milestone, body)

            send_comment(
                smtp=smtp,
                delay=delay,
                mode=mode,
                tracker=tracker,
                frm=frm,
                issue_id=issue_id_map[issue_json["iid"]],
                body=body,
                author_name=note_json["author"]["name"],
                created_at=note_json["created_at"],
                last_edited_at=note_json["last_edited_at"],
                is_system=note_json["system"],
                is_confidential=(note_json["confidential"] is True),
            )

    log.info("Closing closed issues.")

    for issue_json in issue_jsons:
        if issue_json["state"] == "closed":
            close_ticket(
                smtp=smtp,
                delay=delay,
                mode=mode,
                tracker=tracker,
                frm=frm,
                issue_id=issue_id_map[issue_json["iid"]],
                closed_at=issue_json["closed_at"],
                is_closed=(issue_json["state"] == "closed"),
            )

    log.info("Performing delayed closing of issues.")
    for ticket in tickets_to_be_closed:
        close_ticket(
            smtp=ticket[0],
            delay=ticket[1],
            mode=ticket[2],
            tracker=ticket[3],
            frm=ticket[4],
            issue_id=ticket[5],
            closed_at=None,
            is_closed=False,  # Save one line of text.
        )


def parse_args(args_in: list[str]) -> dict[str, Any]:
    parser = argparse.ArgumentParser(
        prog="import_issues.py",
        description="Import Gitlab issues into Sourcehut via SMTP.",
    )

    parser.add_argument(
        "--srht-owner",
        required=True,
        help="Owner of the Sorucehut tracker.",
    )

    parser.add_argument(
        "--srht-tracker",
        required=True,
        help="Name of Sourcehut tracker to submit to.",
    )

    parser.add_argument(
        "--gitlab-project-url",
        required=True,
        help="The base URL the project on Gitlab.",
    )

    parser.add_argument(
        "--mode",
        choices=["print", "send", "hut"],
        default="print",
        help="Action to take.",
    )

    parser.add_argument(
        "--from",
        help="From address if mode is 'send'.",
    )

    parser.add_argument(
        "--smtp-host",
        help="SMTP host to use.",
    )

    parser.add_argument(
        "--smtp-port",
        default=None,
        type=int,
        help="SMTP port to use.",
    )

    parser.add_argument(
        "--smtp-ssl",
        action="store_true",
        help="Use SMTP over SSL.",
    )

    parser.add_argument(
        "--smtp-starttls",
        action="store_true",
        help="Use STARTTLS.",
    )

    parser.add_argument(
        "--smtp-user",
        help="SMTP username.",
    )

    parser.add_argument(
        "--smtp-password",
        help="SMTP password.",
    )

    parser.add_argument(
        "--delay",
        default=None,
        help="Decimal number of seconds to wait between accessing the server.",
    )

    parser.add_argument(
        "--labels-file",
        help="CSV file mapping label IDs to names.",
    )

    parser.add_argument(
        "--skip-labels",
        action="store_true",
        help="Skip mapping label IDs to names.",
    )

    parser.add_argument(
        "--skip-unknown-labels",
        action="store_true",
        help="Skip mapping labels that aren't in the labels file.",
    )

    parser.add_argument(
        "--users-file",
        help="CSV file mapping user IDs to names.",
    )

    parser.add_argument(
        "--skip-users",
        action="store_true",
        help="Skip mapping user IDs to names.",
    )

    parser.add_argument(
        "--skip-unknown-users",
        action="store_true",
        help="Skip mapping users that aren't in the users file.",
    )

    parser.add_argument(
        "--skip-missing-issues",
        action="store_true",
        help="Skip missing Gitlab issue IDs; GL and sr.ht IDs will not match.",
    )

    parser.add_argument(
        "--create-missing-issues",
        action="store_true",
        help="Create missing GL issues in sr.ht to make issue IDs match.",
    )

    parser.add_argument(
        "--include-confidential",
        action="store_true",
        help="Include confidential tickets and notes.",
    )

    parser.add_argument(
        "--skip-confidential",
        action="store_true",
        help="Skip confidential tickets and notes.",
    )

    parser.add_argument(
        "export_dir",
        help="Exported Gitlab tree/project/ directory containing ndjson files.",
    )

    return vars(parser.parse_args(args_in))


def process_smtp(args: dict[str, Any]) -> Optional[smtplib.SMTP]:
    if args["mode"] != "send":
        return None
    else:
        smtp_ssl = args["smtp_ssl"]
        smtp_starttls = args["smtp_starttls"]
        smtp_host = args["smtp_host"] or os.environ.get("SMTP_HOST", "localhost")
        smtp_port = int(
            args["smtp_port"] or os.environ.get("SMTP_PORT", 465 if smtp_ssl else 25)
        )
        smtp_user = args["smtp_user"] or os.environ.get("SMTP_USER", None)
        smtp_password = args["smtp_password"] or os.environ.get("SMTP_PASSWORD", None)

        assert smtp_user, "No SMTP user given."
        assert smtp_password, "No SMTP password given."

        log.info("Connecting to %s:%d, user %r.", smtp_host, smtp_port, smtp_user)

        if smtp_ssl:
            smtp: smtplib.SMTP = smtplib.SMTP_SSL(host=smtp_host, port=smtp_port)
        else:
            smtp = smtplib.SMTP(host=smtp_host, port=smtp_port)

        # If SMTP isn't working:
        # smtp.set_debuglevel(2)

        if smtp_starttls:
            smtp.starttls()

        if smtp_user:
            smtp.login(smtp_user, smtp_password)

        return smtp


def main():
    args = parse_args(sys.argv[1:])

    export_dir = args["export_dir"]
    assert export_dir, "Must have a exported project directory."
    export_dir_path = Path(export_dir)
    assert (
        export_dir_path.is_dir()
    ), f"Project directory is not a directory: {export_dir_path}"

    mode = args["mode"]
    frm = args["from"]

    labels_file = args["labels_file"]
    skip_labels = args["skip_labels"]
    skip_unknown_labels = args["skip_unknown_labels"]
    assert (
        labels_file or skip_labels
    ), "One of --labels-file or --skip-labels must be provided."

    users_file = args["users_file"]
    skip_users = args["skip_users"]
    skip_unknown_users = args["skip_unknown_users"]
    assert (
        skip_users or users_file
    ), "One of --users-file or --skip-users must be provided."

    skip_missing_issues = args["skip_missing_issues"]
    create_missing_issues = args["create_missing_issues"]
    assert not (
        skip_missing_issues and create_missing_issues
    ), "Can accept at most one of --skip-missing-issues and --create-missing-issues."

    include_confidential = args["include_confidential"]
    skip_confidential = args["skip_confidential"]
    assert not (
        include_confidential and skip_confidential
    ), "Can accept at most one of --include-confidential and --skip-confidential."

    srht_owner = args["srht_owner"]
    srht_tracker = args["srht_tracker"]
    tracker = f"~{srht_owner}/{srht_tracker}"

    delay = args["delay"]
    if delay is None:
        if mode == "hut":
            delay = 0.5
        else:
            delay = 5
    else:
        delay = float(delay)

    smtp = process_smtp(args)

    try:
        run(
            smtp=smtp,
            delay=delay,
            mode=mode,
            tracker=tracker,
            frm=frm,
            export_dir_path=export_dir_path,
            gitlab_project_url=args["gitlab_project_url"].rstrip("/"),
            labels_file_path=None if skip_labels else Path(labels_file),
            skip_unknown_labels=skip_unknown_labels,
            users_file_path=None if skip_users else Path(users_file),
            skip_unknown_users=skip_unknown_users,
            skip_missing_issues=skip_missing_issues,
            create_missing_issues=create_missing_issues,
            include_confidential=include_confidential,
            skip_confidential=skip_confidential,
        )
    finally:
        if mode == "send":
            smtp.quit()


if __name__ == "__main__":
    main()