forked from mpeterv/hererocks
-
Notifications
You must be signed in to change notification settings - Fork 12
/
hererocks.py
executable file
·3087 lines (2639 loc) · 127 KB
/
hererocks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""A tool for installing Lua and LuaRocks locally."""
from __future__ import print_function
import argparse
import contextlib
import hashlib
import inspect
import json
import locale
import os
import platform
import re
import shutil
import stat
import string
import subprocess
import sys
import tarfile
import tempfile
import textwrap
import zipfile
try:
from urllib2 import URLError, urlopen
except ImportError:
from urllib.error import URLError
from urllib.request import urlopen
if os.name == "nt":
try:
import _winreg as winreg
except ImportError:
import winreg
hererocks_version = "Hererocks 0.25.1"
__all__ = ["main"]
opts = None
temp_dir = None
activation_script_templates = {
"get_deactivated_path.lua": """
local path = os.getenv("PATH")
local dir_sep = package.config:sub(1, 1)
local path_sep = dir_sep == "\\\\" and ";" or ":"
local hererocks_path = "#LOCATION_DQ#" .. dir_sep .. "bin"
local new_path_parts = {}
local for_fish = arg[1] == "--fish"
if for_fish then
io.stdout:write("set -gx PATH ")
end
for path_part in (path .. path_sep):gmatch("([^" .. path_sep .. "]*)" .. path_sep) do
if path_part ~= hererocks_path then
if for_fish then
path_part = "'" .. path_part:gsub("'", [['\'']]) .. "'"
end
table.insert(new_path_parts, path_part)
end
end
io.stdout:write(table.concat(new_path_parts, for_fish and " " or path_sep))
""",
"activate": """
if declare -f -F deactivate-lua >/dev/null; then
deactivate-lua
fi
deactivate-lua () {
if [ -x '#LOCATION_SQ#/bin/lua' ]; then
PATH=`'#LOCATION_SQ#/bin/lua' '#LOCATION_SQ#/bin/get_deactivated_path.lua'`
export PATH
# Need to rehash under bash and zsh so that new PATH is taken into account.
if [ -n "${BASH-}" ] || [ -n "${ZSH_VERSION-}" ]; then
hash -r 2>/dev/null
fi
fi
unset -f deactivate-lua
}
PATH='#LOCATION_SQ#/bin':"$PATH"
export PATH
# As in deactivate-lua, rehash after changing PATH.
if [ -n "${BASH-}" ] || [ -n "${ZSH_VERSION-}" ]; then
hash -r 2>/dev/null
fi
""",
"activate_posix": """
s=$(command -V deactivate_lua 2>&1)
if [ $? -eq 0 ]; then
if [ "${s##*function*}" = '' ]; then
deactivate_lua
fi;
fi;
deactivate_lua () {
if [ -x '#LOCATION_SQ#/bin/lua' ]; then
PATH=`'#LOCATION_SQ#/bin/lua' '#LOCATION_SQ#/bin/get_deactivated_path.lua'`
export PATH
hash -r 2>/dev/null
fi
unset -f deactivate_lua
}
PATH='#LOCATION_SQ#/bin':"$PATH"
export PATH
hash -r 2>/dev/null
""",
"activate.csh": """
which deactivate-lua >&/dev/null && deactivate-lua
alias deactivate-lua 'if ( -x '\\''#LOCATION_NESTED_SQ#/bin/lua'\\'' ) then; setenv PATH `'\\''#LOCATION_NESTED_SQ#/bin/lua'\\'' '\\''#LOCATION_NESTED_SQ#/bin/get_deactivated_path.lua'\\''`; rehash; endif; unalias deactivate-lua'
setenv PATH '#LOCATION_SQ#/bin':"$PATH"
rehash
""",
"activate.fish": """
if functions -q deactivate-lua
deactivate-lua
end
function deactivate-lua
if test -x '#LOCATION_SQ#/bin/lua'
eval ('#LOCATION_SQ#/bin/lua' '#LOCATION_SQ#/bin/get_deactivated_path.lua' --fish)
end
functions -e deactivate-lua
end
set -gx PATH '#LOCATION_SQ#/bin' $PATH
""",
"activate.bat": """
@echo off
where deactivate-lua >nul 2>nul
if %errorlevel% equ 0 call deactivate-lua
set "PATH=#LOCATION#\\bin;%PATH%"
""",
"deactivate-lua.bat": """
@echo off
if exist "#LOCATION#\\bin\\lua.exe" for /f "usebackq delims=" %%p in (`""#LOCATION_PAREN#\\bin\\lua" "#LOCATION_PAREN#\\bin\\get_deactivated_path.lua""`) DO set "PATH=%%p"
""",
"activate.ps1": """
if (test-path function:deactivate-lua) {
deactivate-lua
}
function global:deactivate-lua () {
if (test-path "#LOCATION#\\bin\\lua.exe") {
$env:PATH = & "#LOCATION#\\bin\\lua.exe" "#LOCATION#\\bin\\get_deactivated_path.lua"
}
remove-item function:deactivate-lua
}
$env:PATH = "#LOCATION#\\bin;" + $env:PATH
"""
}
def write_activation_scripts():
if os.name == "nt":
template_names = ["get_deactivated_path.lua", "activate.bat", "deactivate-lua.bat", "activate.ps1"]
else:
template_names = ["get_deactivated_path.lua", "activate", "activate.csh", "activate.fish", "activate_posix"]
replacements = {
"LOCATION": opts.location,
"LOCATION_DQ": opts.location.replace("\\", "\\\\").replace('"', '\\"'),
"LOCATION_SQ": opts.location.replace("'", "'\\''"),
"LOCATION_NESTED_SQ": opts.location.replace("'", "'\\''").replace("'", "'\\''"),
"LOCATION_PAREN": re.sub("[&,=()]", r"^\g<0>", opts.location)
}
for template_name in template_names:
with open(os.path.join(opts.location, "bin", template_name), "w") as script_handle:
template = activation_script_templates[template_name][1:]
template = textwrap.dedent(template)
script = re.sub(r'#([a-zA-Z_]+)#', lambda match: replacements[match.group(1)], template)
script_handle.write(script)
def is_executable(path):
return os.path.exists(path) and os.access(path, os.F_OK | os.X_OK) and not os.path.isdir(path)
def program_exists(prog):
path = os.environ.get("PATH", os.defpath)
if not path:
return False
if os.name == "nt":
pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
candidates = [prog + ext for ext in pathext]
else:
candidates = [prog]
for directory in path.split(os.pathsep):
for candidate in candidates:
if is_executable(os.path.join(directory, candidate)):
return True
return False
platform_to_lua_target = {
"linux": "linux",
"win": "mingw" if os.name == "nt" and program_exists("gcc") and not program_exists("cl") else "vs",
"darwin": "macosx",
"freebsd": "freebsd"
}
def using_cl():
return opts.target.startswith("vs")
def get_default_lua_target():
for plat, lua_target in platform_to_lua_target.items():
if sys.platform.startswith(plat):
return lua_target
return "posix" if os.name == "posix" else "generic"
def get_default_cache():
if os.name == "nt":
cache_root = os.getenv("LOCALAPPDATA")
if cache_root is None:
cache_root = os.getenv("USERPROFILE")
if cache_root is None:
return None
cache_root = os.path.join(cache_root, "Local Settings", "Application Data")
return os.path.join(cache_root, "HereRocks", "Cache")
else:
cache_root = os.getenv("XDG_CACHE_HOME", "~/.cache")
expanded_cache_root = os.path.expanduser(cache_root)
if expanded_cache_root.startswith("~"):
return None
return os.path.join(expanded_cache_root, "hererocks")
def download(url, filename):
response = urlopen(url, timeout=opts.timeout)
data = response.read()
with open(filename, "wb") as out:
out.write(data)
default_encoding = locale.getpreferredencoding()
def run(*args, **kwargs):
"""Execute a command.
Command can be passed as several arguments, each being a string
or a list of strings; lists are flattened.
If opts.verbose is True, output of the command is shown.
If the command exits with non-zero, print an error message and exit.
If keyward argument get_output is True, output is returned.
Additionally, non-zero exit code with empty output is ignored.
"""
capture = kwargs.get("get_output", False)
args = [arg for arglist in args for arg in (arglist if isinstance(arglist, list) else [arglist])]
if opts.verbose:
print("Running {}".format(" ".join(args)))
live_output = opts.verbose and not capture
runner = subprocess.check_call if live_output else subprocess.check_output
try:
output = runner(args, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as exception:
if capture and not exception.output.strip():
# Ignore errors if output is empty.
return ""
if not live_output:
sys.stdout.write(exception.output.decode(default_encoding, "ignore"))
sys.exit("Error: got exitcode {} from command {}".format(
exception.returncode, " ".join(args)))
except OSError:
sys.exit("Error: couldn't run {}: is {} in PATH?".format(" ".join(args), args[0]))
if opts.verbose and capture:
sys.stdout.write(output.decode(default_encoding, "ignore"))
return capture and output.decode(default_encoding, "ignore").strip()
def get_output(*args):
return run(get_output=True, *args)
def memoize(func):
cache = {}
def wrapper(arg):
if cache.get(arg) is None:
cache[arg] = func(arg)
return cache[arg]
return wrapper
def query_registry(key, value):
keys = [key, key.replace("\\", "\\Wow6432Node\\", 1)]
for candidate in keys:
if opts.verbose:
print("Querying registry key HKEY_LOCAL_MACHINE\\{}:{}".format(candidate, value))
try:
handle = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, candidate)
except WindowsError:
pass
else:
res = winreg.QueryValueEx(handle, value)[0]
winreg.CloseKey(handle)
return res
@memoize
def check_existence(path):
if opts.verbose:
print("Checking existence of {}".format(path))
return os.path.exists(path)
def copy_dir(src, dst, ignore_git_dir=True):
shutil.copytree(src, dst, ignore=(lambda _, __: {".git"}) if ignore_git_dir else None)
def remove_read_only_or_reraise(func, path, exc_info):
if not os.access(path, os.W_OK):
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise
def remove_dir(path):
shutil.rmtree(path, onerror=remove_read_only_or_reraise)
clever_http_git_whitelist = [
"http://github.com/", "https://github.com/",
"http://bitbucket.com/", "https://bitbucket.com/"
]
git_branch_does_accept_tags = None
def git_branch_accepts_tags():
global git_branch_does_accept_tags
if git_branch_does_accept_tags is None:
version_output = get_output("git", "--version")
match = re.search(r"(\d+)\.(\d+)\.?(\d*)", version_output)
if match:
major = int(match.group(1))
minor = int(match.group(2))
tiny = int(match.group(3) or "0")
git_branch_does_accept_tags = (major, minor, tiny) >= (1, 7, 10)
else:
git_branch_does_accept_tags = False
return git_branch_does_accept_tags
def git_clone_command(repo, ref, is_cache):
if is_cache:
# Cache full repos.
return ["git", "clone"], True
# Http(s) transport may be dumb and not understand --depth.
if repo.startswith("http://") or repo.startswith("https://"):
if not any(map(repo.startswith, clever_http_git_whitelist)):
return ["git", "clone"], True
# Have to clone whole repo to get a specific commit.
if all(c in string.hexdigits for c in ref):
return ["git", "clone"], True
if git_branch_accepts_tags():
return ["git", "clone", "--depth=1", "--branch=" + ref], False
else:
return ["git", "clone", "--depth=1"], True
important_identifiers = ["name", "source", "version", "repo", "commit", "location"]
other_identifiers = ["target", "compat", "c flags", "patched", "readline"]
def escape_path(s):
return re.sub(r"[^\w]", "_", s)
def hash_identifiers(identifiers):
return "-".join(escape_path(
identifiers.get(name, "")) for name in important_identifiers + other_identifiers)
def show_identifiers(identifiers):
title = identifiers["name"]
if "version" in identifiers:
title += " " + identifiers["version"]
elif "major version" in identifiers and title != "LuaJIT":
title += " " + identifiers["major version"]
if identifiers["source"] == "release":
print(title)
elif identifiers["source"] == "git":
print("{} @{} (cloned from {})".format(title, identifiers["commit"][:7], identifiers["repo"]))
else:
print("{} (from local sources)".format(title))
for name in other_identifiers:
if identifiers.get(name):
print(" {}: {}".format(name.capitalize(), identifiers[name]))
def copy_files(path, *files):
if not os.path.exists(path):
os.makedirs(path)
for src in files:
if src is not None:
shutil.copy(src, path)
def exe(name):
if os.name == "nt":
return name + ".exe"
else:
return name
def objext():
return ".obj" if using_cl() else ".o"
def sha256_of_file(filename):
with open(filename, "rb") as handler:
contents = handler.read()
return hashlib.sha256(contents).hexdigest()
def strip_extensions(filename):
if filename.endswith(".zip"):
return filename[:-len(".zip")]
elif filename.endswith(".tar.gz"):
return filename[:-len(".tar.gz")]
else:
return filename
class Program(object):
needs_git_dir_for_build = False
def __init__(self, version):
version = self.translations.get(version, version)
if version in self.versions:
# Simple version.
self.source = "release"
self.fetched = False
self.version = version
self.version_suffix = " " + version
elif "@" in version:
# Version from a git repo.
self.source = "git"
if version.startswith("@"):
# Use the default git repo for this program.
self.repo = self.default_repo
ref = version[1:] or "master"
else:
self.repo, _, ref = version.partition("@")
# Have to clone the repo to get the commit ref points to.
self.fetch_repo(ref)
self.commit = get_output("git", "rev-parse", "HEAD")
self.version_suffix = " @" + self.commit[:7]
else:
# Local directory.
self.source = "local"
if not os.path.exists(version):
sys.exit("Error: bad {} version {}".format(self.title, version))
print("Using {} from {}".format(self.title, version))
result_dir = os.path.join(temp_dir, self.name)
copy_dir(version, result_dir, ignore_git_dir=not self.needs_git_dir_for_build)
os.chdir(result_dir)
self.fetched = True
self.version_suffix = ""
def fetch_repo(self, ref):
message = "Cloning {} from {} @{}".format(self.title, self.repo, ref)
if self.repo == self.default_repo and not opts.no_git_cache and opts.downloads is not None:
# Default repos are cached.
if not os.path.exists(opts.downloads):
os.makedirs(opts.downloads)
repo_path = os.path.join(opts.downloads, self.name)
self.fetched = False
if os.path.exists(repo_path):
print(message + " (cached)")
# Sync with origin first.
os.chdir(repo_path)
if not get_output("git", "rev-parse", "--quiet", "--verify", ref):
run("git", "fetch")
run("git", "checkout", ref)
# If HEAD is not detached, we are on a branch that must be synced.
if get_output("git", "symbolic-ref", "-q", "HEAD"):
run("git", "pull", "--rebase")
return
else:
self.fetched = True
repo_path = os.path.join(temp_dir, self.name)
print(message)
clone_command, need_checkout = git_clone_command(self.repo, ref, not self.fetched)
run(clone_command, self.repo, repo_path)
os.chdir(repo_path)
if need_checkout and ref != "master":
run("git", "checkout", ref)
def fetch(self):
if self.fetched:
return
if self.source == "git":
# Currently inside the cached git repo, just copy it somewhere.
result_dir = os.path.join(temp_dir, self.name)
copy_dir(".", result_dir, ignore_git_dir=not self.needs_git_dir_for_build)
os.chdir(result_dir)
return
if opts.downloads is None:
archive_name = os.path.join(temp_dir, self.get_download_name())
else:
if not os.path.exists(opts.downloads):
os.makedirs(opts.downloads)
archive_name = os.path.join(opts.downloads, self.get_download_name())
if opts.downloads and os.path.exists(archive_name):
print("Fetching {}{} (cached)".format(self.title, self.version_suffix))
else:
for url in self.get_download_urls():
print("Fetching {}{} from {}".format(self.title, self.version_suffix, url))
try:
download(url, archive_name)
except URLError as error:
print("Download failed: {}".format(str(error.reason)))
else:
break
else:
sys.exit(1)
print("Verifying SHA256 checksum")
expected_checksum = self.checksums[self.get_download_name()]
observed_checksum = sha256_of_file(archive_name)
if expected_checksum != observed_checksum:
message = "SHA256 checksum mismatch for {}\nExpected: {}\nObserved: {}".format(
archive_name, expected_checksum, observed_checksum)
if opts.ignore_checksums:
print("Warning: " + message)
else:
sys.exit("Error: " + message)
if archive_name.endswith(".zip"):
archive = zipfile.ZipFile(archive_name)
else:
archive = tarfile.open(archive_name, "r:gz")
archive.extractall(temp_dir)
archive.close()
os.chdir(os.path.join(temp_dir, re.sub("-rc[0-9]*$", "", strip_extensions(self.get_download_name()))))
self.fetched = True
def set_identifiers(self):
self.identifiers = {
"name": self.title,
"source": self.source
}
if self.source == "release":
self.identifiers["version"] = self.version
elif self.source == "git":
self.identifiers["repo"] = self.repo
self.identifiers["commit"] = self.commit
def update_identifiers(self, all_identifiers):
self.all_identifiers = all_identifiers
installed_identifiers = all_identifiers.get(self.name)
self.set_identifiers()
if not opts.ignore_installed and self.source != "local" and installed_identifiers is not None:
if hash_identifiers(self.identifiers) == hash_identifiers(installed_identifiers):
print(self.title + self.version_suffix + " already installed")
return False
self.build()
self.install()
all_identifiers[self.name] = self.identifiers
return True
class Lua(Program):
def __init__(self, version):
super(Lua, self).__init__(version)
self.source_files_prefix = self.get_source_files_prefix()
if self.source == "release":
self.major_version = self.major_version_from_version()
else:
self.major_version = self.major_version_from_source()
if not self.version_suffix:
self.set_version_suffix()
self.set_compat()
self.add_options_to_version_suffix()
self.redefines = []
self.compat_cflags = []
self.set_package_paths()
self.add_package_paths_redefines()
self.add_compat_cflags_and_redefines()
@staticmethod
def get_source_files_prefix():
return "src"
def get_source_file_path(self, file_name):
if self.source_files_prefix is None:
return file_name
else:
return os.path.join(self.source_files_prefix, file_name)
@contextlib.contextmanager
def in_source_files_prefix(self):
if self.source_files_prefix is not None:
start_dir = os.getcwd()
os.chdir(self.source_files_prefix)
yield
if self.source_files_prefix is not None:
os.chdir(start_dir)
def major_version_from_source(self):
with open(self.get_source_file_path("lua.h")) as lua_h:
for line in lua_h:
match = re.match(r"^\s*#define\s+LUA_VERSION_NUM\s+50(\d)\s*$", line)
if match:
return "5." + match.group(1)
sys.exit("Error: couldn't infer Lua major version from lua.h")
def set_identifiers(self):
super(Lua, self).set_identifiers()
self.identifiers["target"] = opts.target
self.identifiers["compat"] = self.compat
self.identifiers["c flags"] = opts.cflags or ""
self.identifiers["location"] = opts.location
self.identifiers["major version"] = self.major_version
if using_cl():
cl_help = get_output("cl")
cl_version = re.search(r"(1[56789])\.\d+", cl_help)
cl_arch = re.search(r"(x(?:86)|(?:64))", cl_help)
if not cl_version or not cl_arch:
sys.exit("Error: couldn't determine cl.exe version and architecture")
cl_version = cl_version.group(1)
cl_arch = cl_arch.group(1)
self.identifiers["vs year"] = cl_version_to_vs_year[cl_version]
self.identifiers["vs arch"] = cl_arch
def add_options_to_version_suffix(self):
options = []
if os.name == "nt" or opts.target != get_default_lua_target():
options.append(("target", opts.target))
if self.compat != "default":
options.append(("compat", self.compat))
if opts.cflags is not None:
options.append(("cflags", opts.cflags))
if opts.no_readline:
options.append(("readline", "false"))
if options:
self.version_suffix += " (" + (", ".join(
opt + ": " + value for opt, value in options)) + ")"
def set_package_paths(self):
local_paths_first = self.major_version == "5.1"
module_path = os.path.join(opts.location, "share", "lua", self.major_version)
module_path_parts = [
os.path.join(module_path, "?.lua"),
os.path.join(module_path, "?", "init.lua")
]
module_path_parts.insert(0 if local_paths_first else 2, os.path.join(".", "?.lua"))
if self.major_version in ["5.3", "5.4"]:
module_path_parts.append(os.path.join(".", "?", "init.lua"))
self.package_path = ";".join(module_path_parts)
cmodule_path = os.path.join(opts.location, "lib", "lua", self.major_version)
so_extension = ".dll" if os.name == "nt" else ".so"
cmodule_path_parts = [
os.path.join(cmodule_path, "?" + so_extension),
os.path.join(cmodule_path, "loadall" + so_extension)
]
cmodule_path_parts.insert(0 if local_paths_first else 2,
os.path.join(".", "?" + so_extension))
self.package_cpath = ";".join(cmodule_path_parts)
def add_package_paths_redefines(self):
package_path = self.package_path.replace("\\", "\\\\").replace('"', '\\"')
package_cpath = self.package_cpath.replace("\\", "\\\\").replace('"', '\\"')
self.redefines.extend([
"#undef LUA_PATH_DEFAULT",
"#undef LUA_CPATH_DEFAULT",
"#define LUA_PATH_DEFAULT \"{}\"".format(package_path),
"#define LUA_CPATH_DEFAULT \"{}\"".format(package_cpath)
])
def patch_redefines(self):
luaconf_path = self.get_source_file_path("luaconf.h")
redefines = "\n".join(self.redefines)
with open(luaconf_path, "rb") as luaconf_h:
luaconf_src = luaconf_h.read()
body, _, tail = luaconf_src.rpartition(b"#endif")
with open(luaconf_path, "wb") as luaconf_h:
luaconf_h.write(body)
luaconf_h.write(redefines.encode("UTF-8"))
luaconf_h.write(b"\n#endif")
luaconf_h.write(tail)
def build(self):
if opts.builds and self.source != "local":
self.cached_build_path = os.path.join(opts.builds,
hash_identifiers(self.identifiers))
if os.path.exists(self.cached_build_path):
print("Building " + self.title + self.version_suffix + " (cached)")
os.chdir(self.cached_build_path)
return
else:
self.cached_build_path = None
self.fetch()
print("Building " + self.title + self.version_suffix)
self.patch_redefines()
self.make()
if self.cached_build_path is not None:
copy_dir(".", self.cached_build_path)
def install(self):
print("Installing " + self.title + self.version_suffix)
self.make_install()
class PatchError(Exception):
pass
class LineScanner(object):
def __init__(self, lines):
self.lines = lines
self.line_number = 1
def consume_line(self):
if self.line_number > len(self.lines):
raise PatchError("source is too short")
else:
self.line_number += 1
return self.lines[self.line_number - 2]
class Hunk(object):
def __init__(self, start_line, lines):
self.start_line = start_line
self.lines = lines
def add_new_lines(self, old_lines_scanner, new_lines):
while old_lines_scanner.line_number < self.start_line:
new_lines.append(old_lines_scanner.consume_line())
for line in self.lines:
first_char, rest = line[0], line[1:]
if first_char in " -":
# Deleting or copying a line: it must match what's in the diff.
if rest != old_lines_scanner.consume_line():
raise PatchError("source is different")
if first_char in " +":
# Adding or copying a line: add it to the line list.
new_lines.append(rest)
class FilePatch(object):
def __init__(self, file_name, lines):
self.file_name = file_name
self.hunks = []
self.new_lines = []
hunk_lines = None
start_line = None
for line in lines:
first_char = line[0]
if first_char == "@":
if start_line is not None:
self.hunks.append(Hunk(start_line, hunk_lines))
match = re.match(r"^@@ \-(\d+)", line)
start_line = int(match.group(1))
hunk_lines = []
else:
hunk_lines.append(line)
if start_line is not None:
self.hunks.append(Hunk(start_line, hunk_lines))
def prepare_application(self):
if not os.path.exists(self.file_name):
raise PatchError("{} doesn't exist".format(self.file_name))
with open(self.file_name, "r") as handler:
source = handler.read()
old_lines = source.splitlines()
old_lines_scanner = LineScanner(old_lines)
for hunk in self.hunks:
hunk.add_new_lines(old_lines_scanner, self.new_lines)
while old_lines_scanner.line_number <= len(old_lines):
self.new_lines.append(old_lines_scanner.consume_line())
self.new_lines.append("")
def apply(self):
with open(self.file_name, "wb") as handler:
handler.write("\n".join(self.new_lines).encode("UTF-8"))
class Patch(object):
def __init__(self, src):
# The first and the last lines are empty.
lines = textwrap.dedent(src[1:-1]).splitlines()
lines = [line if line else " " for line in lines]
self.file_patches = []
file_lines = None
file_name = None
for line in lines:
match = re.match(r"^([\w\.]+):$", line)
if match:
if file_name is not None:
self.file_patches.append(FilePatch(file_name, file_lines))
file_name = match.group(1)
file_lines = []
else:
file_lines.append(line)
if file_name is not None:
self.file_patches.append(FilePatch(file_name, file_lines))
def apply(self):
try:
for file_patch in self.file_patches:
file_patch.prepare_application()
except PatchError as e:
return e.args[0]
for file_patch in self.file_patches:
file_patch.apply()
class RioLua(Lua):
name = "lua"
title = "Lua"
base_download_urls = ["https://www.lua.org/ftp", "https://webserver2.tecgraf.puc-rio.br/lua/mirror/ftp"]
work_base_download_url = "https://www.lua.org/work"
default_repo = "https://github.com/lua/lua"
versions = [
"5.1", "5.1.1", "5.1.2", "5.1.3", "5.1.4", "5.1.5",
"5.2.0", "5.2.1", "5.2.2", "5.2.3", "5.2.4",
"5.3.0", "5.3.1", "5.3.2", "5.3.3", "5.3.4", "5.3.5", "5.3.6",
"5.4.0", "5.4.1", "5.4.2", "5.4.3", "5.4.4", "5.4.5", "5.4.6", "5.4.7"
]
translations = {
"5": "5.4.7",
"5.1": "5.1.5",
"5.1.0": "5.1",
"5.2": "5.2.4",
"5.3": "5.3.6",
"5.4": "5.4.7",
"^": "5.4.7",
"latest": "5.4.7"
}
checksums = {
"lua-5.1.tar.gz" : "7f5bb9061eb3b9ba1e406a5aa68001a66cb82bac95748839dc02dd10048472c1",
"lua-5.1.1.tar.gz" : "c5daeed0a75d8e4dd2328b7c7a69888247868154acbda69110e97d4a6e17d1f0",
"lua-5.1.2.tar.gz" : "5cf098c6fe68d3d2d9221904f1017ff0286e4a9cc166a1452a456df9b88b3d9e",
"lua-5.1.3.tar.gz" : "6b5df2edaa5e02bf1a2d85e1442b2e329493b30b0c0780f77199d24f087d296d",
"lua-5.1.4.tar.gz" : "b038e225eaf2a5b57c9bcc35cd13aa8c6c8288ef493d52970c9545074098af3a",
"lua-5.1.5.tar.gz" : "2640fc56a795f29d28ef15e13c34a47e223960b0240e8cb0a82d9b0738695333",
"lua-5.2.0.tar.gz" : "cabe379465aa8e388988073d59b69e76ba0025429d2c1da80821a252cdf6be0d",
"lua-5.2.1.tar.gz" : "64304da87976133196f9e4c15250b70f444467b6ed80d7cfd7b3b982b5177be5",
"lua-5.2.2.tar.gz" : "3fd67de3f5ed133bf312906082fa524545c6b9e1b952e8215ffbd27113f49f00",
"lua-5.2.3.tar.gz" : "13c2fb97961381f7d06d5b5cea55b743c163800896fd5c5e2356201d3619002d",
"lua-5.2.4.tar.gz" : "b9e2e4aad6789b3b63a056d442f7b39f0ecfca3ae0f1fc0ae4e9614401b69f4b",
"lua-5.3.0.tar.gz" : "ae4a5eb2d660515eb191bfe3e061f2b8ffe94dce73d32cfd0de090ddcc0ddb01",
"lua-5.3.1.tar.gz" : "072767aad6cc2e62044a66e8562f51770d941e972dc1e4068ba719cd8bffac17",
"lua-5.3.2.tar.gz" : "c740c7bb23a936944e1cc63b7c3c5351a8976d7867c5252c8854f7b2af9da68f",
"lua-5.3.3.tar.gz" : "5113c06884f7de453ce57702abaac1d618307f33f6789fa870e87a59d772aca2",
"lua-5.3.4.tar.gz" : "f681aa518233bc407e23acf0f5887c884f17436f000d453b2491a9f11a52400c",
"lua-5.3.5.tar.gz" : "0c2eed3f960446e1a3e4b9a1ca2f3ff893b6ce41942cf54d5dd59ab4b3b058ac",
"lua-5.3.6.tar.gz" : "fc5fd69bb8736323f026672b1b7235da613d7177e72558893a0bdcd320466d60",
"lua-5.4.0.tar.gz" : "eac0836eb7219e421a96b7ee3692b93f0629e4cdb0c788432e3d10ce9ed47e28",
"lua-5.4.1.tar.gz" : "4ba786c3705eb9db6567af29c91a01b81f1c0ac3124fdbf6cd94bdd9e53cca7d",
"lua-5.4.2.tar.gz" : "11570d97e9d7303c0a59567ed1ac7c648340cd0db10d5fd594c09223ef2f524f",
"lua-5.4.3.tar.gz" : "f8612276169e3bfcbcfb8f226195bfc6e466fe13042f1076cbde92b7ec96bbfb",
"lua-5.4.4.tar.gz" : "164c7849653b80ae67bec4b7473b884bf5cc8d2dca05653475ec2ed27b9ebf61",
"lua-5.4.5.tar.gz" : "59df426a3d50ea535a460a452315c4c0d4e1121ba72ff0bdde58c2ef31d6f444",
"lua-5.4.6.tar.gz" : "7d5ea1b9cb6aa0b59ca3dde1c6adcb57ef83a1ba8e5432c0ecd06bf439b3ad88",
"lua-5.4.7.tar.gz" : "9fbf5e28ef86c69858f6d3d34eccc32e911c1a28b4120ff3e84aaa70cfbf1e30",
}
all_patches = {
"When loading a file, Lua may call the reader function again after it returned end of input": """
lzio.h:
@@ -59,6 +59,7 @@
lua_Reader reader;
void* data;\t\t\t/* additional data */
lua_State *L;\t\t\t/* Lua state (for reader) */
+ int eoz;\t\t\t/* true if reader has no more data */
};
lzio.c:
@@ -22,10 +22,14 @@
size_t size;
lua_State *L = z->L;
const char *buff;
+ if (z->eoz) return EOZ;
lua_unlock(L);
buff = z->reader(L, z->data, &size);
lua_lock(L);
- if (buff == NULL || size == 0) return EOZ;
+ if (buff == NULL || size == 0) {
+ z->eoz = 1; /* avoid calling reader function next time */
+ return EOZ;
+ }
z->n = size - 1;
z->p = buff;
return char2int(*(z->p++));
@@ -51,6 +55,7 @@
z->data = data;
z->n = 0;
z->p = NULL;
+ z->eoz = 0;
}
""",
"Metatable may access its own deallocated field when it has a self reference in __newindex": """
lvm.c:
@@ -190,18 +190,19 @@
for (loop = 0; loop < MAXTAGLOOP; loop++) {
const TValue *tm;
if (oldval != NULL) {
- lua_assert(ttistable(t) && ttisnil(oldval));
+ Table *h = hvalue(t); /* save 't' table */
+ lua_assert(ttisnil(oldval));
/* must check the metamethod */
- if ((tm = fasttm(L, hvalue(t)->metatable, TM_NEWINDEX)) == NULL &&
+ if ((tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL &&
/* no metamethod; is there a previous entry in the table? */