-
Notifications
You must be signed in to change notification settings - Fork 27
/
zkg
executable file
·3056 lines (2470 loc) · 99.9 KB
/
zkg
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
# https://pypi.org/project/argcomplete/#global-completion
# PYTHON_ARGCOMPLETE_OK
import argparse
import configparser
import errno
import filecmp
import io
import json
import logging
import os
import shutil
import subprocess
import sys
import threading
from collections import OrderedDict
try:
import git
import semantic_version # noqa: F401
except ImportError as error:
print(
"error: zkg failed to import one or more dependencies:\n"
"\n"
"* GitPython: https://pypi.org/project/GitPython\n"
"* semantic-version: https://pypi.org/project/semantic-version\n"
"\n"
"If you use 'pip', they can be installed like:\n"
"\n"
" pip3 install GitPython semantic-version\n"
"\n"
"Also check the following exception output for possible alternate explanations:\n\n"
f"{type(error).__name__}: {error}",
file=sys.stderr,
)
sys.exit(1)
try:
# Argcomplete provides command-line completion for users of argparse.
# We support it if available, but don't complain when it isn't.
import argcomplete
except ImportError:
pass
# For Zeek-bundled installation, prepend the Python path of the Zeek
# installation. This ensures we find the matching zeekpkg module
# first, avoiding potential conflicts with installations elsewhere on
# the system.
ZEEK_PYTHON_DIR = "@PY_MOD_INSTALL_DIR@"
if os.path.isdir(ZEEK_PYTHON_DIR):
sys.path.insert(0, os.path.abspath(ZEEK_PYTHON_DIR))
else:
ZEEK_PYTHON_DIR = None
# Similarly, make Zeek's binary installation path available by
# default. This helps package installations succeed that require
# e.g. zeek-config for their build process.
ZEEK_BIN_DIR = "@ZEEK_BIN_DIR@"
if os.path.isdir(ZEEK_BIN_DIR):
try:
if ZEEK_BIN_DIR not in os.environ["PATH"].split(os.pathsep):
os.environ["PATH"] = ZEEK_BIN_DIR + os.pathsep + os.environ["PATH"]
except KeyError:
os.environ["PATH"] = ZEEK_BIN_DIR
else:
ZEEK_BIN_DIR = None
# Also when bundling with Zeek, use directories in the install tree
# for storing the zkg configuration and its variable state. Support
# for overrides via environment variables simplifies testing.
ZEEK_ZKG_CONFIG_DIR = os.getenv("ZEEK_ZKG_CONFIG_DIR") or "@ZEEK_ZKG_CONFIG_DIR@"
if not os.path.isdir(ZEEK_ZKG_CONFIG_DIR):
ZEEK_ZKG_CONFIG_DIR = None
ZEEK_ZKG_STATE_DIR = os.getenv("ZEEK_ZKG_STATE_DIR") or "@ZEEK_ZKG_STATE_DIR@"
if not os.path.isdir(ZEEK_ZKG_STATE_DIR):
ZEEK_ZKG_STATE_DIR = None
# The default package source we fall back to as needed
ZKG_DEFAULT_SOURCE = "https://github.com/zeek/packages"
# The default package template
ZKG_DEFAULT_TEMPLATE = "https://github.com/zeek/package-template"
import zeekpkg
from zeekpkg._util import (
delete_path,
find_program,
make_dir,
read_zeek_config_line,
std_encoding,
)
from zeekpkg.package import (
BUILTIN_SCHEME,
TRACKING_METHOD_VERSION,
)
from zeekpkg.template import (
LoadError,
Template,
)
from zeekpkg.uservar import (
UserVar,
)
def confirmation_prompt(prompt, default_to_yes=True):
yes = {"y", "ye", "yes"}
if default_to_yes:
prompt += " [Y/n] "
else:
prompt += " [N/y] "
choice = input(prompt).lower()
if not choice:
if default_to_yes:
return True
else:
print("Abort.")
return False
if choice in yes:
return True
print("Abort.")
return False
def prompt_for_user_vars(manager, config, configfile, args, pkg_infos):
answers = {}
for info in pkg_infos:
name = info.package.qualified_name()
requested_user_vars = info.user_vars()
if requested_user_vars is None:
print_error(f'error: malformed user_vars in "{name}"')
sys.exit(1)
for uvar in requested_user_vars:
try:
answers[uvar.name()] = uvar.resolve(
name,
config,
args.user_var,
args.force,
)
except ValueError:
print_error(
f'error: could not determine value of user variable "{uvar.name()}",'
" provide via environment or --user-var",
)
sys.exit(1)
if not args.force and answers:
for key, value in answers.items():
if not config.has_section("user_vars"):
config.add_section("user_vars")
config.set("user_vars", key, value)
if configfile:
with open(configfile, "w", encoding=std_encoding(sys.stdout)) as f:
config.write(f)
print(f"Saved answers to config file: {configfile}")
manager.user_vars = answers
def print_error(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def config_items(config, section):
# Same as config.items(section), but exclude default keys.
defaults = {key for key, _ in config.items("DEFAULT")}
items = sorted(config.items(section))
return [(key, value) for (key, value) in items if key not in defaults]
def file_is_not_empty(path):
return os.path.isfile(path) and os.path.getsize(path) > 0
def find_configfile(args):
if args.user:
configfile = os.path.join(home_config_dir(), "config")
if file_is_not_empty(configfile):
return configfile
return None
configfile = os.environ.get("ZKG_CONFIG_FILE")
if configfile and file_is_not_empty(configfile):
return configfile
configfile = os.path.join(default_config_dir(), "config")
if file_is_not_empty(configfile):
return configfile
return None
def home_config_dir():
return os.path.join(os.path.expanduser("~"), ".zkg")
def default_config_dir():
return ZEEK_ZKG_CONFIG_DIR or home_config_dir()
def default_state_dir():
return ZEEK_ZKG_STATE_DIR or home_config_dir()
def create_config(args, configfile):
config = configparser.ConfigParser()
if configfile:
if not os.path.isfile(configfile):
print_error(f'error: invalid config file "{configfile}"')
sys.exit(1)
config.read(configfile)
if not config.has_section("sources"):
config.add_section("sources")
if not config.has_section("paths"):
config.add_section("paths")
if not config.has_section("templates"):
config.add_section("templates")
if not configfile:
default = os.getenv("ZKG_DEFAULT_SOURCE", ZKG_DEFAULT_SOURCE)
if default:
config.set("sources", "zeek", default)
if not configfile or not config.has_option("templates", "default"):
default = os.getenv("ZKG_DEFAULT_TEMPLATE", ZKG_DEFAULT_TEMPLATE)
if default:
config.set("templates", "default", default)
def config_option_set(config, section, option):
return config.has_option(section, option) and config.get(section, option)
def get_option(config, section, option, default):
if config_option_set(config, section, option):
return config.get(section, option)
return default
if args.user:
def_state_dir = home_config_dir()
else:
def_state_dir = default_state_dir()
state_dir = get_option(config, "paths", "state_dir", os.path.join(def_state_dir))
script_dir = get_option(
config,
"paths",
"script_dir",
os.path.join(state_dir, "script_dir"),
)
plugin_dir = get_option(
config,
"paths",
"plugin_dir",
os.path.join(state_dir, "plugin_dir"),
)
bin_dir = get_option(config, "paths", "bin_dir", os.path.join(state_dir, "bin"))
zeek_dist = get_option(config, "paths", "zeek_dist", "")
config.set("paths", "state_dir", state_dir)
config.set("paths", "script_dir", script_dir)
config.set("paths", "plugin_dir", plugin_dir)
config.set("paths", "bin_dir", bin_dir)
config.set("paths", "zeek_dist", zeek_dist)
def expand_config_values(config, section):
for key, value in config.items(section):
value = os.path.expandvars(os.path.expanduser(value))
config.set(section, key, value)
expand_config_values(config, "sources")
expand_config_values(config, "paths")
expand_config_values(config, "templates")
for key, value in config.items("paths"):
if value and not os.path.isabs(value):
print_error(
"error: invalid config file value for key"
f' "{key}" in section [paths]: "{value}" is not'
" an absolute path",
)
sys.exit(1)
return config
def active_git_branch(path):
try:
repo = git.Repo(path)
except git.NoSuchPathError:
return None
if not repo.working_tree_dir:
return None
try:
rval = repo.active_branch
except TypeError:
# return detached commit
rval = repo.head.commit
if not rval:
return None
rval = str(rval)
return rval
def is_local_git_repo_url(git_url) -> bool:
return (
git_url.startswith(".") or git_url.startswith("/") or is_local_git_repo(git_url)
)
def is_local_git_repo(git_url):
try:
# The Repo class takes a file system path as first arg. This
# can fail in two ways: (1) the path doesn't exist or isn't
# accessible, (2) it's not the root directory of a git repo.
git.Repo(git_url)
return True
except (git.InvalidGitRepositoryError, git.NoSuchPathError):
return False
def is_local_git_repo_dirty(git_url):
if not is_local_git_repo(git_url):
return False
try:
repo = git.Repo(git_url)
except git.NoSuchPathError:
return False
return repo.is_dirty(untracked_files=True)
def check_local_git_repo(git_url):
if is_local_git_repo_url(git_url):
if not is_local_git_repo(git_url):
print_error(f"error: path {git_url} is not a git repository")
return False
if is_local_git_repo_dirty(git_url):
print_error(f"error: local git clone at {git_url} is dirty")
return False
return True
def create_manager(args, config):
state_dir = config.get("paths", "state_dir")
script_dir = config.get("paths", "script_dir")
plugin_dir = config.get("paths", "plugin_dir")
bin_dir = config.get("paths", "bin_dir")
zeek_dist = config.get("paths", "zeek_dist")
try:
manager = zeekpkg.Manager(
state_dir=state_dir,
script_dir=script_dir,
plugin_dir=plugin_dir,
bin_dir=bin_dir,
zeek_dist=zeek_dist,
)
except OSError as error:
if error.errno == errno.EACCES:
print_error(f"{type(error).__name__}: {error}")
def check_permission(d):
if os.access(d, os.W_OK):
return True
print_error(f"error: user does not have write access in {d}")
return False
permissions_trouble = not all(
[
check_permission(state_dir),
check_permission(script_dir),
check_permission(plugin_dir),
check_permission(bin_dir),
],
)
if permissions_trouble and not args.user:
print_error(
f"Consider the --user flag to manage zkg state via {home_config_dir()}/config",
)
sys.exit(1)
raise
extra_sources = []
for key_value in args.extra_source or []:
if "=" not in key_value:
print_error(f'warning: invalid extra source: "{key_value}"')
continue
key, value = key_value.split("=", 1)
if not key or not value:
print_error(f'warning: invalid extra source: "{key_value}"')
continue
extra_sources.append((key, value))
for key, value in extra_sources + config_items(config, "sources"):
error = manager.add_source(name=key, git_url=value)
if error:
print_error(
f'warning: skipped using package source named "{key}": {error}',
)
return manager
def get_changed_state(manager, saved_state, pkg_lst):
"""Returns the list of packages that have changed loaded state.
Args:
saved_state (dict): dictionary of saved load state for installed
packages.
pkg_lst (list): list of package names to be skipped
Returns:
dep_listing (str): string installed packages that have changed state
"""
_lst = [zeekpkg.package.name_from_path(_pkg_path) for _pkg_path in pkg_lst]
dep_listing = ""
for _pkg_name in sorted(manager.installed_package_dependencies()):
if _pkg_name in _lst:
continue
_ipkg = manager.find_installed_package(_pkg_name)
if not _ipkg or _ipkg.status.is_loaded == saved_state[_pkg_name]:
continue
dep_listing += f" {_pkg_name}\n"
return dep_listing
class InstallWorker(threading.Thread):
def __init__(self, manager, package_name, package_version):
super().__init__()
self.manager = manager
self.package_name = package_name
self.package_version = package_version
self.error = ""
def run(self):
self.error = self.manager.install(self.package_name, self.package_version)
def wait(self, msg=None, out=sys.stdout, tty_only=True):
"""Blocks until this thread ends, optionally writing liveness indicators.
This never returns until this thread dies (i.e., is_alive() is False).
When an output file object is provided, the method also indicates
progress by writing a dot character to it once per second. This happens
only when the file is a TTY, unless ``tty_only`` is False. When a
message is given, it gets written out first, regardless of TTY
status. Any output always terminates with a newline.
Args:
msg (str): a message to write first.
out (file-like object): the destination to write to.
tty_only (bool): whether to write progress dots also to non-TTYs.
"""
if out is not None and msg:
out.write(msg)
out.flush()
is_tty = hasattr(out, "isatty") and out.isatty()
while True:
self.join(1.0)
if not self.is_alive():
break
if out is not None and (is_tty or not tty_only):
out.write(".")
out.flush()
if out is not None and (msg or is_tty or not tty_only):
out.write("\n")
out.flush()
def cmd_test(manager, args, config, configfile):
if args.version and len(args.package) > 1:
print_error('error: "test --version" may only be used for a single package')
sys.exit(1)
package_infos = []
for name in args.package:
if not check_local_git_repo(name):
sys.exit(1)
# If the package to be tested is included with Zeek, don't allow
# to run tests due to the potential of conflicts.
bpkg_info = manager.find_builtin_package(name)
if bpkg_info is not None:
print_error(f'cannot run tests for "{name}": built-in package')
sys.exit(1)
version = args.version if args.version else active_git_branch(name)
package_info = manager.info(name, version=version, prefer_installed=False)
if package_info.invalid_reason:
print_error(
f'error: invalid package "{name}": {package_info.invalid_reason}',
)
sys.exit(1)
if not version:
version = package_info.best_version()
package_infos.append((package_info, version))
all_passed = True
for info, version in package_infos:
name = info.package.qualified_name()
if "test_command" not in info.metadata:
print(f"{name}: no test_command found in metadata, skipping")
continue
error_msg, passed, test_dir = manager.test(
name,
version,
test_dependencies=True,
)
if error_msg:
all_passed = False
print_error(f'error: failed to run tests for "{name}": {error_msg}')
continue
if passed:
print(f"{name}: all tests passed")
else:
all_passed = False
clone_dir = os.path.join(
os.path.join(test_dir, "clones"),
info.package.name,
)
print_error(
f'error: package "{name}" tests failed, inspect'
f" contents of {test_dir} for details, especially"
' any "zkg.test_command.{{stderr,stdout}}"'
f" files within {clone_dir}",
)
if not all_passed:
sys.exit(1)
def cmd_install(manager, args, config, configfile):
if args.version and len(args.package) > 1:
print_error('error: "install --version" may only be used for a single package')
sys.exit(1)
package_infos = []
for name in args.package:
if not check_local_git_repo(name):
sys.exit(1)
# Outright prevent installing a package that Zeek has built-in.
bpkg_info = manager.find_builtin_package(name)
if bpkg_info is not None:
print_error(f'cannot install "{name}": built-in package')
sys.exit(1)
version = args.version if args.version else active_git_branch(name)
package_info = manager.info(name, version=version, prefer_installed=False)
if package_info.invalid_reason:
print_error(
f'error: invalid package "{name}": {package_info.invalid_reason}',
)
sys.exit(1)
if not version:
version = package_info.best_version()
package_infos.append((package_info, version, False))
# We modify package_infos below, so copy current state to preserve list of
# packages requested by caller:
orig_pkgs, new_pkgs = package_infos.copy(), []
if not args.nodeps:
to_validate = [
(info.package.qualified_name(), version)
for info, version, _ in package_infos
]
invalid_reason, new_pkgs = manager.validate_dependencies(
to_validate,
ignore_suggestions=args.nosuggestions,
)
if invalid_reason:
print_error("error: failed to resolve dependencies:", invalid_reason)
sys.exit(1)
if not args.force:
package_listing = ""
for info, version, _ in sorted(package_infos, key=lambda x: x[0].package.name):
name = info.package.qualified_name()
package_listing += f" {name} ({version})\n"
print("The following packages will be INSTALLED:")
print(package_listing)
if new_pkgs:
dependency_listing = ""
for info, version, suggested in sorted(
new_pkgs,
key=lambda x: x[0].package.name,
):
name = info.package.qualified_name()
dependency_listing += f" {name} ({version})"
if suggested:
dependency_listing += " (suggested)"
dependency_listing += "\n"
print("The following dependencies will be INSTALLED:")
print(dependency_listing)
allpkgs = package_infos + new_pkgs
extdep_listing = ""
for info, version, _ in sorted(allpkgs, key=lambda x: x[0].package.name):
name = info.package.qualified_name()
extdeps = info.dependencies(field="external_depends")
if extdeps is None:
extdep_listing += f" from {name} ({version}):\n <malformed>\n"
continue
if extdeps:
extdep_listing += f" from {name} ({version}):\n"
for extdep, semver in sorted(extdeps.items()):
extdep_listing += f" {extdep} {semver}\n"
if extdep_listing:
print(
"Verify the following REQUIRED external dependencies:\n"
"(Ensure their installation on all relevant systems before"
" proceeding):",
)
print(extdep_listing)
if not confirmation_prompt("Proceed?"):
return
package_infos += new_pkgs
prompt_for_user_vars(
manager,
config,
configfile,
args,
[info for info, _, _ in package_infos],
)
if not args.skiptests:
# Iterate only over the requested packages here, skipping the
# dependencies. We ask the manager to include dependencies below.
for info, version, _ in orig_pkgs:
name = info.package.qualified_name()
if "test_command" not in info.metadata:
zeekpkg.LOG.info(
f'Skipping unit tests for "{name}": no test_command in metadata',
)
continue
print(f'Running unit tests for "{name}"')
error_msg = ""
# For testing we always process dependencies, since the tests might
# well fail without them. If the user wants --nodeps and the tests
# fail because of it, they'll also need to say --skiptests.
error, passed, test_dir = manager.test(
name,
version,
test_dependencies=True,
)
if error:
error_msg = f"failed to run tests for {name}: {error}"
elif not passed:
clone_dir = os.path.join(
os.path.join(test_dir, "clones"),
info.package.name,
)
error_msg = (
f'"{name}" tests failed, inspect contents of'
f" {test_dir} for details, especially any"
' "zkg.test_command.{{stderr,stdout}}"'
f" files within {clone_dir}"
)
if error_msg:
print_error(f"error: {error_msg}")
if args.force:
sys.exit(1)
if not confirmation_prompt(
"Proceed to install anyway?",
default_to_yes=False,
):
return
installs_failed = []
for info, version, _ in reversed(package_infos):
name = info.package.qualified_name()
is_overwriting = False
ipkg = manager.find_installed_package(name)
if ipkg:
is_overwriting = True
modifications = manager.modified_config_files(ipkg)
backup_files = manager.backup_modified_files(name, modifications)
prev_upstream_config_files = manager.save_temporary_config_files(ipkg)
worker = InstallWorker(manager, name, version)
worker.start()
worker.wait(f'Installing "{name}"')
if worker.error:
print(f'Failed installing "{name}": {worker.error}')
installs_failed.append((name, version))
continue
ipkg = manager.find_installed_package(name)
print(f'Installed "{name}" ({ipkg.status.current_version})')
if is_overwriting:
for i, mf in enumerate(modifications):
next_upstream_config_file = mf[1]
if not os.path.isfile(next_upstream_config_file):
print("\tConfig file no longer exists:")
print("\t\t" + next_upstream_config_file)
print("\tPrevious, locally modified version backed up to:")
print("\t\t" + backup_files[i])
continue
prev_upstream_config_file = prev_upstream_config_files[i][1]
if filecmp.cmp(prev_upstream_config_file, next_upstream_config_file):
# Safe to restore user's version
shutil.copy2(backup_files[i], next_upstream_config_file)
continue
print("\tConfig file has been overwritten with a different version:")
print("\t\t" + next_upstream_config_file)
print("\tPrevious, locally modified version backed up to:")
print("\t\t" + backup_files[i])
if manager.has_scripts(ipkg):
load_error = manager.load(name)
if load_error:
print(f'Failed loading "{name}": {load_error}')
else:
print(f'Loaded "{name}"')
if not args.nodeps:
# Now load runtime dependencies after all dependencies and suggested
# packages have been installed and loaded.
for info, _, _ in sorted(orig_pkgs, key=lambda x: x[0].package.name):
_listing, saved_state = "", manager.loaded_package_states()
name = info.package.qualified_name()
load_error = manager.load_with_dependencies(
zeekpkg.package.name_from_path(name),
)
for _name, _error in load_error:
if not _error:
_listing += f" {_name}\n"
if not _listing:
dep_listing = get_changed_state(manager, saved_state, [name])
if dep_listing:
print(
"The following installed packages were additionally "
"loaded to satisfy runtime dependencies",
)
print(dep_listing)
else:
print(
"The following installed packages could NOT be loaded "
f'to satisfy runtime dependencies for "{name}"',
)
print(_listing)
manager.restore_loaded_package_states(saved_state)
if installs_failed:
print_error(
"error: incomplete installation, the follow packages"
" failed to be installed:",
)
for n, v in installs_failed:
print_error(f" {n} ({v})")
sys.exit(1)
def cmd_bundle(manager, args, config, configfile):
packages_to_bundle = []
prefer_existing_clones = False
if args.manifest:
if len(args.manifest) == 1 and os.path.isfile(args.manifest[0]):
config = configparser.ConfigParser(delimiters="=")
config.optionxform = str
if config.read(args.manifest[0]) and config.has_section("bundle"):
packages = config.items("bundle")
else:
print_error(f'error: "{args.manifest[0]}" is not a valid manifest file')
sys.exit(1)
else:
packages = [(name, "") for name in args.manifest]
to_validate = []
new_pkgs = []
for name, version in packages:
if not check_local_git_repo(name):
sys.exit(1)
if not version:
version = active_git_branch(name)
info = manager.info(name, version=version, prefer_installed=False)
if info.invalid_reason:
print_error(f'error: invalid package "{name}": {info.invalid_reason}')
sys.exit(1)
if not version:
version = info.best_version()
to_validate.append((info.package.qualified_name(), version))
packages_to_bundle.append(
(
info.package.qualified_name(),
info.package.git_url,
version,
False,
False,
),
)
if not args.nodeps:
invalid_reason, new_pkgs = manager.validate_dependencies(
to_validate,
ignore_installed_packages=True,
ignore_suggestions=args.nosuggestions,
)
if invalid_reason:
print_error("error: failed to resolve dependencies:", invalid_reason)
sys.exit(1)
for info, version, suggested in new_pkgs:
packages_to_bundle.append(
(
info.package.qualified_name(),
info.package.git_url,
version,
True,
suggested,
),
)
else:
prefer_existing_clones = True
for ipkg in manager.installed_packages():
packages_to_bundle.append(
(
ipkg.package.qualified_name(),
ipkg.package.git_url,
ipkg.status.current_version,
False,
False,
),
)
if not packages_to_bundle:
print_error("error: no packages to put in bundle")
sys.exit(1)
if not args.force:
package_listing = ""
for name, git_url, version, is_dependency, is_suggestion in packages_to_bundle:
package_listing += f" {name} ({version})"
if is_suggestion:
package_listing += " (suggested)"
elif is_dependency:
package_listing += " (dependency)"
if git_url.startswith(BUILTIN_SCHEME):
package_listing += " (built-in)"
package_listing += "\n"
print(f"The following packages will be BUNDLED into {args.bundle_filename}:")
print(package_listing)
if not confirmation_prompt("Proceed?"):
return
git_urls = [(git_url, version) for _, git_url, version, _, _ in packages_to_bundle]
error = manager.bundle(
args.bundle_filename,
git_urls,
prefer_existing_clones=prefer_existing_clones,
)
if error:
print_error(f"error: failed to create bundle: {error}")
sys.exit(1)
print(f"Bundle successfully written: {args.bundle_filename}")
def cmd_unbundle(manager, args, config, configfile):
prev_load_status = {}
for ipkg in manager.installed_packages():
prev_load_status[ipkg.package.git_url] = ipkg.status.is_loaded
if args.replace:
cmd_purge(manager, args, config, configfile)
error, bundle_info = manager.bundle_info(args.bundle_filename)
if error:
print_error(f"error: failed to unbundle {args.bundle_filename}: {error}")
sys.exit(1)
for git_url, _, pkg_info in bundle_info:
if pkg_info.invalid_reason:
name = pkg_info.package.qualified_name()
print_error(
f"error: bundle {args.bundle_filename} contains invalid package {git_url} ({name}): {pkg_info.invalid_reason}",
)
sys.exit(1)
if not bundle_info: