/
commandline.py
10077 lines (8819 loc) · 433 KB
/
commandline.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
# Copyright (C) 2006 Novell Inc. All rights reserved.
# This program is free software; it may be used, copied, modified
# and distributed under the terms of the GNU General Public Licence,
# either version 2, or version 3 (at your option).
import argparse
import getpass
import glob
import importlib
import importlib.util
import inspect
import os
import pkgutil
import re
import subprocess
import sys
import textwrap
import tempfile
import time
import traceback
from functools import cmp_to_key
from operator import itemgetter
from pathlib import Path
from typing import List
from urllib.parse import urlsplit
from urllib.error import HTTPError
from . import _private
from . import build as osc_build
from . import cmdln
from . import commands as osc_commands
from . import conf
from . import git_scm
from . import oscerr
from . import store as osc_store
from .core import *
from .grabber import OscFileGrabber
from .meter import create_text_meter
from .util import cpio, rpmquery, safewriter
from .util.helper import _html_escape, format_table
class Command:
#: Name of the command as used in the argument parser.
name: str = None
#: Optional aliases to the command.
aliases: List[str] = []
#: Whether the command is hidden from help.
#: Defaults to ``False``.
hidden: bool = False
#: Name of the parent command class.
#: Can be prefixed if the parent comes from a different location,
#: for example ``osc.commands.<ClassName>`` when extending osc command with a plugin.
#: See ``OscMainCommand.MODULES`` for available prefixes.
parent: str = None
def __init__(self, full_name, parent=None):
self.full_name = full_name
self.parent = parent
self.subparsers = None
if not self.name:
raise ValueError(f"Command '{self.full_name}' has no 'name' set")
if parent:
self.parser = self.parent.subparsers.add_parser(
self.name,
aliases=self.aliases,
help=self.get_help(),
description=self.get_description(),
formatter_class=cmdln.HelpFormatter,
conflict_handler="resolve",
prog=f"{self.main_command.name} [global opts] {self.name}",
)
self.parser.set_defaults(_selected_command=self)
else:
self.parser = argparse.ArgumentParser(
prog=self.name,
description=self.get_description(),
formatter_class=cmdln.HelpFormatter,
usage="%(prog)s [global opts] <command> [--help] [opts] [args]",
)
# traverse the parent commands and add their options to the current command
commands = []
cmd = self
while cmd:
commands.append(cmd)
cmd = cmd.parent
# iterating backwards to give the command's options a priority over parent/global options
for cmd in reversed(commands):
cmd.init_arguments()
def __repr__(self):
return f"<osc plugin {self.full_name} at {self.__hash__():#x}>"
def get_help(self):
"""
Return the help text of the command.
The first line of the docstring is returned by default.
"""
if self.hidden:
return argparse.SUPPRESS
if not self.__doc__:
return ""
help_lines = self.__doc__.strip().splitlines()
if not help_lines:
return ""
return help_lines[0]
def get_description(self):
"""
Return the description of the command.
The docstring without the first line is returned by default.
"""
if not self.__doc__:
return ""
help_lines = self.__doc__.strip().splitlines()
if not help_lines:
return ""
# skip the first line that contains help text
help_lines.pop(0)
# remove any leading empty lines
while help_lines and not help_lines[0]:
help_lines.pop(0)
result = "\n".join(help_lines)
result = textwrap.dedent(result)
return result
@property
def main_command(self):
"""
Return reference to the main command that represents the executable
and contains the main instance of ArgumentParser.
"""
if not self.parent:
return self
return self.parent.main_command
def add_argument(self, *args, **kwargs):
"""
Add a new argument to the command's argument parser.
See `argparse <https://docs.python.org/3/library/argparse.html>`_ documentation for allowed parameters.
"""
cmd = self
# Let's inspect if the caller was init_arguments() method.
# In such case use the "parser" argument if specified.
frame_1 = inspect.currentframe().f_back
frame_1_info = inspect.getframeinfo(frame_1)
frame_2 = frame_1.f_back
frame_2_info = inspect.getframeinfo(frame_2)
if (frame_1_info.function, frame_2_info.function) == ("init_arguments", "__init__"):
# this method was called from init_arguments() that was called from __init__
# let's extract the command class from the 2nd frame and ad arguments there
cmd = frame_2.f_locals["self"]
# suppress global options from command help
if cmd != self and not self.parent:
kwargs["help"] = argparse.SUPPRESS
# We're adding hidden options from parent commands to their subcommands to allow
# option intermixing. For all such added hidden options we need to suppress their
# defaults because they would override any option set in the parent command.
if cmd != self:
kwargs["default"] = argparse.SUPPRESS
cmd.parser.add_argument(*args, **kwargs)
def init_arguments(self):
"""
Override to add arguments to the argument parser.
.. note::
Make sure you're adding arguments only by calling ``self.add_argument()``.
Using ``self.parser.add_argument()`` directly is not recommended
because it disables argument intermixing.
"""
def run(self, args):
"""
Override to implement the command functionality.
.. note::
``args.positional_args`` is a list containing any unknown (unparsed) positional arguments.
.. note::
Consider moving any reusable code into a library,
leaving the command-line code only a thin wrapper on top of it.
If the code is generic enough, it should be added to osc directly.
In such case don't hesitate to open an `issue <https://github.com/openSUSE/osc/issues>`_.
"""
raise NotImplementedError()
def register(self, command_class, command_full_name):
if not self.subparsers:
# instantiate subparsers on first use
self.subparsers = self.parser.add_subparsers(dest="command", title="commands")
# Check for parser conflicts.
# This is how Python 3.11+ behaves by default.
if command_class.name in self.subparsers._name_parser_map:
raise argparse.ArgumentError(self.subparsers, f"conflicting subparser: {command_class.name}")
for alias in command_class.aliases:
if alias in self.subparsers._name_parser_map:
raise argparse.ArgumentError(self.subparsers, f"conflicting subparser alias: {alias}")
command = command_class(command_full_name, parent=self)
return command
class MainCommand(Command):
MODULES = ()
def __init__(self):
super().__init__(self.__class__.__name__)
self.command_classes = {}
self.download_progress = None
def post_parse_args(self, args):
pass
def run(self, args):
cmd = getattr(args, "_selected_command", None)
if not cmd:
self.parser.error("Please specify a command")
self.post_parse_args(args)
cmd.run(args)
def load_command(self, cls, module_prefix):
mod_cls_name = f"{module_prefix}.{cls.__name__}"
parent_name = getattr(cls, "parent", None)
if parent_name:
# allow relative references to classes in the the same module/directory
if "." not in parent_name:
parent_name = f"{module_prefix}.{parent_name}"
try:
parent = self.main_command.command_classes[parent_name]
except KeyError:
msg = f"Failed to load command class '{mod_cls_name}' because it references parent '{parent_name}' that doesn't exist"
print(msg, file=sys.stderr)
return None
cmd = parent.register(cls, mod_cls_name)
else:
cmd = self.main_command.register(cls, mod_cls_name)
cmd.full_name = mod_cls_name
self.main_command.command_classes[mod_cls_name] = cmd
return cmd
def load_commands(self):
for module_prefix, module_path in self.MODULES:
module_path = os.path.expanduser(module_path)
# some plugins have their modules installed next to them instead of site-packages
if module_path not in sys.path:
sys.path.append(module_path)
for loader, module_name, _ in pkgutil.iter_modules(path=[module_path]):
full_name = f"{module_prefix}.{module_name}"
spec = loader.find_spec(full_name)
mod = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(mod)
except Exception as e: # pylint: disable=broad-except
msg = f"Failed to load commands from module '{full_name}': {e}"
print(msg, file=sys.stderr)
continue
for name in dir(mod):
if name.startswith("_"):
continue
cls = getattr(mod, name)
if not inspect.isclass(cls):
continue
if not issubclass(cls, Command):
continue
if cls.__module__ != full_name:
# skip classes that weren't defined directly in the loaded plugin module
continue
self.load_command(cls, module_prefix)
def parse_args(self, *args, **kwargs):
namespace, unknown_args = self.parser.parse_known_args(*args, **kwargs)
unrecognized = [i for i in unknown_args if i.startswith("-")]
if unrecognized:
self.parser.error(f"unrecognized arguments: " + " ".join(unrecognized))
namespace.positional_args = list(unknown_args)
return namespace
class OscCommand(Command):
"""
Inherit from this class to create new commands.
The first line of the docstring becomes the help text,
the remaining lines become the command description.
"""
class OscMainCommand(MainCommand):
name = "osc"
MODULES = (
("osc.commands", osc_commands.__path__[0]),
("osc.commands.usr_lib", "/usr/lib/osc-plugins"),
("osc.commands.usr_local_lib", "/usr/local/lib/osc-plugins"),
("osc.commands.home_local_lib", "~/.local/lib/osc-plugins"),
("osc.commands.home", "~/.osc-plugins"),
)
def __init__(self):
super().__init__()
self.args = None
self.download_progress = None
def init_arguments(self):
self.add_argument(
"-v",
"--verbose",
action="store_true",
help="increase verbosity",
)
self.add_argument(
"-q",
"--quiet",
action="store_true",
help="be quiet, not verbose",
)
self.add_argument(
"--debug",
action="store_true",
help="print info useful for debugging",
)
self.add_argument(
"--debugger",
action="store_true",
help="jump into the debugger before executing anything",
)
self.add_argument(
"--post-mortem",
action="store_true",
help="jump into the debugger in case of errors",
)
self.add_argument(
"--traceback",
action="store_true",
help="print call trace in case of errors",
)
self.add_argument(
"-H",
"--http-debug",
action="store_true",
help="debug HTTP traffic (filters some headers)",
)
self.add_argument(
"--http-full-debug",
action="store_true",
help="debug HTTP traffic (filters no headers)",
)
self.add_argument(
"-A",
"--apiurl",
metavar="URL",
help="Open Build Service API URL or a configured alias",
)
self.add_argument(
"--config",
dest="conffile",
metavar="FILE",
help="specify alternate configuration file",
)
self.add_argument(
"--setopt",
metavar="KEY=VALUE",
action="append",
default=[],
help="set a config option for the current program run",
)
self.add_argument(
"--no-keyring",
action="store_true",
help="disable usage of desktop keyring system",
)
def post_parse_args(self, args):
# apiurl hasn't been specified by the user
# we need to set it here because the 'default' option of an argument doesn't support lazy evaluation
if args.apiurl is None:
try:
# try reading the apiurl from the working copy
args.apiurl = osc_store.Store(Path.cwd()).apiurl
except oscerr.NoWorkingCopy:
# we can't use conf.config["apiurl"] because it contains the default "https://api.opensuse.org"
# let's leave setting the right value to conf.get_config()
pass
overrides = {}
for i in args.setopt:
key, value = i.split("=")
overrides[key] = value
try:
conf.get_config(
override_apiurl=args.apiurl,
override_conffile=args.conffile,
override_debug=args.debug,
override_http_debug=args.http_debug,
override_http_full_debug=args.http_full_debug,
override_no_keyring=args.no_keyring,
override_post_mortem=args.post_mortem,
override_traceback=args.traceback,
override_verbose=args.verbose,
overrides=overrides,
)
except oscerr.NoConfigfile as e:
print(e.msg, file=sys.stderr)
print(f"Creating osc configuration file {e.file} ...", file=sys.stderr)
conf.interactive_config_setup(e.file, args.apiurl)
print("done", file=sys.stderr)
self.post_parse_args(args)
except oscerr.ConfigMissingApiurl as e:
print(e.msg, file=sys.stderr)
conf.interactive_config_setup(e.file, e.url, initial=False)
self.post_parse_args(args)
except oscerr.ConfigMissingCredentialsError as e:
print(e.msg, file=sys.stderr)
print("Please enter new credentials.", file=sys.stderr)
conf.interactive_config_setup(e.file, e.url, initial=False)
self.post_parse_args(args)
# write config values back to args
# this is crucial mainly for apiurl to resolve an alias to full url
for i in ["apiurl", "debug", "http_debug", "http_full_debug", "post_mortem", "traceback", "verbose"]:
setattr(args, i, conf.config[i])
args.no_keyring = not conf.config["use_keyring"]
if conf.config["show_download_progress"]:
self.download_progress = create_text_meter()
if not args.apiurl:
self.parser.error("Could not determine apiurl, use -A/--apiurl to specify one")
# needed for LegacyOsc class
self.args = args
def _wrap_legacy_command(self, func_):
class LegacyCommandWrapper(Command):
func = func_
__doc__ = getattr(func_, "__doc__", "")
aliases = getattr(func_, "aliases", [])
hidden = getattr(func_, "hidden", False)
name = getattr(func_, "name", func_.__name__[3:])
def __repr__(self):
result = super().__repr__()
result += f"({self.func.__name__})"
return result
def init_arguments(self):
options = getattr(self.func, "options", [])
for option_args, option_kwargs in options:
self.add_argument(*option_args, **option_kwargs)
def run(self, args):
sig = inspect.signature(self.func)
arg_names = list(sig.parameters.keys())
if arg_names == ["subcmd", "opts"]:
# handler doesn't take positional args via *args
if args.positional_args:
self.parser.error(f"unrecognized arguments: " + " ".join(args.positional_args))
self.func(args.command, args)
else:
# handler takes positional args via *args
self.func(args.command, args, *args.positional_args)
return LegacyCommandWrapper
def load_legacy_commands(self):
# lazy links of attributes that would normally be initialized in the instance of Osc class
class LegacyOsc(Osc): # pylint: disable=used-before-assignment
# pylint: disable=no-self-argument
@property
def argparser(self_):
return self.parser
# pylint: disable=no-self-argument
@property
def download_progress(self_):
return self.download_progress
# pylint: disable=no-self-argument
@property
def options(self_):
return self.args
# pylint: disable=no-self-argument
@options.setter
def options(self_, value):
pass
# pylint: disable=no-self-argument
@property
def subparsers(self_):
return self.subparsers
osc_instance = LegacyOsc()
for name in dir(osc_instance):
if not name.startswith("do_"):
continue
func = getattr(osc_instance, name)
if not inspect.ismethod(func) and not inspect.isfunction(func):
continue
cls = self._wrap_legacy_command(func)
self.load_command(cls, "osc.commands.old")
@classmethod
def main(cls, argv=None, run=True):
"""
Initialize OscMainCommand, load all commands and run the selected command.
"""
cmd = cls()
cmd.load_commands()
cmd.load_legacy_commands()
if run:
args = cmd.parse_args(args=argv)
cmd.run(args)
else:
args = None
return cmd, args
def get_parser():
"""
Needed by argparse-manpage to generate man pages from the argument parser.
"""
main, _ = OscMainCommand.main(run=False)
return main.parser
# ================================================================================
# The legacy code follows.
# Please do not use it if possible.
# ================================================================================
HELP_MULTIBUILD_MANY = """Only work with the specified flavors of a multibuild package.
Globs are resolved according to _multibuild file from server.
Empty string is resolved to a package without a flavor."""
HELP_MULTIBUILD_ONE = "Only work with the specified flavor of a multibuild package."
def pop_args(
args,
arg1_name: str = None,
arg1_is_optional: bool = False,
arg1_default: str = None,
arg2_name: str = None,
arg2_is_optional: bool = False,
arg2_default: str = None,
):
"""
Pop 2 arguments from `args`.
They may be either 2 individual entries or a single entry with values separated with "/".
.. warning::
The `args` list gets modified in this function call!
:param args: List of command-line arguments.
:type args: list(str)
:param arg1_name: Name of the first argument
:type arg1_name: str
:param arg1_is_optional: Whether to error out when arg1 cannot be retrieved.
:type arg1_is_optional: bool
:param arg1_default: Used if arg1 is not specified in `args`.
:type arg1_default: bool
:param arg2_name: Name of the second argument
:type arg2_name: str
:param arg2_is_optional: Whether to error out when arg2 cannot be retrieved.
:type arg2_is_optional: bool
:param arg2_default: Used if arg2 is not specified in `args`.
:type arg2_default: bool
:returns: Project and package.
:rtype: tuple(str)
"""
assert isinstance(args, list)
assert isinstance(arg1_name, str)
assert isinstance(arg2_name, str)
if arg1_is_optional:
arg2_is_optional = True
used_arg1_default = False
try:
arg1 = args.pop(0)
except IndexError:
if not arg1_is_optional and not arg1_default:
raise oscerr.OscValueError(f"Please specify a {arg1_name}") from None
arg1 = arg1_default
used_arg1_default = True
if not isinstance(arg1, (str, type(None))):
raise TypeError(f"{arg1_name.capitalize()} should be 'str', found: {type(arg1).__name__}")
arg2 = None
if arg1 and "/" in arg1:
# project/package, repo/arch, etc.
if arg1.count("/") != 1:
raise oscerr.OscValueError(f"Argument doesn't match the '<{arg1_name}>/<{arg2_name}>' pattern: {arg1}")
arg1, arg2 = arg1.split("/")
if arg2 is None:
try:
arg2 = args.pop(0)
except IndexError:
if not arg2_is_optional and not arg2_default and not used_arg1_default:
# arg2 is not optional and it wasn't specified together with arg1
raise oscerr.OscValueError(f"Please specify a {arg2_name}") from None
arg2 = arg2_default
if not isinstance(arg2, (str, type(None))):
raise TypeError(f"{arg2_name.capitalize()} should be 'str', found: {type(arg2).__name__}")
return arg1, arg2
def pop_project_package_from_args(
args: List[str],
project_is_optional: bool = False,
default_project: str = None,
package_is_optional: bool = False,
default_package: str = None,
):
"""
Pop project and package from given `args`.
They may be either 2 individual entries or a single entry with values separated with "/".
.. warning::
The `args` list gets modified in this function call!
:param args: List of command-line arguments.
:type args: list(str)
:param project_is_optional: Whether to error out when project cannot be retrieved. Implies `package_is_optional=False`.
:type project_is_optional: bool
:param default_project: Used if project is not specified in `args`.
Resolved from the current working copy if set to '.'.
:type default_project: str
:param package_is_optional: Whether to error out when package cannot be retrieved.
:type package_is_optional: bool
:param default_package: Used if package is not specified in `args`.
Resolved from the current working copy if set to '.'.
:type default_package: str
:returns: Project and package.
:rtype: tuple(str)
"""
project, package = pop_args(
args,
arg1_name="project",
arg1_is_optional=project_is_optional,
arg1_default=default_project,
arg2_name="package",
arg2_is_optional=package_is_optional,
arg2_default=default_package,
)
path = Path.cwd()
project_store = None
package_store = None
if project == ".":
# project name taken from the working copy
try:
project_store = osc_store.get_store(path)
project = project_store.project
except oscerr.NoWorkingCopy:
if not project_is_optional:
raise
project = None
if package == ".":
# package name taken from the working copy
try:
package_store = osc_store.get_store(path)
package_store.assert_is_package()
package = package_store.package
except oscerr.NoWorkingCopy:
if package_is_optional:
package = None
elif not project_store and default_package == ".":
# project wasn't retrieved from store, let's ask for specifying a package
raise oscerr.OscValueError("Please specify a package") from None
else:
raise
return project, package
def pop_repository_arch_from_args(
args: List[str],
repository_is_optional: bool = False,
default_repository: str = None,
arch_is_optional: bool = False,
default_arch: str = None,
):
"""
Pop repository and arch from given `args`.
They may be either 2 individual entries or a single entry with values separated with "/".
.. warning::
The `args` list gets modified in this function call!
:param args: List of command-line arguments.
:type args: list(str)
:param repository_is_optional: Whether to error out when project cannot be retrieved. Implies `arch_is_optional=False`.
:type repository_is_optional: bool
:param default_repository: Used if repository is not specified in `args`.
:type default_repository: str
:param arch_is_optional: Whether to error out when arch cannot be retrieved.
:type arch_is_optional: bool
:param default_arch: Used if arch is not specified in `args`.
:type default_arch: str
:returns: Repository and arch.
:rtype: tuple(str)
"""
repository, arch = pop_args(
args,
arg1_name="repository",
arg1_is_optional=repository_is_optional,
arg1_default=default_repository,
arg2_name="arch",
arg2_is_optional=arch_is_optional,
arg2_default=default_arch,
)
return repository, arch
def pop_project_package_repository_arch_from_args(
args: List[str],
project_is_optional: bool = False,
default_project: str = None,
package_is_optional: bool = False,
default_package: str = None,
repository_is_optional: bool = False,
default_repository: str = None,
arch_is_optional: bool = False,
default_arch: str = None,
):
"""
Pop project, package, repository and arch from given `args`.
.. warning::
The `args` list gets modified in this function call!
:param args: List of command-line arguments.
:type args: list(str)
:param project_is_optional: Whether to error out when project cannot be retrieved. Implies `package_is_optional=False`.
:type project_is_optional: bool
:param default_project: Used if project is not specified in `args`.
Resolved from the current working copy if set to '.'.
:type default_project: str
:param package_is_optional: Whether to error out when package cannot be retrieved.
:type package_is_optional: bool
:param default_package: Used if package is not specified in `args`.
Resolved from the current working copy if set to '.'.
:type default_package: str
:param repository_is_optional: Whether to error out when project cannot be retrieved. Implies `arch_is_optional=False`.
:type repository_is_optional: bool
:param default_repository: Used if repository is not specified in `args`.
:type default_repository: str
:param arch_is_optional: Whether to error out when arch cannot be retrieved.
:type arch_is_optional: bool
:param default_arch: Used if arch is not specified in `args`.
:type default_arch: str
:returns: Project, package, repository and arch.
:rtype: tuple(str)
"""
args_backup = args.copy()
if project_is_optional or package_is_optional:
repository_is_optional = True
arch_is_optional = True
try_working_copy = default_project == "." or default_package == "."
try:
# try this sequence first: project package repository arch
project, package = pop_project_package_from_args(
args,
project_is_optional=project_is_optional,
default_project=default_project,
package_is_optional=package_is_optional,
default_package=default_package,
)
if args:
# we got more than 2 arguments -> we shouldn't try to retrieve project and package from a working copy
try_working_copy = False
repository, arch = pop_repository_arch_from_args(
args,
repository_is_optional=repository_is_optional,
default_repository=default_repository,
arch_is_optional=arch_is_optional,
default_arch=default_arch,
)
except oscerr.OscValueError as ex:
if not try_working_copy:
raise ex from None
# then read project and package from working copy and try repository arch
args[:] = args_backup.copy()
project, package = pop_project_package_from_args(
[], default_project=".", default_package="."
)
repository, arch = pop_repository_arch_from_args(
args,
repository_is_optional=repository_is_optional,
default_repository=default_repository,
arch_is_optional=arch_is_optional,
default_arch=default_arch,
)
return project, package, repository, arch
def pop_project_package_targetproject_targetpackage_from_args(
args: List[str],
project_is_optional: bool = False,
default_project: str = None,
package_is_optional: bool = False,
default_package: str = None,
target_project_is_optional: bool = False,
default_target_project: str = None,
target_package_is_optional: bool = False,
default_target_package: str = None,
):
"""
Pop project, package, target project and target package from given `args`.
.. warning::
The `args` list gets modified in this function call!
:param args: List of command-line arguments.
:type args: list(str)
:param project_is_optional: Whether to error out when project cannot be retrieved. Implies `package_is_optional=False`.
:type project_is_optional: bool
:param default_project: Used if project is not specified in `args`.
Resolved from the current working copy if set to '.'.
:type default_project: str
:param package_is_optional: Whether to error out when package cannot be retrieved.
:type package_is_optional: bool
:param default_package: Used if package is not specified in `args`.
Resolved from the current working copy if set to '.'.
:type default_package: str
:param target_project_is_optional: Whether to error out when target project cannot be retrieved. Implies `target_package_is_optional=False`.
:type target_project_is_optional: bool
:param default_target_project: Used if target project is not specified in `args`.
Resolved from the current working copy if set to '.'.
:type default_target_project: str
:param target_package_is_optional: Whether to error out when target package cannot be retrieved.
:type target_package_is_optional: bool
:param default_target_package: Used if target package is not specified in `args`.
Resolved from the current working copy if set to '.'.
:type default_target_package: str
:returns: Project, package, target project and target package.
:rtype: tuple(str)
"""
args_backup = args.copy()
if project_is_optional or package_is_optional:
target_project_is_optional = True
target_package_is_optional = True
try_working_copy = default_project == "." or default_package == "."
try:
# try this sequence first: project package target_project target_package
project, package = pop_project_package_from_args(
args,
project_is_optional=project_is_optional,
default_project=default_project,
package_is_optional=package_is_optional,
default_package=default_package,
)
if args:
# we got more than 2 arguments -> we shouldn't try to retrieve project and package from a working copy
try_working_copy = False
target_project, target_package = pop_project_package_from_args(
args,
project_is_optional=target_project_is_optional,
default_project=default_target_project,
package_is_optional=target_package_is_optional,
default_package=default_target_package,
)
except oscerr.OscValueError as ex:
if not try_working_copy:
raise ex from None
# then read project and package from working copy and target_project target_package
args[:] = args_backup.copy()
project, package = pop_project_package_from_args(
[],
default_project=".",
default_package=".",
package_is_optional=False,
)
target_project, target_package = pop_project_package_from_args(
args,
project_is_optional=target_project_is_optional,
default_project=default_target_project,
package_is_optional=target_package_is_optional,
default_package=default_target_package,
)
return project, package, target_project, target_package
def ensure_no_remaining_args(args):
"""
Error out when `args` still contains arguments.
:raises oscerr.WrongArgs: The `args` list still contains arguments.
"""
if not args:
return
args_str = " ".join(args)
raise oscerr.WrongArgs(f"Unexpected args: {args_str}")
class Osc(cmdln.Cmdln):
"""
openSUSE commander is a command-line interface to the Open Build Service.
Type 'osc <subcommand> --help' for help on a specific subcommand.
For additional information, see
* http://en.opensuse.org/openSUSE:Build_Service_Tutorial
* http://en.opensuse.org/openSUSE:OSC
You can modify osc commands, or roll your own, via the plugin API:
* http://en.opensuse.org/openSUSE:OSC_plugins
"""
name = 'osc'
def __init__(self):
self.options = None
self._load_plugins()
sys.stderr = safewriter.SafeWriter(sys.stderr)
sys.stdout = safewriter.SafeWriter(sys.stdout)
def _debug(self, *args):
# if options are not initialized, still allow to use it
if not hasattr(self, 'options') or self.options.debug:
print(*args, file=sys.stderr)
def get_version(self):
return get_osc_version()
def _process_project_name(self, project):
if isinstance(project, str):
if project == '.':
if is_package_dir(Path.cwd()) or is_project_dir(Path.cwd()):
project = store_read_project(Path.cwd())
else:
raise oscerr.WrongArgs('No working directory')
return project.replace(conf.config['project_separator'], ':')
return project
def add_global_options(self, parser, suppress=False):
def _add_parser_arguments_from_data(argument_parser, data):
for kwargs in data:
args = kwargs.pop("names")
if suppress:
kwargs["help"] = argparse.SUPPRESS
kwargs["default"] = argparse.SUPPRESS
argument_parser.add_argument(*args, **kwargs)
arguments = []
arguments.append(dict(
names=['-v', '--verbose'],
action='store_true',
help='increase verbosity',
))
arguments.append(dict(
names=['-q', '--quiet'],
action='store_true',