/
replace_tool.js
3090 lines (2735 loc) · 126 KB
/
replace_tool.js
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
/*
2019/9/13 8:59:40 初版試營運
2019/12/21 4:12:49 模組化
Usage:
To use these tool functions, you should create a task file: "YYYYMMDD.section title.js", refering to templete: .replace_template.js
> node "YYYYMMDD.section title.js"
# or:
> node "YYYYMMDD.section title.js" "section_title=select this section title"
> node "YYYYMMDD.section title.js" "select this section title"
The `replace_tool.replace()` will:
# Get section title from task file name (command JavaScript file name)
# Guess language of section title assigned in task file name.
# Get diff_id from edit summary
# Get task configuration from section in request page.
# auto-notice: Starting replace task
# main_move_process(): Starting replace task
# finish_work(): finish up
警告:
每個 task_configuration 必須有獨立的 {Object} 設定,避免先前 prepare_operation() 設定過 .move_from_link 之類。
@see 20160923.modify_link.リンク元修正.js 20170828.search_and_replace.js 20161112.modify_category.js
@see https://www.mediawiki.org/wiki/Manual:Pywikibot/replace.py
@see https://meta.wikimedia.org/wiki/Indic-TechCom/Tools/MassMove
@see https://en.wikipedia.org/wiki/User:Plastikspork/massmove.js
@see [[w:ja:Wikipedia:改名提案]], [[w:ja:Wikipedia:移動依頼]]
文章名稱的改變,應考慮上下文的影響。例如:
# 是否應採用 [[new|old]]: using {keep_display_text : true} to preserve title displayed. Default: discard title
# 檢查重定向:"株式会社[[リクルート]]" → "[[株式会社リクルート]]" instead of "株式会社[[リクルートホールディングス]]"
移動 category 時應注意是否需要修改 DEFAULTSORTKEY
另須注意 {{Catmore}} 可能出現斷鏈:[[w:ja:Special:Diff/93070649]]
TODO:
自動處理move from之繁簡轉換
auto add section title @ summary
除重定向頁為 (曖昧さ回避)外,將所有 move_from 的重定向也一起修正
檢查是否為討論頁。 e.g., [[w:ja:Special:Diff/80384825]]
移動頁面相關的機器人或機器使用者需要提出對所有不同頁面內容模型的處理計畫,JSON頁沒有重新導向功能。一般頁面與模板都能重導向。分類頁面則必須移動所有包含的頁面。module 可用<code>return require( 'Module:name' );</code>重導向。
<ref></ref> 中間的連結不會被取代。
https://en.wikipedia.org/wiki/Wikipedia:AutoWikiBrowser/General_fixes
並非所有常規修補程序都適用於所有語言。
: {{コメント}} {{tl|リンク修正依頼/改名}}を使ってみた。 --~~~~
fix https://ja.wikipedia.org/w/index.php?title=%E3%82%A6%E3%82%A9%E3%83%83%E3%82%AB&diff=86465417&oldid=86454811&diffmode=source
read {{cbignore}}?
感謝您的意見。這種情況必須針對個模板來做相應處置,恐怕必須得見到一個修改一個。現階段尚無此打算。
{{混同|[[市原市立朝生原小学|市原市立朝生原小学校]]}}
→{{混同|[[市原市立朝生原小学校]]}}
→{{混同|市原市立朝生原小学校}}
*/
'use strict';
// Load CeJS library and modules.
require('../wiki loader.js');
// Load modules.
CeL.run([
'application.net.wiki.template_functions',
// for CeL.assert()
'application.debug.log',
// 載入不同地區語言的功能 for CeL.gettext()。
'application.locale',
// CeL.wiki.data.is_DAB()
'application.net.wiki.data',
]);
// 20190913.replace.js
log_to = log_to.replace(/\d+$/, 20190913);
//console.trace(log_to);
// global variables using in move_configuration
const DELETE_PAGE = Symbol('DELETE_PAGE');
const REDIRECT_TARGET = Symbol('REDIRECT_TARGET');
const remove_token = CeL.wiki.parser.parser_prototype.each.remove_token;
/** {String}Default requests page */
const bot_requests_page = 'Project:BOTREQ';
// ---------------------------------------------------------------------//
// .wiki
const KEY_wiki_session = 'wiki';
async function setup_wiki_session(meta_configuration) {
/** {Object}wiki operator 操作子. */
let wiki = meta_configuration[KEY_wiki_session];
if (!wiki) {
wiki = meta_configuration[KEY_wiki_session] = new Wikiapi;
//console.trace(login_options);
await wiki.login(login_options);
// await wiki.login(null, null, use_language);
}
return wiki;
}
// ---------------------------------------------------------------------//
async function get_all_sections(meta_configuration) {
meta_configuration = CeL.setup_options(meta_configuration);
const wiki = await setup_wiki_session(meta_configuration);
const all_section_data = Object.create(null);
async function for_each_section(section) {
//console.log(section);
const section_title = section.section_title.title;
//console.trace(section_title);
if (meta_configuration.for_section) {
await meta_configuration.for_section.apply(/* parsed */this, arguments);
}
if (all_section_data[section_title]) {
throw new Error('Duplicated section title: ' + section_title);
}
const section_data = all_section_data[section_title] = Object.create(null);
const section_wikitext = section.toString();
let matched;
function set_process(process) {
section_data.process = process;
section_data[process] = matched[1];
}
// TODO: 必須避免如 <nowiki>{{確認}}</nowiki>
matched = section_wikitext.match(/{{ *(Doing|BOTREQ *\| *(?:着手|調査中|準備中|作業中|仕様)) *[|}]/);
if (matched) {
set_process('doing');
}
matched = section_wikitext.match(/{{ *(Done|完了|BOTREQ *\| *(?:done|済|完了)|利用者の投稿記録リンク) *[|}]/);
if (matched) {
set_process('done');
}
matched = section_wikitext.match(/{{ *(BOTREQ *\| *(?:impossible|不受理)) *[|}]/);
if (matched) {
set_process('deny');
}
matched = section_wikitext.match(/{{ *(確認) *[|}]/);
if (matched) {
set_process('completed');
}
matched = section_wikitext.match(/{{ *(失効|未解決|取り下げ) *[|}]/);
if (matched) {
set_process('withdrawed');
}
matched = section_wikitext.match(/{{ *(解決済み?|済み|スタック) *[|}]/);
if (matched) {
set_process('finished');
}
if (section_data.process) {
return;
}
const task_configuration_from_section = await get_move_configuration_from_section(meta_configuration, section, { no_export: true });
if (task_configuration_from_section) {
section_data.task_configuration = task_configuration_from_section;
}
}
//console.trace(meta_configuration);
await for_bot_requests_section(wiki, meta_configuration, for_each_section,
//await replace_tool.get_all_sections({ for_section(section, index, parent) { }, for_section_options: { need_edit: true, summary: 'Close request' } });
meta_configuration.for_section_options);
//console.trace(all_section_data);
return all_section_data;
}
// ---------------------------------------------------------------------//
/**
* Main entry point to replace wiki pages.
* replace_tool.replace()
*
* @param {Object|String}meta_configuration {
* {String}summary 預設之編輯摘要。總結報告。編集内容の要約。,<br />
* {String|Number}diff_id revision id.<br />
* diff_id: {String}'small_oldid/big_new_diff' or {Number}new_diff,<br />
* {String}section_title section title of [[WP:BOTREQ]]<br />
* ... }
* @param {Object}move_configuration
* pairs to replace. { {String}move_from_link: move_to_link, ... }
*/
async function replace_tool__replace(meta_configuration, move_configuration) {
if (typeof meta_configuration === 'string') {
meta_configuration = {
summary: meta_configuration
}
} else {
meta_configuration = CeL.setup_options(meta_configuration);
}
if (!meta_configuration.no_move_configuration_from_command_line)
get_move_configuration_from_command_line(meta_configuration);
//console.trace(meta_configuration);
if (meta_configuration.use_language)
meta_configuration.language = meta_configuration.use_language;
if (!meta_configuration.language && meta_configuration[KEY_wiki_session]) {
meta_configuration.language = meta_configuration[KEY_wiki_session].append_session_to_options().session.language;
}
if (!meta_configuration.language) {
CeL.env.ignore_COM_error = true;
// Guess language of section title assigned in task file name.
CeL.run('application.locale.encoding');
//console.trace(meta_configuration.section_title);
//CeL.set_debug(9);
// e.g., 'ja-JP'
const language_code = CeL.encoding.guess_text_language(meta_configuration.section_title);
//CeL.set_debug(0);
const matched = language_code && language_code.match(/^([a-z]+)\-/);
if (matched) {
meta_configuration.language = matched[1];
CeL.info([CeL.env.script_name + ': ', {
// gettext_config:{"id":"treat-$1-as-language-$2"}
T: ['Treat %1 as language: %2.', JSON.stringify(meta_configuration.section_title), CeL.gettext.get_alias(language_code) || language_code]
}]);
} else {
const message = CeL.env.script_name + ': '
// gettext_config:{"id":"cannot-detect-language-of-$1"}
+ CeL.gettext('Cannot detect language of %1!', JSON.stringify(meta_configuration.section_title));
CeL.error(message);
if (!meta_configuration.ignore_language)
throw new Error(message);
}
}
let original_language;
if (meta_configuration.language) {
original_language = use_language;
// Set default language. 改變預設之語言。 e.g., 'zh'
set_language(meta_configuration.language);
}
if (meta_configuration.API_URL) {
login_options.API_URL = meta_configuration.API_URL;
} else if (meta_configuration.project) {
login_options.project = meta_configuration.project;
if (meta_configuration.language)
login_options.language = meta_configuration.language;
if (login_options.API_URL)
delete login_options.API_URL;
}
//console.trace(login_options);
/** {Object}wiki operator 操作子. */
await setup_wiki_session(meta_configuration);
await prepare_operation(meta_configuration, move_configuration);
if (original_language) {
// revert changes
use_language = original_language;
}
}
// ---------------------------------------------------------------------//
const work_option_switches = ['keep_display_text', 'keep_initial_case', 'skip_nochange', 'allow_blanking'];
const command_line_switches = ['diff_id', 'section_title', 'replace_text', 'replace_text_pattern', 'also_replace_text_insource', 'use_language', 'task_configuration', 'namespace',
'requests_page_rvlimit',
'no_task_configuration_from_section', 'get_task_configuration_from', 'min_list_length',
'caption', 'allow_eval'].append(work_option_switches);
const command_line_argument_alias = {
diff: 'diff_id',
insource: 'also_replace_text_insource',
};
function convert_special_move_to(move_to_link) {
switch (move_to_link) {
// remove_page
case 'DELETE_PAGE':
return DELETE_PAGE;
case 'REDIRECT_TARGET':
return REDIRECT_TARGET;
case 'subst:':
// 將會在後面 prepare_operation() 處理。
default:
}
return move_to_link;
}
function convert_special_move_to_of_task(task_configuration) {
//console.trace(task_configuration);
for (const [move_from_link, move_to_link] of Object.entries(task_configuration)) {
//console.trace([move_from_link, move_to_link]);
task_configuration[move_from_link] = convert_special_move_to(move_to_link);
}
}
function get_move_configuration_from_command_line(meta_configuration) {
if (CeL.env.arg_hash) {
for (const arg_name in command_line_argument_alias) {
if (arg_name in CeL.env.arg_hash) {
CeL.env.arg_hash[command_line_argument_alias[arg_name]] = CeL.env.arg_hash[arg_name];
}
if (CeL.env.arg_hash.task_configuration) {
try {
//console.trace(CeL.env.arg_hash.task_configuration);
const task_configuration_from_args = JSON.parse(CeL.env.arg_hash.task_configuration);
//console.trace(task_configuration_from_args);
convert_special_move_to_of_task(task_configuration_from_args);
//console.trace(task_configuration_from_args);
meta_configuration.task_configuration_from_args = task_configuration_from_args;
} catch (e) {
//if (!CeL.is_Object(CeL.env.arg_hash.task_configuration))
CeL.error([get_move_configuration_from_command_line.name + ': ', {
// gettext_config:{"id":"invalid-task_configuration-(should-be-$2)-{$3}-$1"}
T: ['Invalid task_configuration (should be %2): {%3} %1', CeL.env.arg_hash.task_configuration, CeL.is_type(JSON), typeof CeL.env.arg_hash.task_configuration]
}]);
}
//assert: !meta_configuration.task_configuration_from_args || CeL.is_Object(meta_configuration.task_configuration_from_args)
}
}
for (const property_name of command_line_switches) {
let value = CeL.env.arg_hash[property_name];
//console.log([property_name, value]);
if (typeof value !== 'boolean' && value !== 0
&& (!value || typeof value === 'string' && !(value = value.trim())))
continue;
//> node "YYYYMMDD.section title.js" "section_title=select this section title"
// e.g., "20200704.「一条ぎょく子」→「一条頊子」の改名に伴うリンク修正依頼.js"
//console.trace(CeL.env.arg_hash);
CeL.info([get_move_configuration_from_command_line.name + ': ', {
// gettext_config:{"id":"get-parameter-$1=$2-from-command-line"}
T: ['Get parameter %1=%2 from command line', property_name, value]
}]);
meta_configuration[property_name] = value;
}
if (meta_configuration.also_replace_text_insource && typeof meta_configuration.also_replace_text_insource === 'string') {
meta_configuration.also_replace_text_insource = meta_configuration.also_replace_text_insource.split('|');
}
//console.trace(meta_configuration);
}
if (meta_configuration.section_title) {
return;
}
let section_title;
if (CeL.env.argv.length > 2 && (section_title = CeL.env.argv[2].trim())
// e.g., "use_project=zh.wikinews"
&& !/^[\w]+=/.test(section_title)) {
//> node "YYYYMMDD.section title.js" "select this section title"
//console.trace(CeL.env.argv[2]);
CeL.info([get_move_configuration_from_command_line.name + ': ', {
// gettext_config:{"id":"get-section-title-from-command-line-argument-$1"}
T: ['Get section title from command line argument: %1', section_title]
}]);
meta_configuration.section_title = section_title;
return;
}
// 可省略 `section_title` 的條件: 檔案名稱即 section_title
section_title = script_name;
if (section_title) {
CeL.info([get_move_configuration_from_command_line.name + ': ', {
// gettext_config:{"id":"get-section-title-from-task-file-name-$1"}
T: ['Get section title from task file name: %1', section_title]
}]);
meta_configuration.section_title = section_title;
return;
}
throw new Error('Cannot extract section title from task file name!');
}
function guess_and_fulfill_meta_configuration_from_page(requests_page_data, meta_configuration) {
//console.log(requests_page_data);
let section_title = meta_configuration.section_title;
let user, diff_to, diff_from;
function set_diff_to(revision) {
user = revision.user;
diff_to = revision.revid;
// diff_from = revision.parentid;
diff_from = null;
}
requests_page_data.revisions.forEach((revision, index, revisions) => {
// for section_title set from script_name @ get_move_configuration_from_command_line(meta_configuration)
let comment = revision.comment && revision.comment.match(/^\/\*(.+)\*\//);
if (comment) {
comment = comment[1];
if (section_title === script_name) {
// 去掉檔名中不能包含的字元。 [\\\/:*?"<>|] → without /\/\*/
// https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
comment = comment.replace(/[\\\/:*?"<>|]/g, '');
}
}
//console.log(section_title);
//console.log(comment);
// console.log(matched);
if (comment && comment.trim() === section_title.trim()) {
// console.log(revision);
if (user === revision.user && diff_to > 0) {
diff_from = revision.parentid;
// At last, diff_from should starts
// from e.g., "→鈴木正人のリンク修正: 新しい節"
} else {
set_diff_to(revision);
}
if (section_title === script_name) {
// 復原檔名中不能包含的字元。
const _section_title = revision.comment.match(/^\/\*(.+)\*\//)[1].trim();
// console.log([section_title, _section_title]);
if (section_title !== _section_title) {
CeL.info([get_move_configuration_from_command_line.name + ': ', {
// gettext_config:{"id":"change-section-title"}
T: 'Change section title:'
}]);
CeL.log(CeL.display_align([
['From\t', section_title],
['To→\t', _section_title]
]));
// TODO: parse
section_title = meta_configuration.section_title = _section_title;
}
}
return;
}
if (index > 0) {
// get diff_id from content
// @see wiki.tracking_revisions()
const content = CeL.wiki.revision_content(revision, true);
if (typeof content === 'string') {
const diff_list = CeL.LCS(content, CeL.wiki.revision_content(revisions[index - 1]), 'diff');
if (diff_list.some(diff => {
const [removed_text, added_text] = diff;
if (!added_text || typeof added_text !== 'string')
return;
const parsed = CeL.wiki.parser(added_text, meta_configuration[KEY_wiki_session].append_session_to_options()).parse();
CeL.assert([added_text, parsed.toString()],
// gettext_config:{"id":"wikitext-parser-checking-$1"}
CeL.gettext('wikitext parser checking: %1', JSON.stringify(added_text)));
let found;
parsed.each('section_title', section_title_token => {
//console.log([section_title, section_title_token.title]);
found = section_title === section_title_token.title.replace(/[“”]/g, '');
if (found) {
if (section_title !== section_title_token.title) {
CeL.info(`${guess_and_fulfill_meta_configuration_from_page.name}: section title: ${JSON.stringify(section_title)} → ${JSON.stringify(section_title_token.title)}`);
section_title = meta_configuration.section_title = section_title_token.title;
}
return parsed.each.exit;
}
});
return found;
})) {
set_diff_to(revisions[index - 1]);
return;
}
}
}
user = null;
});
if (diff_to > 0) {
meta_configuration.diff_id = diff_from > 0 ? diff_from + '/' + diff_to : diff_to;
CeL.info([get_move_configuration_from_command_line.name + ': ', {
// gettext_config:{"id":"get-$1-from-edit-summary-$2"}
T: ['Get %1 from edit summary: %2',
// gettext_config:{"id":"revision-id"}
CeL.gettext('revision id') + ` (diff_id)`, CeL.wiki.title_link_of(`Special:Diff/${meta_configuration.diff_id}#${section_title}`)]
}]);
}
}
// 從已知資訊解開並自動填寫 `meta_configuration`
async function guess_and_fulfill_meta_configuration(wiki, meta_configuration) {
const requests_page = meta_configuration.requests_page || bot_requests_page;
// 可省略 `diff_id` 的條件: 以新章節增加請求,且編輯摘要包含 `/* section_title */`
const section_title = meta_configuration.section_title;
//'max'
const rvlimit = meta_configuration.requests_page_rvlimit || 80;
//console.trace(section_title);
if (section_title) {
CeL.log_temporary({
// gettext_config:{"id":"get-$2-edit-summaries-of-$1"}
T: ['Get %2 edit {{PLURAL:%2|summary|summaries}} of %1', CeL.wiki.title_link_of(requests_page), rvlimit]
});
const requests_page_data = await wiki.page(requests_page, {
redirects: 1,
// rvprop: 'ids|comment|user|content',
rvprop: 'ids|comment|user',
// rvlimit: 'max',
rvlimit,
});
//console.log(requests_page_data);
guess_and_fulfill_meta_configuration_from_page(requests_page_data, meta_configuration);
if (!meta_configuration.diff_id) {
// get diff_id from content
CeL.log_temporary({
// gettext_config:{"id":"get-$2-revision(s)-of-$1"}
T: ['Get %2 {{PLURAL:%2|revision|revisions}} of %1', CeL.wiki.title_link_of(requests_page), rvlimit]
});
const requests_page_data = await wiki.page(requests_page, {
redirects: 1,
rvprop: 'ids|comment|user|content',
// rvlimit: 'max',
rvlimit,
});
guess_and_fulfill_meta_configuration_from_page(requests_page_data, meta_configuration);
}
} else if (meta_configuration.diff_id) {
// Skip
} else {
CeL.error([guess_and_fulfill_meta_configuration.name + ': ', {
// gettext_config:{"id":"no-section-title-set"}
T: 'No section title set!'
}]);
}
if (!meta_configuration.diff_id) {
if (section_title) {
CeL.error(guess_and_fulfill_meta_configuration.name + ': 無法找到是哪個版本添加了此標題,可能是標題較舊,且所設定的回溯 rvlimit 不足?\n' + CeL.wiki.title_link_of(requests_page + '#' + section_title));
}
if (use_language === 'zh' || use_language === 'cmn') {
CeL.error([guess_and_fulfill_meta_configuration.name + ': ', {
T: '請注意標題繁體簡體必須相符!'
}]);
// e.g., 刪除小天體模板時,[[Template:小天体]] redirect to [[Template:小天體]]?
}
if (false) {
// gettext_config:{"id":"unable-to-extract-the-revision-difference-id-from-page-edit-summary-of-$1"}
throw new Error(CeL.gettext('Unable to extract the revision difference id from page edit summary of %1!', CeL.wiki.title_link_of(requests_page)));
}
}
// throw new Error(meta_configuration.section_title);
}
// Check if there are default move configurations.
async function get_move_configuration_from_section(meta_configuration, section, options) {
function get_discussion_link(meta_token) {
let discussion_link;
section.each.call(meta_token, 'link', token => {
//console.trace(token);
if (!discussion_link) {
//discussion_link = token[0] + token[1];
discussion_link = token;
return;
}
CeL.info([get_move_configuration_from_section.name + ': ', {
// gettext_config:{"id":"multiple-discussion-links-exist"}
T: 'Multiple discussion links exist:'
}]);
CeL.log(CeL.display_align([
['\t', CeL.wiki.title_link_of(discussion_link)],
['\t', token.toString()]
]));
discussion_link = null;
return section.each.exit;
});
return discussion_link;
}
if (!meta_configuration.discussion_link) {
section.each('list', list_token => {
if (!/議論場所[::]/.test(list_token[0]))
return;
const discussion_link = get_discussion_link(list_token[0]);
if (discussion_link)
meta_configuration.discussion_link = discussion_link;
// CeL.wiki.parser.parser_prototype.each.exit
return section.each.exit;
});
}
// Do not get move configuration from section.
if (meta_configuration.no_task_configuration_from_section)
return;
const task_configuration_from_section = Object.create(null);
section.each('tag', token => {
if (token.tag !== 'syntaxhighlight' || token.attributes.lang !== 'json')
return;
let task_configuration;
try {
task_configuration = JSON.parse(token[1].toString());
} catch (e) {
CeL.error(e);
}
//console.trace(task_configuration);
task_configuration = task_configuration.replace_tool_configuration;
if (!task_configuration)
return;
meta_configuration.task_configuration_from_page_JSON = task_configuration;
if (task_configuration.insert_layout) {
if (!task_configuration.optioation_type)
task_configuration.optioation_type = 'insert_layout';
if (!task_configuration.list_parser && task_configuration.get_task_configuration_from === 'table')
task_configuration.list_parser = 'table_to_array';
}
for (const option of ["get_task_configuration_from",]) {
if (task_configuration[option]) {
// Copy property.
meta_configuration[option] = task_configuration[option];
}
}
});
function text_processor_for_configuration_from_page(wikitext, page_data/*, work_config*/) {
const task_configuration = this;
const layout = task_configuration.insert_layout_Map
? task_configuration.insert_layout_Map.get(page_data.original_title || page_data.title)
: task_configuration.insert_layout;
const parsed = page_data.parse();
CeL.assert([page_data.wikitext, parsed.toString()],
// gettext_config:{"id":"wikitext-parser-checking-$1"}
CeL.gettext('wikitext parser checking: %1', CeL.wiki.title_link_of(page_data)));
//console.trace(layout);
parsed.insert_layout_element(layout, {
remove_duplicated: true,
main_template_processor(template_token) {
// fix for {{規范控製}}
if (layout.name && template_token.name.includes('控製'))
CeL.wiki.parse.replace_parameter(template_token, CeL.wiki.parse.replace_parameter.KEY_template_name, layout.name);
}
});
//console.trace(layout, parsed);
return parsed.toString();
}
//console.trace(meta_configuration);
if (meta_configuration.get_task_configuration_from === 'table') {
await section.each('table', async table => {
if (!meta_configuration.caption || table.caption === meta_configuration.caption) {
if (meta_configuration.task_configuration_from_page_JSON?.list_parser === "table_to_array") {
// e.g., [[w:zh:Special:Diff/80594886/80595699#請求協助掛長城、不可移動文物的批量提刪模板]]
// full: <syntaxhighlight lang="json">{"replace_tool_configuration":{"get_task_configuration_from":"table","optioation_type":"insert_layout","list_parser":"table_to_array","page_title":"%1","insert_layout":"{{Vfd|%2|date=%3}}"}}</syntaxhighlight>
// <syntaxhighlight lang="json">{"replace_tool_configuration":{"get_task_configuration_from":"table","page_title":"%1","insert_layout":"{{Vfd|%2|date=%3}}"}}</syntaxhighlight>
// {| table |}
const rows = CeL.wiki.table_to_array(table), page_list = [], insert_layout_Map = new Map();
//console.trace(rows);
// Insert layout template on each page.
for (const row of rows) {
row.unshift(meta_configuration.task_configuration_from_page_JSON.page_title);
let page_title = CeL.gettext.apply(null, row);
const parsed = CeL.wiki.parser(page_title).parse();
CeL.assert([page_title, parsed.toString()],
// gettext_config:{"id":"wikitext-parser-checking-$1"}
CeL.gettext('wikitext parser checking: %1', JSON.stringify(page_title)));
// 有連結就採用連結。
parsed.each('link', token => { page_title = token[0].toString(); });
page_list.push(page_title);
row[0] = meta_configuration.task_configuration_from_page_JSON.insert_layout;
const insert_layout = CeL.wiki.parse(CeL.gettext.apply(null, row));
insert_layout_Map.set(page_title, insert_layout);
}
task_configuration_from_section[meta_configuration.task_configuration_from_page_JSON.insert_layout] = {
page_list,
insert_layout_Map,
text_processor: text_processor_for_configuration_from_page,
};
//console.trace(task_configuration_from_section);
} else {
await parse_move_pairs_from_link(table, task_configuration_from_section, meta_configuration);
}
}
});
} else if (meta_configuration.get_task_configuration_from === 'list') {
await section.each('list', async list_token => {
//console.log(list_token);
//console.log(meta_configuration);
if (list_token.length >= (meta_configuration.min_list_length || 3)) {
await parse_move_pairs_from_link(list_token, task_configuration_from_section, meta_configuration);
}
});
} else if (meta_configuration[KEY_wiki_session].is_namespace(meta_configuration.get_task_configuration_from, 'Category')) {
// e.g., [[Special:Diff/79100214/79123647#Category:中國科舉人物中人物添加规范控制]]
// {"replace_tool_configuration":{"get_task_configuration_from":"Category:中國科舉人物","depth":10,"insert_layout":"{{Authority control}}","namespace":0,"excluding_title_includes":["列表"]}}
const main_task_configuration = task_configuration_from_section[meta_configuration.get_task_configuration_from] = {
insert_layout: CeL.wiki.parse(meta_configuration.task_configuration_from_page_JSON.insert_layout),
text_processor: text_processor_for_configuration_from_page,
};
if (!options?.ignore_list && meta_configuration.task_configuration_from_page_JSON.depth >= 2) {
const page_list_to_test = ['葉紹袁']
&& null
;
if (page_list_to_test) {
CeL.error('Test page_list_to_test = ' + page_list_to_test);
//console.trace(page_list_to_test);
}
const wiki_session = meta_configuration[KEY_wiki_session];
await wiki_session.setup_layout_element_to_insert(main_task_configuration.insert_layout);
let category_tree = !page_list_to_test && (await wiki_session.category_tree(meta_configuration.get_task_configuration_from, { depth: meta_configuration.task_configuration_from_page_JSON.depth, cmtype: 'subcat|page|file', get_flat_subcategories: true })).flat_subcategories;
//console.trace(category_tree);
const page_list = page_list_to_test || [];
const namespace = meta_configuration.task_configuration_from_page_JSON.namespace;
// page_filter
let excluding_title_includes = meta_configuration.task_configuration_from_page_JSON.excluding_title_includes;
if (excluding_title_includes) {
if (!Array.isArray(excluding_title_includes))
excluding_title_includes = [excluding_title_includes];
}
if (!page_list_to_test) {
for (let category_page_list of Object.values(category_tree)) {
//console.trace(category_page_list);
if (namespace || namespace === 0) {
category_page_list = category_page_list.filter(page_data => wiki_session.is_namespace(page_data, namespace));
}
if (excluding_title_includes) {
category_page_list = category_page_list.filter(page_data => !excluding_title_includes.some(string => page_data.title.includes(string)));
}
page_list.append(category_page_list);
}
}
//console.trace(page_list);
main_task_configuration.page_list = page_list;
}
}
//console.trace(meta_configuration);
//console.trace(task_configuration_from_section);
// Get task configuration from section in request page.
//[[w:ja:Template:リンク修正依頼/改名]]
section.each('Template:リンク修正依頼/改名', token => {
let discussion_link = token.parameters.提案;
if (!discussion_link) {
} else if (discussion_link.type === 'link') {
//discussion_link = discussion_link[0] + discussion_link[1];
} else {
discussion_link = get_discussion_link(token.parameters.提案);
}
//console.trace([token.parameters.提案, discussion_link]);
// 警告: 必須確保範圍較狹隘的放在前面!
let task_options = token.parameters.options;
if (task_options) {
//console.log(task_options);
try {
task_options = JSON.parse(task_options);
} catch (e) {
//console.trace(meta_configuration);
if (meta_configuration.allow_eval) {
CeL.error({
// gettext_config:{"id":"not-json-try-eval()-$1"}
T: ['Not JSON, try eval(): %1', task_options]
});
eval('task_options = ' + task_options);
//console.trace(task_options);
} else if (!options?.no_export) {
CeL.error({
// gettext_config:{"id":"not-json-you-may-want-to-set-allow_eval=true-$1"}
T: ['Not JSON, you may want to set "allow_eval=true": %1', task_options]
});
throw e;
}
}
//console.log(task_options);
}
function match_link(link) {
if (typeof link !== 'string') {
// e.g., Symbol(DELETE_PAGE)
return;
}
const matched = link.match(/\[\[([^\[\]]+)\]\]/);
return matched && matched[1];
}
function normalize_page_token(index, keep_link) {
//console.log(token.parameters[index]);
let link = typeof index === 'number' ? token.parameters[index].toString().replace(/<!--[\s\S]*?-->/g, '')
// e.g., <nowiki>[[title|display text]]</nowiki>
.replace(/<nowiki\s*>(.*?)<\/nowiki\s*>/g, '$1')
.trim().replace(/{{!}}/g, '|') : index;
const _link = !keep_link && match_link(link);
if (_link) {
CeL.error(`${get_move_configuration_from_section.name}: 指定了精確的連結形式,將僅處理完全符合此形式的連結:${_link}`);
const parsed = CeL.wiki.parse(_link);
CeL.assert([_link, parsed.toString()],
// gettext_config:{"id":"wikitext-parser-checking-$1"}
CeL.gettext('wikitext parser checking: %1', JSON.stringify(_link)));
// @see function prepare_operation(meta_configuration, move_configuration)
if (!parsed[1]) parsed[1] = '#';
if (!parsed[2]) parsed[2] = typeof index === 'number' && index % 2 === 1 ? '' : parsed[0];
link = match_link(parsed.toString());
}
return link;
}
for (let index = 1; token.parameters[index] && token.parameters[index + 1]; index += 2) {
const move_from_link = normalize_page_token(index);
//if (move_from_link.includes('IOS (Apple)')) { console.trace(`Ignore ${CeL.wiki.title_link_of(move_from_link)}`); continue; }
let move_to_link = convert_special_move_to(normalize_page_token(index + 1, true));
const task_configuration = {
discussion_link,
...task_options,
};
if (match_link(move_to_link)) {
// assert: 'keep_display_text' in task_configuration === false
task_configuration.keep_display_text = false;
move_to_link = normalize_page_token(move_to_link);
}
task_configuration.move_to_link = move_to_link;
if (task_configuration_from_section[move_from_link]) {
CeL.error([get_move_configuration_from_section.name + ': ', {
// gettext_config:{"id":"duplicate-task-name-$1!-will-overwrite-old-task-with-new-task-$2→$3"}
T: ['Duplicate task name %1! Will overwrite old task with new task: %2→%3', JSON.stringify(move_from_link), '\n' + JSON.stringify(task_configuration_from_section[move_from_link]) + '\n', '\n' + JSON.stringify(task_configuration) + '\n']
}]);
}
task_configuration_from_section[move_from_link] = task_configuration;
if (Array.isArray(meta_configuration.also_replace_text_insource) ? meta_configuration.also_replace_text_insource.includes(move_from_link) : meta_configuration.also_replace_text_insource) {
// Also replace text in source of **non-linked** pages
task_configuration_from_section[`insource:"${move_from_link}"`] = Object.clone(task_configuration);
//console.log(task_configuration_from_section);
}
}
});
//if (!CeL.is_empty_object(task_configuration_from_section)) return;
CeL.info([get_move_configuration_from_section.name + ': ', {
// gettext_config:{"id":"get-$1-task(s)-from-$2"}
T: ['Get %1 {{PLURAL:%1|task|tasks}} from %2.', Object.keys(task_configuration_from_section).length, section.section_title.link.toString()]
}]);
//console.trace(task_configuration_from_section);
if (!options?.no_export)
meta_configuration.task_configuration_from_section = task_configuration_from_section;
return task_configuration_from_section;
}
async function for_bot_requests_section(wiki, meta_configuration, for_section, options) {
const requests_page = meta_configuration.requests_page || bot_requests_page;
//console.trace(requests_page);
const requests_page_data = await wiki.page(requests_page, { redirects: 1 });
/** {Array} parsed page content 頁面解析後的結構。 */
const parsed = requests_page_data.parse();
CeL.assert([requests_page_data.wikitext, parsed.toString()],
// gettext_config:{"id":"wikitext-parser-checking-$1"}
CeL.gettext('wikitext parser checking: %1', CeL.wiki.title_link_of(requests_page_data)));
const section_title = meta_configuration.section_title;
//console.trace(meta_configuration);
await parsed.each_section(async function (section) {
//console.log([section.section_title && section.section_title.title, section_title]);
//console.log(section.section_title);
if (!section.section_title || section_title && section.section_title.title !== section_title) {
return;
}
// console.log(section.toString());
await for_section.apply(parsed, arguments);
}, {
get_users: true,
level_filter: /*use_language === 'zh' ? 3 :*/ 2,
});
if (options && options.need_edit) {
// console.log(parsed.toString());
await wiki.edit_page(requests_page, parsed.toString(), {
redirects: 1,
sectiontitle: section_title,
//{{BOTREQ|着手}}
summary: options.summary
});
}
}
// 自動提醒/通知
// auto-notice: Starting replace task
async function notice_to_edit(wiki, meta_configuration, move_configuration) {
const options = {
// gettext_config:{"id":"the-requested-robot-task-begins"}
summary: CeL.gettext('The requested robot task begins.')
};
await for_bot_requests_section(wiki, meta_configuration, async function (section) {
//console.trace(section);
meta_configuration.bot_requests_section = section;
// 委託人
meta_configuration.bot_requests_user = section.users[0];
//console.trace(meta_configuration.bot_requests_user);
// 必須執行以從章節讀取設定!
const task_configuration_from_section = await get_move_configuration_from_section(meta_configuration, section);
//console.trace(task_configuration_from_section);
if (CeL.is_empty_object(task_configuration_from_section)
&& (!move_configuration || CeL.is_empty_object(move_configuration))
) {
CeL.warn([notice_to_edit.name + ': ', {
// gettext_config:{"id":"the-section-does-not-set-the-task-configuration-$1"}
T: ['本章節未設定任務內容: %1', meta_configuration.section_title]
}]);
//console.trace(meta_configuration, move_configuration);
options.need_edit = false;
return;
}
const doing_message = meta_configuration.doing_message || (wiki.site_name() === 'jawiki' ?
//{{BOTREQ|着手}}
'{{BOTREQ|作業中}}' : '{{Doing}}');
// let PATTERN = /\n[:* ]*{{BOTREQ\|作業中}}/i;
// PATTERN =
// new RegExp(PATTERN.source + ' .+?' + meta_configuration[KEY_wiki_session].token.login_user_name, PATTERN.flags);
if (section.toString().includes(doing_message) /*PATTERN.test(section.toString())*/) {
CeL.info([notice_to_edit.name + ': ', {
// gettext_config:{"id":"already-reminded-that-the-operation-is-in-progress-$1"}
T: ['Already reminded that the operation is in progress: %1', meta_configuration.section_title]
}]);
options.need_edit = false;
return;
}
let warning_messages = [];
let had_add_user_notice;
if (wiki.site_name() === 'jawiki') {
const disambiguation_removed = [];
Object.keys(task_configuration_from_section).forEach(move_from_link => {
const task_configuration = task_configuration_from_section[move_from_link];
// detect [[title (disambiguation)]] → [[title]]
if (!task_configuration.force_remove_disambiguation && move_from_link.replace(/ \([^()]+\)$/) === task_configuration.move_to_link) {
disambiguation_removed.push(`${CeL.wiki.title_link_of(move_from_link)}→${CeL.wiki.title_link_of(task_configuration.move_to_link)}`);
delete task_configuration_from_section[move_from_link];
}
});
if (disambiguation_removed.length > 0) {
warning_messages.push(`* ${had_add_user_notice ? '' : CeL.wiki.title_link_of(wiki.to_namespace(meta_configuration.bot_requests_user, 'User')) + ': '
}${disambiguation_removed.join(', ')}: 項目付きの曖昧さ回避を解消する場合は、各分野のプロジェクト/ポータルにおける曖昧さ回避関連のルールに準拠したものへの付け替えをお勧めします。([[WP:PRIRDR]])`);
had_add_user_notice = true;
meta_configuration.abort_operation = true;
}
}
const parsed = this;
CeL.assert([CeL.wiki.content_of(this), parsed.toString()],
// gettext_config:{"id":"wikitext-parser-checking-$1"}
CeL.gettext('wikitext parser checking: %1', CeL.wiki.title_link_of(this)));
const index = section.range[1] - 1;
// assert: parsed[index] === section.at(-1)
parsed[index] = parsed[index].toString().trimEnd();
if (warning_messages.length > 0)
parsed[index] += '\n' + warning_messages.join('\n');
if (meta_configuration.abort_operation) {
// gettext_config:{"id":"add-warning-messages"}
options.summary = CeL.gettext('Add warning messages.');
} else {
parsed[index] += `\n* ${doing_message}`;
}
parsed[index] += ' --~~~~\n';
// TODO: +確認用リンク
options.need_edit = true;
}, options);
if (options.need_edit === undefined) {
CeL.info([{