-
Notifications
You must be signed in to change notification settings - Fork 45
/
tasks.py
1929 lines (1605 loc) · 61.2 KB
/
tasks.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
import fnmatch
import glob
import hashlib
import json
import os
import platform
import re
import shutil
import stat
import subprocess
import sys
import zipfile
from datetime import datetime, timezone
from pathlib import Path, PurePath
from tempfile import TemporaryDirectory, mkstemp
import boto3
import requests
from invoke import Collection, task
# Below is from:
# https://stackoverflow.com/questions/3041986/apt-command-line-interface-like-yes-no-input
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via input() and return answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == "":
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")
def get_version(c):
with open(c.plugin.version_file_raw) as f:
return f.readline().strip()
# Handle long filenames or readonly files on windows, see:
# http://bit.ly/2g58Yxu
def rmtree(top):
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
filename = os.path.join(root, name)
os.chmod(filename, stat.S_IWUSR)
try:
os.remove(filename)
except PermissionError:
print(
"Permission error: unable to remove {}. Skipping that file.".format(
filename
)
)
for name in dirs:
try:
os.rmdir(os.path.join(root, name))
except OSError:
print(
"Unable to remove directory {}. Skipping removing that folder.".format(
os.path.join(root, name)
)
)
try:
os.rmdir(top)
except OSError:
print(
"Unable to remove directory {}. Skipping removing that folder.".format(top)
)
# Function to find and replace in a file
def _replace(file_path, regex, subst):
# Create temp file
fh, abs_path = mkstemp()
if sys.version_info[0] < 3:
with os.fdopen(fh, "w") as new_file:
with open(file_path) as old_file:
for line in old_file:
new_file.write(regex.sub(subst, line))
else:
with open(fh, "w", encoding="Latin-1") as new_file:
with open(file_path, encoding="Latin-1") as old_file:
for line in old_file:
new_file.write(regex.sub(subst, line))
os.remove(file_path)
shutil.move(abs_path, file_path)
###############################################################################
# Misc development tasks (change version, deploy GEE scripts)
###############################################################################
@task(
help={
"v": "Version to set",
"testing": "Set for requirements-testing.txt?",
"modules": "Also set versions for any modules specified "
"in ext_libs.local_modules",
"tag": "Also set tag(s)",
"gee": "Also set versions for gee scripts",
}
)
def set_version(c, v=None, testing=False, modules=False, tag=False, gee=False):
# Validate the version matches the regex
if not v:
version_update = False
v = get_version(c)
print(
"No version specified, retaining version {}, but updating SHA and release date".format(
v
)
)
elif not re.match("[0-9]+([.][0-9]+)+", v):
print("Must specify a valid version (example: 0.36)")
return
else:
version_update = True
revision = (
subprocess.check_output(["git", "rev-parse", "HEAD"])
.decode("utf-8")
.strip("\n")[0:8]
)
release_date = datetime.now(timezone.utc).strftime("%Y/%m/%d %H:%M:%SZ")
# Set in version.json
print("Setting version to {} in version.json".format(v))
with open(c.plugin.version_file_details, "w") as f:
json.dump(
{"version": v, "revision": revision, "release_date": release_date},
f,
indent=4,
)
if version_update:
# Set in version.txt
print("Setting version to {} in {}".format(v, c.plugin.version_file_raw))
with open(c.plugin.version_file_raw, "w") as f:
f.write(v)
# Set in Sphinx docs in make.conf
print("Setting version to {} in sphinx conf.py".format(v))
sphinx_regex = re.compile(
'(((version)|(release)) = ")[0-9]+([.][0-9]+)+(rc[0-9]*)?', re.IGNORECASE
)
_replace(
os.path.join(c.sphinx.sourcedir, "conf.py"), sphinx_regex, r"\g<1>" + v
)
# Set in metadata.txt
print("Setting version to {} in metadata.txt".format(v))
sphinx_regex = re.compile("^(version=)[0-9]+([.][0-9]+)+(rc[0-9]*)?")
_replace(
os.path.join(c.plugin.source_dir, "metadata.txt"),
sphinx_regex,
r"\g<1>" + v,
)
requirements_txt_regex = re.compile(
"((trends.earth-schemas.git@)|(trends.earth-algorithms.git@))([.0-9a-z]*)"
)
if gee:
# For the GEE config files the version can't have a dot, so convert to
# underscore
v_gee = v.replace(".", "_")
if not v or not re.match("[0-9]+(_[0-9]+)+(rc[0-9]*)?", v_gee):
print("Must specify a valid version (example: 0.36)")
return
gee_id_regex = re.compile('(, )?"id": "[0-9a-z-]*"(, )?')
gee_script_name_regex = re.compile(
'("name": "[0-9a-zA-Z -]*)( [0-9]+(_[0-9]+)+)(rc[0-9]*)?"'
)
# Set version for GEE scripts
for subdir, dirs, files in os.walk(c.gee.script_dir):
for file in files:
filepath = os.path.join(subdir, file)
if file == "configuration.json":
# Validate the version matches the regex
print("Setting version to {} in {}".format(v, filepath))
# Update the version string
_replace(
filepath, gee_script_name_regex, r"\g<1> " + v_gee + '"'
)
# Clear the ID since a new one will be assigned due to the new name
_replace(filepath, gee_id_regex, "")
elif file == "requirements.txt":
print("Setting version to {} in {}".format(v, filepath))
if ("rc" in v.split(".")[-1]) or (
int(v.split(".")[-1]) % 2 == 0
):
# Last number in version string is even (or this is an RC), so
# use a tagged version of schemas matching this version
_replace(filepath, requirements_txt_regex, r"\g<1>v" + v)
else:
# Last number in version string is odd, so this is a development
# version, so use development version of schemas
_replace(filepath, requirements_txt_regex, r"\g<1>master")
elif file == "__init__.py":
print("Setting version to {} in {}".format(v, filepath))
init_version_regex = re.compile(
"^(__version__[ ]*=[ ]*[\"'])[0-9]+([.][0-9]+)+(rc[0-9]*)?"
)
_replace(filepath, init_version_regex, r"\g<1>" + v)
# Set in scripts.json
print("Setting version to {} in scripts.json".format(v))
scripts_regex = re.compile(
'("version": ")[0-9]+([-._][0-9]+)+(rc[0-9]*)?', re.IGNORECASE
)
_replace(
os.path.join(c.plugin.source_dir, "data", "scripts.json"),
scripts_regex,
r"\g<1>" + v,
)
requirements_file = (
"requirements.txt" if not testing else "requirements-testing.txt"
)
print("Setting version to {} in package {}".format(v, requirements_file))
if ("rc" in v.split(".")[-1]) or (int(v.split(".")[-1]) % 2 == 0):
# Last number in version string is even (or an RC), so use a tagged version
# of schemas matching this version
_replace(requirements_file, requirements_txt_regex, r"\g<1>v" + v)
else:
# Last number in version string is odd, so this is a development
# version, so use development version of schemas
_replace(requirements_file, requirements_txt_regex, r"\g<1>master")
if tag:
set_tag(c)
if modules:
for module in c.plugin.ext_libs.local_modules:
module_path = Path(module["path"]).parent
ret = query_yes_no(
f"Also set version {'and tag ' if tag else ''}for {module['name']}?"
)
if ret:
if tag:
subprocess.check_call(
["invoke", "set-version", "-v", v, "-t"], cwd=module_path
)
else:
subprocess.check_call(
["invoke", "set-version", "-v", v], cwd=module_path
)
@task()
def release_github(c):
v = get_version(c)
# TODO: Add zipfile as an asset
# https://docs.github.com/en/rest/reference/repos#upload-a-release-asset
# Make release
payload = {
"tag_name": "v{}".format(v),
"name": "Version {}".format(v),
"body": """To install this release, download the LDMP.zip file below and then follow [the instructions for installing a release from Github](https://github.com/ConservationInternational/trends.earth#stable-version-from-zipfile).""",
}
s = requests.Session()
res = s.get("https://github.com")
cookies = dict(res.cookies)
r = requests.post(
"{}/repos/{}/{}/releases".format(
c.github.api_url, c.github.repo_owner, c.github.repo_name
),
json=payload,
headers={"Authorization": "token {}".format(c.github.token)},
cookies=cookies,
)
r.raise_for_status()
# TODO: Link asset to release. See:
# https://docs.github.com/en/rest/reference/repos#update-a-release-asset
@task(
help={
"modules": "Also set tag for any modules specified " "in ext_libs.local_modules"
}
)
def set_tag(c, modules=False):
v = get_version(c)
ret = subprocess.run(
["git", "diff-index", "HEAD", "--"], capture_output=True, text=True
)
if ret.stdout != "":
ret = query_yes_no("Uncommitted changes exist in repository. Commit these?")
if ret:
ret = subprocess.run(
["git", "commit", "-m", "Updating version tags for v{}".format(v)]
)
ret.check_returncode()
else:
print("Changes not committed - VERSION TAG NOT SET")
print("Tagging version {} and pushing tag to origin".format(v))
ret = subprocess.run(
["git", "tag", "-l", "v{}".format(v)], capture_output=True, text=True
)
ret.check_returncode()
if "v{}".format(v) in ret.stdout:
# Try to delete this tag on remote in case it exists there
ret = subprocess.run(["git", "push", "origin", "--delete", "v{}".format(v)])
if ret.returncode == 0:
print("Deleted tag v{} on origin".format(v))
subprocess.check_call(
["git", "tag", "-f", "-a", "v{}".format(v), "-m", "Version {}".format(v)]
)
subprocess.check_call(["git", "push", "origin", "v{}".format(v)])
if modules:
for module in c.plugin.ext_libs.local_modules:
module_path = Path(module["path"]).parent
print(f"Also setting tag for {module['name']}")
subprocess.check_call(["invoke", "set-tag"], cwd=module_path)
def check_tecli_python_version():
if sys.version_info[0] < 3:
print(
"ERROR: tecli tasks require Python version > 2 (you are running Python version {}.{})".format(
sys.version_info[0], sys.version_info[1]
)
)
return False
else:
return True
@task
def tecli_login(c):
if not check_tecli_python_version():
return
subprocess.check_call(["python", os.path.abspath(c.gee.tecli), "login"])
@task
def tecli_clear(c):
if not check_tecli_python_version():
return
subprocess.check_call(["python", os.path.abspath(c.gee.tecli), "clear"])
@task(help={"key": "GEE key in JSON format (base64 encoded)"})
def tecli_config(c, key):
if not check_tecli_python_version():
return
subprocess.check_call(
[
"python",
os.path.abspath(c.gee.tecli),
"config",
"set",
"EE_SERVICE_ACCOUNT_JSON",
key,
]
)
@task(help={"script": "Script name", "overwrite": "Overwrite scripts if existing?"})
def tecli_publish(c, script=None, overwrite=False):
if not check_tecli_python_version():
return
if not script and not overwrite:
ret = query_yes_no(
"WARNING: this will overwrite all scripts on the server with version {}.\nDo you wish to continue?".format(
get_version(c)
)
)
if not ret:
return
dirs = next(os.walk(c.gee.script_dir))[1]
n = 0
for dir in dirs:
script_dir = os.path.join(c.gee.script_dir, dir)
if os.path.exists(os.path.join(script_dir, "configuration.json")) and (
script is None or script == dir
):
print("Publishing {}...".format(dir))
subprocess.check_call(
[
"python",
os.path.abspath(c.gee.tecli),
"publish",
"--public=True",
"--overwrite=True",
],
cwd=script_dir,
)
n += 1
if script and n == 0:
print('Script "{}" not found.'.format(script))
# Updating GEE script IDs in config
if script:
subprocess.check_call(["invoke", "update-script-ids", "-s", script])
else:
subprocess.check_call(["invoke", "update-script-ids"])
@task(
help={
"script": "Script name",
"queryParams": "Parameters",
"payload": "Parameters (as json",
}
)
def tecli_run(c, script, queryParams=None, payload=None):
if not check_tecli_python_version():
return
dirs = next(os.walk(c.gee.script_dir))[1]
n = 0
script_dir = None
for dir in dirs:
script_dir = os.path.join(c.gee.script_dir, dir)
if (
os.path.exists(os.path.join(script_dir, "configuration.json"))
and script == dir
):
print("Running {}...".format(dir))
if queryParams:
print("Using given query parameters as input to script.")
subprocess.check_call(
[
"python",
os.path.abspath(c.gee.tecli),
"start",
"--queryParams={}".format(queryParams),
],
cwd=script_dir,
)
elif payload:
print("Using given payload as input to script.")
subprocess.check_call(
[
"python",
os.path.abspath(c.gee.tecli),
"start",
"--payload={}".format(os.path.abspath(payload)),
],
cwd=script_dir,
)
else:
print("Running script without any input parameters.")
subprocess.check_call(
["python", os.path.abspath(c.gee.tecli), "start"], cwd=script_dir
)
n += 1
break
if script and n == 0:
print('Script "{}" not found.'.format(script))
@task(help={"script": "Script name"})
def update_script_ids(c, script=None):
with open(c.gee.scripts_json_file) as fin:
scripts = json.load(fin)
dirs = next(os.walk(c.gee.script_dir))[1]
script_dir = None
for dir in dirs:
script_dir = os.path.join(c.gee.script_dir, dir)
if script:
if script_dir != script:
continue
if os.path.exists(os.path.join(script_dir, "configuration.json")):
with open(os.path.join(script_dir, "configuration.json")) as fin:
config = json.load(fin)
try:
script_name = re.compile("( [0-9]+(_[0-9]+)+$)").sub("", config["name"])
# Find location of this script in the list of scripts in the
# script configuration JSON
script_index = [
index
for index, script in enumerate(scripts)
if script["name"] == script_name
]
assert len(script_index) <= 1
script_index = script_index[0]
try:
scripts[script_index]["id"] = config["id"]
except KeyError:
print(f"No id found in config for {script_name}")
script_version = (
re.compile("^[a-zA-Z0-9-]* ")
.sub("", config["name"])
.replace("_", ".")
)
scripts[script_index]["version"] = script_version
except IndexError:
print(
f"Skipping {script_name} as not found in scripts.json - maybe need to publish?"
)
with open(c.gee.scripts_json_file, "w") as f_out:
json.dump(scripts, f_out, sort_keys=True, indent=4)
@task(help={"script": "Script name"})
def tecli_info(c, script=None):
if not check_tecli_python_version():
return
dirs = next(os.walk(c.gee.script_dir))[1]
n = 0
script_dir = None
for dir in dirs:
script_dir = os.path.join(c.gee.script_dir, dir)
if os.path.exists(os.path.join(script_dir, "configuration.json")) and (
script is None or script == dir
):
print("Checking info on {}...".format(dir))
subprocess.check_call(
["python", os.path.abspath(c.gee.tecli), "info"], cwd=script_dir
)
n += 1
if script and n == 0:
print('Script "{}" not found.'.format(script))
@task(
help={
"script": "Script name",
"since": "Print logs since (number of hours = default 1)",
}
)
def tecli_logs(c, script, since=1):
if not check_tecli_python_version():
return
dirs = next(os.walk(c.gee.script_dir))[1]
n = 0
script_dir = None
for dir in dirs:
script_dir = os.path.join(c.gee.script_dir, dir)
if (
os.path.exists(os.path.join(script_dir, "configuration.json"))
and script == dir
):
print("Checking logs for {}...".format(dir))
subprocess.check_call(
[
"python",
os.path.abspath(c.gee.tecli),
"logs",
f"--since={since}",
],
cwd=script_dir,
)
n += 1
break
if script and n == 0:
print('Script "{}" not found.'.format(script))
###############################################################################
# Setup dependencies and install package
###############################################################################
def not_comments(lines, s, e):
return [line for line in lines[s:e] if line[0] != "#"]
def read_requirements():
"""Return a list of runtime and list of test requirements"""
with open("requirements.txt") as f:
lines = f.readlines()
lines = [line for line in [line.strip() for line in lines] if line]
divider = "# test requirements"
try:
idx = lines.index(divider)
except ValueError:
raise Exception('Expected to find "{}" in requirements.txt'.format(divider))
return not_comments(lines, 0, idx), not_comments(lines, idx + 1, None)
def _safe_remove_folder(rootdir):
"""
Supports removing a folder that may have symlinks in it
Needed on windows to avoid removing the original files linked to within
each folder
"""
rootdir = Path(rootdir)
if rootdir.is_symlink():
rootdir.rmdir()
else:
folders = [path for path in Path(rootdir).iterdir() if path.is_dir()]
for folder in folders:
if folder.is_symlink():
folder.rmdir()
else:
shutil.rmtree(folder)
files = [path for path in Path(rootdir).iterdir()]
for file in files:
file.unlink()
shutil.rmtree(rootdir)
@task(
help={
"clean": "Clean out dependencies first",
"link": "Symlink dependendencies to their local repos",
"pip": 'Path to pip (usually "pip" or "pip3"',
}
)
def plugin_setup(c, clean=True, link=False, pip="pip"):
"""install dependencies"""
ext_libs = os.path.abspath(c.plugin.ext_libs.path)
if clean and os.path.exists(ext_libs):
_safe_remove_folder(ext_libs)
if sys.version_info[0] < 3:
if not os.path.exists(ext_libs):
os.makedirs(ext_libs)
else:
os.makedirs(ext_libs, exist_ok=True)
runtime, test = read_requirements()
os.environ["PYTHONPATH"] = ext_libs
for req in runtime + test:
# Don't install numpy with pyqtgraph as QGIS already has numpy. So use
# the --no-deps flag (-N for short) with that package only.
if "pyqtgraph" in req:
subprocess.check_call(
[pip, "install", "--upgrade", "--no-deps", "-t", ext_libs, req]
)
else:
subprocess.check_call([pip, "install", "--upgrade", "-t", ext_libs, req])
# Remove the .pyc files as these are no allowed on QGIS repo
pyc_files = Path(ext_libs).rglob("*.pyc")
for pyc in pyc_files:
pyc.unlink()
if link:
for module in c.plugin.ext_libs.local_modules:
ln = os.path.abspath(c.plugin.ext_libs.path) + os.path.sep + module["name"]
if os.path.islink(ln):
print(f"{ln} is already a link (to {os.readlink(ln)})")
else:
print(
"Linking local repo of {} to plugin ext_libs".format(module["name"])
)
shutil.rmtree(ln)
os.symlink(module["path"], ln)
@task(
help={
"clean": "remove existing install folder first",
"version": "what version of QGIS to install to",
"profile": "what profile to install to (only applies to QGIS3",
"fast": "Skip compiling numba files",
"link": "Symlink folder to QGIS profile directory",
}
)
def plugin_install(
c, clean=False, version=3, profile="default", fast=False, link=False
):
"""install plugin to qgis"""
set_version(c)
plugin_name = c.plugin.name
src = os.path.join(os.path.dirname(__file__), plugin_name)
if version == 2:
folder = ".qgis2"
elif version == 3:
if platform.system() == "Darwin":
folder = "Library/Application Support/QGIS/QGIS3/profiles/"
if platform.system() == "Linux":
folder = ".local/share/QGIS/QGIS3/profiles/"
if platform.system() == "Windows":
folder = "AppData\\Roaming\\QGIS\\QGIS3\\profiles\\"
folder = os.path.join(folder, profile)
else:
print("ERROR: unknown qgis version {}".format(version))
return
dst_plugins = os.path.join(os.path.expanduser("~"), folder, "python", "plugins")
dst_this_plugin = os.path.join(dst_plugins, plugin_name)
src = os.path.abspath(src)
dst_this_plugin = os.path.abspath(dst_this_plugin)
if not hasattr(os, "symlink") or not link:
if clean and os.path.exists(dst_this_plugin):
print(f"Removing folder {dst_this_plugin}")
_safe_remove_folder(dst_this_plugin)
print(
"Copying plugin to QGIS version {} plugin folder at {}".format(
version, dst_this_plugin
)
)
for root, dirs, files in os.walk(src):
relpath = os.path.relpath(root)
if not os.path.exists(os.path.join(dst_plugins, relpath)):
os.makedirs(os.path.join(dst_plugins, relpath))
for f in _filter_excludes(root, files, c):
try:
shutil.copy(
os.path.join(root, f), os.path.join(dst_plugins, relpath, f)
)
except PermissionError:
print(
"Permission error: unable to copy {} to {}. Skipping that file.".format(
f, os.path.join(dst_plugins, relpath, f)
)
)
_filter_excludes(root, dirs, c)
else:
if clean and os.path.exists(dst_this_plugin):
print(f"Removing folder {dst_this_plugin}")
_safe_remove_folder(dst_this_plugin)
if os.path.exists(dst_this_plugin):
print(
f"Not linking - plugin folder for QGIS version {version} already "
f"exists at {dst_this_plugin}. Use '-c' to clean that folder if "
"desired."
)
else:
print(
"Linking plugin development folder to QGIS version {} plugin folder at {}".format(
version, dst_this_plugin
)
)
os.symlink(src, dst_this_plugin)
def file_changed(infile, outfile):
try:
infile_s = os.stat(infile)
outfile_s = os.stat(outfile)
return infile_s.st_mtime > outfile_s.st_mtime
except Exception:
return True
def _filter_excludes(root, items, c):
excludes = set(c.plugin.excludes)
skips = c.plugin.skip_exclude
def exclude(p):
any([fnmatch.fnmatch(p, e) for e in excludes])
if not items:
return []
# to prevent descending into dirs, modify the list in place
for item in list(items): # copy list or iteration values change
itempath = os.path.join(os.path.relpath(root), item)
if exclude(itempath) and item not in skips:
# debug('Excluding {}'.format(itempath))
items.remove(item)
return items
# Compile all ui and resource files - only used on CI so that gui can be loaded
# on docker image
@task(
help={
"clean": "remove existing install folder first",
}
)
def compile_files(c, clean=False):
pyrcc = "pyrcc5"
pyrcc_path = check_path(pyrcc)
if not pyrcc:
print(
"ERROR: {} is not in your path---unable to compile resource file(s)".format(
pyrcc
)
)
return
else:
res_files = c.plugin.resource_files
res_count = 0
skip_count = 0
for res in res_files:
if os.path.exists(res):
(base, ext) = os.path.splitext(res)
output = "{}.py".format(base)
if clean or file_changed(res, output):
print("Compiling {} to {}".format(res, output))
subprocess.check_call([pyrcc_path, "-o", output, res])
res_count += 1
else:
skip_count += 1
else:
print("{} does not exist---skipped".format(res))
print("Compiled {} resource files. Skipped {}.".format(res_count, skip_count))
# Below is based on pb_tool:
# https://github.com/g-sherman/plugin_build_tool
def check_path(app):
"""Adapted from StackExchange:
http://stackoverflow.com/questions/377017
"""
def is_exe(fpath):
return os.path.exists(fpath) and os.access(fpath, os.X_OK)
def ext_candidates(fpath):
yield fpath
for ext in os.environ.get("PATHEXT", "").split(os.pathsep):
yield fpath + ext
# Also look in folders under this python versions lib path
folders = os.environ["PATH"].split(os.pathsep)
folders.extend(
[x[0] for x in os.walk(os.path.join(os.path.dirname(sys.executable), "Lib"))]
)
fpath, fname = os.path.split(app)
if fpath:
if is_exe(app):
return app
else:
for path in folders:
exe_file = os.path.join(path, app)
for candidate in ext_candidates(exe_file):
if is_exe(candidate):
return candidate
return None
###############################################################################
# Translation
###############################################################################
@task
def lrelease(c):
print("Releasing translations using lrelease...")
lrelease = check_path("lrelease")
if not lrelease:
print(
"ERROR: lrelease is not in your path---unable to release translation files"
)
return
for translation in c.plugin.translations:
subprocess.check_call(
[
lrelease,
os.path.join(c.plugin.i18n_dir, "LDMP_{}.ts".format(translation)),
]
)
@task(
help={
"force": "Force the download of the translations files regardless of whether "
"timestamps on the local computer are newer than those on the server"
}
)
def translate_pull(c, force=False):
print("Pulling transifex translations...")
if force:
subprocess.check_call([c.sphinx.tx_path, "pull", "-f"])
else:
subprocess.check_call([c.sphinx.tx_path, "pull"])
lrelease(c)
# @task
# def translate_update_resources(c):
# print("Updating transifex...")
# subprocess.check_call("sphinx-intl update-txconfig-resources --pot-dir {docroot}/i18n/pot --transifex-project-name {transifex_name}".format(docroot=c.sphinx.docroot, transifex_name=c.sphinx.transifex_name))
#
@task(
help={
"force": "Push source files to transifex without checking modification times",
"version": "what version of QGIS to install to",
}
)
def translate_push(c, force=False, version=3):
print("Building changelog...")
changelog_build(c)
print("Building download page...")
build_download_page(c)
# Below is necessary just to avoid warning messages regarding missing image
# files when Sphinx is used later on
print("Localizing resources...")
localize_resources(c, "en")
print("Gathering strings...")
gettext(c)
print("Generating the pot files for the LDMP toolbox help files...")
for translation in c.plugin.translations:
subprocess.check_call(
c.sphinx.sphinx_intl.split()
+ [
"--config",
f"{c.sphinx.sourcedir}/conf.py",
"update",
"-p",
f"{c.sphinx.docroot}/i18n/pot",
"-l",
f"{translation}",
]
)