-
Notifications
You must be signed in to change notification settings - Fork 198
/
autopkg
executable file
·2786 lines (2463 loc) · 97.1 KB
/
autopkg
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/local/autopkg/python
#
# Copyright 2013 Greg Neagle
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""autopkg tool. Runs autopkg recipes and also handles other
related tasks"""
import copy
import difflib
import glob
import hashlib
import os
import plistlib
import pprint
import shutil
import subprocess
import sys
import time
import traceback
from base64 import b64decode
from typing import Optional
from urllib.parse import quote, urlparse
import yaml
from autopkgcmd import common_parse, gen_common_parser, search_recipes
from autopkglib import (
RECIPE_EXTS,
AutoPackager,
AutoPackagerError,
PreferenceError,
core_processor_names,
extract_processor_name_with_recipe_identifier,
find_binary,
find_recipe_by_identifier,
get_all_prefs,
get_autopkg_version,
get_identifier,
get_pref,
get_processor,
is_mac,
log,
log_err,
plist_serializer,
processor_names,
recipe_from_file,
remove_recipe_extension,
set_pref,
version_equal_or_greater,
)
from autopkglib.autopkgyaml import autopkg_str_representer
from autopkglib.github import GitHubSession, print_gh_search_results
# Catch Python 2 wrappers with an early f-string. Message must be on a single line.
_ = f"""{sys.version_info.major} It looks like you're running the autopkg tool with an incompatible version of Python. Please update your script to use autopkg's included Python (/usr/local/autopkg/python). AutoPkgr users please note that AutoPkgr 1.5.1 and earlier is NOT compatible with autopkg 2. """ # noqa
# If any recipe fails during 'autopkg run', return this exit code
RECIPE_FAILED_CODE = 70
# Override global yaml state with our str representer
# See https://github.com/autopkg/autopkg/issues/768
yaml.add_representer(str, autopkg_str_representer)
# to use with safe_dump:
yaml.representer.SafeRepresenter.add_representer(str, autopkg_str_representer)
def print_version(argv):
"""Prints autopkg version"""
_ = argv[1]
print(get_autopkg_version())
def recipe_has_step_processor(recipe, processor):
"""Does the recipe object contain at least one step with the
named Processor?"""
if "Process" in recipe:
processors = [step.get("Processor") for step in recipe["Process"]]
if processor in processors:
return True
return False
def has_munkiimporter_step(recipe):
"""Does the recipe have a MunkiImporter step?"""
return recipe_has_step_processor(recipe, "MunkiImporter")
def has_check_phase(recipe):
"""Does the recipe have a "check" phase?"""
return recipe_has_step_processor(recipe, "EndOfCheckPhase")
def builds_a_package(recipe):
"""Does this recipe build any packages?"""
return recipe_has_step_processor(recipe, "PkgCreator")
def valid_recipe_dict_with_keys(recipe_dict, keys_to_verify):
"""Attempts to read a dict and ensures the keys in
keys_to_verify exist. Returns False on any failure, True otherwise."""
if recipe_dict:
for key in keys_to_verify:
if key not in recipe_dict:
return False
# if we get here, we found all the keys
return True
return False
def valid_recipe_dict(recipe_dict):
"""Returns True if recipe dict is a valid recipe,
otherwise returns False"""
return (
valid_recipe_dict_with_keys(recipe_dict, ["Input", "Process"])
or valid_recipe_dict_with_keys(recipe_dict, ["Input", "Recipe"])
or valid_recipe_dict_with_keys(recipe_dict, ["Input", "ParentRecipe"])
)
def valid_recipe_file(filename):
"""Returns True if filename contains a valid recipe,
otherwise returns False"""
recipe_dict = recipe_from_file(filename)
return valid_recipe_dict(recipe_dict)
def valid_override_dict(recipe_dict):
"""Returns True if the recipe is a valid override,
otherwise returns False"""
return valid_recipe_dict_with_keys(
recipe_dict, ["Input", "ParentRecipe"]
) or valid_recipe_dict_with_keys(recipe_dict, ["Input", "Recipe"])
def valid_override_file(filename):
"""Returns True if filename contains a valid override,
otherwise returns False"""
override_dict = recipe_from_file(filename)
return valid_override_dict(override_dict)
def find_recipe_by_name(name, search_dirs):
"""Search search_dirs for a recipe by file/directory naming rules"""
# drop extension from the end of the name because we're
# going to add it back on...
name = remove_recipe_extension(name)
# search by "Name", using file/directory hierarchy rules
for directory in search_dirs:
# TODO: Combine with similar code in get_recipe_list()
# and find_recipe_by_identifier()
normalized_dir = os.path.abspath(os.path.expanduser(directory))
patterns = [os.path.join(normalized_dir, f"{name}{ext}") for ext in RECIPE_EXTS]
patterns.extend(
[os.path.join(normalized_dir, f"*/{name}{ext}") for ext in RECIPE_EXTS]
)
for pattern in patterns:
matches = glob.glob(pattern)
for match in matches:
if valid_recipe_file(match):
return match
return None
def find_recipe(id_or_name, search_dirs):
"""find a recipe based on a string that might be an identifier
or a name"""
return find_recipe_by_identifier(id_or_name, search_dirs) or find_recipe_by_name(
id_or_name, search_dirs
)
def get_identifier_from_override(override):
"""Return the identifier from an override, falling back with a
warning to just the 'name' of the recipe."""
# prefer ParentRecipe
identifier = override.get("ParentRecipe")
if identifier:
return identifier
identifier = override["Recipe"].get("identifier")
if identifier:
return identifier
else:
name = override["Recipe"].get("name")
log_err(
"WARNING: Override contains no identifier. Will fall "
"back to matching it by name using search rules. It's "
"recommended to give the original recipe identifier "
"in the override's 'Recipes' dict to ensure the same "
"recipe is always used for this override."
)
return name
def get_repository_from_identifier(identifier: str):
"""Get a repository name from a recipe identifier."""
results = GitHubSession().search_for_name(identifier)
# so now we have a list of items containing file names and URLs
# we want to fetch these so we can look inside the contents for a matching
# identifier
# We just want to fetch the repos that contain these
# Is the name an identifier?
identifier_fragments = identifier.split(".")
if identifier_fragments[0] != "com":
# This is not an identifier
return
correct_item = None
for item in results:
file_contents_raw = do_gh_repo_contents_fetch(
item["repository"]["name"], item.get("path")
)
file_contents_data = plistlib.loads(file_contents_raw)
if file_contents_data.get("Identifier") == identifier:
correct_item = item
break
# Did we get correct item?
if not correct_item:
return
print(f"Found this recipe in repository: {correct_item['repository']['name']}")
return correct_item["repository"]["name"]
def locate_recipe(
name,
override_dirs,
recipe_dirs,
make_suggestions=True,
search_github=True,
auto_pull=False,
):
"""Locates a recipe by name. If the name is the pathname to a file on disk,
we attempt to load that file and use it as recipe. If a parent recipe
is required we first add the child recipe's directory to the search path
so that the parent can be found, assuming it is in the same directory.
Otherwise, we treat name as a recipe name or identifier and search first
the override directories, then the recipe directories for a matching
recipe."""
recipe_file = None
if os.path.isfile(name):
# name is path to a specific recipe or override file
# ignore override and recipe directories
# and attempt to open the file specified by name
if valid_recipe_file(name):
recipe_file = name
if not recipe_file:
# name wasn't a filename. Let's search our local repos.
recipe_file = find_recipe(name, override_dirs + recipe_dirs)
if not recipe_file and make_suggestions:
print(f"Didn't find a recipe for {name}.")
make_suggestions_for(name)
if not recipe_file and search_github:
indef_article = "a"
if name[0].lower() in ["a", "e", "i", "o", "u"]:
indef_article = "an"
if not auto_pull:
answer = input(
f"Search GitHub AutoPkg repos for {indef_article} {name} recipe? "
"[y/n]: "
)
else:
answer = "y"
if answer.lower().startswith("y"):
identifier_fragments = name.split(".")
repo_names = []
if identifier_fragments[0] == "com":
# Filter out "None" results if we don't find a matching recipe
parent_repo = get_repository_from_identifier(name)
repo_names = [parent_repo] if parent_repo else []
if not repo_names:
results_items = GitHubSession().search_for_name(name)
print_gh_search_results(results_items)
# make a list of unique repo names
repo_names = []
for item in results_items:
repo_name = item["repository"]["name"]
if repo_name not in repo_names:
repo_names.append(repo_name)
if len(repo_names) == 1:
# we found results in a single repo, so offer to add it
repo = repo_names[0]
if not auto_pull:
print()
answer = input(f"Add recipe repo '{repo}'? [y/n]: ")
else:
answer = "y"
if answer.lower().startswith("y"):
repo_add([None, "repo-add", repo])
# try once again to locate the recipe, but don't
# search GitHub again!
print()
recipe_dirs = get_search_dirs()
recipe_file = locate_recipe(
name,
override_dirs,
recipe_dirs,
make_suggestions=True,
search_github=False,
auto_pull=auto_pull,
)
elif len(repo_names) > 1:
print()
print("To add a new recipe repo, use 'autopkg repo-add " "<repo name>'")
return None
return recipe_file
def load_recipe(
name,
override_dirs,
recipe_dirs,
preprocessors=None,
postprocessors=None,
make_suggestions=True,
search_github=True,
auto_pull=False,
):
"""Loads a recipe, first locating it by name.
If we find one, we load it and return the dictionary object. If an
override file is used, it prefers finding the original recipe by
identifier rather than name, so that if recipe names shift with
updated recipe repos, the override still applies to the recipe from
which it was derived."""
if override_dirs is None:
override_dirs = []
if recipe_dirs is None:
recipe_dirs = []
recipe = None
recipe_file = locate_recipe(
name,
override_dirs,
recipe_dirs,
make_suggestions=make_suggestions,
search_github=search_github,
auto_pull=auto_pull,
)
if recipe_file:
# read it
recipe = recipe_from_file(recipe_file)
# store parent trust info, but only if this is an override
if recipe_in_override_dir(recipe_file, override_dirs):
parent_trust_info = recipe.get("ParentRecipeTrustInfo")
override_parent = recipe.get("ParentRecipe") or recipe.get("Recipe")
else:
parent_trust_info = None
# does it refer to another recipe?
if recipe.get("ParentRecipe") or recipe.get("Recipe"):
# save current recipe as a child
child_recipe = recipe
parent_id = get_identifier_from_override(recipe)
# add the recipe's directory to the search path
# so that we'll be able to locate the parent
recipe_dirs.append(os.path.dirname(recipe_file))
# load its parent, this time not looking in override directories
recipe = load_recipe(
parent_id,
[],
recipe_dirs,
make_suggestions=make_suggestions,
search_github=search_github,
auto_pull=auto_pull,
)
if recipe:
# merge child_recipe
recipe["Identifier"] = get_identifier(child_recipe)
recipe["Description"] = child_recipe.get(
"Description", recipe.get("Description", "")
)
for key in list(child_recipe["Input"].keys()):
recipe["Input"][key] = child_recipe["Input"][key]
# take the highest of the two MinimumVersion keys, if they exist
for candidate_recipe in [recipe, child_recipe]:
if "MinimumVersion" not in list(candidate_recipe.keys()):
candidate_recipe["MinimumVersion"] = "0"
if version_equal_or_greater(
child_recipe["MinimumVersion"], recipe["MinimumVersion"]
):
recipe["MinimumVersion"] = child_recipe["MinimumVersion"]
recipe["Process"].extend(child_recipe.get("Process", []))
if recipe.get("RECIPE_PATH"):
if "PARENT_RECIPES" not in recipe:
recipe["PARENT_RECIPES"] = []
recipe["PARENT_RECIPES"] = [recipe["RECIPE_PATH"]] + recipe[
"PARENT_RECIPES"
]
recipe["RECIPE_PATH"] = recipe_file
else:
# no parent recipe, so the current recipe is invalid
log_err(f"Could not find parent recipe for {name}")
else:
recipe["RECIPE_PATH"] = recipe_file
# re-add original stored parent trust info or remove it if it was picked
# up from a parent recipe
if recipe:
if parent_trust_info:
recipe["ParentRecipeTrustInfo"] = parent_trust_info
if override_parent:
recipe["ParentRecipe"] = override_parent
else:
log_err(f"No parent recipe specified for {name}")
elif "ParentRecipeTrustInfo" in recipe:
del recipe["ParentRecipeTrustInfo"]
if recipe:
# store the name the user used to locate this recipe
recipe["name"] = name
if recipe and preprocessors:
steps = []
for preprocessor_name in preprocessors:
steps.append({"Processor": preprocessor_name})
steps.extend(recipe["Process"])
recipe["Process"] = steps
if recipe and postprocessors:
steps = recipe["Process"]
for postprocessor_name in postprocessors:
steps.append({"Processor": postprocessor_name})
recipe["Process"] = steps
return recipe
def get_recipe_info(
recipe_name,
override_dirs,
recipe_dirs,
make_suggestions=True,
search_github=True,
auto_pull=False,
):
"""Loads a recipe, then prints some information about it. Override aware."""
recipe = load_recipe(
recipe_name,
override_dirs,
recipe_dirs,
make_suggestions=make_suggestions,
search_github=search_github,
auto_pull=auto_pull,
)
if recipe:
log(
"Description: {}".format(
"\n ".join(
recipe.get("Description", "").splitlines()
)
)
)
log(f"Identifier: {get_identifier(recipe)}")
log(f"Munki import recipe: {has_munkiimporter_step(recipe)}")
log(f"Has check phase: {has_check_phase(recipe)}")
log(f"Builds package: {builds_a_package(recipe)}")
log(f"Recipe file path: {recipe['RECIPE_PATH']}")
if recipe.get("PARENT_RECIPES"):
log(
"Parent recipe(s): {}".format(
"\n ".join(recipe["PARENT_RECIPES"])
)
)
log("Input values: ")
output = pprint.pformat(recipe.get("Input", {}), indent=4)
log(" " + output[1:-1])
return True
else:
log_err(f"No valid recipe found for {recipe_name}")
return False
def git_cmd():
"""Returns a path to a git binary, priority in the order below.
Returns None if none found.
1. app pref 'GIT_PATH'
2. a 'git' binary that can be found in the PATH environment variable
3. '/usr/bin/git'
"""
return find_binary("git")
class GitError(Exception):
"""Exception to throw if git fails"""
pass
def run_git(git_options_and_arguments, git_directory=None):
"""Run a git command and return its output if successful;
raise GitError if unsuccessful."""
gitcmd = git_cmd()
if not gitcmd:
raise GitError("ERROR: git is not installed!")
cmd = [gitcmd]
cmd.extend(git_options_and_arguments)
try:
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=git_directory,
text=True,
)
(cmd_out, cmd_err) = proc.communicate()
except OSError as err:
raise GitError from OSError(
f"ERROR: git execution failed with error code {err.errno}: "
f"{err.strerror}"
)
if proc.returncode != 0:
raise GitError(f"ERROR: {cmd_err}")
else:
return cmd_out
def get_recipe_repo(git_path):
"""git clone git_path to local disk and return local path"""
# figure out a local directory name to clone to
parts = urlparse(git_path)
domain_and_port = parts.netloc
# discard user name if any
if "@" in domain_and_port:
domain_and_port = domain_and_port.split("@", 1)[1]
# discard port if any
domain = domain_and_port.split(":")[0]
reverse_domain = ".".join(reversed(domain.split(".")))
# discard file extension if any
url_path = os.path.splitext(parts.path)[0]
dest_name = reverse_domain + url_path.replace("/", ".")
recipe_repo_dir = get_pref("RECIPE_REPO_DIR") or "~/Library/AutoPkg/RecipeRepos"
recipe_repo_dir = os.path.expanduser(recipe_repo_dir)
dest_dir = os.path.join(recipe_repo_dir, dest_name)
dest_dir = os.path.abspath(dest_dir)
gitcmd = git_cmd()
if not gitcmd:
log_err("No git binary could be found!")
return None
if os.path.exists(dest_dir):
# probably should attempt a git pull
# check to see if this is really a git repo first
if not os.path.isdir(os.path.join(dest_dir, ".git")):
log_err(f"{dest_dir} exists and is not a git repo!")
return None
log(f"Attempting git pull for {dest_dir}...")
try:
log(run_git(["pull"], git_directory=dest_dir))
return dest_dir
except GitError as err:
log_err(err)
return None
else:
log(f"Attempting git clone for {git_path}...")
try:
log(run_git(["clone", git_path, dest_dir]))
return dest_dir
except GitError as err:
log_err(err)
return None
return None
def write_plist_exit_on_fail(plist_dict, path):
"""Writes a dict to a new plist at path, exits the program
if the write fails."""
try:
with open(path, "wb") as f:
plistlib.dump(plist_serializer(plist_dict), f)
except (TypeError, OverflowError):
log_err(f"Failed to save plist to {path}.")
sys.exit(-1)
def print_tool_info(options):
"""Eventually will print some information about the tool
and environment. For now, just print the current prefs"""
_ = options
print("Current preferences:")
pprint.pprint(get_all_prefs())
def get_repo_info(path_or_url):
"""Given a path or URL, find a locally installed repo and return
infomation in a dictionary about it"""
repo_info = {}
recipe_repos = get_pref("RECIPE_REPOS") or {}
parsed = urlparse(path_or_url)
if parsed.netloc:
# it's a URL, look it up and find the associated path
repo_url = path_or_url
for repo_path in list(recipe_repos.keys()):
test_url = recipe_repos[repo_path].get("URL")
if repo_url == test_url:
# found it; copy the dict info
repo_info["path"] = repo_path
repo_info.update(recipe_repos[repo_path])
# get out now!
return repo_info
else:
repo_path = os.path.abspath(os.path.expanduser(path_or_url))
if repo_path in recipe_repos:
repo_info["path"] = repo_path
repo_info.update(recipe_repos[repo_path])
return repo_info
def save_pref_or_warn(key, value):
"""Saves a key and value to preferences, warning if there is an issue"""
try:
set_pref(key, value)
except PreferenceError as err:
log_err(f"WARNING: {err}")
def get_search_dirs():
"""Return search dirs from preferences or default list"""
default = [".", "~/Library/AutoPkg/Recipes", "/Library/AutoPkg/Recipes"]
dirs = get_pref("RECIPE_SEARCH_DIRS")
if isinstance(dirs, str):
# convert a string to a list
dirs = [dirs]
return dirs or default
def get_override_dirs():
"""Return override dirs from preferences or default list"""
default = ["~/Library/AutoPkg/RecipeOverrides"]
dirs = get_pref("RECIPE_OVERRIDE_DIRS")
if isinstance(dirs, str):
# convert a string to a list
dirs = [dirs]
return dirs or default
def add_search_and_override_dir_options(parser):
"""Several subcommands use these same options"""
parser.add_option(
"-d",
"--search-dir",
metavar="DIRECTORY",
dest="search_dirs",
action="append",
default=[],
help=("Directory to search for recipes. Can be specified " "multiple times."),
)
parser.add_option(
"--override-dir",
metavar="DIRECTORY",
dest="override_dirs",
action="append",
default=[],
help=(
"Directory to search for recipe overrides. Can be "
"specified multiple times."
),
)
########################
# subcommand functions #
########################
def expand_repo_url(url):
"""Given a GitHub repo URL-ish name, returns a full GitHub URL. Falls
back to the 'autopkg' GitHub org, and full non-GitHub URLs return
unmodified.
Examples:
'user/reciperepo' -> 'https://github.com/user/reciperepo'
'reciperepo' -> 'https://github.com/autopkg/reciperepo'
'http://some/repo/url -> 'http://some/repo/url'
'git@server:repo/url -> 'ssh://git@server/repo/url'
'/some/path -> '/some/path'
'~/some/path -> '~/some/path'
"""
# Strip trailing slashes
url = url.rstrip("/")
# Parse URL to determine scheme
parsed_url = urlparse(url)
if url.startswith(("/", "~")):
# If the URL looks like a file path, return as is.
pass
elif not parsed_url.scheme:
if ":" in parsed_url.path and (
"/" not in parsed_url.path
or parsed_url.path.find(":") < parsed_url.path.find("/")
):
# If no URL scheme was given check for scp-like syntax, where there is
# no slash before the first colon and convert this to a valid ssh url
url = url.replace(":", "/", 1)
url = f"ssh://{url}"
# If no URL scheme was given in the URL, try GitHub URLs
elif "/" in url:
# If URL looks like 'name/repo' then prepend the base GitHub URL
url = f"https://github.com/{url}"
else:
# Assume it's a repo within the 'autopkg' org
url = f"https://github.com/autopkg/{url}"
return url
def repo_add(argv):
"""Add/update one or more repos of recipes"""
verb = argv[1]
parser = gen_common_parser()
parser.set_usage(
f"""Usage: %prog {verb} recipe_repo_url
Download one or more new recipe repos and add it to the search path.
The 'recipe_repo_url' argument can be of the following forms:
- repo (implies 'https://github.com/autopkg/repo')
- user/repo (implies 'https://github.com/user/repo')
- (http[s]://|git://|ssh://|user@server:)path/to/any/git/repo
Example: '%prog repo-add recipes'
..adds the autopkg/recipes repo from GitHub."""
)
# Parse arguments
arguments = common_parse(parser, argv)[1]
if len(arguments) < 1:
log_err("Need at least one recipe repo URL!")
return -1
recipe_search_dirs = get_search_dirs()
recipe_repos = get_pref("RECIPE_REPOS") or {}
for repo_url in arguments:
if "file://" in repo_url:
log_err(
"AutoPkg does not handle file:// URIs; "
"add to your local Recipes folder instead."
)
continue
repo_url = expand_repo_url(repo_url)
new_recipe_repo_dir = get_recipe_repo(repo_url)
if new_recipe_repo_dir:
if new_recipe_repo_dir not in recipe_search_dirs:
log(f"Adding {new_recipe_repo_dir} to RECIPE_SEARCH_DIRS...")
recipe_search_dirs.append(new_recipe_repo_dir)
# add info about this repo to our prefs
recipe_repos[new_recipe_repo_dir] = {"URL": repo_url}
# save our updated RECIPE_REPOS and RECIPE_SEARCH_DIRS
save_pref_or_warn("RECIPE_REPOS", recipe_repos)
save_pref_or_warn("RECIPE_SEARCH_DIRS", recipe_search_dirs)
log("Updated search path:")
for search_dir in get_pref("RECIPE_SEARCH_DIRS"):
log(f" '{search_dir}'")
def repo_delete(argv):
"""Delete a recipe repo"""
verb = argv[1]
parser = gen_common_parser()
parser.set_usage(
f"Usage: %prog {verb} recipe_repo_path_or_url [...]\n"
"Delete one or more recipe repo and remove it from the search "
"path."
)
# Parse arguments
arguments = common_parse(parser, argv)[1]
if len(arguments) < 1:
log_err("Need at least one recipe repo path or URL!")
return -1
recipe_repos = get_pref("RECIPE_REPOS") or {}
recipe_search_dirs = get_search_dirs()
for path_or_url in arguments:
path_or_url = expand_repo_url(path_or_url)
repo_path = get_repo_info(path_or_url).get("path")
if not repo_path:
log_err(f"ERROR: Can't find an installed repo for {path_or_url}")
continue
else:
log(f"Removing repo at {repo_path}...")
# first, remove from RECIPE_SEARCH_DIRS
if repo_path in recipe_search_dirs:
recipe_search_dirs.remove(repo_path)
# now remove the repo files
try:
shutil.rmtree(repo_path)
except OSError as err:
log_err(f"ERROR: Could not remove {repo_path}: {err}")
else:
# last, remove from RECIPE_REPOS
del recipe_repos[repo_path]
# save our updated RECIPE_REPOS and RECIPE_SEARCH_DIRS
save_pref_or_warn("RECIPE_REPOS", recipe_repos)
save_pref_or_warn("RECIPE_SEARCH_DIRS", recipe_search_dirs)
def repo_list(argv):
"""List recipe repos"""
verb = argv[1]
parser = gen_common_parser()
parser.set_usage(f"Usage: %prog {verb}\n" "List all installed recipe repos.")
_options, _arguments = common_parse(parser, argv)
recipe_repos = get_pref("RECIPE_REPOS") or {}
if recipe_repos:
for key in sorted(recipe_repos.keys()):
print(f"{key} ({recipe_repos[key]['URL']})")
print()
else:
print("No recipe repos.")
def repo_update(argv):
"""Update one or more recipe repos"""
verb = argv[1]
parser = gen_common_parser()
parser.set_usage(
f"Usage: %prog {verb} recipe_repo_path_or_url [...]\n"
"Update one or more recipe repos.\n"
"You may also use 'all' to update all installed recipe "
"repos."
)
# Parse arguments
arguments = common_parse(parser, argv)[1]
if len(arguments) < 1:
log_err("Need at least one recipe repo path or URL!")
return -1
if "all" in arguments:
# just get all repos
recipe_repos = get_pref("RECIPE_REPOS") or {}
repo_dirs = [key for key in list(recipe_repos.keys())]
else:
repo_dirs = []
for path_or_url in arguments:
path_or_url = expand_repo_url(path_or_url)
repo_path = get_repo_info(path_or_url).get("path")
if not repo_path:
log_err(f"ERROR: Can't find an installed repo for {path_or_url}")
else:
repo_dirs.append(repo_path)
for repo_dir in repo_dirs:
# resolve ~ and symlinks before passing to git
repo_dir = os.path.abspath(os.path.expanduser(repo_dir))
log(f"Attempting git pull for {repo_dir}...")
try:
log(run_git(["pull"], git_directory=repo_dir))
except GitError as err:
log_err(err)
def do_gh_repo_contents_fetch(
repo: str, path: str, use_token=False, decode=True
) -> Optional[bytes]:
"""Fetch file contents from GitHub and return as a string."""
gh_session = GitHubSession()
if use_token:
gh_session.setup_token()
# Do the search, including text match metadata
(results, code) = gh_session.call_api(
f"/repos/autopkg/{repo}/contents/{quote(path)}"
)
if code == 403:
log_err(
"You've probably hit the GitHub's search rate limit, officially 5 "
"requests per minute.\n"
)
if results:
log_err("Server response follows:\n")
log_err(results.get("message", None))
log_err(results.get("documentation_url", None))
return None
if results is None or code is None:
log_err("A GitHub API error occurred!")
return None
if decode:
return b64decode(results["content"])
return results["content"]
def display_help(argv, subcommands):
"""Display top-level help"""
main_command_name = os.path.basename(argv[0])
print(
f"Usage: {main_command_name} <verb> <options>, where <verb> is one of "
"the following:"
)
print()
# find length of longest subcommand
max_key_len = max([len(key) for key in list(subcommands.keys())])
for key in sorted(subcommands.keys()):
# pad name of subcommand to make pretty columns
subcommand = key + (" " * (max_key_len - len(key)))
print(f" {subcommand} ({subcommands[key]['help']})")
print()
if len(argv) > 1 and argv[1] not in subcommands:
print(f"Error: unknown verb: {argv[1]}")
else:
print(f"{main_command_name} <verb> --help for more help for that verb")
def get_info(argv):
"""Display info about configuration or a recipe"""
verb = argv[1]
parser = gen_common_parser()
parser.set_usage(f"Usage: {'%prog'} {verb} [options] [recipe]")
# Parse arguments
add_search_and_override_dir_options(parser)
parser.add_option(
"-q",
"--quiet",
action="store_true",
help=("Don't offer to search Github if a recipe can't be found."),
)
parser.add_option(
"-p",
"--pull",
action="store_true",
help=(
"Pull the parent repos if they can't be found in the search path. "
"Implies agreement to search GitHub."
),
)
(options, arguments) = common_parse(parser, argv)
override_dirs = options.override_dirs or get_override_dirs()
search_dirs = options.search_dirs or get_search_dirs()
make_suggestions = True
if options.quiet:
# don't make suggestions if we want to be quiet
make_suggestions = False
if len(arguments) == 0:
# return configuration info
print_tool_info(options)
return 0
elif len(arguments) == 1:
if get_recipe_info(
arguments[0],
override_dirs,
search_dirs,
make_suggestions=make_suggestions,
search_github=make_suggestions,
auto_pull=options.pull,
):
return 0
else:
return -1
else:
log_err("Too many recipes!")
return -1
def processor_info(argv):
"""Display info about a processor"""
def print_vars(var_dict, indent=0):
"""Print a dict of dicts and strings"""
for key, value in list(var_dict.items()):
if isinstance(value, dict):
print(" " * indent, f"{key}:")
print_vars(value, indent=indent + 2)
else:
print(" " * indent, f"{key}: {value}")
verb = argv[1]
parser = gen_common_parser()
parser.set_usage(f"Usage: {'%prog'} {verb} [options] processorname")
parser.add_option(
"-r", "--recipe", metavar="RECIPE", help="Name of recipe using the processor."