/
commandline.py
8780 lines (7587 loc) · 374 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).
from __future__ import print_function
from . import cmdln
from . import conf
from . import oscerr
import sys
import time
import imp
import inspect
try:
from urllib.parse import urlsplit
from urllib.error import HTTPError
ET_ENCODING = "unicode"
except ImportError:
#python 2.x
from urlparse import urlsplit
from urllib2 import HTTPError
ET_ENCODING = "utf-8"
from optparse import SUPPRESS_HELP
from .core import *
from .util import safewriter
MAN_HEADER = r""".TH %(ucname)s "1" "%(date)s" "%(name)s %(version)s" "User Commands"
.SH NAME
%(name)s \- openSUSE build service command-line tool.
.SH SYNOPSIS
.B %(name)s
[\fIGLOBALOPTS\fR] \fISUBCOMMAND \fR[\fIOPTS\fR] [\fIARGS\fR...]
.br
.B %(name)s
\fIhelp SUBCOMMAND\fR
.SH DESCRIPTION
openSUSE build service command-line tool.
"""
MAN_FOOTER = r"""
.SH "SEE ALSO"
Type 'osc help <subcommand>' for more detailed help on a specific subcommand.
.PP
For additional information, see
* http://en.opensuse.org/openSUSE:Build_Service_Tutorial
* http://en.opensuse.org/openSUSE:OSC
.PP
You can modify osc commands, or roll your own, via the plugin API:
* http://en.opensuse.org/openSUSE:OSC_plugins
.SH AUTHOR
osc was written by several authors. This man page is automatically generated.
"""
class Osc(cmdln.Cmdln):
"""Usage: osc [GLOBALOPTS] SUBCOMMAND [OPTS] [ARGS...]
or: osc help SUBCOMMAND
openSUSE build service command-line tool.
Type 'osc help <subcommand>' for help on a specific subcommand.
${command_list}
${help_list}
global ${option_list}
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'
conf = None
man_header = MAN_HEADER
man_footer = MAN_FOOTER
def __init__(self, *args, **kwargs):
# the plugins have to be loaded before the
# superclass' __init__ method is called
self._load_plugins()
cmdln.Cmdln.__init__(self, *args, **kwargs)
cmdln.Cmdln.do_help.aliases.append('h')
sys.stderr = safewriter.SafeWriter(sys.stderr)
sys.stdout = safewriter.SafeWriter(sys.stdout)
def get_version(self):
return get_osc_version()
def get_optparser(self):
"""this is the parser for "global" options (not specific to subcommand)"""
optparser = cmdln.CmdlnOptionParser(self, version=get_osc_version())
optparser.add_option('--debugger', action='store_true',
help='jump into the debugger before executing anything')
optparser.add_option('--post-mortem', action='store_true',
help='jump into the debugger in case of errors')
optparser.add_option('-t', '--traceback', action='store_true',
help='print call trace in case of errors')
optparser.add_option('-H', '--http-debug', action='store_true',
help='debug HTTP traffic (filters some headers)')
optparser.add_option('--http-full-debug', action='store_true',
help='debug HTTP traffic (filters no headers)')
optparser.add_option('-d', '--debug', action='store_true',
help='print info useful for debugging')
optparser.add_option('-A', '--apiurl', dest='apiurl',
metavar='URL/alias',
help='specify URL to access API server at or an alias')
optparser.add_option('-c', '--config', dest='conffile',
metavar='FILE',
help='specify alternate configuration file')
optparser.add_option('--no-keyring', action='store_true',
help='disable usage of desktop keyring system')
optparser.add_option('--no-gnome-keyring', action='store_true',
help='disable usage of GNOME Keyring')
optparser.add_option('-v', '--verbose', dest='verbose', action='count', default=0,
help='increase verbosity')
optparser.add_option('-q', '--quiet', dest='verbose', action='store_const', const=-1,
help='be quiet, not verbose')
return optparser
def postoptparse(self, try_again = True):
"""merge commandline options into the config"""
try:
conf.get_config(override_conffile = self.options.conffile,
override_apiurl = self.options.apiurl,
override_debug = self.options.debug,
override_http_debug = self.options.http_debug,
override_http_full_debug = self.options.http_full_debug,
override_traceback = self.options.traceback,
override_post_mortem = self.options.post_mortem,
override_no_keyring = self.options.no_keyring,
override_no_gnome_keyring = self.options.no_gnome_keyring,
override_verbose = self.options.verbose)
except oscerr.NoConfigfile as e:
print(e.msg, file=sys.stderr)
print('Creating osc configuration file %s ...' % e.file, file=sys.stderr)
import getpass
config = {}
config['user'] = raw_input('Username: ')
config['pass'] = getpass.getpass()
if self.options.no_keyring:
config['use_keyring'] = '0'
if self.options.no_gnome_keyring:
config['gnome_keyring'] = '0'
if self.options.apiurl:
config['apiurl'] = self.options.apiurl
conf.write_initial_config(e.file, config)
print('done', file=sys.stderr)
if try_again:
self.postoptparse(try_again = False)
except oscerr.ConfigMissingApiurl as e:
print(e.msg, file=sys.stderr)
import getpass
user = raw_input('Username: ')
passwd = getpass.getpass()
conf.add_section(e.file, e.url, user, passwd)
if try_again:
self.postoptparse(try_again = False)
self.options.verbose = conf.config['verbose']
self.download_progress = None
if conf.config.get('show_download_progress', False):
from .meter import TextMeter
self.download_progress = TextMeter(hide_finished=True)
def get_cmd_help(self, cmdname):
doc = self._get_cmd_handler(cmdname).__doc__
doc = self._help_reindent(doc)
doc = self._help_preprocess(doc, cmdname)
doc = doc.rstrip() + '\n' # trim down trailing space
return self._str(doc)
def get_api_url(self):
try:
localdir = os.getcwd()
except Exception as e:
## check for Stale NFS file handle: '.'
try:
os.stat('.')
except Exception as ee:
e = ee
print("os.getcwd() failed: ", e, file=sys.stderr)
sys.exit(1)
if (is_package_dir(localdir) or is_project_dir(localdir)) and not self.options.apiurl:
return store_read_apiurl(os.curdir)
else:
return conf.config['apiurl']
# overridden from class Cmdln() to use config variables in help texts
def _help_preprocess(self, help, cmdname):
help_msg = cmdln.Cmdln._help_preprocess(self, help, cmdname)
return help_msg % conf.config
def do_init(self, subcmd, opts, project, package=None):
"""${cmd_name}: Initialize a directory as working copy
Initialize an existing directory to be a working copy of an
(already existing) buildservice project/package.
(This is the same as checking out a package and then copying sources
into the directory. It does NOT create a new package. To create a
package, use 'osc meta pkg ... ...')
You wouldn't normally use this command.
To get a working copy of a package (e.g. for building it or working on
it, you would normally use the checkout command. Use "osc help
checkout" to get help for it.
usage:
osc init PRJ
osc init PRJ PAC
${cmd_option_list}
"""
apiurl = self.get_api_url()
if not package:
Project.init_project(apiurl, os.curdir, project, conf.config['do_package_tracking'])
print('Initializing %s (Project: %s)' % (os.curdir, project))
else:
Package.init_package(apiurl, project, package, os.curdir)
store_write_string(os.curdir, '_files', show_files_meta(apiurl, project, package) + '\n')
print('Initializing %s (Project: %s, Package: %s)' % (os.curdir, project, package))
@cmdln.alias('ls')
@cmdln.alias('ll')
@cmdln.alias('lL')
@cmdln.alias('LL')
@cmdln.option('-a', '--arch', metavar='ARCH',
help='specify architecture (only for binaries)')
@cmdln.option('-r', '--repo', metavar='REPO',
help='specify repository (only for binaries)')
@cmdln.option('-b', '--binaries', action='store_true',
help='list built binaries instead of sources')
@cmdln.option('-e', '--expand', action='store_true',
help='expand linked package (only for sources)')
@cmdln.option('-u', '--unexpand', action='store_true',
help='always work with unexpanded (source) packages')
@cmdln.option('-v', '--verbose', action='store_true',
help='print extra information')
@cmdln.option('-l', '--long', action='store_true', dest='verbose',
help='print extra information')
@cmdln.option('-D', '--deleted', action='store_true',
help='show only the former deleted projects or packages')
@cmdln.option('-M', '--meta', action='store_true',
help='list meta data files')
@cmdln.option('-R', '--revision', metavar='REVISION',
help='specify revision (only for sources)')
def do_list(self, subcmd, opts, *args):
"""${cmd_name}: List sources or binaries on the server
Examples for listing sources:
ls # list all projects (deprecated)
ls / # list all projects
ls . # take PROJECT/PACKAGE from current dir.
ls PROJECT # list packages in a project
ls PROJECT PACKAGE # list source files of package of a project
ls PROJECT PACKAGE <file> # list <file> if this file exists
ls -v PROJECT PACKAGE # verbosely list source files of package
ls -l PROJECT PACKAGE # verbosely list source files of package
ll PROJECT PACKAGE # verbosely list source files of package
LL PROJECT PACKAGE # verbosely list source files of expanded link
With --verbose, the following fields will be shown for each item:
MD5 hash of file
Revision number of the last commit
Size (in bytes)
Date and time of the last commit
Examples for listing binaries:
ls -b PROJECT # list all binaries of a project
ls -b PROJECT -a ARCH # list ARCH binaries of a project
ls -b PROJECT -r REPO # list binaries in REPO
ls -b PROJECT PACKAGE REPO ARCH
Usage:
${cmd_name} [PROJECT [PACKAGE]]
${cmd_name} -b [PROJECT [PACKAGE [REPO [ARCH]]]]
${cmd_option_list}
"""
args = slash_split(args)
if subcmd == 'll':
opts.verbose = True
if subcmd == 'lL' or subcmd == 'LL':
opts.verbose = True
opts.expand = True
project = None
package = None
fname = None
if len(args) == 0:
# For consistency with *all* other commands
# this lists what the server has in the current wd.
# CAUTION: 'osc ls -b' already works like this.
pass
if len(args) > 0:
project = args[0]
if project == '/':
project = None
if project == '.':
cwd = os.getcwd()
if is_project_dir(cwd):
project = store_read_project(cwd)
elif is_package_dir(cwd):
project = store_read_project(cwd)
package = store_read_package(cwd)
if len(args) > 1:
package = args[1]
if len(args) > 2:
if opts.deleted:
raise oscerr.WrongArgs("Too many arguments when listing deleted packages")
if opts.binaries:
if opts.repo:
if opts.repo != args[2]:
raise oscerr.WrongArgs("conflicting repos specified ('%s' vs '%s')"%(opts.repo, args[2]))
else:
opts.repo = args[2]
else:
fname = args[2]
if len(args) > 3:
if not opts.binaries:
raise oscerr.WrongArgs('Too many arguments')
if opts.arch:
if opts.arch != args[3]:
raise oscerr.WrongArgs("conflicting archs specified ('%s' vs '%s')"%(opts.arch, args[3]))
else:
opts.arch = args[3]
if opts.binaries and opts.expand:
raise oscerr.WrongOptions('Sorry, --binaries and --expand are mutual exclusive.')
apiurl = self.get_api_url()
# list binaries
if opts.binaries:
# ls -b toplevel doesn't make sense, so use info from
# current dir if available
if len(args) == 0:
cwd = os.getcwd()
if is_project_dir(cwd):
project = store_read_project(cwd)
elif is_package_dir(cwd):
project = store_read_project(cwd)
package = store_read_package(cwd)
if not project:
raise oscerr.WrongArgs('There are no binaries to list above project level.')
if opts.revision:
raise oscerr.WrongOptions('Sorry, the --revision option is not supported for binaries.')
repos = []
if opts.repo and opts.arch:
repos.append(Repo(opts.repo, opts.arch))
elif opts.repo and not opts.arch:
repos = [repo for repo in get_repos_of_project(apiurl, project) if repo.name == opts.repo]
elif opts.arch and not opts.repo:
repos = [repo for repo in get_repos_of_project(apiurl, project) if repo.arch == opts.arch]
else:
repos = get_repos_of_project(apiurl, project)
results = []
for repo in repos:
results.append((repo, get_binarylist(apiurl, project, repo.name, repo.arch, package=package, verbose=opts.verbose)))
for result in results:
indent = ''
if len(results) > 1:
print('%s/%s' % (result[0].name, result[0].arch))
indent = ' '
if opts.verbose:
for f in result[1]:
print("%9d %s %-40s" % (f.size, shorttime(f.mtime), f.name))
else:
for f in result[1]:
print(indent+f)
# list sources
elif not opts.binaries:
if not args:
for prj in meta_get_project_list(apiurl, opts.deleted):
print(prj)
elif len(args) == 1:
if opts.verbose:
if self.options.verbose:
print('Sorry, the --verbose option is not implemented for projects.', file=sys.stderr)
for pkg in meta_get_packagelist(apiurl, project, deleted = opts.deleted, expand = opts.expand):
print(pkg)
elif len(args) == 2 or len(args) == 3:
link_seen = False
print_not_found = True
rev = opts.revision
for i in [ 1, 2 ]:
l = meta_get_filelist(apiurl,
project,
package,
verbose=opts.verbose,
expand=opts.expand,
meta=opts.meta,
deleted=opts.deleted,
revision=rev)
link_seen = '_link' in l
if opts.verbose:
out = [ '%s %7s %9d %s %s' % (i.md5, i.rev, i.size, shorttime(i.mtime), i.name) \
for i in l if not fname or fname == i.name ]
if len(out) > 0:
print_not_found = False
print('\n'.join(out))
elif fname:
if fname in l:
print(fname)
print_not_found = False
else:
print('\n'.join(l))
if opts.expand or opts.unexpand or not link_seen:
break
m = show_files_meta(apiurl, project, package)
li = Linkinfo()
li.read(ET.fromstring(''.join(m)).find('linkinfo'))
if li.haserror():
raise oscerr.LinkExpandError(project, package, li.error)
project, package, rev = li.project, li.package, li.rev
if rev:
print('# -> %s %s (%s)' % (project, package, rev))
else:
print('# -> %s %s (latest)' % (project, package))
opts.expand = True
if fname and print_not_found:
print('file \'%s\' does not exist' % fname)
return 1
@cmdln.option('-s', '--skip-disabled', action='store_true',
help='Skip disabled channels. Otherwise the source gets added, but not the repositories.')
@cmdln.option('-e', '--enable-all', action='store_true',
help='Enable all added channels including the ones disabled by default.')
def do_addchannels(self, subcmd, opts, *args):
"""${cmd_name}: Add channels to project.
The command adds all channels which are defined to be used for a given source package.
The source link target is used to lookup the channels. The command can be
used for a certain package or for all in the specified project.
In case no channel is defined the operation is just returning.
Examples:
osc addchannels [PROJECT [PACKAGE]]
${cmd_option_list}
"""
apiurl = self.get_api_url()
localdir = os.getcwd()
channel = None
if not args:
if is_project_dir(localdir) or is_package_dir(localdir):
project = store_read_project(localdir)
elif is_package_dir(localdir):
project = store_read_project(localdir)
channel = store_read_package(localdir)
else:
raise oscerr.WrongArgs('Either specify project [package] or call it from a project/package working copy')
else:
project = args[0]
query = {'cmd': 'addchannels'}
if opts.enable_all and opts.skip_disabled:
raise oscerr.WrongOptions('--enable-all and --skip-disabled options are mutually exclusive')
elif opts.enable_all:
query['mode'] = 'enable_all'
elif opts.skip_disabled:
query['mode'] = 'skip_disabled'
print("Looking for channels...")
url = makeurl(apiurl, ['source', project], query=query)
if channel:
url = makeurl(apiurl, ['source', project, channel], query=query)
f = http_POST(url)
@cmdln.alias('enablechannel')
def do_enablechannels(self, subcmd, opts, *args):
"""${cmd_name}: Enables channels
Enables existing channel packages in a project. Enabling means adding the
needed repositories for building.
The command can be used to enable a specific one or all channels of a project.
Examples:
osc enablechannels [PROJECT [CHANNEL_PACKAGE]]
${cmd_option_list}
"""
apiurl = self.get_api_url()
localdir = os.getcwd()
channel = None
if not args:
if is_project_dir(localdir):
project = store_read_project(localdir)
elif is_package_dir(localdir):
project = store_read_project(localdir)
channel = store_read_package(localdir)
else:
raise oscerr.WrongArgs('Either specify project [package] or call it from a project/package working copy')
else:
project = args[0]
if len(args) > 1:
channel = args[1]
query = {}
if channel:
query['cmd'] = 'enablechannel'
else:
query = {'cmd': 'modifychannels', 'mode': 'enable_all'}
print("Enable channel(s)...")
url = makeurl(apiurl, ['source', project], query=query)
if channel:
url = makeurl(apiurl, ['source', project, channel], query=query)
f = http_POST(url)
@cmdln.option('-f', '--force', action='store_true',
help='force generation of new patchinfo file, do not update existing one.')
def do_patchinfo(self, subcmd, opts, *args):
"""${cmd_name}: Generate and edit a patchinfo file.
A patchinfo file describes the packages for an update and the kind of
problem it solves.
This command either creates a new _patchinfo or updates an existing one.
Examples:
osc patchinfo
osc patchinfo [PROJECT [PATCH_NAME]]
${cmd_option_list}
"""
apiurl = self.get_api_url()
project_dir = localdir = os.getcwd()
patchinfo = 'patchinfo'
if len(args) == 0:
if is_project_dir(localdir):
project = store_read_project(localdir)
apiurl = self.get_api_url()
for p in meta_get_packagelist(apiurl, project):
if p.startswith("_patchinfo") or p.startswith("patchinfo"):
patchinfo = p
else:
if is_package_dir(localdir):
project = store_read_project(localdir)
patchinfo = store_read_package(localdir)
apiurl = self.get_api_url()
if not os.path.exists('_patchinfo'):
sys.exit('Current checked out package has no _patchinfo. Either call it from project level or specify patch name.')
else:
sys.exit('This command must be called in a checked out project or patchinfo package.')
else:
project = args[0]
if len(args) > 1:
patchinfo = args[1]
filelist = None
if patchinfo:
try:
filelist = meta_get_filelist(apiurl, project, patchinfo)
except HTTPError:
pass
if opts.force or not filelist or not '_patchinfo' in filelist:
print("Creating new patchinfo...")
query = 'cmd=createpatchinfo&name=' + patchinfo
if opts.force:
query += "&force=1"
url = makeurl(apiurl, ['source', project], query=query)
f = http_POST(url)
for p in meta_get_packagelist(apiurl, project):
if p.startswith("_patchinfo") or p.startswith("patchinfo"):
patchinfo = p
else:
print("Update existing _patchinfo file...")
query = 'cmd=updatepatchinfo'
url = makeurl(apiurl, ['source', project, patchinfo], query=query)
f = http_POST(url)
# CAUTION:
# Both conf.config['checkout_no_colon'] and conf.config['checkout_rooted']
# fool this test:
if is_package_dir(localdir):
pac = Package(localdir)
pac.update()
filename = "_patchinfo"
else:
checkout_package(apiurl, project, patchinfo, prj_dir=project_dir)
filename = project_dir + "/" + patchinfo + "/_patchinfo"
run_editor(filename)
@cmdln.alias('bsdevelproject')
@cmdln.alias('dp')
@cmdln.option('-r', '--raw', action='store_true', help='deprecated option')
def do_develproject(self, subcmd, opts, *args):
"""${cmd_name}: print the devel project / package of a package
Examples:
osc develproject PRJ PKG
osc develproject
${cmd_option_list}
"""
args = slash_split(args)
apiurl = self.get_api_url()
if len(args) == 0:
project = store_read_project(os.curdir)
package = store_read_package(os.curdir)
elif len(args) == 2:
project = args[0]
package = args[1]
else:
raise oscerr.WrongArgs('need Project and Package')
devprj, devpkg = show_devel_project(apiurl, project, package)
if devprj is None:
print('%s / %s has no devel project' % (project, package))
elif devpkg and devpkg != package:
print("%s %s" % (devprj, devpkg))
else:
print(devprj)
@cmdln.alias('sdp')
@cmdln.option('-u', '--unset', action='store_true',
help='remove devel project')
def do_setdevelproject(self, subcmd, opts, *args):
"""${cmd_name}: Set the devel project / package of a package
Examples:
osc setdevelproject [PRJ PKG] DEVPRJ [DEVPKG]
${cmd_option_list}
"""
args = slash_split(args)
apiurl = self.get_api_url()
devprj, devpkg = None, None
if len(args) == 3 or len(args) == 4:
project, package = args[0], args[1]
devprj = args[2]
if len(args) == 4:
devpkg = args[3]
elif len(args) >= 1 and len(args) <= 2:
project, package = store_read_project(os.curdir), store_read_package(os.curdir)
devprj = args[0]
if len(args) == 2:
devpkg = args[1]
else:
if opts.unset:
project, package = store_read_project(os.curdir), store_read_package(os.curdir)
else:
raise oscerr.WrongArgs('need at least DEVPRJ (and possibly DEVPKG)')
set_devel_project(apiurl, project, package, devprj, devpkg)
@cmdln.option('-c', '--create', action='store_true',
help='Create a new token')
@cmdln.option('-d', '--delete', metavar='TOKENID',
help='Create a new token')
@cmdln.option('-t', '--trigger', metavar='TOKENID',
help='Trigger the action of a token')
def do_token(self, subcmd, opts, *args):
"""${cmd_name}: Show and manage authentication token
Authentication token can be used to run specific commands without
sending credentials.
Usage:
osc token
osc token --create [<PROJECT> <PACKAGE>]
osc token --delete <TOKENID>
osc token --trigger <TOKENID>
${cmd_option_list}
"""
args = slash_split(args)
apiurl = self.get_api_url()
url = apiurl + "/person/" + conf.get_apiurl_usr(apiurl) + "/token"
if opts.create:
print("Create a new token")
url += "?cmd=create"
if len(args) > 1:
url += "&project=" + args[0]
url += "&package=" + args[1]
f = http_POST(url)
while True:
buf = f.read(16384)
if not buf:
break
sys.stdout.write(buf)
elif opts.delete:
print("Delete token")
url += "/" + opts.delete
http_DELETE(url)
elif opts.trigger:
print("Trigger token")
url = apiurl + "/trigger/runservice"
req = URLRequest(url)
req.get_method = lambda: "POST"
req.add_header('Content-Type', 'application/octet-stream')
req.add_header('Authorization', "Token "+opts.trigger)
fd = urlopen(req, data=None)
print(fd.read())
else:
# just list token
for data in streamfile(url, http_GET):
sys.stdout.write(data)
@cmdln.option('-a', '--attribute', metavar='ATTRIBUTE',
help='affect only a given attribute')
@cmdln.option('--attribute-defaults', action='store_true',
help='include defined attribute defaults')
@cmdln.option('--attribute-project', action='store_true',
help='include project values, if missing in packages ')
@cmdln.option('-f', '--force', action='store_true',
help='force the save operation, allows one to ignores some errors like depending repositories. For prj meta only.')
@cmdln.option('-F', '--file', metavar='FILE',
help='read metadata from FILE, instead of opening an editor. '
'\'-\' denotes standard input. ')
@cmdln.option('-r', '--revision', metavar='REV',
help='checkout given revision instead of head revision. For prj and prjconf meta only')
@cmdln.option('-m', '--message', metavar='TEXT',
help='specify log message TEXT. For prj and prjconf meta only')
@cmdln.option('-e', '--edit', action='store_true',
help='edit metadata')
@cmdln.option('-c', '--create', action='store_true',
help='create attribute without values')
@cmdln.option('-R', '--remove-linking-repositories', action='store_true',
help='Try to remove also all repositories building against remove ones.')
@cmdln.option('-s', '--set', metavar='ATTRIBUTE_VALUES',
help='set attribute values')
@cmdln.option('--delete', action='store_true',
help='delete a pattern or attribute')
def do_meta(self, subcmd, opts, *args):
"""${cmd_name}: Show meta information, or edit it
Show or edit build service metadata of type <prj|pkg|prjconf|user|pattern>.
This command displays metadata on buildservice objects like projects,
packages, or users. The type of metadata is specified by the word after
"meta", like e.g. "meta prj".
prj denotes metadata of a buildservice project.
prjconf denotes the (build) configuration of a project.
pkg denotes metadata of a buildservice package.
user denotes the metadata of a user.
pattern denotes installation patterns defined for a project.
To list patterns, use 'osc meta pattern PRJ'. An additional argument
will be the pattern file to view or edit.
With the --edit switch, the metadata can be edited. Per default, osc
opens the program specified by the environmental variable EDITOR with a
temporary file. Alternatively, content to be saved can be supplied via
the --file switch. If the argument is '-', input is taken from stdin:
osc meta prjconf home:user | sed ... | osc meta prjconf home:user -F -
For meta prj and prjconf updates optional commit messages can be applied with --message.
When trying to edit a non-existing resource, it is created implicitly.
Examples:
osc meta prj PRJ
osc meta pkg PRJ PKG
osc meta pkg PRJ PKG -e
Usage:
osc meta <prj|prjconf> [-r|--revision REV] ARGS...
osc meta <prj|pkg|prjconf|user|pattern> ARGS...
osc meta <prj|pkg|prjconf|user|pattern> [-m|--message TEXT] -e|--edit ARGS...
osc meta <prj|pkg|prjconf|user|pattern> [-m|--message TEXT] -F|--file ARGS...
osc meta pattern --delete PRJ PATTERN
osc meta attribute PRJ [PKG [SUBPACKAGE]] [--attribute ATTRIBUTE] [--create|--delete|--set [value_list]]
${cmd_option_list}
"""
args = slash_split(args)
if not args or args[0] not in metatypes.keys():
raise oscerr.WrongArgs('Unknown meta type. Choose one of %s.' \
% ', '.join(metatypes))
cmd = args[0]
del args[0]
if cmd in ['pkg']:
min_args, max_args = 0, 2
elif cmd in ['pattern']:
min_args, max_args = 1, 2
elif cmd in ['attribute']:
min_args, max_args = 1, 3
elif cmd in ['prj', 'prjconf']:
min_args, max_args = 0, 1
else:
min_args, max_args = 1, 1
if len(args) < min_args:
raise oscerr.WrongArgs('Too few arguments.')
if len(args) > max_args:
raise oscerr.WrongArgs('Too many arguments.')
apiurl = self.get_api_url()
# Specific arguments
#
# If project or package arguments missing, assume to work
# with project and/or package in current local directory.
attributepath = []
if cmd in ['prj', 'prjconf']:
if len(args) < 1:
apiurl = store_read_apiurl(os.curdir)
project = store_read_project(os.curdir)
else:
project = args[0]
elif cmd == 'pkg':
if len(args) < 2:
apiurl = store_read_apiurl(os.curdir)
project = store_read_project(os.curdir)
if len(args) < 1:
package = store_read_package(os.curdir)
else:
package = args[0]
else:
project = args[0]
package = args[1]
elif cmd == 'attribute':
project = args[0]
if len(args) > 1:
package = args[1]
else:
package = None
if opts.attribute_project:
raise oscerr.WrongOptions('--attribute-project works only when also a package is given')
if len(args) > 2:
subpackage = args[2]
else:
subpackage = None
attributepath.append('source')
attributepath.append(project)
if package:
attributepath.append(package)
if subpackage:
attributepath.append(subpackage)
attributepath.append('_attribute')
elif cmd == 'user':
user = args[0]
elif cmd == 'pattern':
project = args[0]
if len(args) > 1:
pattern = args[1]
else:
pattern = None
# enforce pattern argument if needed
if opts.edit or opts.file:
raise oscerr.WrongArgs('A pattern file argument is required.')
if cmd not in ['prj', 'prjconf'] and (opts.message or opts.revision):
raise oscerr.WrongOptions('options --revision and --message are only supported for the prj or prjconf subcommand')
# show
if not opts.edit and not opts.file and not opts.delete and not opts.create and not opts.set:
if cmd == 'prj':
sys.stdout.write(''.join(show_project_meta(apiurl, project, opts.revision)))
elif cmd == 'pkg':
sys.stdout.write(''.join(show_package_meta(apiurl, project, package)))
elif cmd == 'attribute':
sys.stdout.write(''.join(show_attribute_meta(apiurl, project, package, subpackage,
opts.attribute, opts.attribute_defaults, opts.attribute_project)))
elif cmd == 'prjconf':
sys.stdout.write(''.join(show_project_conf(apiurl, project, opts.revision)))
elif cmd == 'user':
r = get_user_meta(apiurl, user)
if r:
sys.stdout.write(''.join(r))
elif cmd == 'pattern':
if pattern:
r = show_pattern_meta(apiurl, project, pattern)
if r:
sys.stdout.write(''.join(r))
else:
r = show_pattern_metalist(apiurl, project)
if r:
sys.stdout.write('\n'.join(r) + '\n')
# edit
if opts.edit and not opts.file:
if cmd == 'prj':
edit_meta(metatype='prj',
edit=True,
force=opts.force,
remove_linking_repositories=opts.remove_linking_repositories,
path_args=quote_plus(project),
apiurl=apiurl,
msg = opts.message,
template_args=({
'name': project,
'user': conf.get_apiurl_usr(apiurl)}))
elif cmd == 'pkg':
edit_meta(metatype='pkg',
edit=True,
path_args=(quote_plus(project), quote_plus(package)),
apiurl=apiurl,
template_args=({
'name': package,
'user': conf.get_apiurl_usr(apiurl)}))
elif cmd == 'prjconf':
edit_meta(metatype='prjconf',
edit=True,
path_args=quote_plus(project),
apiurl=apiurl,
msg = opts.message,
template_args=None)
elif cmd == 'user':
edit_meta(metatype='user',
edit=True,
path_args=(quote_plus(user)),
apiurl=apiurl,
template_args=({'user': user}))
elif cmd == 'pattern':
edit_meta(metatype='pattern',
edit=True,
path_args=(project, pattern),
apiurl=apiurl,
template_args=None)
# create attribute entry
if (opts.create or opts.set) and cmd == 'attribute':
if not opts.attribute:
raise oscerr.WrongOptions('no attribute given to create')
values = ''
if opts.set:
opts.set = opts.set.replace('&', '&').replace('<', '<').replace('>', '>')
for i in opts.set.split(','):
values += '<value>%s</value>' % i
aname = opts.attribute.split(":")
if len(aname) != 2:
raise oscerr.WrongOptions('Given attribute is not in "NAMESPACE:NAME" style')
d = '<attributes><attribute namespace=\'%s\' name=\'%s\' >%s</attribute></attributes>' % (aname[0], aname[1], values)
url = makeurl(apiurl, attributepath)
for data in streamfile(url, http_POST, data=d):
sys.stdout.write(data)
# upload file
if opts.file:
if opts.file == '-':
f = sys.stdin.read()
else:
try:
f = open(opts.file).read()
except:
sys.exit('could not open file \'%s\'.' % opts.file)
if cmd == 'prj':
edit_meta(metatype='prj',
data=f,
edit=opts.edit,
force=opts.force,
remove_linking_repositories=opts.remove_linking_repositories,
apiurl=apiurl,
msg = opts.message,
path_args=quote_plus(project))
elif cmd == 'pkg':
edit_meta(metatype='pkg',
data=f,
edit=opts.edit,
apiurl=apiurl,
path_args=(quote_plus(project), quote_plus(package)))
elif cmd == 'prjconf':
edit_meta(metatype='prjconf',
data=f,
edit=opts.edit,
apiurl=apiurl,