--csv/--format options for osc results
[opensuse:osc.git] / osc / commandline.py
1 # Copyright (C) 2006 Novell Inc.  All rights reserved.
2 # This program is free software; it may be used, copied, modified
3 # and distributed under the terms of the GNU General Public Licence,
4 # either version 2, or version 3 (at your option).
5
6
7 from core import *
8 import cmdln
9 import conf
10 import oscerr
11 import urlgrabber.progress
12 from optparse import SUPPRESS_HELP
13
14 MAN_HEADER = r""".TH %(ucname)s "1" "%(date)s" "%(name)s %(version)s" "User Commands"
15 .SH NAME
16 %(name)s \- openSUSE build service command-line tool.
17 .SH SYNOPSIS
18 .B %(name)s
19 [\fIGLOBALOPTS\fR] \fISUBCOMMAND \fR[\fIOPTS\fR] [\fIARGS\fR...]
20 .br
21 .B %(name)s
22 \fIhelp SUBCOMMAND\fR
23 .SH DESCRIPTION
24 openSUSE build service command-line tool.
25 """
26 MAN_FOOTER = r"""
27 .SH "SEE ALSO"
28 Type 'osc help <subcommand>' for more detailed help on a specific subcommand.
29 .PP
30 For additional information, see
31  * http://en.opensuse.org/Build_Service_Tutorial
32  * http://en.opensuse.org/Build_Service/CLI
33 .PP
34 You can modify osc commands, or roll you own, via the plugin API:
35  * http://en.opensuse.org/Build_Service/osc_plugins
36 .SH AUTHOR
37 osc was written by several authors. This man page is automatically generated.
38 """
39
40 class Osc(cmdln.Cmdln):
41     """Usage: osc [GLOBALOPTS] SUBCOMMAND [OPTS] [ARGS...]
42     or: osc help SUBCOMMAND
43
44     openSUSE build service command-line tool.
45     Type 'osc help <subcommand>' for help on a specific subcommand.
46
47     ${command_list}
48     ${help_list}
49     global ${option_list}
50     For additional information, see
51     * http://en.opensuse.org/Build_Service_Tutorial
52     * http://en.opensuse.org/Build_Service/CLI
53
54     You can modify osc commands, or roll you own, via the plugin API:
55     * http://en.opensuse.org/Build_Service/osc_plugins
56     """
57     name = 'osc'
58     conf = None
59
60     man_header = MAN_HEADER
61     man_footer = MAN_FOOTER
62
63     def __init__(self, *args, **kwargs):
64         cmdln.Cmdln.__init__(self, *args, **kwargs)
65         cmdln.Cmdln.do_help.aliases.append('h')
66
67     def get_version(self):
68         return get_osc_version()
69
70     def get_optparser(self):
71         """this is the parser for "global" options (not specific to subcommand)"""
72
73         optparser = cmdln.CmdlnOptionParser(self, version=get_osc_version())
74         optparser.add_option('--debugger', action='store_true',
75                       help='jump into the debugger before executing anything')
76         optparser.add_option('--post-mortem', action='store_true',
77                       help='jump into the debugger in case of errors')
78         optparser.add_option('-t', '--traceback', action='store_true',
79                       help='print call trace in case of errors')
80         optparser.add_option('-H', '--http-debug', action='store_true',
81                       help='debug HTTP traffic')
82         optparser.add_option('-d', '--debug', action='store_true',
83                       help='print info useful for debugging')
84         optparser.add_option('-A', '--apiurl', dest='apiurl',
85                       metavar='URL/alias',
86                       help='specify URL to access API server at or an alias')
87         optparser.add_option('-c', '--config', dest='conffile',
88                       metavar='FILE',
89                       help='specify alternate configuration file')
90         optparser.add_option('--no-keyring', action='store_true',
91                       help='disable usage of desktop keyring system')
92         optparser.add_option('--no-gnome-keyring', action='store_true',
93                       help='disable usage of GNOME Keyring')
94         optparser.add_option('-v', '--verbose', dest='verbose', action='count', default=0,
95                       help='increase verbosity')
96         optparser.add_option('-q', '--quiet',   dest='verbose', action='store_const', const=-1,
97                       help='be quiet, not verbose')
98         return optparser
99
100
101     def postoptparse(self, try_again = True):
102         """merge commandline options into the config"""
103         try:
104             conf.get_config(override_conffile = self.options.conffile,
105                             override_apiurl = self.options.apiurl,
106                             override_debug = self.options.debug,
107                             override_http_debug = self.options.http_debug,
108                             override_traceback = self.options.traceback,
109                             override_post_mortem = self.options.post_mortem,
110                             override_no_keyring = self.options.no_keyring,
111                             override_no_gnome_keyring = self.options.no_gnome_keyring,
112                             override_verbose = self.options.verbose)
113         except oscerr.NoConfigfile, e:
114             print >>sys.stderr, e.msg
115             print >>sys.stderr, 'Creating osc configuration file %s ...' % e.file
116             import getpass
117             config = {}
118             config['user'] = raw_input('Username: ')
119             config['pass'] = getpass.getpass()
120             if self.options.no_keyring:
121                 config['use_keyring'] = '0'
122             if self.options.no_gnome_keyring:
123                 config['gnome_keyring'] = '0'
124             if self.options.apiurl:
125                 config['apiurl'] = self.options.apiurl
126
127             conf.write_initial_config(e.file, config)
128             print >>sys.stderr, 'done'
129             if try_again: self.postoptparse(try_again = False)
130         except oscerr.ConfigMissingApiurl, e:
131             print >>sys.stderr, e.msg
132             import getpass
133             user = raw_input('Username: ')
134             passwd = getpass.getpass()
135             conf.add_section(e.file, e.url, user, passwd)
136             if try_again: self.postoptparse(try_again = False)
137
138         self.options.verbose = conf.config['verbose']
139         self.download_progress = None
140         if conf.config.get('show_download_progress', False):
141             from meter import TextMeter
142             self.download_progress = TextMeter()
143
144
145     def get_cmd_help(self, cmdname):
146         doc = self._get_cmd_handler(cmdname).__doc__
147         doc = self._help_reindent(doc)
148         doc = self._help_preprocess(doc, cmdname)
149         doc = doc.rstrip() + '\n' # trim down trailing space
150         return self._str(doc)
151
152
153     # overridden from class Cmdln() to use config variables in help texts
154     def _help_preprocess(self, help, cmdname):
155         help = cmdln.Cmdln._help_preprocess(self, help, cmdname)
156         return help % conf.config
157
158
159     def do_init(self, subcmd, opts, project, package=None):
160         """${cmd_name}: Initialize a directory as working copy
161
162         Initialize an existing directory to be a working copy of an
163         (already existing) buildservice project/package.
164
165         (This is the same as checking out a package and then copying sources
166         into the directory. It does NOT create a new package. To create a
167         package, use 'osc meta pkg ... ...')
168
169         You wouldn't normally use this command.
170
171         To get a working copy of a package (e.g. for building it or working on
172         it, you would normally use the checkout command. Use "osc help
173         checkout" to get help for it.
174
175         usage:
176             osc init PRJ
177             osc init PRJ PAC
178         ${cmd_option_list}
179         """
180
181         if not package:
182             init_project_dir(conf.config['apiurl'], os.curdir, project)
183             print 'Initializing %s (Project: %s)' % (os.curdir, project)
184         else:
185             init_package_dir(conf.config['apiurl'], project, package, os.path.curdir)
186             print 'Initializing %s (Project: %s, Package: %s)' % (os.curdir, project, package)
187
188     @cmdln.alias('ls')
189     @cmdln.alias('ll')
190     @cmdln.alias('lL')
191     @cmdln.alias('LL')
192     @cmdln.option('-a', '--arch', metavar='ARCH',
193                         help='specify architecture (only for binaries)')
194     @cmdln.option('-r', '--repo', metavar='REPO',
195                         help='specify repository (only for binaries)')
196     @cmdln.option('-b', '--binaries', action='store_true',
197                         help='list built binaries instead of sources')
198     @cmdln.option('-R', '--revision', metavar='REVISION',
199                         help='specify revision (only for sources)')
200     @cmdln.option('-e', '--expand', action='store_true',
201                         help='expand linked package (only for sources)')
202     @cmdln.option('-u', '--unexpand', action='store_true',
203                         help='always work with unexpanded (source) packages')
204     @cmdln.option('-v', '--verbose', action='store_true',
205                         help='print extra information')
206     @cmdln.option('-l', '--long', action='store_true', dest='verbose',
207                         help='print extra information')
208     def do_list(self, subcmd, opts, *args):
209         """${cmd_name}: List sources or binaries on the server
210
211         Examples for listing sources:
212            ls                         # list all projects
213            ls PROJECT                  # list packages in a project
214            ls PROJECT PACKAGE          # list source files of package of a project
215            ls PROJECT PACKAGE <file>   # list <file> if this file exists
216            ls -v PROJECT PACKAGE       # verbosely list source files of package
217            ls -l PROJECT PACKAGE       # verbosely list source files of package
218            ll PROJECT PACKAGE          # verbosely list source files of package
219            LL PROJECT PACKAGE          # verbosely list source files of expanded link
220
221         With --verbose, the following fields will be shown for each item:
222            MD5 hash of file
223            Revision number of the last commit
224            Size (in bytes)
225            Date and time of the last commit
226
227         Examples for listing binaries:
228            ls -b PROJECT               # list all binaries of a project
229            ls -b PROJECT -a ARCH       # list ARCH binaries of a project
230            ls -b PROJECT -r REPO       # list binaries in REPO
231            ls -b PROJECT PACKAGE REPO ARCH
232
233         Usage:
234            ${cmd_name} [PROJECT [PACKAGE]]
235            ${cmd_name} -b [PROJECT [PACKAGE [REPO [ARCH]]]]
236         ${cmd_option_list}
237         """
238
239         apiurl = conf.config['apiurl']
240         args = slash_split(args)
241         if subcmd == 'll':
242             opts.verbose = True
243         if subcmd == 'lL' or subcmd == 'LL':
244             opts.verbose = True
245             opts.expand = True
246
247         project = None
248         package = None
249         fname = None
250         if len(args) > 0:
251             project = args[0]
252         if len(args) > 1:
253             package = args[1]
254         if len(args) > 2:
255             if opts.binaries:
256                 if opts.repo:
257                     if opts.repo != args[2]:
258                         raise oscerr.WrongArgs("conflicting repos specified ('%s' vs '%s')"%(opts.repo, args[2]))
259                 else:
260                     opts.repo = args[2]
261             else:
262                 fname = args[2]
263
264         if len(args) > 3:
265             if not opts.binaries:
266                 raise oscerr.WrongArgs('Too many arguments')
267             if opts.arch:
268                 if opts.arch != args[3]:
269                     raise oscerr.WrongArgs("conflicting archs specified ('%s' vs '%s')"%(opts.arch, args[3]))
270             else:
271                 opts.arch = args[3]
272
273
274         if opts.binaries and opts.expand:
275             raise oscerr.WrongOptions('Sorry, --binaries and --expand are mutual exclusive.')
276
277         # list binaries
278         if opts.binaries:
279             # ls -b toplevel doesn't make sense, so use info from
280             # current dir if available
281             if len(args) == 0:
282                 dir = os.getcwd()
283                 if is_project_dir(dir):
284                     project = store_read_project(dir)
285                     apiurl = store_read_apiurl(dir)
286                 elif is_package_dir(dir):
287                     project = store_read_project(dir)
288                     package = store_read_package(dir)
289                     apiurl = store_read_apiurl(dir)
290
291             if not project:
292                 raise oscerr.WrongArgs('There are no binaries to list above project level.')
293             if opts.revision:
294                 raise oscerr.WrongOptions('Sorry, the --revision option is not supported for binaries.')
295
296             repos = []
297
298             if opts.repo and opts.arch:
299                 repos.append(Repo(opts.repo, opts.arch))
300             elif opts.repo and not opts.arch:
301                 repos = [repo for repo in get_repos_of_project(apiurl, project) if repo.name == opts.repo]
302             elif opts.arch and not opts.repo:
303                 repos = [repo for repo in get_repos_of_project(apiurl, project) if repo.arch == opts.arch]
304             else:
305                 repos = get_repos_of_project(apiurl, project)
306
307             results = []
308             for repo in repos:
309                 results.append((repo, get_binarylist(apiurl, project, repo.name, repo.arch, package=package, verbose=opts.verbose)))
310
311             for result in results:
312                 indent = ''
313                 if len(results) > 1:
314                     print '%s/%s' % (result[0].name, result[0].arch)
315                     indent = ' '
316
317                 if opts.verbose:
318                     for f in result[1]:
319                         print "%9d %s %-40s" % (f.size, shorttime(f.mtime), f.name)
320                 else:
321                     for f in result[1]:
322                         print indent+f
323
324         # list sources
325         elif not opts.binaries:
326             if not args:
327                 print '\n'.join(meta_get_project_list(conf.config['apiurl']))
328
329             elif len(args) == 1:
330                 if opts.verbose:
331                     if self.options.verbose:
332                         print >>sys.stderr, 'Sorry, the --verbose option is not implemented for projects.'
333                 if opts.expand:
334                     raise oscerr.WrongOptions('Sorry, the --expand option is not implemented for projects.')
335
336                 print '\n'.join(meta_get_packagelist(conf.config['apiurl'], project))
337
338             elif len(args) == 2 or len(args) == 3:
339                 link_seen = False
340                 print_not_found = True
341                 rev = opts.revision
342                 for i in [ 1, 2 ]:
343                     l = meta_get_filelist(conf.config['apiurl'],
344                                       project,
345                                       package,
346                                       verbose=opts.verbose,
347                                       expand=opts.expand,
348                                       revision=rev)
349                     link_seen = '_link' in l
350                     if opts.verbose:
351                         out = [ '%s %7s %9d %s %s' % (i.md5, i.rev, i.size, shorttime(i.mtime), i.name) \
352                             for i in l if not fname or fname == i.name ]
353                         if len(out) > 0:
354                             print_not_found = False
355                             print '\n'.join(out)
356                     elif fname:
357                         if fname in l:
358                             print fname
359                             print_not_found = False
360                     else:
361                         print '\n'.join(l)
362                     if opts.expand or opts.unexpand or not link_seen: break
363                     m = show_files_meta(conf.config['apiurl'], project, package)
364                     li = Linkinfo()
365                     li.read(ET.fromstring(''.join(m)).find('linkinfo'))
366                     if li.haserror():
367                         raise oscerr.LinkExpandError(project, package, li.error)
368                     project, package, rev = li.project, li.package, li.rev
369                     if rev:
370                         print '# -> %s %s (%s)' % (project, package, rev)
371                     else:
372                         print '# -> %s %s (latest)' % (project, package)
373                     opts.expand = True
374                 if fname and print_not_found:
375                     print 'file \'%s\' does not exist' % fname
376
377
378     @cmdln.option('-f', '--force', action='store_true',
379                         help='force generation of new patchinfo file')
380     @cmdln.option('--force-update', action='store_true',
381                         help='drops away collected packages from an already built patch and let it collect again')
382     def do_patchinfo(self, subcmd, opts, *args):
383         """${cmd_name}: Generate and edit a patchinfo file.
384
385         A patchinfo file describes the packages for an update and the kind of
386         problem it solves.
387
388         Examples:
389             osc patchinfo
390             osc patchinfo PATCH_NAME
391         ${cmd_option_list}
392         """
393
394         project_dir = localdir = os.getcwd()
395         if is_project_dir(localdir):
396             project = store_read_project(localdir)
397             apiurl = store_read_apiurl(localdir)
398         else:
399             sys.exit('This command must be called in a checked out project.')
400         patchinfo = None
401         for p in meta_get_packagelist(apiurl, project):
402             if p.startswith("_patchinfo:"):
403                 patchinfo = p
404
405         if opts.force or not patchinfo:
406             print "Creating initial patchinfo..."
407             query='cmd=createpatchinfo'
408             if args and args[0]:
409                 query += "&name=" + args[0]
410             url = makeurl(apiurl, ['source', project], query=query)
411             f = http_POST(url)
412             for p in meta_get_packagelist(apiurl, project):
413                 if p.startswith("_patchinfo:"):
414                     patchinfo = p
415
416         if not os.path.exists(project_dir + "/" + patchinfo):
417             checkout_package(apiurl, project, patchinfo, prj_dir=project_dir)
418
419         if sys.platform[:3] != 'win':
420             editor = os.getenv('EDITOR', default='vim')
421         else:
422             editor = os.getenv('EDITOR', default='notepad')
423         subprocess.call('%s %s' % (editor, project_dir + "/" + patchinfo + "/_patchinfo"), shell=True)
424
425
426     @cmdln.option('-a', '--attribute', metavar='ATTRIBUTE',
427                         help='affect only a given attribute')
428     @cmdln.option('--attribute-defaults', action='store_true',
429                         help='include defined attribute defaults')
430     @cmdln.option('--attribute-project', action='store_true',
431                         help='include project values, if missing in packages ')
432     @cmdln.option('-F', '--file', metavar='FILE',
433                         help='read metadata from FILE, instead of opening an editor. '
434                         '\'-\' denotes standard input. ')
435     @cmdln.option('-e', '--edit', action='store_true',
436                         help='edit metadata')
437     @cmdln.option('-c', '--create', action='store_true',
438                         help='create attribute without values')
439     @cmdln.option('-s', '--set', metavar='ATTRIBUTE_VALUES',
440                         help='set attribute values')
441     @cmdln.option('--delete', action='store_true',
442                         help='delete a pattern or attribute')
443     def do_meta(self, subcmd, opts, *args):
444         """${cmd_name}: Show meta information, or edit it
445
446         Show or edit build service metadata of type <prj|pkg|prjconf|user|pattern>.
447
448         This command displays metadata on buildservice objects like projects,
449         packages, or users. The type of metadata is specified by the word after
450         "meta", like e.g. "meta prj".
451
452         prj denotes metadata of a buildservice project.
453         prjconf denotes the (build) configuration of a project.
454         pkg denotes metadata of a buildservice package.
455         user denotes the metadata of a user.
456         pattern denotes installation patterns defined for a project.
457
458         To list patterns, use 'osc meta pattern PRJ'. An additional argument
459         will be the pattern file to view or edit.
460
461         With the --edit switch, the metadata can be edited. Per default, osc
462         opens the program specified by the environmental variable EDITOR with a
463         temporary file. Alternatively, content to be saved can be supplied via
464         the --file switch. If the argument is '-', input is taken from stdin:
465         osc meta prjconf home:user | sed ... | osc meta prjconf home:user -F -
466
467         When trying to edit a non-existing resource, it is created implicitly.
468
469
470         Examples:
471             osc meta prj PRJ
472             osc meta pkg PRJ PKG
473             osc meta pkg PRJ PKG -e
474             osc meta attribute PRJ [PKG [SUBPACKAGE]] [--attribute ATTRIBUTE] [--create|--delete|--set [value_list]]
475
476         Usage:
477             osc meta <prj|pkg|prjconf|user|pattern|attribute> ARGS...
478             osc meta <prj|pkg|prjconf|user|pattern|attribute> -e|--edit ARGS...
479             osc meta <prj|pkg|prjconf|user|pattern|attribute> -F|--file ARGS...
480             osc meta pattern --delete PRJ PATTERN
481         ${cmd_option_list}
482         """
483
484         args = slash_split(args)
485
486         if not args or args[0] not in metatypes.keys():
487             raise oscerr.WrongArgs('Unknown meta type. Choose one of %s.' \
488                                                % ', '.join(metatypes))
489
490         cmd = args[0]
491         del args[0]
492
493         if cmd in ['pkg']:
494             min_args, max_args = 2, 2
495         elif cmd in ['pattern']:
496             min_args, max_args = 1, 2
497         elif cmd in ['attribute']:
498             min_args, max_args = 1, 3
499         else:
500             min_args, max_args = 1, 1
501         if len(args) < min_args:
502             raise oscerr.WrongArgs('Too few arguments.')
503         if len(args) > max_args:
504             raise oscerr.WrongArgs('Too many arguments.')
505
506         # specific arguments
507         attributepath = []
508         if cmd == 'prj':
509             project = args[0]
510         elif cmd == 'pkg':
511             project, package = args[0:2]
512         elif cmd == 'attribute':
513             project = args[0]
514             if len(args) > 1:
515                 package = args[1]
516             else:
517                 package = None
518                 if opts.attribute_project:
519                     raise oscerr.WrongOptions('--attribute-project works only when also a package is given')
520             if len(args) > 2:
521                 subpackage = args[2]
522             else:
523                 subpackage = None
524             attributepath.append('source')
525             attributepath.append(project)
526             if package:
527                 attributepath.append(package)
528             if subpackage:
529                 attributepath.append(subpackage)
530             attributepath.append('_attribute')
531         elif cmd == 'prjconf':
532             project = args[0]
533         elif cmd == 'user':
534             user = args[0]
535         elif cmd == 'pattern':
536             project = args[0]
537             if len(args) > 1:
538                 pattern = args[1]
539             else:
540                 pattern = None
541                 # enforce pattern argument if needed
542                 if opts.edit or opts.file:
543                     raise oscerr.WrongArgs('A pattern file argument is required.')
544
545         # show
546         if not opts.edit and not opts.file and not opts.delete and not opts.create and not opts.set:
547             if cmd == 'prj':
548                 sys.stdout.write(''.join(show_project_meta(conf.config['apiurl'], project)))
549             elif cmd == 'pkg':
550                 sys.stdout.write(''.join(show_package_meta(conf.config['apiurl'], project, package)))
551             elif cmd == 'attribute':
552                 sys.stdout.write(''.join(show_attribute_meta(conf.config['apiurl'], project, package, subpackage, opts.attribute, opts.attribute_defaults, opts.attribute_project)))
553             elif cmd == 'prjconf':
554                 sys.stdout.write(''.join(show_project_conf(conf.config['apiurl'], project)))
555             elif cmd == 'user':
556                 r = get_user_meta(conf.config['apiurl'], user)
557                 if r:
558                     sys.stdout.write(''.join(r))
559             elif cmd == 'pattern':
560                 if pattern:
561                     r = show_pattern_meta(conf.config['apiurl'], project, pattern)
562                     if r:
563                         sys.stdout.write(''.join(r))
564                 else:
565                     r = show_pattern_metalist(conf.config['apiurl'], project)
566                     if r:
567                         sys.stdout.write('\n'.join(r) + '\n')
568
569         # edit
570         if opts.edit and not opts.file:
571             if cmd == 'prj':
572                 edit_meta(metatype='prj',
573                           edit=True,
574                           path_args=quote_plus(project),
575                           template_args=({
576                                   'name': project,
577                                   'user': conf.config['user']}))
578             elif cmd == 'pkg':
579                 edit_meta(metatype='pkg',
580                           edit=True,
581                           path_args=(quote_plus(project), quote_plus(package)),
582                           template_args=({
583                                   'name': package,
584                                   'user': conf.config['user']}))
585             elif cmd == 'prjconf':
586                 edit_meta(metatype='prjconf',
587                           edit=True,
588                           path_args=quote_plus(project),
589                           template_args=None)
590             elif cmd == 'user':
591                 edit_meta(metatype='user',
592                           edit=True,
593                           path_args=(quote_plus(user)),
594                           template_args=({'user': user}))
595             elif cmd == 'pattern':
596                 edit_meta(metatype='pattern',
597                           edit=True,
598                           path_args=(project, pattern),
599                           template_args=None)
600
601         # create attribute entry
602         if (opts.create or opts.set) and cmd == 'attribute':
603             if not opts.attribute:
604                 raise oscerr.WrongOptions('no attribute given to create')
605             values = ''
606             if opts.set:
607                 opts.set = opts.set.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
608                 for i in opts.set.split(','):
609                     values += '<value>%s</value>' % i
610             aname = opts.attribute.split(":")
611             d = '<attributes><attribute namespace=\'%s\' name=\'%s\' >%s</attribute></attributes>' % (aname[0], aname[1], values)
612             url = makeurl(conf.config['apiurl'], attributepath)
613             for data in streamfile(url, http_POST, data=d):
614                 sys.stdout.write(data)
615
616         # upload file
617         if opts.file:
618
619             if opts.file == '-':
620                 f = sys.stdin.read()
621             else:
622                 try:
623                     f = open(opts.file).read()
624                 except:
625                     sys.exit('could not open file \'%s\'.' % opts.file)
626
627             if cmd == 'prj':
628                 edit_meta(metatype='prj',
629                           data=f,
630                           edit=opts.edit,
631                           path_args=quote_plus(project))
632             elif cmd == 'pkg':
633                 edit_meta(metatype='pkg',
634                           data=f,
635                           edit=opts.edit,
636                           path_args=(quote_plus(project), quote_plus(package)))
637             elif cmd == 'prjconf':
638                 edit_meta(metatype='prjconf',
639                           data=f,
640                           edit=opts.edit,
641                           path_args=quote_plus(project))
642             elif cmd == 'user':
643                 edit_meta(metatype='user',
644                           data=f,
645                           edit=opts.edit,
646                           path_args=(quote_plus(user)))
647             elif cmd == 'pattern':
648                 edit_meta(metatype='pattern',
649                           data=f,
650                           edit=opts.edit,
651                           path_args=(project, pattern))
652
653
654         # delete
655         if opts.delete:
656             path = metatypes[cmd]['path']
657             if cmd == 'pattern':
658                 path = path % (project, pattern)
659                 u = makeurl(conf.config['apiurl'], [path])
660                 http_DELETE(u)
661             elif cmd == 'attribute':
662                 if not opts.attribute:
663                     raise oscerr.WrongOptions('no attribute given to create')
664                 attributepath.append(opts.attribute)
665                 u = makeurl(conf.config['apiurl'], attributepath)
666                 for data in streamfile(u, http_DELETE):
667                     sys.stdout.write(data)
668             else:
669                 raise oscerr.WrongOptions('The --delete switch is only for pattern metadata or attributes.')
670
671
672     @cmdln.option('-m', '--message', metavar='TEXT',
673                   help='specify message TEXT')
674     @cmdln.option('-r', '--revision', metavar='REV',
675                   help='for "create", specify a certain source revision ID (the md5 sum)')
676     @cmdln.option('-s', '--supersede', metavar='SUPERSEDE',
677                   help='Superseding another request by this one')
678     @cmdln.option('--nodevelproject', action='store_true',
679                   help='do not follow a defined devel project ' \
680                        '(primary project where a package is developed)')
681     @cmdln.option('--cleanup', action='store_true',
682                   help='remove package if submission gets accepted (default for home:<id>:branch projects)')
683     @cmdln.option('--no-cleanup', action='store_true',
684                   help='never remove source package on accept, but update its content')
685     @cmdln.option('--no-update', action='store_true',
686                   help='never touch source package on accept (will break source links)')
687     @cmdln.option('-d', '--diff', action='store_true',
688                   help='show diff only instead of creating the actual request')
689     @cmdln.option('--yes', action='store_true',
690                   help='proceed without asking.')
691     @cmdln.alias("sr")
692     @cmdln.alias("submitreq")
693     @cmdln.alias("submitpac")
694     def do_submitrequest(self, subcmd, opts, *args):
695         """${cmd_name}: Create request to submit source into another Project
696
697         [See http://en.opensuse.org/Build_Service/Collaboration for information
698         on this topic.]
699
700         See the "request" command for showing and modifing existing requests.
701
702         usage:
703             osc submitreq [OPTIONS]
704             osc submitreq [OPTIONS] DESTPRJ [DESTPKG]
705             osc submitreq [OPTIONS] SOURCEPRJ SOURCEPKG DESTPRJ [DESTPKG]
706         ${cmd_option_list}
707         """
708
709         src_update = conf.config['submitrequest_on_accept_action'] or None
710         # we should check here for home:<id>:branch and default to update, but that would require OBS 1.7 server
711         if opts.cleanup:
712             src_update = "cleanup"
713         elif opts.no_cleanup:
714             src_update = "update"
715         elif opts.no_update:
716             src_update = "noupdate"
717
718         args = slash_split(args)
719
720         # remove this block later again
721         oldcmds = ['create', 'list', 'log', 'show', 'decline', 'accept', 'delete', 'revoke']
722         if args and args[0] in oldcmds:
723             print "************************************************************************"
724             print "* WARNING: It looks that you are using this command with a             *"
725             print "*          deprecated syntax.                                          *"
726             print "*          Please run \"osc sr --help\" and \"osc rq --help\"              *"
727             print "*          to see the new syntax.                                      *"
728             print "************************************************************************"
729             if args[0] == 'create':
730                 args.pop(0)
731             else:
732                 sys.exit(1)
733
734         if len(args) > 4:
735             raise oscerr.WrongArgs('Too many arguments.')
736
737         if len(args) > 0 and len(args) <= 2 and is_project_dir(os.getcwd()):
738             sys.exit('osc submitrequest from project directory is only working without target specs and for source linked files\n')
739
740         apiurl = conf.config['apiurl']
741
742         if len(args) == 0 and is_project_dir(os.getcwd()):
743             import cgi
744             # submit requests for multiple packages are currently handled via multiple requests
745             # They could be also one request with multiple actions, but that avoids to accepts parts of it.
746             project = store_read_project(os.curdir)
747             apiurl = store_read_apiurl(os.curdir)
748
749             sr_ids = []
750             pi = []
751             pac = []
752             targetprojects = []
753             # loop via all packages for checking their state
754             for p in meta_get_packagelist(apiurl, project):
755                 if p.startswith("_patchinfo:"):
756                     pi.append(p)
757                 else:
758                     # get _link info from server, that knows about the local state ...
759                     u = makeurl(apiurl, ['source', project, p])
760                     f = http_GET(u)
761                     root = ET.parse(f).getroot()
762                     linkinfo = root.find('linkinfo')
763                     if linkinfo == None:
764                         print "Package ", p, " is not a source link."
765                         sys.exit("This is currently not supported.")
766                     if linkinfo.get('error'):
767                         print "Package ", p, " is a broken source link."
768                         sys.exit("Please fix this first")
769                     t = linkinfo.get('project')
770                     if t:
771                         if len(root.findall('entry')) > 1: # This is not really correct, but should work mostly
772                                                            # Real fix is to ask the api if sources are modificated
773                                                            # but there is no such call yet.
774                             targetprojects.append(t)
775                             pac.append(p)
776                             print "Submitting package ", p
777                         else:
778                             print "  Skipping package ", p
779                     else:
780                         print "Skipping package ", p,  " since it is a source link pointing inside the project."
781
782             if not opts.yes:
783                 if pi:
784                     print "Submitting patchinfo ", ', '.join(pi), " to ", ', '.join(targetprojects)
785                 print "\nEverything fine? Can we create the requests ? [y/n]"
786                 if sys.stdin.read(1) != "y":
787                     print >>sys.stderr, 'Aborted...'
788                     raise oscerr.UserAbort()
789
790             # loop via all packages to do the action
791             for p in pac:
792                 result = create_submit_request(apiurl, project, p)
793                 if not result:
794 #                    sys.exit(result)
795                     sys.exit("submit request creation failed")
796                 sr_ids.append(result)
797
798             # create submit requests for all found patchinfos
799             actionxml=""
800             options_block=""
801             if src_update:
802                 options_block="""<options><sourceupdate>%s</sourceupdate></options> """ % (src_update)
803
804             for p in pi:
805                 for t in targetprojects:
806                     s = """<action type="submit"> <source project="%s" package="%s" /> <target project="%s" package="%s" /> %s </action>"""  % \
807                            (project, p, t, p, options_block)
808                     actionxml += s
809
810             if actionxml != "":
811                 xml = """<request> %s <state name="new"/> <description>%s</description> </request> """ % \
812                       (actionxml, cgi.escape(opts.message or ""))
813                 u = makeurl(apiurl, ['request'], query='cmd=create')
814                 f = http_POST(u, data=xml)
815
816                 root = ET.parse(f).getroot()
817                 sr_ids.append(root.get('id'))
818
819             print "Requests created: ",
820             for i in sr_ids:
821                 print i,
822             sys.exit('Successfull finished')
823
824         elif len(args) <= 2:
825             # try using the working copy at hand
826             p = findpacs(os.curdir)[0]
827             src_project = p.prjname
828             src_package = p.name
829             apiurl = p.apiurl
830             if len(args) == 0 and p.islink():
831                 dst_project = p.linkinfo.project
832                 dst_package = p.linkinfo.package
833             elif len(args) > 0:
834                 dst_project = args[0]
835                 if len(args) == 2:
836                     dst_package = args[1]
837                 else:
838                     dst_package = src_package
839             else:
840                 sys.exit('Package \'%s\' is not a source link, so I cannot guess the submit target.\n'
841                          'Please provide it the target via commandline arguments.' % p.name)
842
843             modified = [i for i in p.filenamelist if p.status(i) != ' ' and p.status(i) != '?']
844             if len(modified) > 0:
845                 print 'Your working copy has local modifications.'
846                 repl = raw_input('Proceed without committing the local changes? (y|N) ')
847                 if repl != 'y':
848                     raise oscerr.UserAbort()
849         elif len(args) >= 3:
850             # get the arguments from the commandline
851             src_project, src_package, dst_project = args[0:3]
852             if len(args) == 4:
853                 dst_package = args[3]
854             else:
855                 dst_package = src_package
856         else:
857             raise oscerr.WrongArgs('Incorrect number of arguments.\n\n' \
858                   + self.get_cmd_help('request'))
859
860         if not opts.nodevelproject:
861             devloc = None
862             try:
863                 devloc = show_develproject(apiurl, dst_project, dst_package)
864             except urllib2.HTTPError:
865                 print >>sys.stderr, """\
866 Warning: failed to fetch meta data for '%s' package '%s' (new package?) """ \
867                     % (dst_project, dst_package)
868                 pass
869
870             if devloc and \
871                dst_project != devloc and \
872                src_project != devloc:
873                 print """\
874 A different project, %s, is defined as the place where development
875 of the package %s primarily takes place.
876 Please submit there instead, or use --nodevelproject to force direct submission.""" \
877                 % (devloc, dst_package)
878                 if not opts.diff:
879                     sys.exit(1)
880
881         rdiff = None
882         if opts.diff or not opts.message:
883             try:
884                 rdiff = 'old: %s/%s\nnew: %s/%s' %(dst_project, dst_package, src_project, src_package)
885                 rdiff += server_diff(apiurl,
886                                     dst_project, dst_package, opts.revision,
887                                     src_project, src_package, None, True)
888             except:
889                 rdiff = ''
890         if opts.diff:
891             print rdiff
892         else:
893             reqs = get_request_list(apiurl, dst_project, dst_package, req_type='submit')
894             user = conf.get_apiurl_usr(apiurl)
895             myreqs = [ i for i in reqs if i.state.who == user ]
896             repl = ''
897             if len(myreqs) > 0:
898                 print 'You already created the following submit request: %s.' % \
899                       ', '.join([str(i.reqid) for i in myreqs ])
900                 repl = raw_input('Supersede the old requests? (y/n/c) ')
901                 if repl.lower() == 'c':
902                     print >>sys.stderr, 'Aborting'
903                     raise oscerr.UserAbort()
904
905             if not opts.message:
906                 difflines = []
907                 doappend = False
908                 changes_re = re.compile(r'^--- .*\.changes ')
909                 for line in rdiff.split('\n'):
910                     if line.startswith('--- '):
911                         if changes_re.match(line):
912                             doappend = True
913                         else:
914                             doappend = False
915                     if doappend:
916                         difflines.append(line)
917                 opts.message = edit_message(footer=rdiff, template='\n'.join(parse_diff_for_commit_message('\n'.join(difflines))))
918
919             result = create_submit_request(apiurl,
920                                            src_project, src_package,
921                                            dst_project, dst_package,
922                                            opts.message, orev=opts.revision, src_update=src_update)
923             if repl.lower() == 'y':
924                 for req in myreqs:
925                     change_request_state(apiurl, str(req.reqid), 'superseded',
926                                          'superseded by %s' % result, result)
927
928             if opts.supersede:
929                 r = change_request_state(conf.config['apiurl'],
930                         opts.supersede, 'superseded', opts.message or '', result)
931
932             print 'created request id', result
933
934
935     @cmdln.option('-m', '--message', metavar='TEXT',
936                   help='specify message TEXT')
937     @cmdln.alias("dr")
938     @cmdln.alias("deletereq")
939     def do_deleterequest(self, subcmd, opts, *args):
940         """${cmd_name}: Create request to delete a package or project
941
942
943         usage:
944             osc deletereq [-m TEXT] PROJECT [PACKAGE]
945         ${cmd_option_list}
946         """
947
948         args = slash_split(args)
949
950         if len(args) < 1:
951             raise oscerr.WrongArgs('Please specify at least a project.')
952         if len(args) > 2:
953             raise oscerr.WrongArgs('Too many arguments.')
954
955         apiurl = conf.config['apiurl']
956
957         project = args[0]
958         package = None
959         if len(args) > 1:
960             package = args[1]
961
962         if not opts.message:
963             opts.message = edit_message()
964
965         result = create_delete_request(apiurl, project, package, opts.message)
966         print result
967
968
969     @cmdln.option('-m', '--message', metavar='TEXT',
970                   help='specify message TEXT')
971     @cmdln.alias("cr")
972     @cmdln.alias("changedevelreq")
973     def do_changedevelrequest(self, subcmd, opts, *args):
974         """${cmd_name}: Create request to change the devel package definition.
975
976         [See http://en.opensuse.org/Build_Service/Collaboration for information
977         on this topic.]
978
979         See the "request" command for showing and modifing existing requests.
980
981         osc changedevelrequest PROJECT PACKAGE DEVEL_PROJECT [DEVEL_PACKAGE]
982         """
983
984         if len(args) > 4:
985             raise oscerr.WrongArgs('Too many arguments.')
986
987         if len(args) == 0 and is_package_dir('.') and len(conf.config['getpac_default_project']):
988             wd = os.curdir
989             devel_project = store_read_project(wd)
990             devel_package = package = store_read_package(wd)
991             apiurl = store_read_apiurl(wd)
992             project = conf.config['getpac_default_project']
993         else:
994             if len(args) < 3:
995                 raise oscerr.WrongArgs('Too few arguments.')
996
997             apiurl = conf.config['apiurl']
998
999             devel_project = args[2]
1000             project = args[0]
1001             package = args[1]
1002             devel_package = package
1003             if len(args) > 3:
1004                 devel_package = args[3]
1005
1006         if not opts.message:
1007             import textwrap
1008             footer=textwrap.TextWrapper(width = 66).fill(
1009                     'please explain why you like to change the devel project of %s/%s to %s/%s'
1010                     % (project,package,devel_project,devel_package))
1011             opts.message = edit_message(footer)
1012
1013         result = create_change_devel_request(apiurl,
1014                                        devel_project, devel_package,
1015                                        project, package,
1016                                        opts.message)
1017         print result
1018
1019
1020     @cmdln.option('-d', '--diff', action='store_true',
1021                   help='generate a diff')
1022     @cmdln.option('-u', '--unified', action='store_true',
1023                   help='output the diff in the unified diff format')
1024     @cmdln.option('-m', '--message', metavar='TEXT',
1025                   help='specify message TEXT')
1026     @cmdln.option('-t', '--type', metavar='TYPE',
1027                   help='limit to requests which contain a given action type (submit/delete/change_devel)')
1028     @cmdln.option('-a', '--all', action='store_true',
1029                         help='all states. Same as\'-s all\'')
1030     @cmdln.option('-s', '--state', default='',  # default is 'all' if no args given, 'new' otherwise
1031                         help='only list requests in one of the comma separated given states (new/accepted/revoked/declined) or "all" [default=new, or all, if no args given]')
1032     @cmdln.option('-D', '--days', metavar='DAYS',
1033                         help='only list requests in state "new" or changed in the last DAYS. [default=%(request_list_days)s]')
1034     @cmdln.option('-U', '--user', metavar='USER',
1035                         help='same as -M, but for the specified USER')
1036     @cmdln.option('-b', '--brief', action='store_true', default=False,
1037                         help='print output in list view as list subcommand')
1038     @cmdln.option('-M', '--mine', action='store_true',
1039                         help='only show requests created by yourself')
1040     @cmdln.option('-B', '--bugowner', action='store_true',
1041                         help='also show requests about packages where I am bugowner')
1042     @cmdln.option('-i', '--interactive', action='store_true',
1043                         help='interactive review of request')
1044     @cmdln.option('--non-interactive', action='store_true',
1045                         help='non-interactive review of request')
1046     @cmdln.option('--exclude-target-project', action='append',
1047                         help='exclude target project from request list')
1048     @cmdln.option('--involved-projects', action='store_true',
1049                         help='show all requests for project/packages where USER is involved')
1050     @cmdln.alias("rq")
1051     @cmdln.alias("review")
1052     def do_request(self, subcmd, opts, *args):
1053         """${cmd_name}: Show and modify requests
1054
1055         [See http://en.opensuse.org/Build_Service/Collaboration for information
1056         on this topic.]
1057
1058         This command shows and modifies existing requests. To create new requests
1059         you need to call one of the following:
1060           osc submitrequest
1061           osc deleterequest
1062           osc changedevelrequest
1063         To send low level requests to the buildservice API, use:
1064           osc api
1065
1066         This command has the following sub commands:
1067
1068         "list" lists open requests attached to a project or package or person.
1069         Uses the project/package of the current directory if none of
1070         -M, -U USER, project/package are given.
1071
1072         "log" will show the history of the given ID
1073
1074         "show" will show the request itself, and generate a diff for review, if
1075         used with the --diff option. The keyword show can be omitted if the ID is numeric.
1076
1077         "decline" will change the request state to "declined" and append a
1078         message that you specify with the --message option.
1079
1080         "wipe" will permanently delete a request.
1081
1082         "revoke" will set the request state to "revoked" and append a
1083         message that you specify with the --message option.
1084
1085         "accept" will change the request state to "accepted" and will trigger
1086         the actual submit process. That would normally be a server-side copy of
1087         the source package to the target package.
1088
1089         "checkout" will checkout the request's source package. This only works for "submit" requests.
1090
1091         usage:
1092             osc request list [-M] [-U USER] [-s state] [-D DAYS] [-t type] [-B] [PRJ [PKG]]
1093             osc request log ID
1094             osc request [show] [-d] [-b] ID
1095             osc request accept [-m TEXT] ID
1096             osc request decline [-m TEXT] ID
1097             osc request revoke [-m TEXT] ID
1098             osc request wipe ID
1099             osc request checkout/co ID
1100             osc review accept [-m TEXT] ID
1101             osc review decline [-m TEXT] ID
1102         ${cmd_option_list}
1103         """
1104
1105         args = slash_split(args)
1106
1107         if opts.all and opts.state:
1108             raise oscerr.WrongOptions('Sorry, the options \'--all\' and \'--state\' ' \
1109                     'are mutually exclusive.')
1110         if opts.mine and opts.user:
1111             raise oscerr.WrongOptions('Sorry, the options \'--user\' and \'--mine\' ' \
1112                     'are mutually exclusive.')
1113         if opts.interactive and opts.non_interactive:
1114             raise oscerr.WrongOptions('Sorry, the options \'--interactive\' and ' \
1115                     '\'--non-interactive\' are mutually exclusive')
1116
1117         if not args:
1118             args = [ 'list' ]
1119             opts.mine = 1
1120             if opts.state == '':
1121                 opts.state = 'all'
1122
1123         if opts.state == '':
1124             opts.state = 'new'
1125
1126         cmds = ['list', 'log', 'show', 'decline', 'accept', 'wipe', 'revoke', 'checkout', 'co', 'help']
1127         if not args or args[0] not in cmds:
1128             raise oscerr.WrongArgs('Unknown request action %s. Choose one of %s.' \
1129                                                % (args[0],', '.join(cmds)))
1130
1131         cmd = args[0]
1132         del args[0]
1133
1134         if cmd == 'help':
1135             return self.do_help(['help', 'request'])
1136
1137         if cmd in ['wipe']:
1138             min_args, max_args = 1, 1
1139         elif cmd in ['list']:
1140             min_args, max_args = 0, 2
1141         else:
1142             min_args, max_args = 1, 1
1143         if len(args) < min_args:
1144             raise oscerr.WrongArgs('Too few arguments.')
1145         if len(args) > max_args:
1146             raise oscerr.WrongArgs('Too many arguments.')
1147
1148         apiurl = conf.config['apiurl']
1149
1150         if cmd == 'list':
1151             package = None
1152             project = None
1153             if len(args) > 0:
1154                 project = args[0]
1155             elif not opts.mine and not opts.user:
1156                 try:
1157                     project = store_read_project(os.curdir)
1158                     apiurl = store_read_apiurl(os.curdir)
1159                     package = store_read_package(os.curdir)
1160                 except oscerr.NoWorkingCopy:
1161                     pass
1162
1163             if len(args) > 1:
1164                 package = args[1]
1165         elif cmd in ['log', 'show', 'decline', 'accept', 'wipe', 'revoke', 'checkout', 'co']:
1166             reqid = args[0]
1167
1168         # list
1169         if cmd == 'list':
1170             states = ('new', 'accepted', 'revoked', 'declined')
1171             state_list = opts.state.split(',')
1172             if opts.state == 'all':
1173                 state_list = ['all']
1174             else:
1175                 for s in state_list:
1176                     if not s in states:
1177                         raise oscerr.WrongArgs('Unknown state \'%s\', try one of %s' % (s, ','.join(states)))
1178             who = ''
1179             if opts.mine:
1180                 who = conf.get_apiurl_usr(apiurl)
1181             if opts.user:
1182                 who = opts.user
1183             if opts.all:
1184                 state_list = ['all']
1185
1186             ## FIXME -B not implemented!
1187             if opts.bugowner:
1188                 if (self.options.debug):
1189                     print 'list: option --bugowner ignored: not impl.'
1190
1191             if opts.involved_projects:
1192                 who = who or conf.get_apiurl_usr(apiurl)
1193                 results = get_user_projpkgs_request_list(apiurl, who, req_state=state_list,
1194                                                          req_type=opts.type, exclude_projects=opts.exclude_target_project or [])
1195             else:
1196                 results = get_request_list(apiurl, project, package, who,
1197                                            state_list, opts.type, opts.exclude_target_project or [])
1198             results.sort(reverse=True)
1199             import time
1200             days = opts.days or conf.config['request_list_days']
1201             since = ''
1202             try:
1203                 days = int(days)
1204             except ValueError:
1205                 days = 0
1206             if days > 0:
1207                 since = time.strftime('%Y-%m-%dT%H:%M:%S',time.localtime(time.time()-days*24*3600))
1208
1209             skipped = 0
1210             ## bs has received 2009-09-20 a new xquery compare() function
1211             ## which allows us to limit the list inside of get_request_list
1212             ## That would be much faster for coolo. But counting the remainder
1213             ## would not be possible with current xquery implementation.
1214             ## Workaround: fetch all, and filter on client side.
1215
1216             ## FIXME: date filtering should become implemented on server side
1217             for result in results:
1218                 if days == 0 or result.state.when > since or result.state.name == 'new':
1219                     print result.list_view()
1220                 else:
1221                     skipped += 1
1222             if skipped:
1223                 print "There are %d requests older than %s days.\n" % (skipped, days)
1224
1225         elif cmd == 'log':
1226             for l in get_request_log(conf.config['apiurl'], reqid):
1227                 print l
1228
1229         # show
1230         elif cmd == 'show':
1231             r = get_request(conf.config['apiurl'], reqid)
1232             if opts.brief:
1233                 print r.list_view()
1234             elif (opts.interactive or conf.config['request_show_interactive']) and not opts.non_interactive:
1235                 return request_interactive_review(conf.config['apiurl'], r)
1236             else:
1237                 print r
1238             # fixme: will inevitably fail if the given target doesn't exist
1239             if opts.diff and r.actions[0].type != 'submit':
1240                 raise oscerr.WrongOptions('\'--diff\' is not possible for request type: \'%s\'' % r.actions[0].type)
1241             elif opts.diff:
1242                 try:
1243                     print server_diff(conf.config['apiurl'],
1244                                       r.actions[0].dst_project, r.actions[0].dst_package, None,
1245                                       r.actions[0].src_project, r.actions[0].src_package, r.actions[0].src_rev, opts.unified, True)
1246                 except urllib2.HTTPError, e:
1247                     e.osc_msg = 'Diff not possible'
1248                     raise
1249
1250         # checkout
1251         elif cmd == 'checkout' or cmd == 'co':
1252             r = get_request(conf.config['apiurl'], reqid)
1253             submits = [ i for i in r.actions if i.type == 'submit' ]
1254             if not len(submits):
1255                 raise oscerr.WrongArgs('\'checkout\' only works for \'submit\' requests')
1256             checkout_package(conf.config['apiurl'], submits[0].src_project, submits[0].src_package, \
1257                 submits[0].src_rev, expand_link=True, prj_dir=submits[0].src_project)
1258
1259         else:
1260             if not opts.message:
1261                 opts.message = edit_message()
1262             state_map = {'accept' : 'accepted', 'decline' : 'declined', 'wipe' : 'deleted', 'revoke' : 'revoked'}
1263             # Change review state only
1264             if subcmd == 'review':
1265                 if cmd in ['accept', 'decline']:
1266                     r = change_review_state(conf.config['apiurl'],
1267                             reqid, state_map[cmd], conf.config['user'], '', opts.message or '')
1268                     print r
1269             # Change state of entire request
1270             elif cmd in ['accept', 'decline', 'wipe', 'revoke']:
1271                 r = change_request_state(conf.config['apiurl'],
1272                         reqid, state_map[cmd], opts.message or '')
1273                 print r
1274
1275     # editmeta and its aliases are all depracated
1276     @cmdln.alias("editprj")
1277     @cmdln.alias("createprj")
1278     @cmdln.alias("editpac")
1279     @cmdln.alias("createpac")
1280     @cmdln.alias("edituser")
1281     @cmdln.alias("usermeta")
1282     @cmdln.hide(1)
1283     def do_editmeta(self, subcmd, opts, *args):
1284         """${cmd_name}:
1285
1286         Obsolete command to edit metadata. Use 'meta' now.
1287
1288         See the help output of 'meta'.
1289
1290         """
1291
1292         print >>sys.stderr, 'This command is obsolete. Use \'osc meta <metatype> ...\'.'
1293         print >>sys.stderr, 'See \'osc help meta\'.'
1294         #self.do_help([None, 'meta'])
1295         return 2
1296
1297
1298     @cmdln.option('-r', '--revision', metavar='rev',
1299                   help='use the specified revision.')
1300     @cmdln.option('-u', '--unset', action='store_true',
1301                   help='remove revision in link, it will point always to latest revision')
1302     def do_setlinkrev(self, subcmd, opts, *args):
1303         """${cmd_name}: Updates a revision number in a source link.
1304
1305         This command adds or updates a specified revision number in a source link.
1306         The current revision of the source is used, if no revision number is specified.
1307
1308         usage:
1309             osc setlinkrev
1310             osc setlinkrev PROJECT [PACKAGE]
1311         ${cmd_option_list}
1312         """
1313
1314         args = slash_split(args)
1315         apiurl = conf.config['apiurl']
1316         package = None
1317         if len(args) == 0:
1318             p = findpacs(os.curdir)[0]
1319             project = p.prjname
1320             package = p.name
1321             apiurl = p.apiurl
1322             if not p.islink():
1323                 sys.exit('Local directory is no checked out source link package, aborting')
1324         elif len(args) == 2:
1325             project = args[0]
1326             package = args[1]
1327         elif len(args) == 1:
1328             project = args[0]
1329         else:
1330             raise oscerr.WrongArgs('Incorrect number of arguments.\n\n' \
1331                   + self.get_cmd_help('setlinkrev'))
1332
1333         if package:
1334             packages = [ package ]
1335         else:
1336             packages = meta_get_packagelist(apiurl, project)
1337
1338         for p in packages:
1339             print "setting revision for package", p
1340             if opts.unset:
1341                 rev=-1
1342             else:
1343                 rev, dummy = parseRevisionOption(opts.revision)
1344             set_link_rev(apiurl, project, p, rev)
1345
1346
1347     def do_linktobranch(self, subcmd, opts, *args):
1348         """${cmd_name}: Convert a package containing a classic link with patch to a branch
1349
1350         This command tells the server to convert a _link with or without a project.diff
1351         to a branch. This is a full copy with a _link file pointing to the branched place.
1352
1353         usage:
1354             osc linktobranch                    # can be used in checked out package
1355             osc linktobranch PROJECT PACKAGE
1356         ${cmd_option_list}
1357         """
1358
1359         args = slash_split(args)
1360         if len(args) == 0:
1361             wd = os.curdir
1362             project = store_read_project(wd)
1363             package = store_read_package(wd)
1364             apiurl = store_read_apiurl(wd)
1365             update_local_dir = True
1366         elif len(args) < 2:
1367             raise oscerr.WrongArgs('Too few arguments (required none or two)')
1368         elif len(args) > 2:
1369             raise oscerr.WrongArgs('Too many arguments (required none or two)')
1370         else:
1371             apiurl = conf.config['apiurl']
1372             project = args[0]
1373             package = args[1]
1374             update_local_dir = False
1375
1376         # execute
1377         link_to_branch(apiurl, project, package)
1378         if update_local_dir:
1379             pac = Package(wd)
1380             pac.update(rev=pac.latest_rev())
1381
1382
1383     @cmdln.option('-C', '--cicount', choices=['add', 'copy', 'local'],
1384                   help='cicount attribute in the link, known values are add, copy, and local, default in buildservice is currently add.')
1385     @cmdln.option('-c', '--current', action='store_true',
1386                   help='link fixed against current revision.')
1387     @cmdln.option('-r', '--revision', metavar='rev',
1388                   help='link the specified revision.')
1389     @cmdln.option('-f', '--force', action='store_true',
1390                   help='overwrite an existing link file if it is there.')
1391     @cmdln.option('-d', '--disable-publish', action='store_true',
1392                   help='disable publishing of the linked package')
1393     def do_linkpac(self, subcmd, opts, *args):
1394         """${cmd_name}: "Link" a package to another package
1395
1396         A linked package is a clone of another package, but plus local
1397         modifications. It can be cross-project.
1398
1399         The DESTPAC name is optional; the source packages' name will be used if
1400         DESTPAC is omitted.
1401
1402         Afterwards, you will want to 'checkout DESTPRJ DESTPAC'.
1403
1404         To add a patch, add the patch as file and add it to the _link file.
1405         You can also specify text which will be inserted at the top of the spec file.
1406
1407         See the examples in the _link file.
1408
1409         usage:
1410             osc linkpac SOURCEPRJ SOURCEPAC DESTPRJ [DESTPAC]
1411         ${cmd_option_list}
1412         """
1413
1414         args = slash_split(args)
1415
1416         if not args or len(args) < 3:
1417             raise oscerr.WrongArgs('Incorrect number of arguments.\n\n' \
1418                   + self.get_cmd_help('linkpac'))
1419
1420         rev, dummy = parseRevisionOption(opts.revision)
1421
1422         src_project = args[0]
1423         src_package = args[1]
1424         dst_project = args[2]
1425         if len(args) > 3:
1426             dst_package = args[3]
1427         else:
1428             dst_package = src_package
1429
1430         if src_project == dst_project and src_package == dst_package:
1431             raise oscerr.WrongArgs('Error: source and destination are the same.')
1432
1433         if src_project == dst_project and not opts.cicount:
1434             # in this case, the user usually wants to build different spec
1435             # files from the same source
1436             opts.cicount = "copy"
1437
1438         if opts.current:
1439             rev = show_upstream_rev(conf.config['apiurl'], src_project, src_package)
1440
1441         if rev and not checkRevision(src_project, src_package, rev):
1442             print >>sys.stderr, 'Revision \'%s\' does not exist' % rev
1443             sys.exit(1)
1444
1445         link_pac(src_project, src_package, dst_project, dst_package, opts.force, rev, opts.cicount, opts.disable_publish)
1446
1447     @cmdln.option('-m', '--map-repo', metavar='SRC=TARGET[,SRC=TARGET]',
1448                   help='Allows repository mapping(s) to be given as SRC=TARGET[,SRC=TARGET]')
1449     @cmdln.option('-d', '--disable-publish', action='store_true',
1450                   help='disable publishing of the aggregated package')
1451     def do_aggregatepac(self, subcmd, opts, *args):
1452         """${cmd_name}: "Aggregate" a package to another package
1453
1454         Aggregation of a package means that the build results (binaries) of a
1455         package are basically copied into another project.
1456         This can be used to make packages available from building that are
1457         needed in a project but available only in a different project. Note
1458         that this is done at the expense of disk space. See
1459         http://en.opensuse.org/Build_Service/Tips_and_Tricks#_link_and__aggregate
1460         for more information.
1461
1462         The DESTPAC name is optional; the source packages' name will be used if
1463         DESTPAC is omitted.
1464
1465         usage:
1466             osc aggregatepac SOURCEPRJ SOURCEPAC DESTPRJ [DESTPAC]
1467         ${cmd_option_list}
1468         """
1469
1470         args = slash_split(args)
1471
1472         if not args or len(args) < 3:
1473             raise oscerr.WrongArgs('Incorrect number of arguments.\n\n' \
1474                   + self.get_cmd_help('aggregatepac'))
1475
1476         src_project = args[0]
1477         src_package = args[1]
1478         dst_project = args[2]
1479         if len(args) > 3:
1480             dst_package = args[3]
1481         else:
1482             dst_package = src_package
1483
1484         if src_project == dst_project and src_package == dst_package:
1485             raise oscerr.WrongArgs('Error: source and destination are the same.')
1486
1487         repo_map = {}
1488         if opts.map_repo:
1489             for pair in opts.map_repo.split(','):
1490                 src_tgt = pair.split('=')
1491                 if len(src_tgt) != 2:
1492                     raise oscerr.WrongOptions('map "%s" must be SRC=TARGET[,SRC=TARGET]' % opts.map_repo)
1493                 repo_map[src_tgt[0]] = src_tgt[1]
1494
1495         aggregate_pac(src_project, src_package, dst_project, dst_package, repo_map, opts.disable_publish)
1496
1497
1498     @cmdln.option('-c', '--client-side-copy', action='store_true',
1499                         help='do a (slower) client-side copy')
1500     @cmdln.option('-k', '--keep-maintainers', action='store_true',
1501                         help='keep original maintainers. Default is remove all and replace with the one calling the script.')
1502     @cmdln.option('-d', '--keep-develproject', action='store_true',
1503                         help='keep develproject tag in the package metadata')
1504     @cmdln.option('-r', '--revision', metavar='rev',
1505                         help='link the specified revision.')
1506     @cmdln.option('-t', '--to-apiurl', metavar='URL',
1507                         help='URL of destination api server. Default is the source api server.')
1508     @cmdln.option('-m', '--message', metavar='TEXT',
1509                   help='specify message TEXT')
1510     @cmdln.option('-e', '--expand', action='store_true',
1511                         help='if the source package is a link then copy the expanded version of the link')
1512     def do_copypac(self, subcmd, opts, *args):
1513         """${cmd_name}: Copy a package
1514
1515         A way to copy package to somewhere else.
1516
1517         It can be done across buildservice instances, if the -t option is used.
1518         In that case, a client-side copy is implied.
1519
1520         Using --client-side-copy always involves downloading all files, and
1521         uploading them to the target.
1522
1523         The DESTPAC name is optional; the source packages' name will be used if
1524         DESTPAC is omitted.
1525
1526         usage:
1527             osc copypac SOURCEPRJ SOURCEPAC DESTPRJ [DESTPAC]
1528         ${cmd_option_list}
1529         """
1530
1531         args = slash_split(args)
1532
1533         if not args or len(args) < 3:
1534             raise oscerr.WrongArgs('Incorrect number of arguments.\n\n' \
1535                   + self.get_cmd_help('copypac'))
1536
1537         src_project = args[0]
1538         src_package = args[1]
1539         dst_project = args[2]
1540         if len(args) > 3:
1541             dst_package = args[3]
1542         else:
1543             dst_package = src_package
1544
1545         src_apiurl = conf.config['apiurl']
1546         if opts.to_apiurl:
1547             dst_apiurl = conf.config['apiurl_aliases'].get(opts.to_apiurl, opts.to_apiurl)
1548         else:
1549             dst_apiurl = src_apiurl
1550
1551         if src_project == dst_project and \
1552            src_package == dst_package and \
1553            src_apiurl == dst_apiurl:
1554             raise oscerr.WrongArgs('Source and destination are the same.')
1555
1556         if src_apiurl != dst_apiurl:
1557             opts.client_side_copy = True
1558
1559         rev, dummy = parseRevisionOption(opts.revision)
1560
1561         if opts.message:
1562             comment = opts.message
1563         else:
1564             if not rev:
1565                 rev = show_upstream_rev(src_apiurl, src_project, src_package)
1566             comment = 'osc copypac from project:%s package:%s revision:%s' % ( src_project, src_package, rev )
1567
1568         r = copy_pac(src_apiurl, src_project, src_package,
1569                      dst_apiurl, dst_project, dst_package,
1570                      client_side_copy=opts.client_side_copy,
1571                      keep_maintainers=opts.keep_maintainers,
1572                      keep_develproject=opts.keep_develproject,
1573                      expand=opts.expand,
1574                      revision=rev,
1575                      comment=comment)
1576         print r
1577
1578
1579     @cmdln.option('-c', '--checkout', action='store_true',
1580                         help='Checkout branched package afterwards ' \
1581                                 '(\'osc bco\' is a shorthand for this option)' )
1582     @cmdln.option('-a', '--attribute', metavar='ATTRIBUTE',
1583                         help='Use this attribute to find affected packages (default is OBS:Maintained)')
1584     @cmdln.option('-u', '--update-project-attribute', metavar='UPDATE_ATTRIBUTE',
1585                         help='Use this attribute to find update projects (default is OBS:UpdateProject) ')
1586     def do_mbranch(self, subcmd, opts, *args):
1587         """${cmd_name}: Multiple branch of a package
1588
1589         [See http://en.opensuse.org/Build_Service/Concepts/Maintenance for information
1590         on this topic.]
1591
1592         This command is used for creating multiple links of defined version of a package
1593         in one project. This is esp. used for maintenance updates.
1594
1595         The branched package will live in
1596             home:USERNAME:branches:ATTRIBUTE:PACKAGE
1597         if nothing else specified.
1598
1599         usage:
1600             osc mbranch [ SOURCEPACKAGE [ TARGETPROJECT ] ]
1601         ${cmd_option_list}
1602         """
1603         args = slash_split(args)
1604         tproject = None
1605
1606         maintained_attribute = conf.config['maintained_attribute']
1607         maintained_update_project_attribute = conf.config['maintained_update_project_attribute']
1608
1609         if not len(args) or len(args) > 2:
1610             raise oscerr.WrongArgs('Wrong number of arguments.')
1611         if len(args) >= 1:
1612             package = args[0]
1613         if len(args) >= 2:
1614             tproject = args[1]
1615
1616         r = attribute_branch_pkg(conf.config['apiurl'], maintained_attribute, maintained_update_project_attribute, \
1617                                  package, tproject)
1618
1619         if r is None:
1620             print >>sys.stderr, 'ERROR: Attribute branch call came not back with a project.'
1621             sys.exit(1)
1622
1623         print "Project " + r + " created."
1624
1625         if opts.checkout:
1626             init_project_dir(conf.config['apiurl'], r, r)
1627             print statfrmt('A', r)
1628
1629             # all packages
1630             for package in meta_get_packagelist(conf.config['apiurl'], r):
1631                 try:
1632                     checkout_package(conf.config['apiurl'], r, package, expand_link = True, prj_dir = r)
1633                 except:
1634                     print >>sys.stderr, 'Error while checkout package:\n', package
1635
1636             if conf.config['verbose']:
1637                 print 'Note: You can use "osc delete" or "osc submitpac" when done.\n'
1638
1639
1640     @cmdln.alias('branchco')
1641     @cmdln.alias('bco')
1642     @cmdln.alias('getpac')
1643     @cmdln.option('--nodevelproject', action='store_true',
1644                         help='do not follow a defined devel project ' \
1645                              '(primary project where a package is developed)')
1646     @cmdln.option('-c', '--checkout', action='store_true',
1647                         help='Checkout branched package afterwards ' \
1648                                 '(\'osc bco\' is a shorthand for this option)' )
1649     @cmdln.option('-r', '--revision', metavar='rev',
1650                         help='branch against a specific revision')
1651     @cmdln.option('-m', '--message', metavar='TEXT',
1652                         help='specify message TEXT')
1653     def do_branch(self, subcmd, opts, *args):
1654         """${cmd_name}: Branch a package
1655
1656         [See http://en.opensuse.org/Build_Service/Collaboration for information
1657         on this topic.]
1658
1659         Create a source link from a package of an existing project to a new
1660         subproject of the requesters home project (home:branches:)
1661
1662         The branched package will live in
1663             home:USERNAME:branches:PROJECT/PACKAGE
1664         if nothing else specified.
1665
1666         With getpac or bco, the branched package will come from
1667             %(getpac_default_project)s
1668         if nothing else specified.
1669
1670         usage:
1671             osc branch SOURCEPROJECT SOURCEPACKAGE
1672             osc branch SOURCEPROJECT SOURCEPACKAGE TARGETPROJECT
1673             osc branch SOURCEPROJECT SOURCEPACKAGE TARGETPROJECT TARGETPACKAGE
1674             osc getpac  SOURCEPACKAGE
1675             osc bco ...
1676         ${cmd_option_list}
1677         """
1678
1679         if subcmd == 'getpac' or subcmd == 'branchco' or subcmd == 'bco': opts.checkout = True
1680         args = slash_split(args)
1681         tproject = tpackage = None
1682
1683         if (subcmd == 'getpac' or subcmd == 'bco') and len(args) == 1:
1684             print >>sys.stderr, 'defaulting to %s/%s' % (conf.config['getpac_default_project'], args[0])
1685             # python has no args.unshift ???
1686             args = [ conf.config['getpac_default_project'] , args[0] ]
1687
1688         if len(args) < 2 or len(args) > 4:
1689             raise oscerr.WrongArgs('Wrong number of arguments.')
1690         expected = 'home:%s:branches:%s' % (conf.config['user'], args[0])
1691         if len(args) >= 3:
1692             expected = tproject = args[2]
1693         if len(args) >= 4:
1694             tpackage = args[3]
1695
1696         if not opts.message:
1697                 footer='please specify the purpose of your branch'
1698                 template='This package was branched from %s in order to ...\n' % args[0]
1699                 opts.message = edit_message(footer, template)
1700
1701         exists, targetprj, targetpkg, srcprj, srcpkg = \
1702                 branch_pkg(conf.config['apiurl'], args[0], args[1],
1703                            nodevelproject=opts.nodevelproject, rev=opts.revision,
1704                            target_project=tproject, target_package=tpackage,
1705                            return_existing=opts.checkout, msg=opts.message or '')
1706         if exists:
1707             print >>sys.stderr, 'Using existing branch project: %s' % targetprj
1708
1709         devloc = None
1710         if not exists and (srcprj is not None and srcprj != args[0] or \
1711                            srcprj is None and targetprj != expected):
1712             devloc = srcprj or targetprj
1713             if not srcprj and 'branches:' in targetprj:
1714                 devloc = targetprj.split('branches:')[1]
1715             print '\nNote: The branch has been created of a different project,\n' \
1716                   '              %s,\n' \
1717                   '      which is the primary location of where development for\n' \
1718                   '      that package takes place.\n' \
1719                   '      That\'s also where you would normally make changes against.\n' \
1720                   '      A direct branch of the specified package can be forced\n' \
1721                   '      with the --nodevelproject option.\n' % devloc
1722
1723         package = tpackage or args[1]
1724         if opts.checkout:
1725             checkout_package(conf.config['apiurl'], targetprj, package,
1726                              expand_link=True, prj_dir=targetprj)
1727             if conf.config['verbose']:
1728                 print 'Note: You can use "osc delete" or "osc submitpac" when done.\n'
1729         else:
1730             apiopt = ''
1731             if conf.get_configParser().get('general', 'apiurl') != conf.config['apiurl']:
1732                 apiopt = '-A %s ' % conf.config['apiurl']
1733             print 'A working copy of the branched package can be checked out with:\n\n' \
1734                   'osc %sco %s/%s' \
1735                       % (apiopt, targetprj, package)
1736         print_request_list(conf.config['apiurl'], args[0], args[1])
1737         if devloc:
1738             print_request_list(conf.config['apiurl'], devloc, args[1])
1739
1740
1741
1742     @cmdln.option('-f', '--force', action='store_true',
1743                         help='deletes a package or an empty project')
1744     def do_rdelete(self, subcmd, opts, *args):
1745         """${cmd_name}: Delete a project or packages on the server.
1746
1747         As a safety measure, project must be empty (i.e., you need to delete all
1748         packages first). If you are sure that you want to remove this project and all
1749         its packages use \'--force\' switch.
1750
1751         usage:
1752            osc rdelete -f PROJECT
1753            osc rdelete PROJECT PACKAGE [PACKAGE ...]
1754
1755         ${cmd_option_list}
1756         """
1757
1758         args = slash_split(args)
1759         if len(args) < 1:
1760             raise oscerr.WrongArgs('Missing argument.')
1761         prj = args[0]
1762         pkgs = args[1:]
1763
1764         if pkgs:
1765             for pkg in pkgs:
1766                # careful: if pkg is an empty string, the package delete request results
1767                # into a project delete request - which works recursively...
1768                 if pkg:
1769                     delete_package(conf.config['apiurl'], prj, pkg)
1770         elif len(meta_get_packagelist(conf.config['apiurl'], prj)) >= 1 and not opts.force:
1771             print >>sys.stderr, 'Project contains packages. It must be empty before deleting it. ' \
1772                                 'If you are sure that you want to remove this project and all its ' \
1773                                 'packages use the \'--force\' switch'
1774             sys.exit(1)
1775         else:
1776             delete_project(conf.config['apiurl'], prj)
1777
1778     @cmdln.hide(1)
1779     def do_deletepac(self, subcmd, opts, *args):
1780         print """${cmd_name} is obsolete !
1781
1782                  Please use either
1783                    osc delete       for checked out packages or projects
1784                  or
1785                    osc rdelete      for server side operations."""
1786
1787         sys.exit(1)
1788
1789     @cmdln.hide(1)
1790     @cmdln.option('-f', '--force', action='store_true',
1791                         help='deletes a project and its packages')
1792     def do_deleteprj(self, subcmd, opts, project):
1793         """${cmd_name} is obsolete !
1794
1795                  Please use
1796                    osc rdelete PROJECT
1797         """
1798         sys.exit(1)
1799
1800     @cmdln.alias('metafromspec')
1801     @cmdln.option('', '--specfile', metavar='FILE',
1802                       help='Path to specfile. (if you pass more than working copy this option is ignored)')
1803     def do_updatepacmetafromspec(self, subcmd, opts, *args):
1804         """${cmd_name}: Update package meta information from a specfile
1805
1806         ARG, if specified, is a package working copy.
1807
1808         ${cmd_usage}
1809         ${cmd_option_list}
1810         """
1811
1812         args = parseargs(args)
1813         if opts.specfile and len(args) == 1:
1814             specfile = opts.specfile
1815         else:
1816             specfile = None
1817         pacs = findpacs(args)
1818         for p in pacs:
1819             p.read_meta_from_spec(specfile)
1820             p.update_package_meta()
1821
1822
1823     @cmdln.alias('di')
1824     @cmdln.option('-c', '--change', metavar='rev',
1825                         help='the change made by revision rev (like -r rev-1:rev).'
1826                              'If rev is negative this is like -r rev:rev-1.')
1827     @cmdln.option('-r', '--revision', metavar='rev1[:rev2]',
1828                         help='If rev1 is specified it will compare your working copy against '
1829                              'the revision (rev1) on the server. '
1830                              'If rev1 and rev2 are specified it will compare rev1 against rev2 '
1831                              '(NOTE: changes in your working copy are ignored in this case)')
1832     @cmdln.option('-p', '--plain', action='store_true',
1833                         help='output the diff in plain (not unified) diff format')
1834     @cmdln.option('--missingok', action='store_true',
1835                         help='do not fail if the source or target project/package does not exist on the server')
1836     def do_diff(self, subcmd, opts, *args):
1837         """${cmd_name}: Generates a diff
1838
1839         Generates a diff, comparing local changes against the repository
1840         server.
1841
1842         ARG, specified, is a filename to include in the diff.
1843
1844         ${cmd_usage}
1845         ${cmd_option_list}
1846         """
1847
1848         args = parseargs(args)
1849         pacs = findpacs(args)
1850
1851         if opts.change:
1852             try:
1853                 rev = int(opts.change)
1854                 if rev > 0:
1855                     rev1 = rev - 1
1856                     rev2 = rev
1857                 elif rev < 0:
1858                     rev1 = -rev
1859                     rev2 = -rev - 1
1860                 else:
1861                     return
1862             except:
1863                 print >>sys.stderr, 'Revision \'%s\' not an integer' % opts.change
1864                 return
1865         else:
1866             rev1, rev2 = parseRevisionOption(opts.revision)
1867         diff = ''
1868         for pac in pacs:
1869             if not rev2:
1870                 diff += ''.join(make_diff(pac, rev1))
1871             else:
1872                 diff += server_diff(pac.apiurl, pac.prjname, pac.name, rev1,
1873                                     pac.prjname, pac.name, rev2, not opts.plain, opts.missingok)
1874         if len(diff) > 0:
1875             print diff
1876
1877
1878     @cmdln.option('--oldprj', metavar='OLDPRJ',
1879                   help='project to compare against'
1880                   ' (deprecated, use 3 argument form)')
1881     @cmdln.option('--oldpkg', metavar='OLDPKG',
1882                   help='package to compare against'
1883                   ' (deprecated, use 3 argument form)')
1884     @cmdln.option('-r', '--revision', metavar='N[:M]',
1885                   help='revision id, where N = old revision and M = new revision')
1886     @cmdln.option('-p', '--plain', action='store_true',
1887                   help='output the diff in plain (not unified) diff format')
1888     @cmdln.option('-c', '--change', metavar='rev',
1889                         help='the change made by revision rev (like -r rev-1:rev). '
1890                              'If rev is negative this is like -r rev:rev-1.')
1891     @cmdln.option('--missingok', action='store_true',
1892                         help='do not fail if the source or target project/package does not exist on the server')
1893     def do_rdiff(self, subcmd, opts, *args):
1894         """${cmd_name}: Server-side "pretty" diff of two packages
1895
1896         Compares two packages (three or four arguments) or shows the
1897         changes of a specified revision of a package (two arguments)
1898
1899         If no revision is specified the latest revision is used.
1900
1901         Note that this command doesn't return a normal diff (which could be
1902         applied as patch), but a "pretty" diff, which also compares the content
1903         of tarballs.
1904
1905
1906         usage:
1907             osc ${cmd_name} OLDPRJ OLDPAC NEWPRJ [NEWPAC]
1908             osc ${cmd_name} PROJECT PACKAGE
1909         ${cmd_option_list}
1910         """
1911
1912         args = slash_split(args)
1913
1914         rev1 = None
1915         rev2 = None
1916
1917         old_project = None
1918         old_package = None
1919         new_project = None
1920         new_package = None
1921
1922         if len(args) == 2:
1923             new_project = args[0]
1924             new_package = args[1]
1925             if opts.oldprj:
1926                 old_project = opts.oldprj
1927             if opts.oldpkg:
1928                 old_package = opts.oldpkg
1929         elif len(args) == 3 or len(args) == 4:
1930             if opts.oldprj or opts.oldpkg:
1931                 raise oscerr.WrongArgs('--oldpkg and --oldprj are only valid with two arguments')
1932             old_project = args[0]
1933             new_package = old_package = args[1]
1934             new_project = args[2]
1935             if len(args) == 4:
1936                 new_package = args[3]
1937         else:
1938             raise oscerr.WrongArgs('Wrong number of arguments')
1939
1940
1941         if opts.change:
1942             try:
1943                 rev = int(opts.change)
1944                 if rev > 0:
1945                     rev1 = rev - 1
1946                     rev2 = rev
1947                 elif rev < 0:
1948                     rev1 = -rev
1949                     rev2 = -rev - 1
1950                 else:
1951                     return
1952             except:
1953                 print >>sys.stderr, 'Revision \'%s\' not an integer' % opts.change
1954                 return
1955         else:
1956             if opts.revision:
1957                 rev1, rev2 = parseRevisionOption(opts.revision)
1958
1959         rdiff = server_diff(conf.config['apiurl'],
1960                             old_project, old_package, rev1,
1961                             new_project, new_package, rev2, not opts.plain, opts.missingok)
1962         print rdiff
1963
1964     @cmdln.hide(1)
1965     @cmdln.alias('in')
1966     def do_install(self, subcmd, opts, *args):
1967         """${cmd_name}: install a package after build via zypper in -r
1968
1969         Not implemented yet. Use osc repourls,
1970         select the url you best like (standard),
1971         chop off after the last /, this should work with zypper.
1972
1973
1974         ${cmd_usage}
1975         ${cmd_option_list}
1976         """
1977
1978         args = slash_split(args)
1979         args = expand_proj_pack(args)
1980
1981         ## FIXME:
1982         ## if there is only one argument, and it ends in .ymp
1983         ## then fetch it, Parse XML to get the first
1984         ##  metapackage.group.repositories.repository.url
1985         ## and construct zypper cmd's for all
1986         ##  metapackage.group.software.item.name
1987         ##
1988         ## if args[0] is already an url, the use it as is.
1989
1990         cmd = "sudo zypper -p http://download.opensuse.org/repositories/%s/%s --no-refresh -v in %s" % (re.sub(':',':/',args[0]), 'openSUSE_11.1', args[1])
1991         print self.do_install.__doc__
1992         print "Example: \n" + cmd
1993
1994
1995     def do_repourls(self, subcmd, opts, *args):
1996         """${cmd_name}: Shows URLs of .repo files
1997
1998         Shows URLs on which to access the project .repos files (yum-style
1999         metadata) on download.opensuse.org.
2000
2001         usage:
2002            osc repourls [PROJECT]
2003
2004         ${cmd_option_list}
2005         """
2006
2007         apiurl = conf.config['apiurl']
2008
2009         if len(args) == 1:
2010             project = args[0]
2011         elif len(args) == 0:
2012             project = store_read_project('.')
2013             apiurl = store_read_apiurl('.')
2014         else:
2015             raise oscerr.WrongArgs('Wrong number of arguments')
2016
2017         # XXX: API should somehow tell that
2018         url_tmpl = 'http://download.opensuse.org/repositories/%s/%s/%s.repo'
2019         repos = get_repositories_of_project(apiurl, project)
2020         for repo in repos:
2021             print url_tmpl % (project.replace(':', ':/'), repo, project)
2022
2023
2024     @cmdln.option('-r', '--revision', metavar='rev',
2025                         help='checkout the specified revision. '
2026                              'NOTE: if you checkout the complete project '
2027                              'this option is ignored!')
2028     @cmdln.option('-e', '--expand-link', action='store_true',
2029                         help='if a package is a link, check out the expanded '
2030                              'sources (no-op, since this became the default)')
2031     @cmdln.option('-u', '--unexpand-link', action='store_true',
2032                         help='if a package is a link, check out the _link file ' \
2033                              'instead of the expanded sources')
2034     @cmdln.option('-c', '--current-dir', action='store_true',
2035                         help='place PACKAGE folder in the current directory' \
2036                              'instead of a PROJECT/PACKAGE directory')
2037     @cmdln.option('-s', '--source-service-files', action='store_true',
2038                         help='server side generated files of source services' \
2039                              'gets downloaded as well' )
2040     @cmdln.alias('co')
2041     def do_checkout(self, subcmd, opts, *args):
2042         """${cmd_name}: Check out content from the repository
2043
2044         Check out content from the repository server, creating a local working
2045         copy.
2046
2047         When checking out a single package, the option --revision can be used
2048         to specify a revision of the package to be checked out.
2049
2050         When a package is a source link, then it will be checked out in
2051         expanded form. If --unexpand-link option is used, the checkout will
2052         instead produce the raw _link file plus patches.
2053
2054         usage:
2055             osc co PROJECT [PACKAGE] [FILE]
2056                osc co PROJECT                    # entire project
2057                osc co PROJECT PACKAGE            # a package
2058                osc co PROJECT PACKAGE FILE       # single file -> to current dir
2059
2060             while inside a project directory:
2061                osc co PACKAGE                    # check out PACKAGE from project
2062
2063         ${cmd_option_list}
2064         """
2065
2066         if opts.unexpand_link:
2067             expand_link = False
2068         else:
2069             expand_link = True
2070         if opts.source_service_files:
2071             service_files = True
2072         else:
2073             service_files = False
2074
2075         args = slash_split(args)
2076         project = package = filename = None
2077         apiurl = conf.config['apiurl']
2078         try:
2079             project = project_dir = args[0]
2080             package = args[1]
2081             filename = args[2]
2082         except:
2083             pass
2084
2085         if args and len(args) == 1:
2086             localdir = os.getcwd()
2087             if is_project_dir(localdir):
2088                 project = store_read_project(localdir)
2089                 project_dir = localdir
2090                 package = args[0]
2091                 apiurl = store_read_apiurl(localdir)
2092
2093         rev, dummy = parseRevisionOption(opts.revision)
2094         if rev==None:
2095             rev="latest"
2096
2097         if rev and rev != "latest" and not checkRevision(project, package, rev):
2098             print >>sys.stderr, 'Revision \'%s\' does not exist' % rev
2099             sys.exit(1)
2100
2101         if filename:
2102             get_source_file(apiurl, project, package, filename, revision=rev, progress_obj=self.download_progress)
2103
2104         elif package:
2105             if opts.current_dir:
2106                 project_dir = None
2107             checkout_package(apiurl, project, package, rev, expand_link=expand_link, \
2108                              prj_dir=project_dir, service_files=service_files, progress_obj=self.download_progress)
2109             print_request_list(apiurl, project, package)
2110
2111         elif project:
2112             prj_dir = project
2113             if sys.platform[:3] == 'win':
2114                 prj_dir = prj_dir.replace(':', ';')
2115             if os.path.exists(prj_dir):
2116                 sys.exit('osc: project \'%s\' already exists' % project)
2117
2118             # check if the project does exist (show_project_meta will throw an exception)
2119             show_project_meta(apiurl, project)
2120
2121             init_project_dir(apiurl, prj_dir, project)
2122             print statfrmt('A', prj_dir)
2123
2124             # all packages
2125             for package in meta_get_packagelist(apiurl, project):
2126                 try:
2127                     checkout_package(apiurl, project, package, expand_link = expand_link, \
2128                                      prj_dir = prj_dir, service_files = service_files, progress_obj=self.download_progress)
2129                 except oscerr.LinkExpandError, e:
2130                     print >>sys.stderr, 'Link cannot be expanded:\n', e
2131                     print >>sys.stderr, 'Use "osc repairlink" for fixing merge conflicts:\n'
2132                     # check out in unexpanded form at least
2133                     checkout_package(apiurl, project, package, expand_link = False, \
2134                                      prj_dir = prj_dir, service_files = service_files, progress_obj=self.download_progress)
2135             print_request_list(apiurl, project)
2136
2137         else:
2138             raise oscerr.WrongArgs('Missing argument.\n\n' \
2139                   + self.get_cmd_help('checkout'))
2140
2141
2142     @cmdln.option('-q', '--quiet', action='store_true',
2143                         help='print as little as possible')
2144     @cmdln.option('-v', '--verbose', action='store_true',
2145                         help='print extra information')
2146     @cmdln.alias('st')
2147     def do_status(self, subcmd, opts, *args):
2148         """${cmd_name}: Show status of files in working copy
2149
2150         Show the status of files in a local working copy, indicating whether
2151         files have been changed locally, deleted, added, ...
2152
2153         The first column in the output specifies the status and is one of the
2154         following characters:
2155           ' ' no modifications
2156           'A' Added
2157           'C' Conflicted
2158           'D' Deleted
2159           'M' Modified
2160           '?' item is not under version control
2161           '!' item is missing (removed by non-osc command) or incomplete
2162
2163         examples:
2164           osc st
2165           osc st <directory>
2166           osc st file1 file2 ...
2167
2168         usage:
2169             osc status [OPTS] [PATH...]
2170         ${cmd_option_list}
2171         """
2172
2173         args = parseargs(args)
2174
2175         # storage for single Package() objects
2176         pacpaths = []
2177         # storage for a project dir ( { prj_instance : [ package objects ] } )
2178         prjpacs = {}
2179         for arg in args:
2180             # when 'status' is run inside a project dir, it should
2181             # stat all packages existing in the wc
2182             if is_project_dir(arg):
2183                 prj = Project(arg, False)
2184
2185                 if conf.config['do_package_tracking']:
2186                     prjpacs[prj] = []
2187                     for pac in prj.pacs_have:
2188                         # we cannot create package objects if the dir does not exist
2189                         if not pac in prj.pacs_broken:
2190                             prjpacs[prj].append(os.path.join(arg, pac))
2191                 else:
2192                     pacpaths += [arg + '/' + n for n in prj.pacs_have]
2193             elif is_package_dir(arg):
2194                 pacpaths.append(arg)
2195             elif os.path.isfile(arg):
2196                 pacpaths.append(arg)
2197             else:
2198                 msg = '\'%s\' is neither a project or a package directory' % arg
2199                 raise oscerr.NoWorkingCopy, msg
2200         lines = []
2201         # process single packages
2202         lines = getStatus(findpacs(pacpaths), None, opts.verbose, opts.quiet)
2203         # process project dirs
2204         for prj, pacs in prjpacs.iteritems():
2205             lines += getStatus(findpacs(pacs), prj, opts.verbose, opts.quiet)
2206         if lines:
2207             print '\n'.join(lines)
2208
2209
2210     def do_add(self, subcmd, opts, *args):
2211         """${cmd_name}: Mark files to be added upon the next commit
2212
2213         usage:
2214             osc add FILE [FILE...]
2215         ${cmd_option_list}
2216         """
2217         if not args:
2218             raise oscerr.WrongArgs('Missing argument.\n\n' \
2219                   + self.get_cmd_help('add'))
2220
2221         filenames = parseargs(args)
2222         addFiles(filenames)
2223
2224
2225     def do_mkpac(self, subcmd, opts, *args):
2226         """${cmd_name}: Create a new package under version control
2227
2228         usage:
2229             osc mkpac new_package
2230         ${cmd_option_list}
2231         """
2232         if not conf.config['do_package_tracking']:
2233             print >>sys.stderr, "to use this feature you have to enable \'do_package_tracking\' " \
2234                                 "in the [general] section in the configuration file"
2235             sys.exit(1)
2236
2237         if len(args) != 1:
2238             raise oscerr.WrongArgs('Wrong number of arguments.')
2239
2240         createPackageDir(args[0])
2241
2242     @cmdln.option('-r', '--recursive', action='store_true',
2243                         help='If CWD is a project dir then scan all package dirs as well')
2244     @cmdln.alias('ar')
2245     def do_addremove(self, subcmd, opts, *args):
2246         """${cmd_name}: Adds new files, removes disappeared files
2247
2248         Adds all files new in the local copy, and removes all disappeared files.
2249
2250         ARG, if specified, is a package working copy.
2251
2252         ${cmd_usage}
2253         ${cmd_option_list}
2254         """
2255
2256         args = parseargs(args)
2257         arg_list = args[:]
2258         for arg in arg_list:
2259             if is_project_dir(arg) and conf.config['do_package_tracking']:
2260                 prj = Project(arg, False)
2261                 for pac in prj.pacs_unvers:
2262                     pac_dir = getTransActPath(os.path.join(prj.dir, pac))
2263                     if os.path.isdir(pac_dir):
2264                         addFiles([pac_dir], prj)
2265                 for pac in prj.pacs_broken:
2266                     if prj.get_state(pac) != 'D':
2267                         prj.set_state(pac, 'D')
2268                         print statfrmt('D', getTransActPath(os.path.join(prj.dir, pac)))
2269                 if opts.recursive:
2270                     for pac in prj.pacs_have:
2271                         state = prj.get_state(pac)
2272                         if state != None and state != 'D':
2273                             pac_dir = getTransActPath(os.path.join(prj.dir, pac))
2274                             args.append(pac_dir)
2275                 args.remove(arg)
2276                 prj.write_packages()
2277             elif is_project_dir(arg):
2278                 print >>sys.stderr, 'osc: addremove is not supported in a project dir unless ' \
2279                                     '\'do_package_tracking\' is enabled in the configuration file'
2280                 sys.exit(1)
2281
2282         pacs = findpacs(args)
2283         for p in pacs:
2284             p.todo = p.filenamelist + p.filenamelist_unvers
2285
2286             for filename in p.todo:
2287                 if os.path.isdir(filename):
2288                     continue
2289                 # ignore foo.rXX, foo.mine for files which are in 'C' state
2290                 if os.path.splitext(filename)[0] in p.in_conflict:
2291                     continue
2292                 state = p.status(filename)
2293
2294                 if state == '?':
2295                     # TODO: should ignore typical backup files suffix ~ or .orig
2296                     p.addfile(filename)
2297                     print statfrmt('A', getTransActPath(os.path.join(p.dir, filename)))
2298                 elif state == '!':
2299                     p.put_on_deletelist(filename)
2300                     p.write_deletelist()
2301                     os.unlink(os.path.join(p.storedir, filename))
2302                     print statfrmt('D', getTransActPath(os.path.join(p.dir, filename)))
2303
2304
2305
2306     @cmdln.alias('ci')
2307     @cmdln.alias('checkin')
2308     @cmdln.option('-m', '--message', metavar='TEXT',
2309                   help='specify log message TEXT')
2310     @cmdln.option('-F', '--file', metavar='FILE',
2311                   help='read log message from FILE')
2312     @cmdln.option('-f', '--force', default=False, action="store_true",
2313                   help='force commit - do not tests a file list')
2314     def do_commit(self, subcmd, opts, *args):
2315         """${cmd_name}: Upload content to the repository server
2316
2317         Upload content which is changed in your working copy, to the repository
2318         server.
2319
2320         Optionally checks the state of a working copy, if found a file with
2321         unknown state, it requests an user input:
2322          * skip - don't change anything, just move to another file
2323          * remove - remove a file from dir
2324          * edit file list - edit filelist using EDITOR
2325          * commit - don't check anything and commit package
2326          * abort - abort commit - this is default value
2327         This can be supressed by check_filelist config item, or -f/--force
2328         command line option.
2329
2330         examples:
2331            osc ci                   # current dir
2332            osc ci <dir>
2333            osc ci file1 file2 ...
2334
2335         ${cmd_usage}
2336         ${cmd_option_list}
2337         """
2338
2339         args = parseargs(args)
2340
2341         msg = ''
2342         if opts.message:
2343             msg = opts.message
2344         elif opts.file:
2345             try:
2346                 msg = open(opts.file).read()
2347             except:
2348                 sys.exit('could not open file \'%s\'.' % opts.file)
2349
2350         arg_list = args[:]
2351         for arg in arg_list:
2352             if conf.config['do_package_tracking'] and is_project_dir(arg):
2353                 Project(arg).commit(msg=msg)
2354                 if not msg:
2355                     msg = edit_message()
2356                 args.remove(arg)
2357
2358         pacs = findpacs(args)
2359
2360         if conf.config['check_filelist'] and not opts.force:
2361             check_filelist_before_commit(pacs)
2362
2363         if not msg:
2364             template = store_read_file(os.path.abspath('.'), '_commit_msg')
2365             # open editor for commit message
2366             # but first, produce status and diff to append to the template
2367             footer = diffs = []
2368             lines = []
2369             for pac in pacs:
2370                 changed = getStatus([pac], quiet=True)
2371                 if changed:
2372                     footer += changed
2373                     diffs += ['\nDiff for working copy: %s' % pac.dir]
2374                     diffs += make_diff(pac, 0)
2375                     lines.extend(get_commit_message_template(pac))
2376             if template == None:
2377                 template='\n'.join(lines)
2378             # if footer is empty, there is nothing to commit, and no edit needed.
2379             if footer:
2380                 msg = edit_message(footer='\n'.join(footer), template=template)
2381
2382             if msg:
2383                 store_write_string(os.path.abspath('.'), '_commit_msg', msg)
2384             else:
2385                 store_unlink_file(os.path.abspath('.'), '_commit_msg')
2386
2387         if conf.config['do_package_tracking'] and len(pacs) > 0:
2388             prj_paths = {}
2389             single_paths = []
2390             files = {}
2391             # it is possible to commit packages from different projects at the same
2392             # time: iterate over all pacs and put each pac to the right project in the dict
2393             for pac in pacs:
2394                 path = os.path.normpath(os.path.join(pac.dir, os.pardir))
2395                 if is_project_dir(path):
2396                     pac_path = os.path.basename(os.path.normpath(pac.absdir))
2397                     prj_paths.setdefault(path, []).append(pac_path)
2398                     files[pac_path] = pac.todo
2399                 else:
2400                     single_paths.append(pac.dir)
2401             for prj, packages in prj_paths.iteritems():
2402                 Project(prj).commit(tuple(packages), msg, files)
2403             for pac in single_paths:
2404                 Package(pac).commit(msg)
2405         else:
2406             for p in pacs:
2407                 p.commit(msg)
2408
2409         store_unlink_file(os.path.abspath('.'), '_commit_msg')
2410
2411     @cmdln.option('-r', '--revision', metavar='REV',
2412                         help='update to specified revision (this option will be ignored '
2413                              'if you are going to update the complete project or more than '
2414                              'one package)')
2415     @cmdln.option('-u', '--unexpand-link', action='store_true',
2416                         help='if a package is an expanded link, update to the raw _link file')
2417     @cmdln.option('-e', '--expand-link', action='store_true',
2418                         help='if a package is a link, update to the expanded sources')
2419     @cmdln.option('-s', '--source-service-files', action='store_true',
2420                         help='Use server side generated sources instead of local generation.' )
2421     @cmdln.alias('up')
2422     def do_update(self, subcmd, opts, *args):
2423         """${cmd_name}: Update a working copy
2424
2425         examples:
2426
2427         1. osc up
2428                 If the current working directory is a package, update it.
2429                 If the directory is a project directory, update all contained
2430                 packages, AND check out newly added packages.
2431
2432                 To update only checked out packages, without checking out new
2433                 ones, you might want to use "osc up *" from within the project
2434                 dir.
2435
2436         2. osc up PAC
2437                 Update the packages specified by the path argument(s)
2438
2439         When --expand-link is used with source link packages, the expanded
2440         sources will be checked out. Without this option, the _link file and
2441         patches will be checked out. The option --unexpand-link can be used to
2442         switch back to the "raw" source with a _link file plus patch(es).
2443
2444         ${cmd_usage}
2445         ${cmd_option_list}
2446         """
2447
2448         if (opts.expand_link and opts.unexpand_link) \
2449             or (opts.expand_link and opts.revision) \
2450             or (opts.unexpand_link and opts.revision):
2451             raise oscerr.WrongOptions('Sorry, the options --expand-link, --unexpand-link and '
2452                      '--revision are mutually exclusive.')
2453
2454         if opts.source_service_files: service_files = True
2455         else: service_files = False
2456
2457         args = parseargs(args)
2458         arg_list = args[:]
2459
2460         for arg in arg_list:
2461             if is_project_dir(arg):
2462                 prj = Project(arg, progress_obj=self.download_progress)
2463
2464                 if conf.config['do_package_tracking']:
2465                     prj.update(expand_link=opts.expand_link,
2466                                unexpand_link=opts.unexpand_link)
2467                     args.remove(arg)
2468                 else:
2469                     # if not tracking package, and 'update' is run inside a project dir,
2470                     # it should do the following:
2471                     # (a) update all packages
2472                     args += prj.pacs_have
2473                     # (b) fetch new packages
2474                     prj.checkout_missing_pacs(expand_link = not opts.unexpand_link)
2475                     args.remove(arg)
2476                 print_request_list(prj.apiurl, prj.name)
2477
2478         args.sort()
2479         pacs = findpacs(args, progress_obj=self.download_progress)
2480
2481         if opts.revision and len(args) == 1:
2482             rev, dummy = parseRevisionOption(opts.revision)
2483             if not checkRevision(pacs[0].prjname, pacs[0].name, rev, pacs[0].apiurl):
2484                 print >>sys.stderr, 'Revision \'%s\' does not exist' % rev
2485                 sys.exit(1)
2486         else:
2487             rev = None
2488
2489         for p in pacs:
2490             if len(pacs) > 1:
2491                 print 'Updating %s' % p.name
2492
2493             # FIXME: ugly workaround for #399247
2494             if opts.expand_link or opts.unexpand_link:
2495                 if [ i for i in p.filenamelist+p.filenamelist_unvers if p.status(i) != ' ' and p.status(i) != '?']:
2496                     print >>sys.stderr, 'osc: cannot expand/unexpand because your working ' \
2497                                         'copy has local modifications.\nPlease revert/commit them ' \
2498                                         'and try again.'
2499                     sys.exit(1)
2500
2501             if not rev:
2502                 if opts.expand_link and p.islink() and not p.isexpanded():
2503                     if p.haslinkerror():
2504                         try:
2505                             rev = show_upstream_xsrcmd5(p.apiurl, p.prjname, p.name, revision=p.rev)
2506                         except:
2507                             rev = show_upstream_xsrcmd5(p.apiurl, p.prjname, p.name, revision=p.rev, linkrev="base")
2508                             p.mark_frozen()
2509                     else:
2510                         rev = p.linkinfo.xsrcmd5
2511                     print 'Expanding to rev', rev
2512                 elif opts.unexpand_link and p.islink() and p.isexpanded():
2513                     print 'Unexpanding to rev', p.linkinfo.lsrcmd5
2514                     rev = p.linkinfo.lsrcmd5
2515                 elif p.islink() and p.isexpanded():
2516                     rev = p.latest_rev()
2517
2518             p.update(rev, service_files)
2519             if opts.unexpand_link:
2520                 p.unmark_frozen()
2521             rev = None
2522             print_request_list(p.apiurl, p.prjname, p.name)
2523
2524
2525     @cmdln.option('-f', '--force', action='store_true',
2526                         help='forces removal of entire package and its files')
2527     @cmdln.alias('rm')
2528     @cmdln.alias('del')
2529     @cmdln.alias('remove')
2530     def do_delete(self, subcmd, opts, *args):
2531         """${cmd_name}: Mark files or package directories to be deleted upon the next 'checkin'
2532
2533         usage:
2534             cd .../PROJECT/PACKAGE
2535             osc delete FILE [...]
2536             cd .../PROJECT
2537             osc delete PACKAGE [...]
2538
2539         This command works on check out copies. Use "rdelete" for working on server
2540         side only. This is needed for removing the entire project.
2541
2542         As a safety measure, projects must be empty (i.e., you need to delete all
2543         packages first).
2544
2545         If you are sure that you want to remove a package and all
2546         its files use \'--force\' switch. Sometimes this also works without --force.
2547
2548         ${cmd_option_list}
2549         """
2550
2551         if not args:
2552             raise oscerr.WrongArgs('Missing argument.\n\n' \
2553                   + self.get_cmd_help('delete'))
2554
2555         args = parseargs(args)
2556         # check if args contains a package which was removed by
2557         # a non-osc command and mark it with the 'D'-state
2558         arg_list = args[:]
2559         for i in arg_list:
2560             if not os.path.exists(i):
2561                 prj_dir, pac_dir = getPrjPacPaths(i)
2562                 if is_project_dir(prj_dir):
2563                     prj = Project(prj_dir, False)
2564                     if i in prj.pacs_broken:
2565                         if prj.get_state(i) != 'A':
2566                             prj.set_state(pac_dir, 'D')
2567                         else:
2568                             prj.del_package_node(i)
2569                         print statfrmt('D', getTransActPath(i))
2570                         args.remove(i)
2571                         prj.write_packages()
2572         pacs = findpacs(args)
2573
2574         for p in pacs:
2575             if not p.todo:
2576                 prj_dir, pac_dir = getPrjPacPaths(p.absdir)
2577                 if is_project_dir(prj_dir):
2578                     if conf.config['do_package_tracking']:
2579                         prj = Project(prj_dir, False)
2580                         prj.delPackage(p, opts.force)
2581                     else:
2582                         print "WARNING: package tracking is disabled, operation skipped !"
2583             else:
2584                 pathn = getTransActPath(p.dir)
2585                 for filename in p.todo:
2586                     ret, state = p.delete_file(filename, opts.force)
2587                     if ret:
2588                         print statfrmt('D', os.path.join(pathn, filename))
2589                         continue
2590                     if state == '?':
2591                         sys.exit('\'%s\' is not under version control' % filename)
2592                     elif state in ['A', 'M'] and not opts.force:
2593                         sys.exit('\'%s\' has local modifications (use --force to remove this file)' % filename)
2594
2595
2596     def do_resolved(self, subcmd, opts, *args):
2597         """${cmd_name}: Remove 'conflicted' state on working copy files
2598
2599         If an upstream change can't be merged automatically, a file is put into
2600         in 'conflicted' ('C') state. Within the file, conflicts are marked with
2601         special <<<<<<< as well as ======== and >>>>>>> lines.
2602
2603         After manually resolving all conflicting parts, use this command to
2604         remove the 'conflicted' state.
2605
2606         Note:  this subcommand does not semantically resolve conflicts or
2607         remove conflict markers; it merely removes the conflict-related
2608         artifact files and allows PATH to be committed again.
2609
2610         usage:
2611             osc resolved FILE [FILE...]
2612         ${cmd_option_list}
2613         """
2614
2615         if not args:
2616             raise oscerr.WrongArgs('Missing argument.\n\n' \
2617                   + self.get_cmd_help('resolved'))
2618
2619         args = parseargs(args)
2620         pacs = findpacs(args)
2621
2622         for p in pacs:
2623             for filename in p.todo:
2624                 print 'Resolved conflicted state of "%s"' % filename
2625                 p.clear_from_conflictlist(filename)
2626
2627
2628     @cmdln.alias('platforms')
2629     def do_repositories(self, subcmd, opts, *args):
2630         """${cmd_name}: Shows available repositories
2631
2632         Examples:
2633         1. osc repositories
2634                 Shows all available repositories/build targets
2635
2636         2. osc repositories <project>
2637                 Shows the configured repositories/build targets of a project
2638
2639         ${cmd_usage}
2640         ${cmd_option_list}
2641         """
2642
2643         if args:
2644             project = args[0]
2645             print '\n'.join(get_repositories_of_project(conf.config['apiurl'], project))
2646         else:
2647             print '\n'.join(get_repositories(conf.config['apiurl']))
2648
2649
2650     @cmdln.hide(1)
2651     def do_results_meta(self, subcmd, opts, *args):
2652         print "Command results_meta is obsolete. Please use: osc results --xml"
2653         sys.exit(1)
2654
2655     @cmdln.hide(1)
2656     @cmdln.option('-l', '--last-build', action='store_true',
2657                         help='show last build results (succeeded/failed/unknown)')
2658     @cmdln.option('-r', '--repo', action='append', default = [],
2659                         help='Show results only for specified repo(s)')
2660     @cmdln.option('-a', '--arch', action='append', default = [],
2661                         help='Show results only for specified architecture(s)')
2662     @cmdln.option('', '--xml', action='store_true',
2663                         help='generate output in XML (former results_meta)')
2664     def do_rresults(self, subcmd, opts, *args):
2665         print "Command rresults is obsolete. Running 'osc results' instead"
2666         self.do_results('results', opts, *args)
2667         sys.exit(1)
2668
2669
2670     @cmdln.option('-f', '--force', action='store_true', default=False,
2671                         help="Don't ask and delete files")
2672     def do_rremove(self, subcmd, opts, project, package, *files):
2673         """${cmd_name}: Remove source files from selected package
2674
2675         ${cmd_usage}
2676         ${cmd_option_list}
2677         """
2678
2679         if len(files) == 0:
2680             if not '/' in project:
2681                 raise oscerr.WrongArgs("Missing operand, type osc help rremove for help")
2682             else:
2683                 files = (package, )
2684                 project, package = project.split('/')
2685
2686         for file in files:
2687             if not opts.force:
2688                 resp = raw_input("rm: remove source file `%s' from `%s/%s'? (yY|nN) " % (file, project, package))
2689                 if resp not in ('y', 'Y'):
2690                     continue
2691             try:
2692                 delete_files(conf.config['apiurl'], project, package, (file, ))
2693             except urllib2.HTTPError, e:
2694                 if opts.force:
2695                     print >>sys.stderr, e
2696                     body = e.read()
2697                     if e.code in [ 400, 403, 404, 500 ]:
2698                         if '<summary>' in body:
2699                             msg = body.split('<summary>')[1]
2700                             msg = msg.split('</summary>')[0]
2701                             print >>sys.stderr, msg
2702                 else:
2703                     raise e
2704
2705     @cmdln.alias('r')
2706     @cmdln.option('-l', '--last-build', action='store_true',
2707                         help='show last build results (succeeded/failed/unknown)')
2708     @cmdln.option('-r', '--repo', action='append', default = [],
2709                         help='Show results only for specified repo(s)')
2710     @cmdln.option('-a', '--arch', action='append', default = [],
2711                         help='Show results only for specified architecture(s)')
2712     @cmdln.option('', '--xml', action='store_true', default=False,
2713                         help='generate output in XML (former results_meta)')
2714     @cmdln.option('', '--csv', action='store_true', default=False,
2715                         help='generate output in CSV format')
2716     @cmdln.option('', '--format', default='%(repository)s|%(arch)s|%(state)s|%(dirty)s|%(code)s|%(details)s',
2717                         help='format string for csv output')
2718     def do_results(self, subcmd, opts, *args):
2719         """${cmd_name}: Shows the build results of a package
2720
2721         Usage:
2722             osc results (inside working copy)
2723             osc results remote_project remote_package
2724
2725         ${cmd_option_list}
2726         """
2727
2728         args = slash_split(args)
2729
2730         apiurl = conf.config['apiurl']
2731         if len(args) == 0:
2732             wd = os.curdir
2733             if is_project_dir(wd):
2734                 opts.csv = None
2735                 opts.arch = None
2736                 opts.repo = None
2737                 opts.hide_legend = None
2738                 opts.name_filter = None
2739                 opts.status_filter = None
2740                 opts.vertical = None
2741                 self.do_prjresults('prjresults', opts, *args)
2742                 sys.exit(0)
2743             else:
2744                 project = store_read_project(wd)
2745                 package = store_read_package(wd)
2746                 apiurl = store_read_apiurl(wd)
2747         elif len(args) < 2:
2748             raise oscerr.WrongArgs('Too few arguments (required none or two)')
2749         elif len(args) > 2:
2750             raise oscerr.WrongArgs('Too many arguments (required none or two)')
2751         else:
2752             project = args[0]
2753             package = args[1]
2754
2755         if opts.xml and opts.csv:
2756             raise oscerr.WrongOptions("--xml and --csv are mutual exclusive")
2757
2758         if opts.xml:
2759             func = show_results_meta
2760             delim = ''
2761         elif opts.csv:
2762             def _func(*args):
2763                 return format_results(get_package_results(*args), opts.format)
2764             func = _func
2765             delim = '\n'
2766         else:
2767             func = get_results
2768             delim = '\n'
2769
2770         print delim.join(func(apiurl, project, package, opts.last_build, opts.repo, opts.arch))
2771
2772     # WARNING: this function is also called by do_results. You need to set a default there
2773     #          as well when adding a new option!
2774     @cmdln.option('-q', '--hide-legend', action='store_true',
2775                         help='hide the legend')
2776     @cmdln.option('-c', '--csv', action='store_true',
2777                         help='csv output')
2778     @cmdln.option('-s', '--status-filter', metavar='STATUS',
2779                         help='show only packages with buildstatus STATUS (see legend)')
2780     @cmdln.option('-n', '--name-filter', metavar='EXPR',
2781                         help='show only packages whose names match EXPR')
2782     @cmdln.option('-a', '--arch', metavar='ARCH',
2783                         help='show results only for specified architecture(s)')
2784     @cmdln.option('-r', '--repo', metavar='REPO',
2785                         help='show results only for specified repo(s)')
2786     @cmdln.option('-V', '--vertical', action='store_true',
2787                         help='list packages vertically instead horizontally')
2788     @cmdln.alias('pr')
2789     def do_prjresults(self, subcmd, opts, *args):
2790         """${cmd_name}: Shows project-wide build results
2791
2792         Usage:
2793             osc prjresults (inside working copy)
2794             osc prjresults PROJECT
2795
2796         ${cmd_option_list}
2797         """
2798
2799         if args:
2800             apiurl = conf.config['apiurl']
2801             if len(args) == 1:
2802                 project = args[0]
2803             else:
2804                 raise oscerr.WrongArgs('Wrong number of arguments.')
2805         else:
2806             wd = os.curdir
2807             project = store_read_project(wd)
2808             apiurl = store_read_apiurl(wd)
2809
2810         print '\n'.join(get_prj_results(apiurl, project, hide_legend=opts.hide_legend, csv=opts.csv, status_filter=opts.status_filter, name_filter=opts.name_filter, repo=opts.repo, arch=opts.arch, vertical=opts.vertical))
2811
2812
2813     @cmdln.option('-q', '--hide-legend', action='store_true',
2814                         help='hide the legend')
2815     @cmdln.option('-c', '--csv', action='store_true',
2816                         help='csv output')
2817     @cmdln.option('-s', '--status-filter', metavar='STATUS',
2818                         help='show only packages with buildstatus STATUS (see legend)')
2819     @cmdln.option('-n', '--name-filter', metavar='EXPR',
2820                         help='show only packages whose names match EXPR')
2821
2822     @cmdln.hide(1)
2823     def do_rprjresults(self, subcmd, opts, *args):
2824         print "Command rprjresults is obsolete. Please use 'osc prjresults'"
2825         sys.exit(1)
2826
2827     @cmdln.alias('bl')
2828     @cmdln.option('-s', '--start', metavar='START',
2829                     help='get log starting from the offset')
2830     def do_buildlog(self, subcmd, opts, *args):
2831         """${cmd_name}: Shows the build log of a package
2832
2833         Shows the log file of the build of a package. Can be used to follow the
2834         log while it is being written.
2835         Needs to be called from within a package directory.
2836
2837         The arguments REPOSITORY and ARCH are the first two columns in the 'osc
2838         results' output. If the buildlog url is used buildlog command has the
2839         same behavior as remotebuildlog.
2840
2841         ${cmd_usage} [REPOSITORY ARCH | BUILDLOGURL]
2842         ${cmd_option_list}
2843         """
2844
2845         repository = arch = None
2846
2847         if len(args) == 1 and args[0].startswith('http'):
2848             apiurl, project, package, repository, arch = parse_buildlogurl(args[0])
2849         else:
2850             wd = os.curdir
2851             package = store_read_package(wd)
2852             project = store_read_project(wd)
2853             apiurl = store_read_apiurl(wd)
2854
2855         offset=0
2856         if opts.start:
2857             offset = int(opts.start)
2858
2859         if not repository or not arch:
2860             if len(args) < 2:
2861                 self.print_repos()
2862             else:
2863                 repository = args[0]
2864                 arch = args[1]
2865
2866         print_buildlog(apiurl, project, package, repository, arch, offset)
2867
2868
2869     def print_repos(self):
2870         wd = os.curdir
2871         doprint = False
2872         if is_package_dir(wd):
2873             str = "package"
2874             doprint = True
2875         elif is_project_dir(wd):
2876             str = "project"
2877             doprint = True
2878
2879         if doprint:
2880             print 'Valid arguments for this %s are:' % str
2881             print
2882             self.do_repos(None, None)
2883             print
2884         raise oscerr.WrongArgs('Missing arguments')
2885
2886     @cmdln.alias('rbl')
2887     @cmdln.alias('rbuildlog')
2888     @cmdln.option('-s', '--start', metavar='START',
2889                     help='get log starting from the offset')
2890     def do_remotebuildlog(self, subcmd, opts, *args):
2891         """${cmd_name}: Shows the build log of a package
2892
2893         Shows the log file of the build of a package. Can be used to follow the
2894         log while it is being written.
2895
2896         usage:
2897             osc remotebuildlog project package repository arch
2898             or
2899             osc remotebuildlog project/package/repository/arch
2900             or
2901             osc remotebuildlog buildlogurl
2902         ${cmd_option_list}
2903         """
2904         if len(args) == 1 and args[0].startswith('http'):
2905             apiurl, project, package, repository, arch = parse_buildlogurl(args[0])
2906         else:
2907             args = slash_split(args)
2908             apiurl = conf.config['apiurl']
2909             if len(args) < 4:
2910                 raise oscerr.WrongArgs('Too few arguments.')
2911             elif len(args) > 4:
2912                 raise oscerr.WrongArgs('Too many arguments.')
2913             else:
2914                 project, package, repository, arch = args
2915
2916         offset=0
2917         if opts.start:
2918             offset = int(opts.start)
2919
2920         print_buildlog(apiurl, project, package, repository, arch, offset)
2921
2922     @cmdln.alias('lbl')
2923     @cmdln.option('-s', '--start', metavar='START',
2924                   help='get log starting from offset')
2925     def do_localbuildlog(self, subcmd, opts, *args):
2926         """${cmd_name}: Shows the build log of a local buildchroot
2927
2928         usage:
2929             osc lbl [REPOSITORY ARCH]
2930             osc lbl # show log of newest last local build
2931
2932         ${cmd_option_list}
2933         """
2934         if conf.config['build-type']:
2935             # FIXME: raise Exception instead
2936             print >>sys.stderr, 'Not implemented for VMs'
2937             sys.exit(1)
2938
2939         if len(args) == 0:
2940             package = store_read_package('.')
2941             import glob
2942             files = glob.glob(os.path.join(os.getcwd(), store, "_buildinfo-*"))
2943             if not files:
2944                 self.print_repos()
2945                 raise oscerr.WrongArgs('No buildconfig found, please specify repo and arch manually.')
2946             cfg = files[0]
2947             # find newest file
2948             for f in files[1:]:
2949                 if os.stat(f).st_mtime > os.stat(cfg).st_mtime:
2950                     cfg = f
2951             root = ET.parse(cfg).getroot()
2952             project = root.get("project")
2953             repo = root.get("repository")
2954             arch = root.find("arch").text
2955         elif len(args) == 2:
2956             project = store_read_project('.')
2957             package = store_read_package('.')
2958             repo = args[0]
2959             arch = args[1]
2960         else:
2961             if is_package_dir(os.curdir):
2962                 self.print_repos()
2963             raise oscerr.WrongArgs('Wrong number of arguments.')
2964
2965         buildroot = os.environ.get('OSC_BUILD_ROOT', conf.config['build-root'])
2966         buildroot = buildroot % {'project': project, 'package': package,
2967                                  'repo': repo, 'arch': arch}
2968         offset = 0
2969         if opts.start:
2970             offset = int(opts.start)
2971         logfile = os.path.join(buildroot, '.build.log')
2972         if not os.path.isfile(logfile):
2973             raise oscerr.OscIOError(None, 'logfile \'%s\' does not exist' % logfile)
2974         f = open(logfile, 'r')
2975         f.seek(offset)
2976         data = f.read(BUFSIZE)
2977         while len(data):
2978             sys.stdout.write(data)
2979             data = f.read(BUFSIZE)
2980         f.close()
2981
2982     @cmdln.alias('tr')
2983     def do_triggerreason(self, subcmd, opts, *args):
2984         """${cmd_name}: Show reason why a package got triggered to build
2985
2986         The server decides when a package needs to get rebuild, this command
2987         shows the detailed reason for a package. A brief reason is also stored
2988         in the jobhistory, which can be accessed via "osc jobhistory".
2989
2990         Trigger reasons might be:
2991           - new build (never build yet or rebuild manually forced)
2992           - source change (eg. on updating sources)
2993           - meta change (packages which are used for building have changed)
2994           - rebuild count sync (In case that it is configured to sync release numbers)
2995
2996         usage in package or project directory:
2997             osc reason REPOSITORY ARCH
2998             osc reason PROJECT PACKAGE REPOSITORY ARCH
2999
3000         ${cmd_option_list}
3001         """
3002         wd = os.curdir
3003         args = slash_split(args)
3004         project = package = repository = arch = None
3005
3006         if len(args) < 2:
3007             self.print_repos()
3008
3009         if len(args) == 2: # 2
3010             if is_package_dir('.'):
3011                 package = store_read_package(wd)
3012             else:
3013                 raise oscerr.WrongArgs('package is not specified.')
3014             project = store_read_project(wd)
3015             apiurl = store_read_apiurl(wd)
3016             repository = args[0]
3017             arch = args[1]
3018         elif len(args) == 4:
3019             apiurl = conf.config['apiurl']
3020             project = args[0]
3021             package = args[1]
3022             repository = args[2]
3023             arch = args[3]
3024         else:
3025             raise oscerr.WrongArgs('Too many arguments.')
3026
3027         print apiurl, project, package, repository, arch
3028         xml = show_package_trigger_reason(apiurl, project, package, repository, arch)
3029         root = ET.fromstring(xml)
3030         reason = root.find('explain').text
3031         print reason
3032         if reason == "meta change":
3033             print "changed keys:"
3034             for package in root.findall('packagechange'):
3035                 print "  ", package.get('change'), package.get('key')
3036
3037
3038     # FIXME: the new osc syntax should allow to specify multiple packages
3039     # FIXME: the command should optionally use buildinfo data to show all dependencies
3040     @cmdln.alias('whatdependson')
3041     def do_dependson(self, subcmd, opts, *args):
3042         """${cmd_name}: Show the build dependencies
3043
3044         The command dependson and whatdependson can be used to find out what
3045         will be triggered when a certain package changes.
3046         This is no guarantee, since the new build might have changed dependencies.
3047
3048         dependson shows the build dependencies inside of a project, valid for a
3049         given repository and architecture.
3050         NOTE: to see all binary packages, which can trigger a build you need to
3051               refer the buildinfo, since this command shows only the dependencies
3052               inside of a project.
3053
3054         The arguments REPOSITORY and ARCH can be taken from the first two columns
3055         of the 'osc repos' output.
3056
3057         usage in package or project directory:
3058             osc dependson REPOSITORY ARCH
3059             osc whatdependson REPOSITORY ARCH
3060
3061         usage:
3062             osc dependson PROJECT [PACKAGE] REPOSITORY ARCH
3063             osc whatdependson PROJECT [PACKAGE] REPOSITORY ARCH
3064
3065         ${cmd_option_list}
3066         """
3067         wd = os.curdir
3068         args = slash_split(args)
3069         project = packages = repository = arch = reverse = None
3070
3071         if len(args) < 2 and (is_package_dir('.') or is_project_dir('.')):
3072             self.print_repos()
3073
3074         if len(args) > 5:
3075             raise oscerr.WrongArgs('Too many arguments.')
3076
3077         if len(args) < 3: # 2
3078             if is_package_dir('.'):
3079                 packages = [store_read_package(wd)]
3080             elif not is_project_dir('.'):
3081                 raise oscerr.WrongArgs('Project and package is not specified.')
3082             project = store_read_project(wd)
3083             apiurl = store_read_apiurl(wd)
3084             repository = args[0]
3085             arch = args[1]
3086
3087         if len(args) == 3:
3088             apiurl = conf.config['apiurl']
3089             project = args[0]
3090             repository = args[1]
3091             arch = args[2]
3092
3093         if len(args) == 4:
3094             apiurl = conf.config['apiurl']
3095             project = args[0]
3096             packages = [args[1]]
3097             repository = args[2]