-
Notifications
You must be signed in to change notification settings - Fork 1
/
kpac
executable file
·1760 lines (1543 loc) · 64.9 KB
/
kpac
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
__version__ = '30'
#--- User Configurable Defaults
# You can use `kpac --dir=package --i18ndir=package/translate`
# or edit the variables below to always run `kpac` with defaults.
sourceDirDefault = 'package'
translateDirDefault = 'package/translate'
compendiumDirDefault = '.compendium'
qtMinVer="6.0"
kfMinVer="6.0" # KDE Frameworks
plasmaMinVer="6.0"
filenameTag=f"plasma{plasmaMinVer.replace('.', '_')}"
#---
import argparse
import configparser
from collections import namedtuple
import datetime
import functools
import glob
import json
import logging
import os
from pprint import pprint
import re
import subprocess
import shutil
import sys
#---
logger = logging.getLogger('kpac')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
#---
class TC:
Reset = '\033[0m'
Bold = '\033[1m'
FG_Black='\033[30m'
FG_Red='\033[31m'
FG_Green='\033[32m'
FG_Orange='\033[33m'
FG_Blue='\033[34m'
FG_Purple='\033[35m'
FG_Cyan='\033[36m'
FG_LightGray='\033[37m'
FG_DarkGray='\033[90m'
FG_LightRed='\033[91m'
FG_LightGreen='\033[92m'
FG_Yellow='\033[93m'
FG_LightBlue='\033[94m'
FG_Pink='\033[95m'
FG_LightCyan='\033[96m'
FG_White='\033[97m'
@staticmethod
def stripColors(str):
return re.sub('\033' + '\[((\d{1,2});)?(\d{1,2})m', '', str)
def echoTC(terminalColor, *args):
line = terminalColor + ' '.join(args) + TC.Reset
if not sys.stdout.isatty():
line = TC.stripColors(line)
print(line)
def echoGray(*args):
echoTC(TC.FG_DarkGray, *args)
def echoRed(*args):
echoTC(TC.FG_LightRed, *args)
def echoGreen(*args):
echoTC(TC.FG_LightGreen, *args)
def echoWarning(*args):
echoTC(TC.FG_Orange, *args)
def echoError(*args):
echoTC(TC.FG_LightRed + TC.Bold, *args)
# KDE rc files differences:
# Keys are cAsE sensitive
# No spaces around the =
# [Sections can have spaces and : colons]
# Parses [Sub][Sections] as "Sub][Sections", but cannot have comments on the [Section] line
class KdeConfig(configparser.ConfigParser):
def __init__(self, filename):
super().__init__()
# Keep case sensitive keys
# http://stackoverflow.com/questions/19359556/configparser-reads-capital-keys-and-make-them-lower-case
self.optionxform = str
# Parse SubSections as "Sub][Sections"
self.SECTCRE = re.compile(r"\[(?P<header>.+?)]\w*$")
self.filename = filename
self.read(self.filename)
#--- GetText
POT_DEFAULT_HEADER="""# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\\n"
"Report-Msgid-Bugs-To: \\n"
"POT-Creation-Date: 2000-12-31 23:59-0000\\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n"
"Language-Team: LANGUAGE <LL@li.org>\\n"
"Language: \\n"
"MIME-Version: 1.0\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
"""
PoMessage = namedtuple('PoMessage', ['ctxt', 'id', 'str'])
class PoFile:
def __init__(self, filepath):
self.filepath = filepath
self.text = None
self.messages = []
with open(self.filepath, 'r') as fin:
self.text = fin.read()
self.parse()
@property
def msgPattern(self):
# Edit/Test: https://regex101.com/r/kEJCVL
patt = r'(msgctxt[ \t]+(".*")[ \t]*\n)?'
patt += r'((".*"[ \t]*\n)*)'
patt += r'(msgid[ \t]+(".*")[ \t]*\n)'
patt += r'((".*"[ \t]*\n)*)'
patt += r'(msgstr[ \t]+(".*")[ \t]*\n)'
patt += r'((".*"[ \t]*\n)*)'
return patt
def _joinMsgStr(self, line1, line234):
if line1 is None:
return None
elif line234 is None:
return line1.strip().strip('\"')
else:
lines = [line1] + line234.split('\n')
msgstr = ""
for line in lines:
msgstr += line.strip().strip('\"')
return msgstr
def parse(self):
for m in re.finditer(self.msgPattern, self.text):
msgCtx = self._joinMsgStr(m.group(2), m.group(3))
msgId = self._joinMsgStr(m.group(6), m.group(7))
msgStr = self._joinMsgStr(m.group(10), m.group(11))
msg = PoMessage(msgCtx, msgId, msgStr)
self.messages.append(msg)
def getMsgStr(self, msgid, msgctxt=None):
for msg in self.messages:
if msg.ctxt == msgctxt and msg.id == msgid:
return msg.str
return None
#---
def isCommandInstalled(name):
return shutil.which(name) is not None
class LineReplace:
def __init__(self, filepath):
self.filepath = filepath
self.lines = None
self.output = ''
def __enter__(self):
with open(self.filepath, 'r') as fin:
self.lines = fin.readlines()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
print(f"Did not write {self.filepath} due to error")
return # Skip writing to file if there's an error.
with open(self.filepath, 'w') as fout:
fout.write(self.output)
def write(self, text):
self.output += text
def jsonDumpTabbed(filepath, data):
with open(filepath, 'w') as fout:
json.dump(data, fout,
ensure_ascii=False,
indent='\t',
sort_keys=True,
)
fout.write('\n') # Trailing newline at EOF
#---
# grep matchStr filepath
def grep_line(matchStr, filepath):
with open(filepath, 'r') as fin:
for line in fin.read().splitlines():
if matchStr in line:
return line
return None
def grep_line_iter(matchStr, filepath):
with open(filepath, 'r') as fin:
for line in fin.read().splitlines():
if matchStr in line:
yield line
def grep_re_count(matchStr, filepath):
with open(filepath, 'r') as fin:
return len(re.findall(matchStr, fin.read()))
# sed -i 's/aaa/bbb/' filepath
def sed_str(a, b, filepath):
with LineReplace(filepath) as rep:
for line in rep.lines:
line = line.replace(a, b)
rep.write(line)
def sed_re(a, b, filepath):
with LineReplace(filepath) as rep:
for line in rep.lines:
line = re.sub(a, b, line)
rep.write(line)
# diff aFilepath bFilePath
def diff(aFilepath, bFilepath):
p = subprocess.run([
'diff',
aFilepath,
bFilepath,
], capture_output=True)
return p.stdout.decode('utf-8')
def is_diff(aFilepath, bFilepath):
return diff(aFilepath, bFilepath).strip() != ""
# git_diff --color filepath
def git_diff_color(filepath):
p = subprocess.run(['git', 'diff', '--color', filepath], capture_output=True)
return p.stdout.decode('utf-8')
def git_diff_color_noindex(aFilepath, bFilepath):
p = subprocess.run(['git', 'diff', '--color', '--no-index', aFilepath, bFilepath], capture_output=True)
return p.stdout.decode('utf-8')
#---
@functools.cache
def kpackagetool():
if isCommandInstalled('kpackagetool6'):
return 'kpackagetool6'
elif isCommandInstalled('kpackagetool5'):
return 'kpackagetool5'
else:
print("[error] Could not find 'kpackagetool6'")
sys.exit(1)
@functools.cache
def kstart():
if isCommandInstalled('kstart'):
return 'kstart'
elif isCommandInstalled('kstart5'):
return 'kstart5'
else:
print("[error] Could not find 'kstart'")
sys.exit(1)
#---
# https://stackoverflow.com/questions/3191664/list-of-all-locales-and-their-short-codes/28357857#28357857
langArr = [
["af_ZA", "af", "Afrikaans (South Africa)"],
["ak_GH", "ak", "Akan (Ghana)"],
["am_ET", "am", "Amharic (Ethiopia)"],
["ar_EG", "ar", "Arabic (Egypt)"],
["as_IN", "as", "Assamese (India)"],
["az_AZ", "az", "Azerbaijani (Azerbaijan)"],
["be_BY", "be", "Belarusian (Belarus)"],
["bem_ZM", "bem", "Bemba (Zambia)"],
["bg_BG", "bg", "Bulgarian (Bulgaria)"],
["bo_IN", "bo", "Tibetan (India)"],
["bs_BA", "bs", "Bosnian (Bosnia and Herzegovina)"],
["ca_ES", "ca", "Catalan (Spain)"],
["chr_US", "ch", "Cherokee (United States)"],
["cs_CZ", "cs", "Czech (Czech Republic)"],
["cy_GB", "cy", "Welsh (United Kingdom)"],
["da_DK", "da", "Danish (Denmark)"],
["de_DE", "de", "German (Germany)"],
["el_GR", "el", "Greek (Greece)"],
["es_MX", "es", "Spanish (Mexico)"],
["et_EE", "et", "Estonian (Estonia)"],
["eu_ES", "eu", "Basque (Spain)"],
["fa_IR", "fa", "Persian (Iran)"],
["ff_SN", "ff", "Fulah (Senegal)"],
["fi_FI", "fi", "Finnish (Finland)"],
["fo_FO", "fo", "Faroese (Faroe Islands)"],
["fr_CA", "fr", "French (Canada)"],
["ga_IE", "ga", "Irish (Ireland)"],
["gl_ES", "gl", "Galician (Spain)"],
["gu_IN", "gu", "Gujarati (India)"],
["gv_GB", "gv", "Manx (United Kingdom)"],
["ha_NG", "ha", "Hausa (Nigeria)"],
["he_IL", "he", "Hebrew (Israel)"],
["hi_IN", "hi", "Hindi (India)"],
["hr_HR", "hr", "Croatian (Croatia)"],
["hu_HU", "hu", "Hungarian (Hungary)"],
["hy_AM", "hy", "Armenian (Armenia)"],
["id_ID", "id", "Indonesian (Indonesia)"],
["ig_NG", "ig", "Igbo (Nigeria)"],
["is_IS", "is", "Icelandic (Iceland)"],
["it_IT", "it", "Italian (Italy)"],
["ja_JP", "ja", "Japanese (Japan)"],
["ka_GE", "ka", "Georgian (Georgia)"],
["kk_KZ", "kk", "Kazakh (Kazakhstan)"],
["kl_GL", "kl", "Kalaallisut (Greenland)"],
["km_KH", "km", "Khmer (Cambodia)"],
["kn_IN", "kn", "Kannada (India)"],
["ko_KR", "ko", "Korean (South Korea)"],
["ko_KR", "ko", "Korean (South Korea)"],
["lg_UG", "lg", "Ganda (Uganda)"],
["lt_LT", "lt", "Lithuanian (Lithuania)"],
["lv_LV", "lv", "Latvian (Latvia)"],
["mg_MG", "mg", "Malagasy (Madagascar)"],
["mk_MK", "mk", "Macedonian (Macedonia)"],
["ml_IN", "ml", "Malayalam (India)"],
["mr_IN", "mr", "Marathi (India)"],
["ms_MY", "ms", "Malay (Malaysia)"],
["mt_MT", "mt", "Maltese (Malta)"],
["my_MM", "my", "Burmese (Myanmar [Burma])"],
["nb_NO", "nb", "Norwegian Bokmål (Norway)"],
["ne_NP", "ne", "Nepali (Nepal)"],
["nl_NL", "nl", "Dutch (Netherlands)"],
["nn_NO", "nn", "Norwegian Nynorsk (Norway)"],
["om_ET", "om", "Oromo (Ethiopia)"],
["or_IN", "or", "Oriya (India)"],
["pa_PK", "pa", "Punjabi (Pakistan)"],
["pl_PL", "pl", "Polish (Poland)"],
["ps_AF", "ps", "Pashto (Afghanistan)"],
["pt_BR", "pt", "Portuguese (Brazil)"],
["ro_RO", "ro", "Romanian (Romania)"],
["ru_RU", "ru", "Russian (Russia)"],
["rw_RW", "rw", "Kinyarwanda (Rwanda)"],
["si_LK", "si", "Sinhala (Sri Lanka)"],
["sk_SK", "sk", "Slovak (Slovakia)"],
["sl_SI", "sl", "Slovenian (Slovenia)"],
["so_SO", "so", "Somali (Somalia)"],
["sq_AL", "sq", "Albanian (Albania)"],
["sr_RS", "sr", "Serbian (Serbia)"],
["sv_SE", "sv", "Swedish (Sweden)"],
["sw_KE", "sw", "Swahili (Kenya)"],
["ta_IN", "ta", "Tamil (India)"],
["te_IN", "te", "Telugu (India)"],
["th_TH", "th", "Thai (Thailand)"],
["ti_ER", "ti", "Tigrinya (Eritrea)"],
["to_TO", "to", "Tonga (Tonga)"],
["tr_TR", "tr", "Turkish (Turkey)"],
["uk_UA", "uk", "Ukrainian (Ukraine)"],
["ur_IN", "ur", "Urdu (India)"],
["uz_UZ", "uz", "Uzbek (Uzbekistan)"],
["vi_VN", "vi", "Vietnamese (Vietnam)"],
["yo_NG", "yo", "Yoruba (Nigeria)"],
["yo_NG", "yo", "Yoruba (Nigeria)"],
["yue_HK", "yu", "Cantonese (Hong Kong)"],
["zh_CN", "zh", "Chinese (China)"],
["zu_ZA", "zu", "Zulu (South Africa)"],
]
def applyLocaleToEnv(env, langCode):
def lookupLang(langStr):
for lang in langArr:
if lang[1] == langStr:
return lang
raise Exception("localetest doesn't recognize the language " + langStr + '.')
if ":" in langCode:
l1, l2, _ = langCode.split(":")
else:
lang = lookupLang(langCode)
l1, l2, l3 = lang
language = l1 + ':' + l2
langUtf8 = l1 + '.UTF-8'
if env is None:
env = os.environ.copy()
env['LANGUAGE'] = language
env['LANG'] = langUtf8
env['LC_TIME'] = langUtf8
logger.info("LANGUAGE=%s", language)
logger.info("LANG=%s", langUtf8)
logger.info("LC_TIME=%s", langUtf8)
return env
class KPackage:
def __init__(self,
sourceDir="package",
translateDir="package/translate",
compendiumDir=".compendium",
buildTag=""
):
self.sourceDir = sourceDir
self.translateDir = translateDir
self.compendiumDir = compendiumDir
if len(buildTag) >= 1:
self.buildTag = '-' + buildTag
else:
self.buildTag = ''
self.buildFilenameFormat = "{packageName}-v{packageVersion}{buildTag}"
self.buildExt = "zip"
self.parseMetadata()
def parseMetadata(self):
#--- Parse metadata as global variables
self.jsonMetaFilepath = os.path.join(self.sourceDir, 'metadata.json')
self.desktopMetaFilepath = os.path.join(self.sourceDir, 'metadata.desktop')
if os.path.exists(self.jsonMetaFilepath):
# .json
with open(self.jsonMetaFilepath, 'r') as fin:
metadata = json.load(fin)
self.packageServiceType = metadata.get('KPackageStructure')
if self.packageServiceType is None:
# desktoptojson will port X-KDE-ServiceTypes to KPlugin.ServiceTypes[0] by default
echoWarning("[warning] metadata.json needs KPackageStructure set in Plasma6")
self.packageServiceType = (metadata.get('KPlugin', {}).get('ServiceTypes', []) + [None])[0]
if self.packageServiceType is None:
echoError("[error] metadata.json is missing KPackageStructure, and can't fallback to ServiceTypes either.")
sys.exit(1)
self.packageNamespace = metadata.get('KPlugin', {})['Id']
self.packageName = self.packageNamespace.split('.')[-1]
self.packageVersion = metadata.get('KPlugin', {}).get('Version', '')
self.packageAuthor = (metadata.get('KPlugin', {}).get('Authors', []) + [{'Name': ''}])[0].get('Name', '')
self.packageAuthorEmail = (metadata.get('KPlugin', {}).get('Authors', []) + [{'Name': ''}])[0].get('Email', '')
self.packageWebsite = metadata.get('KPlugin', {}).get('Website', '')
self.packageComment = metadata.get('KPlugin', {}).get('Description', '')
elif os.path.exists(self.desktopMetaFilepath):
# .desktop
metadata = KdeConfig(self.desktopMetaFilepath)
self.packageServiceType = metadata.get('Desktop Entry', 'X-KDE-ServiceTypes')
self.packageNamespace = metadata.get('Desktop Entry', 'X-KDE-PluginInfo-Name')
self.packageName = self.packageNamespace.split('.')[-1]
self.packageVersion = metadata.get('Desktop Entry', 'X-KDE-PluginInfo-Version', fallback='')
self.packageAuthor = metadata.get('Desktop Entry', 'X-KDE-PluginInfo-Author', fallback='')
self.packageAuthorEmail = metadata.get('Desktop Entry', 'X-KDE-PluginInfo-Email', fallback='')
self.packageWebsite = metadata.get('Desktop Entry', 'X-KDE-PluginInfo-Website', fallback='')
self.packageComment = metadata.get('Desktop Entry', 'Comment', fallback='')
else:
echoError("Could not find metadata.json or metadata.desktop in '{}'".format(self.sourceDir))
sys.exit(1)
if self.packageServiceType == "Plasma/Applet":
self.buildExt = "plasmoid" # Renamed zip
def printMetadata(self):
logger.info("Namespace: %s", self.packageNamespace)
logger.info("Name: %s", self.packageName)
logger.info("Version: %s", self.packageVersion)
logger.info("Author: %s", self.packageAuthor)
logger.info("AuthorEmail: %s", self.packageAuthorEmail)
logger.info("Website: %s", self.packageWebsite)
logger.info("Comment: %s", self.packageComment)
logger.info("KPackageStructure: %s", self.packageServiceType)
logger.info("")
def install(self, restart=True):
# kpackagetool6 -t Plasma/Applet -s package
p = subprocess.Popen([
kpackagetool(),
'--type', self.packageServiceType,
'--show', self.packageNamespace,
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
# Not installed: "Error: Can't find plugin metadata: org.kde.plasma.name" is returncode=3
isAlreadyInstalled = p.returncode == 0
# logger.debug("isInstalledReturnCode: %s", p.returncode)
if isAlreadyInstalled:
# kpackagetool5 -t Plasma/Applet -u package
proc = subprocess.run([kpackagetool(),
'--type', self.packageServiceType,
'--upgrade', self.sourceDir,
], capture_output=True)
outText = proc.stdout.decode('utf-8').strip()
errText = proc.stderr.decode('utf-8').strip()
if proc.returncode == 0:
if outText:
print(outText)
else:
failOutText = 'Error: Plugin {} is not installed.'.format(self.packageNamespace)
failErrPattern = r'KPackageStructure of KPluginMetaData\(pluginId:"{}", fileName: "(.+){}"\) does not match requested format "{}"'.format(
re.escape(self.packageNamespace),
re.escape(os.path.join(self.packageNamespace, 'metadata.json')),
re.escape(self.packageServiceType)
)
m = re.search(failErrPattern, errText)
if outText == failOutText and m:
print(m.group(0))
echoWarning("[Note] When trying to upgrade a Plasma 5 package with metadata.desktop in Plasma 6, we need to remove the old install first.")
# Note: kpackagetool6 --remove will also fail.
if isCommandInstalled('kpackagetool5'):
echoWarning("[Note] Detected kpackagetool5, running: kpackagetool5 --type {} --remove {}".format(self.packageServiceType, self.sourceDir))
proc = subprocess.call(['kpackagetool5',
'--type', self.packageServiceType,
'--remove', self.sourceDir,
])
else:
echoError("[error] kpackagetool5 not found.")
installedPath = os.path.join(m.group(1), self.packageNamespace)
echoError("[error] Please manually delete the '{}' folder.".format(installedPath))
sys.exit(1)
exitCode = subprocess.call([kpackagetool(),
'--type', self.packageServiceType,
'--install', self.sourceDir,
])
if exitCode != 0:
echoError("[error] Error when calling: {} --type {} --install {}".format(kpackagetool(), self.packageServiceType, self.sourceDir))
sys.exit(1)
if restart:
subprocess.call([kstart(),
'--',
'plasmashell', '--replace',
])
else:
# kpackagetool5 -t Plasma/Applet -i package
subprocess.call([kpackagetool(),
'--type', self.packageServiceType,
'--install', self.sourceDir,
])
def uninstall(self):
# kpackagetool5 -t Plasma/Applet -r package
subprocess.call([kpackagetool(),
'--type', self.packageServiceType,
'--remove', self.sourceDir,
])
#---
def plasmoidviewer(self, *args, env=None):
if env is None:
env = os.environ.copy()
def test(self,
*args,
langCode=None,
env=None,
dpi=1,
**kwargs
):
if env is None:
env = os.environ.copy()
if langCode is not None:
env = applyLocaleToEnv(env, langCode)
self.i18nBuild()
if dpi != 1:
env['QT_DEVICE_PIXEL_RATIO'] = str(dpi)
# https://invent.kde.org/plasma/libplasma/-/commit/386c5539c6833867112aba299380df3ac48cd47c
noContextProps = False
if noContextProps:
env['PLASMA_NO_CONTEXTPROPERTIES'] = '1'
procArgs = list(args)
for key, value in kwargs.items():
if len(key) == 1:
procArgs.append('-' + key)
else:
procArgs.append('--' + key)
procArgs.append(value)
subprocess.call([
'plasmoidviewer',
'-a', self.sourceDir,
*procArgs
], env=env)
def testDesktop(self, **kwargs):
self.test(
l='floating',
f='planar',
**kwargs
)
def testHorizontal(self, **kwargs):
self.test(
l='topedge',
f='horizontal',
**kwargs
)
def testVertical(self, **kwargs):
self.test(
l='leftedge',
f='vertical',
**kwargs
)
@property
def translationDomain(self):
if self.packageServiceType == 'Plasma/Applet':
return "plasma_applet_{}".format(self.packageNamespace)
else:
echoError("[kpac-i18n] TODO: Map translationDomain for '{}' ServiceType".format(self.packageServiceType))
sys.exit(1)
@property
def bugAddress(self):
return self.packageWebsite
@property
def newBugAddress(self):
m = re.search(r'^((https?:\/\/)?github\.com\/([^\/]+)\/([^\/]+))\/?', self.packageWebsite)
if m:
return m.group(0) + '/issues/new'
else:
return self.packageWebsite
@property
def translateRoot(self):
# package/tranlate/ => package/tranlate/../
# tranlate/ => tranlate/../package/
return os.path.relpath(self.sourceDir, self.translateDir) # Usually '..' or '../package'
#---
def checkI18nCommand(self, cmd):
if not isCommandInstalled(cmd):
echoError("[kpac-i18n] Error: {} command not found. Need to install gettext.".format(cmd))
echoError("[kpac-i18n] Run 'sudo apt install gettext' (Kubuntu/KDE Neon)")
echoError("[kpac-i18n] Run 'sudo zypper install gettext-tools' (openSUSE)")
sys.exit(1)
def getLangCompendiumPath(self, langCode):
return os.path.join(self.compendiumDir, 'compendium-{}.po'.format(langCode))
def i18nCompendium(self):
byDomainsDir = os.path.join(self.compendiumDir, 'bydomains')
localeDir='/usr/share/locale/kf5'
autoDeleteByDomainsDir = True
updateCompendium = False
for dirPath in sorted(glob.glob(os.path.join(localeDir, '*'))):
if not os.path.isdir(dirPath):
continue
langCode = os.path.basename(dirPath)
if '@' in langCode: # Eg: 'be@latin'
continue
moLangDir = os.path.join(localeDir, langCode, 'LC_MESSAGES')
poLangDir = os.path.join(byDomainsDir, langCode)
os.makedirs(poLangDir, exist_ok=True)
langCompendiumPath = self.getLangCompendiumPath(langCode)
if os.path.exists(langCompendiumPath) and not updateCompendium:
continue
echoGray("[kpac-i18n] " + TC.Bold + "[Extracting Messages]" + TC.Reset + TC.FG_DarkGray + ' ' + moLangDir)
for moFilepath in sorted(glob.glob(os.path.join(moLangDir, '*.mo'))):
domain, ext = os.path.splitext(os.path.basename(moFilepath))
poFilepath = os.path.join(poLangDir, domain+'.po')
print("'{}' => '{}'".format(moFilepath, os.path.abspath(poFilepath)))
returncode = subprocess.call([
'msgunfmt',
'-i', moFilepath,
'-o', poFilepath,
])
if returncode != 0:
echoError("[kpac-i18n] error while calling msgunfmt. aborting.")
sys.exit(1)
echoGray("[kpac-i18n] " + TC.Bold + "[Generating Compendium]" + TC.Reset + TC.FG_DarkGray + ' ' + os.path.basename(langCompendiumPath))
poLangFileList = list(sorted(glob.glob(os.path.join(poLangDir, '*.po'))))
if langCode == 'el':
# msgcat: Input po files have different Plural-Forms. Invalid output file was created.
# Please, fix the plurals.
for poLangFile in poLangFileList:
sed_str(
"Plural-Forms: nplurals=2; plural=(n != 1);",
"Plural-Forms: nplurals=2; plural=n != 1;",
poLangFile
)
elif langCode == 'fa':
# msgcat: Input po files have different Plural-Forms. Invalid output file was created.
# Please, fix the plurals.
for poLangFile in poLangFileList:
sed_str(
"Plural-Forms: nplurals=2; plural=(n > 1);",
"Plural-Forms: nplurals=1; plural=0;",
poLangFile
)
elif langCode == 'is':
# msgcat: memory exhausted
continue
elif langCode == 'kk':
# msgcat: memory exhausted
continue
elif langCode == 'km':
# msgcat: memory exhausted
continue
elif langCode == 'mai':
# msgcat: memory exhausted
continue
elif langCode == 'pa':
# msgcat: memory exhausted
continue
returncode = subprocess.call([
'msgcat',
'--use-first',
'--sort-output',
'-o', langCompendiumPath,
] + poLangFileList)
if returncode != 0:
echoError("[kpac-i18n] error while calling msgcat. aborting.")
sys.exit(1)
if autoDeleteByDomainsDir and poLangDir:
echoWarning('Deleting', os.path.abspath(poLangDir))
shutil.rmtree(os.path.abspath(poLangDir))
echoGreen("[kpac-i18n] Done compiling messages")
def i18nMerge(self, useCompendium=False):
# https://techbase.kde.org/Development/Tutorials/Localization/i18n_Build_Systems
# https://techbase.kde.org/Development/Tutorials/Localization/i18n_Build_Systems/Outside_KDE_repositories
# https://invent.kde.org/sysadmin/l10n-scripty/-/blob/master/extract-messages.sh
# self.bugAddress = 'https://github.com/User/plasmoid-widgetname'
# self.newBugAddress = 'https://github.com/User/plasmoid-widgetname/issues/new'
# self.translateDir = 'package/translate/'
# self.translateRoot = '..'
self.removeOldI18nScripts()
self.checkI18nCommand('xgettext')
echoGray("[kpac-i18n] " + TC.Bold + "[Extracting messages]")
potArgs = [
'--from-code=UTF-8',
'--width=200', # Don't wrap on short sentences
'--add-location=file', # Filename only, no line numbers
]
oldTemplateFilename = 'template.pot'
newTemplateFilename = 'template.pot.new'
oldTemplatePath = os.path.join(self.translateDir, oldTemplateFilename)
newTemplatePath = os.path.join(self.translateDir, newTemplateFilename)
if os.path.exists(self.jsonMetaFilepath):
echoGray("[kpac-i18n] Extracting metadata.json")
with open(self.jsonMetaFilepath, 'r') as fin:
metadata = json.load(fin)
# This template header is overwritten later so the only changes needed is
# 'charset=CHARSET' => 'charset=UTF-8' so that xgettext doesn't complain.
# POT_DEFAULT_HEADER already has the charset=UTF-8 replaced.
newTemplateText = POT_DEFAULT_HEADER
kp = metadata.get('KPlugin', {})
trKeywords = [
'Name',
'Description',
]
relativeMetadataPath = os.path.relpath(self.jsonMetaFilepath, self.translateDir)
for keyword in trKeywords:
keywordMessage = kp.get(keyword, '')
keywordMessage = keywordMessage.replace('\"', r'\"')
if keyword != "":
# keywordText = f"#: {relativeMetadataPath}\nmsgctxt \"{keyword}\"\nmsgid \"{keywordMessage}\"\nmsgstr \"\"\n\n"
keywordText = f"#: {relativeMetadataPath}\nmsgid \"{keywordMessage}\"\nmsgstr \"\"\n\n"
newTemplateText += keywordText
with open(newTemplatePath, 'w') as fout:
fout.write(newTemplateText)
else:
# TODO: Port parsing Desktop File
# Note: xgettext v0.20.1 (Kubuntu 20.04) and below will attempt to translate Icon,
# so we need to specify Name, GenericName, Comment, and Keywords.
# https://github.com/Zren/plasma-applet-lib/issues/1
# https://savannah.gnu.org/support/?108887
# find "${packageRoot}" -name '*.desktop' | sort > "${DIR}/infiles.list"
# xgettext \
# ${potArgs} \
# --files-from="${DIR}/infiles.list" \
# --language=Desktop \
# -k -kName -kGenericName -kComment -kKeywords \
# -D "${packageRoot}" \
# -D "${DIR}" \
# -o "template.pot.new" \
# || \
# { echoRed "[translate/merge] error while calling xgettext. aborting."; exit 1; }
pass
# See Ki18n's extract-messages.sh for a full example:
# https://invent.kde.org/sysadmin/l10n-scripty/-/blob/master/extract-messages.sh#L25
# The -kN_ and -kaliasLocale keywords are mentioned in the Outside_KDE_repositories wiki.
# We don't need -kN_ since we don't use intltool-extract but might as well keep it.
# I have no idea what -kaliasLocale is used for. Googling aliasLocale found only listed kde1 code.
# We don't need to parse -ki18nd since that'll extract messages from other domains.
infilesPath = os.path.join(self.translateDir, 'infiles.list')
with open(infilesPath, 'w') as fout:
findProc = subprocess.Popen([
'find',
self.translateRoot,
'-name', '*.cpp',
'-o', '-name', '*.h',
'-o', '-name', '*.c',
'-o', '-name', '*.qml',
'-o', '-name', '*.js',
], stdout=subprocess.PIPE, cwd=self.translateDir)
sortProc = subprocess.call([
'sort'
], stdin=findProc.stdout, stdout=fout)
findProc.wait()
potArgs += [
# '--files-from', infilesPath,
'--files-from', 'infiles.list',
'-C', '-kde',
'-ci18n',
'-ki18n:1',
'-ki18nc:1c,2',
'-ki18np:1,2',
'-ki18ncp:1c,2,3',
'-kki18n:1',
'-kki18nc:1c,2',
'-kki18np:1,2',
'-kki18ncp:1c,2,3',
'-kxi18n:1',
'-kxi18nc:1c,2',
'-kxi18np:1,2',
'-kxi18ncp:1c,2,3',
'-kkxi18n:1',
'-kkxi18nc:1c,2',
'-kkxi18np:1,2',
'-kkxi18ncp:1c,2,3',
'-kI18N_NOOP:1',
'-kI18NC_NOOP:1c,2',
'-kI18N_NOOP2:1c,2',
'-kI18N_NOOP2_NOSTRIP:1c,2',
'-ktr2i18n:1',
'-ktr2xi18n:1',
'-kN_:1',
'-kaliasLocale',
'--package-name', self.packageName,
'--msgid-bugs-address', self.bugAddress,
]
returncode = subprocess.call(['xgettext'] + potArgs + [
'-D', self.translateRoot,
'-D', '.', # cwd should be translateDir
'--join-existing',
'-o', newTemplateFilename,
], cwd=self.translateDir)
if returncode != 0:
echoError("[kpac-i18n] error while calling xgettext. aborting.")
sys.exit(1)
if not os.path.exists(newTemplatePath):
# Error generating template.pot.new
echoError('[kpac-i18n] template.pot.new does not exist')
sys.exit(1)
# Replace gettext placeholders
with LineReplace(newTemplatePath) as rep:
for line in rep.lines:
line = line.replace(
"Content-Type: text/plain; charset=CHARSET",
"Content-Type: text/plain; charset=UTF-8",
)
line = line.replace(
"# SOME DESCRIPTIVE TITLE.",
"# Translation of {} in LANGUAGE".format(self.packageName),
)
line = line.replace(
"# Copyright (C) YEAR THE PACKAGE\'S COPYRIGHT HOLDER",
"# Copyright (C) {}".format(datetime.date.today().year),
)
rep.write(line)
if os.path.exists(oldTemplatePath):
# Temporary replace with oldPotDate
# Note: We need to rstrip the trailing \n" since it's annoying to escape just the newline.
newPotDate = grep_line('POT-Creation-Date:', newTemplatePath).rstrip('\\n\"')
oldPotDate = grep_line('POT-Creation-Date:', oldTemplatePath).rstrip('\\n\"')
sed_str(newPotDate, oldPotDate, newTemplatePath)
changes = diff(oldTemplatePath, newTemplatePath)
if changes.strip() != "":
sed_str(oldPotDate, newPotDate, newTemplatePath) # Revert back to newPotDate
os.rename(newTemplatePath, oldTemplatePath)
addedKeys = []
removedKeys = []
for line in changes.splitlines():
if "> msgid" in line:
addedKeys.append(line.rstrip('\n')[8:])
elif "< msgid" in line:
removedKeys.append(line.rstrip('\n')[8:])
duplicateKeys = set(addedKeys) & set(removedKeys)
for key in duplicateKeys:
addedKeys.remove(key)
removedKeys.remove(key)
echoGray("[kpac-i18n] {} changed".format(oldTemplatePath))
echoGreen("[kpac-i18n] Added Keys:")
if len(addedKeys) >= 1:
for key in sorted(addedKeys):
echoGreen(key)
print("")
echoRed("[kpac-i18n] Removed Keys:")
if len(removedKeys) >= 1:
for key in sorted(removedKeys):
echoRed(key)
print("")
echoGray("[kpac-i18n] Moved Keys:")
if len(duplicateKeys) >= 1:
for key in sorted(duplicateKeys):
echoGray(key)
print("")
else:
# No changes
echoGray("[kpac-i18n] No changes to {}".format(oldTemplatePath))
os.remove(newTemplatePath)
else:
# template.pot didn't already exist
echoGray("[kpac-i18n] Created {}".format(oldTemplatePath))
os.rename(newTemplatePath, oldTemplatePath)
#--- Status Table Header
potMessageCount = grep_re_count('msgstr ""\n(\n|$)', oldTemplatePath)
status = ""
statusFormat = "| {:<8} | {:>7} | {:>5} |\n" # .format("fr", "27/27", "100%")
status += "| Locale | Lines | % Done|\n"
status += "|----------|---------|-------|\n"
status += statusFormat.format("Template", potMessageCount, "")
os.remove(infilesPath)
echoGray("[kpac-i18n] Done extracting messages")
#--- Merge
echoGray("[kpac-i18n] " + TC.Bold + "[Merging messages]")
for catFilepath in sorted(glob.glob(os.path.join(self.translateDir, '*.po'))):
catLocale = os.path.splitext(os.path.basename(catFilepath))[0]
echoGray("[kpac-i18n] Updating {} ({})".format(catFilepath, catLocale))
newCatFilepath = catFilepath + ".new"
shutil.copyfile(catFilepath, newCatFilepath)
# Make sure the catalog uses UTF-8
sed_str(
"Content-Type: text/plain; charset=CHARSET",
"Content-Type: text/plain; charset=UTF-8",
newCatFilepath
)
mergeCmd = ['msgmerge']
catUsesGenerator = grep_line("X-Generator:", catFilepath)
if catUsesGenerator is None:
mergeCmd += ["--width=400"]
langCompendiumPath = self.getLangCompendiumPath(catLocale)
if useCompendium and os.path.exists(langCompendiumPath):
echoGray("[kpac-i18n] Using compendium at '{}'".format(langCompendiumPath))
mergeCmd += [
"--compendium=" + langCompendiumPath,
]
mergeCmd += [
'--add-location=file',
'--no-fuzzy-matching',
'-o', newCatFilepath,
newCatFilepath,
oldTemplatePath,
]
returncode = subprocess.call(mergeCmd)
if returncode != 0:
echoError("[kpac-i18n] Error while merging changes into {}".format(newCatFilepath))
sys.exit(1)
# Replace gettext placeholders
with LineReplace(newCatFilepath) as rep:
for line in rep.lines:
line = line.replace(
"# SOME DESCRIPTIVE TITLE.",
"# Translation of {} in {}".format(self.packageName, catLocale),
)
line = line.replace(
"# Translation of {} in LANGUAGE".format(self.packageName),
"# Translation of {} in {}".format(self.packageName, catLocale),
)
line = line.replace(
"# Copyright (C) YEAR THE PACKAGE\'S COPYRIGHT HOLDER",
"# Copyright (C) {}".format(datetime.date.today().year),
)
rep.write(line)
# with open(newCatFilepath, 'r') as fin: