forked from svigerske/trac-to-github
-
Notifications
You must be signed in to change notification settings - Fork 5
/
migrate.py
executable file
·2912 lines (2566 loc) · 122 KB
/
migrate.py
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
#!/usr/bin/env python3
'''
Copyright © 2022-2023 Matthias Koeppe
Kwankyu Lee
Sebastian Oehms
Dima Pasechnik
Modified and extended for the migration of SageMath from Trac to GitHub.
Copyright © 2018-2019 Stefan Vigerske <[email protected]>
This is a modified/extended version of trac-to-gitlab from https://github.com/moimael/trac-to-gitlab.
It has been adapted to fit the needs of a specific Trac to GitLab conversion.
Then it has been adapted to fit the needs to another Trac to GitHub conversion.
Copyright © 2013 Eric van der Vlist <[email protected]>
Jens Neuhalfen <http://www.neuhalfen.name/>
This software 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
(at your option) any later version.
This sotfware 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 for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
'''
import re
import os
import sys
import configparser
import contextlib
import ast
import codecs
import logging
import mimetypes
import types
import gzip
import json
from collections import defaultdict
from copy import copy
from datetime import datetime
from difflib import unified_diff
from time import sleep
from roman import toRoman
from xmlrpc import client
from github import Github, GithubObject, InputFileContent
from github.Attachment import Attachment
from github.NamedUser import NamedUser
from github.Repository import Repository
from github.GithubException import IncompletableObject
from enum import Enum
from migration_archive_writer import MigrationArchiveWritingRequester
import markdown
from markdown.extensions.tables import TableExtension
from rich.console import Console
from rich.table import Table
#import github as gh
#gh.enable_console_debug_logging()
log = logging.getLogger("trac_to_gh")
default_config = {
'migrate' : 'true',
'keywords_to_labels' : 'false',
'export' : 'true', # attachments
'url' : 'https://api.github.com'
}
sleep_after_request = 2.0
sleep_after_attachment = 60.0
sleep_after_10tickets = 0.0 # TODO maybe this can be reduced due to the longer sleep after attaching something
sleep_before_xmlrpc = 0.33
sleep_before_xmlrpc_retry = 30.0
config = configparser.ConfigParser(default_config)
if len(sys.argv) > 1 :
config.read(sys.argv[1])
else :
config.read('migrate.cfg')
trac_url = config.get('source', 'url')
cgit_url = None
if config.has_option('source', 'cgit_url'):
cgit_url = config.get('source', 'cgit_url')
milestone_prefix_from = ''
if config.has_option('source', 'milestone_prefix'):
milestone_prefix_from = config.get('source', 'milestone_prefix')
trac_path = None
if config.has_option('source', 'path') :
trac_path = config.get('source', 'path')
keep_trac_ticket_references = config.getboolean('source', 'keep_trac_ticket_references')
class subdir(Enum):
"""
Enum for subdirectories of `trac_url_dir`
"""
def optional_path(self):
"""
Return the optional path for this sub directory
according to `trac_path`
"""
if trac_path:
return os.path.join(trac_path, self.value)
ticket = 'ticket'
wiki = 'wiki'
query = 'query'
report = 'report'
attachment = 'attachment'
raw_attachment = 'raw-attachment'
attachment_ticket = 'attachment/ticket'
raw_attachment_ticket = 'raw-attachment/ticket'
root = ''
class cgit_cmd(Enum):
"""
Enum for git commands used in the cgit web interface.
"""
commit = 'commit'
diff = 'diff'
tree = 'tree'
log = 'log'
tag = 'tag'
refs = 'refs'
plain = 'plain'
patch = 'patch'
default = ''
trac_url_dir = os.path.dirname(trac_url)
trac_url_ticket = os.path.join(trac_url_dir, subdir.ticket.value)
trac_url_wiki = os.path.join(trac_url_dir, subdir.wiki.value)
trac_url_query = os.path.join(trac_url_dir, subdir.query.value)
trac_url_report = os.path.join(trac_url_dir, subdir.report.value)
trac_url_attachment = os.path.join(trac_url_dir, subdir.attachment.value)
if config.has_option('target', 'issues_repo_url'):
target_url_issues_repo = config.get('target', 'issues_repo_url')
target_url_git_repo = config.get('target', 'git_repo_url')
if config.has_option('wiki', 'url'):
target_url_wiki = config.get('wiki', 'url')
github_api_url = config.get('target', 'url')
github_token = None
if config.has_option('target', 'token') :
github_token = config.get('target', 'token')
elif config.has_option('target', 'username'):
github_username = config.get('target', 'username')
github_password = config.get('target', 'password')
else:
github_username = None
github_project = config.get('target', 'project_name')
migration_archive = None
if config.has_option('target', 'migration_archive'):
migration_archive = config.get('target', 'migration_archive')
users_map = {}
user_full_names = {}
username_modules = []
if config.has_option('target', 'username_modules'):
username_modules = ast.literal_eval(config.get('target', 'username_modules'))
for module in username_modules:
module = __import__(module)
users_map.update(module.trac_to_github())
user_full_names.update(module.trac_full_names())
users_map.update(ast.literal_eval(config.get('target', 'usernames')))
unknown_users_prefix = ''
if config.has_option('target', 'unknown_users_prefix'):
unknown_users_prefix = config.get('target', 'unknown_users_prefix')
milestone_prefix_to = ''
if config.has_option('target', 'milestone_prefix'):
milestone_prefix_to = config.get('target', 'milestone_prefix')
must_convert_issues = config.getboolean('issues', 'migrate')
only_issues = None
if config.has_option('issues', 'only_issues'):
only_issues = ast.literal_eval(config.get('issues', 'only_issues'))
blacklist_issues = None
if config.has_option('issues', 'blacklist_issues'):
blacklist_issues = ast.literal_eval(config.get('issues', 'blacklist_issues'))
filter_issues = 'max=0&order=id'
if config.has_option('issues', 'filter_issues') :
filter_issues = config.get('issues', 'filter_issues')
try:
keywords_to_labels = config.getboolean('issues', 'keywords_to_labels')
except ValueError:
keywords_to_labels = ast.literal_eval(config.get('issues', 'keywords_to_labels'))
migrate_milestones = config.getboolean('issues', 'migrate_milestones')
milestones_to_labels = {}
if config.has_option('issues', 'milestones_to_labels'):
milestones_to_labels = ast.literal_eval(config.get('issues', 'milestones_to_labels'))
canceled_milestones = {}
if config.has_option('issues', 'canceled_milestones'):
canceled_milestones = ast.literal_eval(config.get('issues', 'canceled_milestones'))
components_to_labels = {}
if config.has_option('issues', 'components_to_labels'):
components_to_labels = ast.literal_eval(config.get('issues', 'components_to_labels'))
add_label = None
if config.has_option('issues', 'add_label'):
add_label = config.get('issues', 'add_label')
# 6-digit hex notation with leading '#' sign (e.g. #FFAABB) or one of the CSS color names
# (https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#Color_keywords)
labelcolor = {
'component' : '08517b',
'priority' : 'ff0000',
'severity' : 'ee0000',
'type' : '008080',
'keyword' : 'eeeeee',
'milestone' : '008080',
'resolution' : '008080',
}
if config.has_option('issues', 'label_colors'):
labelcolor.update(ast.literal_eval(config.get('issues', 'label_colors')))
ignored_values = []
if config.has_option('issues', 'ignored_values'):
ignored_values = ast.literal_eval(config.get('issues', 'ignored_values'))
ignored_names = set([])
if config.has_option('issues', 'ignored_names'):
ignored_names = set(ast.literal_eval(config.get('issues', 'ignored_names')))
ignored_mentions = set([])
if config.has_option('issues', 'ignored_mentions'):
ignored_mentions = set(ast.literal_eval(config.get('issues', 'ignored_mentions')))
attachment_export = config.getboolean('attachments', 'export')
if attachment_export:
attachment_export_dir = config.get('attachments', 'export_dir')
if config.has_option('attachments', 'export_url'):
attachment_export_url = config.get('attachments', 'export_url')
if not attachment_export_url.endswith('/') :
attachment_export_url += '/'
else:
attachment_export_url = target_url_issues_repo
if not attachment_export_url.endswith('/') :
attachment_export_url += '/'
attachment_export_url += 'files/'
must_convert_wiki = config.getboolean('wiki', 'migrate')
wiki_export_dir = None
if must_convert_wiki or config.has_option('wiki', 'export_dir'):
wiki_export_dir = config.get('wiki', 'export_dir')
default_multilines = False
if config.has_option('source', 'default_multilines') :
# set this boolean in the source section of the configuration file
# to change the default of the multilines flag in the function
# trac2markdown
default_multilines = config.getboolean('source', 'default_multilines')
from diskcache import Cache
cache = Cache('trac_cache', size_limit=int(20e9))
gh_labels = dict()
gh_user = None
closing_commits = {} # (src_ticket_id, commit) -> closing_commit
def read_closing_commits():
# Generated using write-closing-commits.sh
if os.path.exists('closing_commits.txt'):
with open('closing_commits.txt', 'r') as f:
for line_number, line in enumerate(f.readlines(), start=1):
if m := re.match('^([0-9a-f]{40}) Merge: ([0-9a-f]{40}) ([0-9a-f]{40}) Trac #([0-9]+):', line):
sha = m.group(1)
parent2_sha = m.group(3)
src_ticket_id = int(m.group(4))
try:
other_sha = closing_commits[src_ticket_id, parent2_sha]
except KeyError:
pass
else:
log.warning(f'closing_commits.txt:{line_number}: multiple commits for ticket #{src_ticket_id} {parent2_sha}: {other_sha}, {sha}')
closing_commits[src_ticket_id, parent2_sha] = sha
elif line:
log.warning(f'closing_commits.txt:{line_number}: malformed line')
# The file wiki_path_conversion_table.txt is created if not exists. If it
# exists, the table below is constructed from the data in the file.
create_wiki_link_conversion_table = False
wiki_path_conversion_table = {}
if os.path.exists('wiki_path_conversion_table.txt'):
with open('wiki_path_conversion_table.txt', 'r') as f:
for line in f.readlines():
trac_wiki_path, wiki_path = line[:-1].split(' ')
wiki_path_conversion_table[trac_wiki_path] = wiki_path
elif must_convert_wiki:
create_wiki_link_conversion_table = True
RE_CAMELCASE1 = re.compile(r'(?<=\s)((?:[A-Z][a-z0-9]+){2,})(?=[\s\.\,\:\;\?\!])')
RE_CAMELCASE2 = re.compile(r'(?<=\s)((?:[A-Z][a-z0-9]+){2,})$')
RE_HEADING1 = re.compile(r'^(=)\s(.+)\s=\s*([\#][^\s]*)?')
RE_HEADING2 = re.compile(r'^(==)\s(.+)\s==\s*([\#][^\s]*)?')
RE_HEADING3 = re.compile(r'^(===)\s(.+)\s===\s*([\#][^\s]*)?')
RE_HEADING4 = re.compile(r'^(====)\s(.+)\s====\s*([\#][^\s]*)?')
RE_HEADING5 = re.compile(r'^(=====)\s(.+)\s=====\s*([\#][^\s]*)?')
RE_HEADING6 = re.compile(r'^(======)\s(.+)\s======\s*([\#][^\s]*)?')
RE_HEADING1a = re.compile(r'^(=)\s([^#]+)([\#][^\s]*)?')
RE_HEADING2a = re.compile(r'^(==)\s([^#]+)([\#][^\s]*)?')
RE_HEADING3a = re.compile(r'^(===)\s([^#]+)([\#][^\s]*)?')
RE_HEADING4a = re.compile(r'^(====)\s([^#]+)([\#][^\s]*)?')
RE_HEADING5a = re.compile(r'^(=====)\s([^#]+)([\#][^\s]*)?')
RE_HEADING6a = re.compile(r'^(======)\s([^#]+)([\#][^\s]*)?')
RE_SUPERSCRIPT1 = re.compile(r'\^([^\s]+?)\^')
RE_SUBSCRIPT1 = re.compile(r',,([^\s]+?),,')
RE_IMAGE1 = re.compile(r'\[\[Image\(source:([^(]+)\)\]\]')
RE_IMAGE2 = re.compile(r'\[\[Image\(([^),]+)\)\]\]')
RE_IMAGE3 = re.compile(r'\[\[Image\(([^),]+),\slink=([^(]+)\)\]\]')
RE_IMAGE4 = re.compile(r'\[\[Image\((http[^),]+),\s([^)]+)\)\]\]')
RE_IMAGE5 = re.compile(r'\[\[Image\(([^),]+),\s([^)]+)\)\]\]')
RE_IMAGE6 = re.compile(r'\[\[Image\(([^),]+),\s*([^)]+),\s*([^)]+)\)\]\]')
RE_HTTPS1 = re.compile(r'\[\[(https?://[^\s\]\|]+)\s*\|\s*(.+?)\]\]')
RE_HTTPS2 = re.compile(r'\[\[(https?://[^\]]+)\]\]')
RE_HTTPS3 = re.compile(r'\[(https?://[^\s\[\]\|]+)\s*[\s\|]\s*([^\[\]]+)\]')
RE_HTTPS4 = re.compile(r'\[(https?://[^\s\[\]\|]+)\]')
RE_TICKET_COMMENT1 = re.compile(r'\[\[ticket:([1-9]\d*)#comment:([1-9]\d*)\s*\|\s*(.+?)\]\]')
RE_TICKET_COMMENT2 = re.compile(r'\[\[ticket:([1-9]\d*)#comment:([1-9]\d*)\]\]')
RE_TICKET_COMMENT3 = re.compile(r'\[ticket:([1-9]\d*)#comment:([1-9]\d*)\s+(.*?)\]')
RE_TICKET_COMMENT4 = re.compile(r'\[ticket:([1-9]\d*)#comment:([0])\s+(.*?)\]')
RE_TICKET_COMMENT5 = re.compile(r'\[comment:ticket:([1-9]\d*):([1-9]\d*)\s+(.*?)\]')
RE_TICKET_COMMENT6 = re.compile(r'ticket:([1-9]\d*)#comment:([1-9]\d*)')
RE_COMMENT1 = re.compile(r'\[\[comment:([1-9]\d*)\]\]')
RE_COMMENT2 = re.compile(r'\[\[comment:([1-9]\d*)\s*\|\s*(.+?)\]\]')
RE_COMMENT3 = re.compile(r'\[comment:([1-9]\d*)\s+(.*?)\]')
RE_COMMENT4 = re.compile(r'(?<=\s)comment:([1-9]\d*)') # need to exclude the string as part of http url
RE_ATTACHMENT1 = re.compile(r'\[\[attachment:([^\s\|\]]+)[\s\|](.+?)\]\]')
RE_ATTACHMENT2 = re.compile(r'\[\[attachment:([^\s]+?)\]\]')
RE_ATTACHMENT3 = re.compile(r'\[attachment:([^\s\|\]]+)[\s\|](.+?)\]')
RE_ATTACHMENT4 = re.compile(r'\[attachment:([^\s]+?)\]')
RE_ATTACHMENT5 = re.compile(r'(?<=\s)attachment:([^\s]+)\.\s')
RE_ATTACHMENT6 = re.compile(r'^attachment:([^\s]+)\.\s')
RE_ATTACHMENT7 = re.compile(r'(?<=\s)attachment:([^\s]+)')
RE_ATTACHMENT8 = re.compile(r'^attachment:([^\s]+)')
RE_LINEBREAK1= re.compile(r'(\[\[br\]\])')
RE_LINEBREAK2 = re.compile(r'(\[\[BR\]\])')
RE_LINEBREAK3 = re.compile(r'(\\\\\s*)')
RE_WIKI1 = re.compile(r'\[\["([^\]\|]+)["]\s*([^\[\]"]+)?["]?\]\]')
RE_WIKI2 = re.compile(r'\[\[\s*([^\]|]+)[\|]([^\[\]\|]+)\]\]')
RE_WIKI3 = re.compile(r'\[\[\s*([^\]]+)\]\]')
RE_WIKI4 = re.compile(r'\[wiki:"([^\[\]\|]+)["]\s*([^\[\]"]+)?["]?\]')
RE_WIKI5 = re.compile(r'\[wiki:([^\s\[\]\|]+)\s*[\s\|]\s*([^\[\]]+)\]')
RE_WIKI6 = re.compile(r'\[wiki:([^\s\[\]]+)\]')
RE_WIKI7 = re.compile(r'\[/wiki/([^\s\[\]]+)\s+([^\[\]]+)\]')
RE_QUERY1 = re.compile(r'\[query:\?')
RE_SOURCE1 = re.compile(r'\[source:([^\s\[\]]+)\s+([^\[\]]+)\]')
RE_SOURCE2 = re.compile(r'source:([\S]+)')
RE_BOLDTEXT1 = re.compile(r'\'\'\'(.*?)\'\'\'')
RE_ITALIC1 = re.compile(r'\'\'(.*?)\'\'')
RE_ITALIC2 = re.compile(r'(?<=\s)//(.*?)//')
RE_TICKET1 = re.compile(r'[\s]%s/([1-9]\d{0,4})' % trac_url_ticket)
RE_TICKET2 = re.compile(r'\#([1-9]\d{0,4})')
RE_UNDERLINED_CODE1 = re.compile(r'(?<=\s)_([a-zA-Z_]+)_(?=[\s,)])')
RE_UNDERLINED_CODE2 = re.compile(r'(?<=\s)_([a-zA-Z_]+)_$')
RE_UNDERLINED_CODE3 = re.compile(r'^_([a-zA-Z_]+)_(?=\s)')
RE_CODE_SNIPPET = re.compile(r'(?<!`){{{(.*?)}}}(?!\})')
RE_GITHUB_MENTION1 = re.compile('(?<=\s)@([a-zA-Z][-a-zA-Z0-9._]*[a-zA-Z0-9])')
RE_GITHUB_MENTION2 = re.compile('^@([a-zA-Z][-a-zA-Z0-9._]*[a-zA-Z0-9])')
RE_RULE = re.compile(r'^[-]{4,}\s*')
RE_NO_CAMELCASE = re.compile(r'\!(([A-Z][a-z0-9]+){2,})')
RE_COLOR = re.compile(r'<span style="color: ([a-zA-Z]+)">([a-zA-Z]+)</span>')
RE_TRAC_REPORT = re.compile(r'\[report:([0-9]+)\s*(.*?)\]')
RE_COMMIT_LIST1 = re.compile(r'\|\[(.+?)\]\((.*)\)\|<code>(.*?)</code>\|')
RE_COMMIT_LIST2 = re.compile(r'\|\[(.+?)\]\((.*)\)\|`(.*?)`\|')
RE_COMMIT_LIST3 = re.compile(r'\|(.*?)\|(.*?)\|')
RE_NEW_COMMITS = re.compile(r'(?sm)(New commits:)\n((?:\|[^\n]*\|(?:\n|$))+)')
RE_LAST_NEW_COMMITS = re.compile(r'(?sm)(Last \d+ new commits:)\n((?:\|[^\n]*\|(?:\n|$))+)')
class CodeTag:
"""
Handler for code protectors.
"""
def replace(self, text):
"""
Return the given string with protection tags replaced by their proper counterparts.
"""
text = text.replace(self.tag, self._code)
return text
def __init__(self, tag, code):
self.tag = tag
self._code = code
at_sign = CodeTag('AT__SIGN__IN__CODE', '@')
linebreak_sign1 = CodeTag('LINEBREAK__SIGN1__IN__CODE', r'\\')
linebreak_sign2 = CodeTag('LINEBREAK__SIGN2__IN__CODE', r'[[br]]')
linebreak_sign3 = CodeTag('LINEBREAK__SIGN3__IN__CODE', r'[[BR]]')
class Brackets:
"""
Handler for bracket protectors.
"""
def replace(self, text):
"""
Return the given string with protection tags replaced by their proper counterparts.
"""
text = text.replace(self.open, self._open_bracket)
text = text.replace(self.close, self._close_bracket)
return text
def __init__(self, open_tag, close_tag, open_bracket, close_bracket):
self.open = open_tag
self.close = close_tag
self._open_bracket = open_bracket
self._close_bracket = close_bracket
link_displ = Brackets('OPENING__LEFT__BRACKET', 'CLOSING__RIGHT__BRACKET', '[', ']')
proc_code = Brackets('OPENING__PROCESSOR__CODE', 'CLOSING__PROCESSOR__CODE', '```', '```')
proc_td = Brackets('OPENING__PROCESSOR__TD', 'CLOSING__PROCESSOR__TD', r'<div align="left">', r'</div>')
class SourceUrlConversionHelper:
"""
Conversion helper for pattern involving url-data from source configuration.
"""
class regex(Enum):
pass
def __init__(self, url):
self._re = {}
if not url:
# path might be optional dependend on configuration
return
for reg in self.regex:
expr, path, argument = reg.value
if isinstance(path, Enum):
path = path.value
if path is None:
# path might be optional dependend on configuration
continue
path = os.path.join(url, path)
self._re[reg] = re.compile(r'%s%s' % (self._url_pattern(path), expr))
def _url_pattern(self, url):
pattern = url.replace('https', 'https?')
pattern = pattern.replace('.', '\\.')
return pattern
def sub(self, text):
if not len(self._re):
# all expressions are optional and not activ
return text
for reg in self._re.keys():
expr, path, argument = reg.value
text = self._re[reg].sub(argument, text)
return text
class TracUrlConversionHelper(SourceUrlConversionHelper):
"""
Conversion helper for pattern involving the Trac url.
"""
class regex(Enum):
"""
"""
def convert_wiki_link(match):
trac_path = match.group(1)
if trac_path in wiki_path_conversion_table:
wiki_path = wiki_path_conversion_table[trac_path]
return os.path.join(target_url_wiki, wiki_path)
return match.group(0)
def convert_ticket_attachment(match):
ticket_id = match.group(1)
filename = match.group(2)
if keep_trac_ticket_references:
return os.path.join(trac_url_attachment, 'ticket', ticket_id, filename)
return gh_attachment_url(ticket_id, filename)
TICKET1 = [r'/(\d+)#comment:(\d+)?', subdir.ticket, r'ticket:\1#comment:\2']
TICKET2 = [r'/(\d+)#comment:(\d+)?', subdir.ticket.optional_path(), r'ticket:\1#comment:\2']
TICKET3 = [r'/(\d+)', subdir.ticket, r'%s/issues/\1' % target_url_issues_repo]
TICKET4 = [r'/(\d+)', subdir.ticket.optional_path(), r'%s/issues/\1' % target_url_issues_repo]
WIKI1= [r'/([/\-\w0-9@:%._+~#=]+)', subdir.wiki, convert_wiki_link]
ATTACHMENT1 = [r'/(\d+)/([/\-\w0-9@:%._+~#=]+)', subdir.attachment_ticket, convert_ticket_attachment]
ATTACHMENT2 = [r'/(\d+)/([/\-\w0-9@:%._+~#=]+)', subdir.attachment_ticket.optional_path(), convert_ticket_attachment]
ATTACHMENT3 = [r'/(\d+)/([/\-\w0-9@:%._+~#=]+)', subdir.raw_attachment_ticket, convert_ticket_attachment]
ATTACHMENT4 = [r'/(\d+)/([/\-\w0-9@:%._+~#=]+)', subdir.raw_attachment_ticket.optional_path(), convert_ticket_attachment]
class CgitConversionHelper(SourceUrlConversionHelper):
"""
Conversion helper for pattern involving the cgit web interface.
"""
class regex(Enum):
"""
"""
def convert_git_link_diff1(match):
path = match.group(1)
hash1 = match.group(2)
return os.path.join(target_url_git_repo, 'blob', hash1, path)
def convert_git_link_diff2(match):
path = match.group(1)
hash1 = match.group(2)
return os.path.join(target_url_git_repo, 'compare', hash1 + '...' + path)
def convert_git_link_diff3(match):
hash1 = match.group(1)
hash2 = match.group(2)
return os.path.join(target_url_git_repo, 'compare', hash1 + '...' + hash2)
def convert_git_link_diff4(match):
hash1 = match.group(1)
return os.path.join(target_url_git_repo, 'commit', hash1)
def convert_git_link_diff5(match):
path1 = match.group(1)
path2 = match.group(2)
hash1 = match.group(3)
return os.path.join(target_url_git_repo, 'compare', hash1 + '...' + path2)
def convert_git_link_diff6(match):
branch = match.group(1)
path = match.group(2)
return os.path.join(target_url_git_repo, 'compare', path + '...' + branch)
def convert_git_link_diff7(match):
branch = match.group(1)
return os.path.join(target_url_git_repo, 'commits', branch)
def convert_git_link_diff8(match):
branch = match.group(1)
return os.path.join(target_url_git_repo, 'commits', branch)
def convert_git_link_commit1(match):
path = match.group(1)
hash1 = match.group(2)
return os.path.join(target_url_git_repo, 'commit', hash1)
def convert_git_link_commit3(match):
hash1 = match.group(1)
return os.path.join(target_url_git_repo, 'commit', hash1)
def convert_git_link_commit4(match):
path = match.group(1)
return os.path.join(target_url_git_repo, 'commits', path)
def convert_git_link_commit5(match):
path = match.group(1)
return os.path.join(target_url_git_repo, 'commit', path)
def convert_git_link_commit6(match):
path = match.group(1)
branch = match.group(2)
hash1 = match.group(3)
return os.path.join(target_url_git_repo, 'compare', hash1 + '...' + branch)
def convert_git_link_commit7(match):
path = match.group(1)
hash1 = match.group(2)
return os.path.join(target_url_git_repo, 'commit', hash1, path)
def convert_git_link_tree1(match):
path = match.group(1)
return os.path.join(target_url_git_repo, 'blob/develop', path)
def convert_git_link_tree2(match):
branch = match.group(1)
return os.path.join(target_url_git_repo, 'tree', branch)
def convert_git_link_log1(match):
path = match.group(1)
return os.path.join(target_url_git_repo, 'commits', path)
def convert_git_link_log3(match):
hash1 = match.group(1)
hash2 = match.group(2)
hash3 = match.group(3)
return os.path.join(target_url_git_repo, 'compare', hash1 + '...' + hash2)
def convert_git_link_log4(match):
path = match.group(1)
hash1 = match.group(2)
return os.path.join(target_url_git_repo, 'commits', 'develop?after=' + hash1 + '+0' + '&branch=develop'
+ '&path%5B%5D=' + '&path%5B%5D='.join(path.split('/')) + '&qualified_name=refs%2Fheads%2Fdevelop')
def convert_git_link_log5(match):
path = match.group(1)
return os.path.join(target_url_git_repo, 'commits/develop', path)
def convert_git_link_plain(match):
path = match.group(1)
branch = match.group(2)
return os.path.join(target_url_git_repo, 'blob', branch, path)
def convert_git_link_patch(match):
hash1 = match.group(1)
return os.path.join(target_url_git_repo, 'commit', hash1 + '.patch')
def convert_git_link(match): # catch all missed git link
import pdb; pdb.set_trace()
DIFF1 = [r'/([/\-\w0-9@:%._+~#=]+)\?id=([0-9a-f]+)', cgit_cmd.diff, convert_git_link_diff1]
DIFF2 = [r'/?\?h=([/\-\w0-9@:%._+~#=]+)&id2=([0-9a-f]+)', cgit_cmd.diff, convert_git_link_diff2]
DIFF3 = [r'/?\?id2?=([0-9a-f]+)&id=([0-9a-f]+)', cgit_cmd.diff, convert_git_link_diff3]
DIFF4 = [r'/?\?id=([0-9a-f]+)', cgit_cmd.diff, convert_git_link_diff4]
DIFF5 = [r'/?([/\-\w0-9@:%._+~#=]+)\?h=([/\-\w0-9@:%._+~#=]+)&id=([0-9a-f]+)', cgit_cmd.diff, convert_git_link_diff5]
DIFF6 = [r'/?\?id2=([/\-\w0-9@:%._+~#=]+)&id=([/\-\w0-9@:%._+~#=]+)', cgit_cmd.diff, convert_git_link_diff6]
DIFF7 = [r'/?\?h=([/\-\w0-9@:%._+~#=]+)', cgit_cmd.diff, convert_git_link_diff7]
DIFF8 = [r'/?\?id=([/\-\w0-9@:%._+~#=]+)', cgit_cmd.diff, convert_git_link_diff8]
COMMIT1 = [r'/?\?h=([/\-\w0-9@:%._+~#=]+)&id=([0-9a-f]+)', cgit_cmd.commit, convert_git_link_commit1]
COMMIT2 = [r'id=([0-9a-f]+)', cgit_cmd.commit, convert_git_link_commit3] # misspelled
COMMIT3 = [r'/?\?id=([0-9a-f]+)', cgit_cmd.commit, convert_git_link_commit3]
COMMIT4 = [r'/?\?h=([/\-\w0-9@:%._+~#=]+)', cgit_cmd.commit, convert_git_link_commit4]
COMMIT5 = [r'/?\?id=([/\-\w0-9@:%._+~#=]+)', cgit_cmd.commit, convert_git_link_commit5]
COMMIT6 = [r'/([/\-\w0-9@:%._+~#=]+)\?h=([/\-\w0-9@:%._+~#=]+)&id=([0-9a-f]+)', cgit_cmd.commit, convert_git_link_commit6]
COMMIT7 = [r'/([/\-\w0-9@:%._+~#=]+)\?id=([0-9a-f]+)', cgit_cmd.commit, convert_git_link_commit7]
COMMIT8 = [r'/([/\-\w0-9@:%._+~#=]+)\?h=([0-9a-f]+)', cgit_cmd.commit, convert_git_link_commit7]
TREE1 = [r'/([/\-\w0-9@:%._+~#=]+)', cgit_cmd.tree, convert_git_link_tree1]
TREE2 = [r'/?\?h=([/\-\w0-9@:%._+~#=]+)', cgit_cmd.tree, convert_git_link_tree2]
TREE3 = [r'/src/?', cgit_cmd.tree, r'%s/blob/master/src' % target_url_git_repo]
LOG1 = [r'/?\?h=([/\-\w0-9@:%._+~#=]+)', cgit_cmd.log, convert_git_link_log1]
LOG2 = [r'/?\?q=([0-9a-f]+)..([0-9a-f]+)&h=([0-9a-f]+)&qt=range', cgit_cmd.log, convert_git_link_log3]
LOG3 = [r'/?([/\-\w0-9@:%._+~#=]+)\?h=([0-9a-f]+)', cgit_cmd.log, convert_git_link_log4]
LOG4 = [r'/?([/\-\w0-9@:%._+~#=]+)', cgit_cmd.log, convert_git_link_log5]
PLAIN1 = [r'/([/\-\w0-9@:%._+~#=]+)\?h=([/\-\w0-9@:%._+~#=]+)', cgit_cmd.plain, convert_git_link_plain]
PATCH1 = [r'/?\?id=([0-9a-f]+)', cgit_cmd.patch, convert_git_link_patch]
REFS1 = [r'/?', cgit_cmd.refs, r'%s/branches' % target_url_git_repo]
TAG1 = [r'/?\?id=([/\-\w0-9@:%._+~#=]+)', cgit_cmd.tag, r'%s/releases/tag/\1' % target_url_git_repo]
DEF = [r'/(.*)', cgit_cmd.default, convert_git_link] # catch all missed
trac_url_conv_help = TracUrlConversionHelper(trac_url_dir)
cgit_conv_help = CgitConversionHelper(cgit_url)
RE_WRONG_FORMAT1 = re.compile(r'comment:(\d+):ticket:(\d+)')
RE_REPLYING_TO = re.compile(r'Replying to \[comment:(\d+)\s([\-\w0-9@._]+)\]')
RE_REPLYING_TO_TICKET = re.compile(r'Replying to \[ticket:(\d+)\s([\-\w0-9@._]+)\]')
def inline_code_snippet(match):
code = match.group(1)
code = code.replace(r'@', at_sign.tag)
code = code.replace(r'\\', linebreak_sign1.tag)
code = code.replace(r'[[br]]', linebreak_sign2.tag)
code = code.replace(r'[[BR]]', linebreak_sign3.tag)
if '`' in code:
return '<code>' + code.replace('`', r'\`') + '</code>'
else:
return '`' + code + '`'
def convert_replying_to(match):
comment_id = match.group(1)
username = match.group(2)
name = convert_trac_username(username)
if name: # github username
name = '@' + name
else:
name = username
return 'Replying to [comment:{} {}]'.format(comment_id, name)
def convert_replying_to_ticket(match):
ticket_id = match.group(1)
username = match.group(2)
name = convert_trac_username(username)
if name: # github username
name = '@' + name
else:
name = username
return 'Replying to [ticket:{}#comment:0 {}]'.format(ticket_id, name)
def commits_list(match):
t = match.group(1) + '\n'
t += '<table>'
for c in match.group(2).split('\n')[2:]: # the first two are blank header
if not c:
continue
m = RE_COMMIT_LIST1.match(c)
if m:
commit_id = m.group(1)
commit_url = m.group(2)
commit_msg = m.group(3).replace('\`', '`')
t += r'<tr><td><a href="{}"><code>{}</code></a></td><td><code>{}</code></td></tr>'.format(commit_url, commit_id, commit_msg)
else:
m = RE_COMMIT_LIST2.match(c)
if m:
commit_id = m.group(1)
commit_url = m.group(2)
commit_msg = m.group(3)
t += r'<tr><td><a href="{}"><code>{}</code></a></td><td><code>{}</code></td></tr>'.format(commit_url, commit_id, commit_msg)
else: # unusual format
m = RE_COMMIT_LIST3.match(c)
commit_id = m.group(1)
commit_msg = m.group(2)
t += r'<tr><td><code>{}</code></td><td><code>{}</code></td></tr>'.format(commit_id, commit_msg)
t += '</table>\n'
return t
def github_mention(match):
username = match.group(1)
github_username = convert_trac_username(username, is_mention=True)
if github_username:
return '@' + github_username
return '`@`' + username
def trac2markdown(text, base_path, conv_help, multilines=default_multilines):
# conversion of url
text = trac_url_conv_help.sub(text)
text = cgit_conv_help.sub(text)
# some normalization
text = RE_WRONG_FORMAT1.sub(r'ticket:\2#comment:\1', text)
text = RE_REPLYING_TO.sub(convert_replying_to, text)
text = RE_REPLYING_TO_TICKET.sub(convert_replying_to_ticket, text)
text = re.sub('\r\n', '\n', text)
text = re.sub(r'\swiki:([a-zA-Z]+)', r' [wiki:\1]', text)
text = re.sub(r'\[\[TOC[^]]*\]\]', '', text)
text = re.sub(r'(?m)\[\[PageOutline\]\]\s*\n', '', text)
if multilines:
text = re.sub(r'^\S[^\n]+([^=-_|])\n([^\s`*0-9#=->-_|])', r'\1 \2', text)
def heading_replace(match):
"""
Return the replacement for the heading
"""
level = len(match.group(1))
heading = match.group(2).rstrip()
if not isinstance(conv_help, IssuesConversionHelper) and create_wiki_link_conversion_table:
with open('wiki_path_conversion_table.txt', "a") as f:
f.write(conv_help._trac_wiki_path + '#' + heading.replace(' ', '') + ' '
+ conv_help._wiki_path + '#' + heading.replace(' ', '-'))
f.write('\n')
# There might be a second item if an anchor is set.
# We ignore this anchor since it is automatically
# set it GitHub Markdown.
return '#'*level + ' ' + heading
a = []
level = 0
in_td = False
in_code = False
in_html = False
in_list = False
in_table = False
quote_depth_decreased = False
block = []
table = []
list_indents = []
previous_line = ''
quote_prefix = ''
text_lines = text.split('\n') + ['']
text_lines.reverse()
line = True
while text_lines:
non_blank_previous_line = bool(line)
line = text_lines.pop()
# cut quote prefix
if line.startswith(quote_prefix):
line = line[len(quote_prefix):]
else:
if in_code or in_html: # to recover from interrupted codeblock
text_lines.append(line) # put it back
text_lines.append(quote_prefix + '}}}')
line = non_blank_previous_line
continue
if line: # insert a blank line when quote depth decreased
quote_depth_decreased = True
quote_prefix = ''
if not (in_code or in_html):
# quote
prefix = ''
m = re.match('^((?:>\s)*>\s)', line)
if m:
prefix += m.group(1)
m = re.match('^(>[>\s]*)', line[len(prefix):])
if m:
prefix += m.group(1)
quote_prefix += prefix
if quote_depth_decreased:
a.append(quote_prefix)
quote_depth_decreased = False
line = line[len(prefix):]
if previous_line:
line = previous_line + line
previous_line = ''
line_temporary = line.lstrip()
if line_temporary.startswith('{{{') and in_code:
level += 1
elif re.match(r'{{{\s*#!td', line_temporary):
in_td = True
in_td_level = level
in_td_prefix = re.search('{{{', line).start()
in_td_n = 0
in_td_defect = 0
line = re.sub(r'{{{\s*#!td', r'%s' % proc_td.open, line)
level += 1
elif re.match(r'{{{\s*#!html', line_temporary) and not (in_code or in_html):
in_html = True
in_html_level = level
in_html_prefix = re.search('{{{', line).start()
in_html_n = 0
in_html_defect =0
line = re.sub(r'{{{\s*#!html', r'', line)
level += 1
elif re.match(r'{{{\s*#!', line_temporary) and not (in_code or in_html): # code: python, diff, ...
in_code = True
in_code_level = level
in_code_prefix = re.search('{{{', line).start()
in_code_n = 0
in_code_defect = 0
if non_blank_previous_line:
line = '\n' + line
line = re.sub(r'{{{\s*#!([^\s]+)', r'%s\1' % proc_code.open, line)
level += 1
elif line_temporary.rstrip() == '{{{' and not (in_code or in_html):
# check dangling #!...
next_line = text_lines.pop()
if next_line.startswith(quote_prefix):
m = re.match('#!([a-zA-Z]+)', next_line[len(quote_prefix):].strip())
if m:
if m.group(1) == 'html':
text_lines.append(quote_prefix + line.replace('{{{', '{{{#!html'))
continue
line = line.rstrip() + m.group(1)
else:
text_lines.append(next_line)
else:
text_lines.append(next_line)
in_code = True
in_code_level = level
in_code_prefix = re.search('{{{', line).start()
in_code_n = 0
in_code_defect = 0
if line_temporary.rstrip() == '{{{':
if non_blank_previous_line:
line = '\n' + line
line = line.replace('{{{', proc_code.open, 1)
else:
if non_blank_previous_line:
line = '\n' + line
line = line.replace('{{{', proc_code.open + '\n' , 1)
level += 1
elif line_temporary.rstrip() == '}}}':
level -= 1
if in_td and in_td_level == level:
in_td = False
in_td_prefix = 0
if in_td_defect > 0:
for i in range(in_td_n):
prev_line = a[-i-1]
a[-i-1] = prev_line[:len(quote_prefix)] + in_td_defect*' ' + prev_line[len(quote_prefix):]
line = re.sub(r'}}}', r'%s' % proc_td.close, line)
elif in_html and in_html_level == level:
in_html = False
id_html_prefix = 0
if in_html_defect > 0:
for i in range(in_html_n):
prev_line = a[-i-1]
a[-i-1] = prev_line[:len(quote_prefix)] + in_html_defect*' ' + prev_line[len(quote_prefix):]
line = re.sub(r'}}}', r'', line)
elif in_code and in_code_level == level:
in_code = False
in_code_prefix = 0
if in_code_defect > 0:
for i in range(in_code_n):
prev_line = a[-i-1]
a[-i-1] = prev_line[:len(quote_prefix)] + in_code_defect*' ' + prev_line[len(quote_prefix):]
line = re.sub(r'}}}', r'%s' % proc_code.close, line)
else:
# adjust badly indented codeblocks
if in_td:
if line.strip():
indent = re.search('[^\s]', line).start()
if indent < in_td_prefix:
in_td_defect = max(in_td_defect, in_td_prefix - indent)
in_td_n += 1
if in_html:
if line.strip():
indent = re.search('[^\s]', line).start()
if indent < in_html_prefix:
in_html_defect = max(in_html_defect, in_html_prefix - indent)
in_html_n += 1
if in_code:
if line.strip():
indent = re.search('[^\s]', line).start()
if indent < in_code_prefix:
in_code_defect = max(in_code_defect, in_code_prefix - indent)
in_code_n += 1
# CamelCase wiki link
if not (in_code or in_html or in_td):
new_line = ''
depth = 0
start = 0
end = 0
l = len(line)
for i in range(l + 1):
if i == l:
end = i
elif line[i] == '[':
if depth == 0:
end = i
depth += 1
elif line[i] == ']':
depth -= 1
if depth == 0:
start = i + 1
new_line += line[end:start]
if end > start:
converted_part = RE_CAMELCASE1.sub(conv_help.camelcase_wiki_link, line[start:end])
converted_part = RE_CAMELCASE2.sub(conv_help.camelcase_wiki_link, converted_part)
new_line += converted_part
start = end
line = new_line
if not (in_code or in_html):
# heading
line = re.sub(r'^(\s*)# ', r'\1\# ', line) # first fix unintended heading
line = RE_HEADING1.sub(heading_replace, line)
line = RE_HEADING2.sub(heading_replace, line)
line = RE_HEADING3.sub(heading_replace, line)
line = RE_HEADING4.sub(heading_replace, line)
line = RE_HEADING5.sub(heading_replace, line)
line = RE_HEADING6.sub(heading_replace, line)
line = RE_HEADING1a.sub(heading_replace, line)
line = RE_HEADING2a.sub(heading_replace, line)
line = RE_HEADING3a.sub(heading_replace, line)
line = RE_HEADING4a.sub(heading_replace, line)
line = RE_HEADING5a.sub(heading_replace, line)
line = RE_HEADING6a.sub(heading_replace, line)
# code surrounded by underline, mistaken as italics by github
line = RE_UNDERLINED_CODE1.sub(r'`_\1_`', line)
line = RE_UNDERLINED_CODE2.sub(r'`_\1_`', line)
line = RE_UNDERLINED_CODE3.sub(r'`_\1_`', line)
# code snippet
line = RE_CODE_SNIPPET.sub(inline_code_snippet, line)
line = RE_SUPERSCRIPT1.sub(r'<sup>\1</sup>', line) # superscript ^abc^
line = RE_SUBSCRIPT1.sub(r'<sub>\1</sub>', line) # subscript ,,abc,,
line = RE_QUERY1.sub(r'[%s?' % trac_url_query, line) # preconversion to URL format
line = RE_HTTPS1.sub(conv_help.wiki_link, line)
line = RE_HTTPS2.sub(conv_help.wiki_link, line) # link without display text
line = RE_HTTPS3.sub(conv_help.wiki_link, line)
line = RE_HTTPS4.sub(conv_help.wiki_link, line)
line = RE_IMAGE1.sub(conv_help.image_link_under_tree, line)
line = RE_IMAGE2.sub(conv_help.image_link, line)
line = RE_IMAGE3.sub(conv_help.image_link, line)
line = RE_IMAGE4.sub(r'<img src="\1" \2>', line)
line = RE_IMAGE5.sub(conv_help.wiki_image, line) # \2 is image width
line = RE_IMAGE6.sub(conv_help.image_link, line) # \2 is image width, \3 is alignment
line = RE_TICKET_COMMENT1.sub(conv_help.ticket_comment_link, line)
line = RE_TICKET_COMMENT2.sub(conv_help.ticket_comment_link, line)
line = RE_TICKET_COMMENT3.sub(conv_help.ticket_comment_link, line)
line = RE_TICKET_COMMENT4.sub(conv_help.ticket_comment_link, line)
line = RE_TICKET_COMMENT5.sub(conv_help.ticket_comment_link, line)
line = RE_TICKET_COMMENT6.sub(conv_help.ticket_comment_link, line)
line = RE_COMMENT1.sub(conv_help.comment_link, line)
line = RE_COMMENT2.sub(conv_help.comment_link, line)
line = RE_COMMENT3.sub(conv_help.comment_link, line)
line = RE_COMMENT4.sub(conv_help.comment_link, line)
line = RE_ATTACHMENT1.sub(conv_help.attachment, line)
line = RE_ATTACHMENT2.sub(conv_help.attachment, line)
line = RE_ATTACHMENT3.sub(conv_help.attachment, line)
line = RE_ATTACHMENT4.sub(conv_help.attachment, line)
line = RE_ATTACHMENT5.sub(conv_help.attachment, line)