]> git.decadent.org.uk Git - dak.git/blob - dak/process_new.py
upload.source can be null, fall back to upload.changes
[dak.git] / dak / process_new.py
1 #!/usr/bin/env python
2 # vim:set et ts=4 sw=4:
3
4 """ Handles NEW and BYHAND packages
5
6 @contact: Debian FTP Master <ftpmaster@debian.org>
7 @copyright: 2001, 2002, 2003, 2004, 2005, 2006  James Troup <james@nocrew.org>
8 @copyright: 2009 Joerg Jaspert <joerg@debian.org>
9 @copyright: 2009 Frank Lichtenheld <djpig@debian.org>
10 @license: GNU General Public License version 2 or later
11 """
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2 of the License, or
15 # (at your option) any later version.
16
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 # GNU General Public License for more details.
21
22 # You should have received a copy of the GNU General Public License
23 # along with this program; if not, write to the Free Software
24 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
26 ################################################################################
27
28 # 23:12|<aj> I will not hush!
29 # 23:12|<elmo> :>
30 # 23:12|<aj> Where there is injustice in the world, I shall be there!
31 # 23:13|<aj> I shall not be silenced!
32 # 23:13|<aj> The world shall know!
33 # 23:13|<aj> The world *must* know!
34 # 23:13|<elmo> oh dear, he's gone back to powerpuff girls... ;-)
35 # 23:13|<aj> yay powerpuff girls!!
36 # 23:13|<aj> buttercup's my favourite, who's yours?
37 # 23:14|<aj> you're backing away from the keyboard right now aren't you?
38 # 23:14|<aj> *AREN'T YOU*?!
39 # 23:15|<aj> I will not be treated like this.
40 # 23:15|<aj> I shall have my revenge.
41 # 23:15|<aj> I SHALL!!!
42
43 ################################################################################
44
45 import copy
46 import errno
47 import os
48 import readline
49 import stat
50 import sys
51 import time
52 import contextlib
53 import pwd
54 import apt_pkg, apt_inst
55 import examine_package
56 import subprocess
57 from sqlalchemy import or_
58
59 from daklib.dbconn import *
60 from daklib.queue import *
61 from daklib import daklog
62 from daklib import utils
63 from daklib.regexes import re_no_epoch, re_default_answer, re_isanum, re_package
64 from daklib.dak_exceptions import CantOpenError, AlreadyLockedError, CantGetLockError
65 from daklib.summarystats import SummaryStats
66 from daklib.config import Config
67 from daklib.policy import UploadCopy, PolicyQueueUploadHandler
68
69 # Globals
70 Options = None
71 Logger = None
72
73 Priorities = None
74 Sections = None
75
76 ################################################################################
77 ################################################################################
78 ################################################################################
79
80 class Section_Completer:
81     def __init__ (self, session):
82         self.sections = []
83         self.matches = []
84         for s, in session.query(Section.section):
85             self.sections.append(s)
86
87     def complete(self, text, state):
88         if state == 0:
89             self.matches = []
90             n = len(text)
91             for word in self.sections:
92                 if word[:n] == text:
93                     self.matches.append(word)
94         try:
95             return self.matches[state]
96         except IndexError:
97             return None
98
99 ############################################################
100
101 class Priority_Completer:
102     def __init__ (self, session):
103         self.priorities = []
104         self.matches = []
105         for p, in session.query(Priority.priority):
106             self.priorities.append(p)
107
108     def complete(self, text, state):
109         if state == 0:
110             self.matches = []
111             n = len(text)
112             for word in self.priorities:
113                 if word[:n] == text:
114                     self.matches.append(word)
115         try:
116             return self.matches[state]
117         except IndexError:
118             return None
119
120 ################################################################################
121
122 def takenover_binaries(upload, missing, session):
123     rows = []
124     source = upload.source.source if upload.source else upload.changes.source
125     binaries = set([x.package for x in upload.binaries])
126     for m in missing:
127         if m['type'] != 'dsc':
128             binaries.remove(m['package'])
129     if binaries:
130         source = upload.binaries[0].source.source
131         suite = upload.target_suite.overridesuite or \
132                     upload.target_suite.suite_name
133         suites = [s[0] for s in session.query(Suite.suite_name).filter \
134                                     (or_(Suite.suite_name == suite,
135                                      Suite.overridesuite == suite)).all()]
136         rows = session.query(DBSource.source, DBBinary.package).distinct(). \
137                              filter(DBBinary.package.in_(binaries)). \
138                              join(DBBinary.source). \
139                              filter(DBSource.source != source). \
140                              join(DBBinary.suites). \
141                              filter(Suite.suite_name.in_(suites)). \
142                              order_by(DBSource.source, DBBinary.package).all()
143     return rows
144
145 ################################################################################
146
147 def print_new (upload, missing, indexed, session, file=sys.stdout):
148     check_valid(missing, session)
149     index = 0
150     for m in missing:
151         index += 1
152         if m['type'] != 'deb':
153             package = '{0}:{1}'.format(m['type'], m['package'])
154         else:
155             package = m['package']
156         section = m['section']
157         priority = m['priority']
158         if indexed:
159             line = "(%s): %-20s %-20s %-20s" % (index, package, priority, section)
160         else:
161             line = "%-20s %-20s %-20s" % (package, priority, section)
162         line = line.strip()
163         if not m['valid']:
164             line = line + ' [!]'
165         print >>file, line
166     takenover = takenover_binaries(upload, missing, session)
167     if takenover:
168         print '\n\nBINARIES TAKEN OVER\n'
169         for t in takenover:
170             print '%s: %s' % (t[0], t[1])
171     notes = get_new_comments(upload.policy_queue, upload.changes.source)
172     for note in notes:
173         print "\nAuthor: %s\nVersion: %s\nTimestamp: %s\n\n%s" \
174               % (note.author, note.version, note.notedate, note.comment)
175         print "-" * 72
176     return len(notes) > 0
177
178 ################################################################################
179
180 def index_range (index):
181     if index == 1:
182         return "1"
183     else:
184         return "1-%s" % (index)
185
186 ################################################################################
187 ################################################################################
188
189 def edit_new (overrides, upload, session):
190     # Write the current data to a temporary file
191     (fd, temp_filename) = utils.temp_filename()
192     temp_file = os.fdopen(fd, 'w')
193     print_new (upload, overrides, indexed=0, session=session, file=temp_file)
194     temp_file.close()
195     # Spawn an editor on that file
196     editor = os.environ.get("EDITOR","vi")
197     result = os.system("%s %s" % (editor, temp_filename))
198     if result != 0:
199         utils.fubar ("%s invocation failed for %s." % (editor, temp_filename), result)
200     # Read the edited data back in
201     temp_file = utils.open_file(temp_filename)
202     lines = temp_file.readlines()
203     temp_file.close()
204     os.unlink(temp_filename)
205
206     overrides_map = dict([ ((o['type'], o['package']), o) for o in overrides ])
207     new_overrides = []
208     # Parse the new data
209     for line in lines:
210         line = line.strip()
211         if line == "" or line[0] == '#':
212             continue
213         s = line.split()
214         # Pad the list if necessary
215         s[len(s):3] = [None] * (3-len(s))
216         (pkg, priority, section) = s[:3]
217         if pkg.find(':') != -1:
218             type, pkg = pkg.split(':', 1)
219         else:
220             type = 'deb'
221         if (type, pkg) not in overrides_map:
222             utils.warn("Ignoring unknown package '%s'" % (pkg))
223         else:
224             if section.find('/') != -1:
225                 component = section.split('/', 1)[0]
226             else:
227                 component = 'main'
228             new_overrides.append(dict(
229                     package=pkg,
230                     type=type,
231                     section=section,
232                     component=component,
233                     priority=priority,
234                     ))
235     return new_overrides
236
237 ################################################################################
238
239 def edit_index (new, upload, index):
240     package = new[index]['package']
241     priority = new[index]["priority"]
242     section = new[index]["section"]
243     ftype = new[index]["type"]
244     done = 0
245     while not done:
246         print "\t".join([package, priority, section])
247
248         answer = "XXX"
249         if ftype != "dsc":
250             prompt = "[B]oth, Priority, Section, Done ? "
251         else:
252             prompt = "[S]ection, Done ? "
253         edit_priority = edit_section = 0
254
255         while prompt.find(answer) == -1:
256             answer = utils.our_raw_input(prompt)
257             m = re_default_answer.match(prompt)
258             if answer == "":
259                 answer = m.group(1)
260             answer = answer[:1].upper()
261
262         if answer == 'P':
263             edit_priority = 1
264         elif answer == 'S':
265             edit_section = 1
266         elif answer == 'B':
267             edit_priority = edit_section = 1
268         elif answer == 'D':
269             done = 1
270
271         # Edit the priority
272         if edit_priority:
273             readline.set_completer(Priorities.complete)
274             got_priority = 0
275             while not got_priority:
276                 new_priority = utils.our_raw_input("New priority: ").strip()
277                 if new_priority not in Priorities.priorities:
278                     print "E: '%s' is not a valid priority, try again." % (new_priority)
279                 else:
280                     got_priority = 1
281                     priority = new_priority
282
283         # Edit the section
284         if edit_section:
285             readline.set_completer(Sections.complete)
286             got_section = 0
287             while not got_section:
288                 new_section = utils.our_raw_input("New section: ").strip()
289                 if new_section not in Sections.sections:
290                     print "E: '%s' is not a valid section, try again." % (new_section)
291                 else:
292                     got_section = 1
293                     section = new_section
294
295         # Reset the readline completer
296         readline.set_completer(None)
297
298     new[index]["priority"] = priority
299     new[index]["section"] = section
300     if section.find('/') != -1:
301         component = section.split('/', 1)[0]
302     else:
303         component = 'main'
304     new[index]['component'] = component
305
306     return new
307
308 ################################################################################
309
310 def edit_overrides (new, upload, session):
311     print
312     done = 0
313     while not done:
314         print_new (upload, new, indexed=1, session=session)
315         prompt = "edit override <n>, Editor, Done ? "
316
317         got_answer = 0
318         while not got_answer:
319             answer = utils.our_raw_input(prompt)
320             if not answer.isdigit():
321                 answer = answer[:1].upper()
322             if answer == "E" or answer == "D":
323                 got_answer = 1
324             elif re_isanum.match (answer):
325                 answer = int(answer)
326                 if answer < 1 or answer > len(new):
327                     print "{0} is not a valid index.  Please retry.".format(answer)
328                 else:
329                     got_answer = 1
330
331         if answer == 'E':
332             new = edit_new(new, upload, session)
333         elif answer == 'D':
334             done = 1
335         else:
336             edit_index (new, upload, answer - 1)
337
338     return new
339
340
341 ################################################################################
342
343 def check_pkg (upload, upload_copy, session):
344     missing = []
345     save_stdout = sys.stdout
346     changes = os.path.join(upload_copy.directory, upload.changes.changesname)
347     suite_name = upload.target_suite.suite_name
348     handler = PolicyQueueUploadHandler(upload, session)
349     missing = [(m['type'], m["package"]) for m in handler.missing_overrides(hints=missing)]
350     try:
351         sys.stdout = os.popen("less -R -", 'w', 0)
352         print examine_package.display_changes(suite_name, changes)
353
354         source = upload.source
355         if source is not None:
356             source_file = os.path.join(upload_copy.directory, os.path.basename(source.poolfile.filename))
357             print examine_package.check_dsc(suite_name, source_file)
358
359         for binary in upload.binaries:
360             binary_file = os.path.join(upload_copy.directory, os.path.basename(binary.poolfile.filename))
361             examined = examine_package.check_deb(suite_name, binary_file)
362             # We always need to call check_deb to display package relations for every binary,
363             # but we print its output only if new overrides are being added.
364             if ("deb", binary.package) in missing:
365                 print examined
366
367         print examine_package.output_package_relations()
368     except IOError as e:
369         if e.errno == errno.EPIPE:
370             utils.warn("[examine_package] Caught EPIPE; skipping.")
371         else:
372             raise
373     except KeyboardInterrupt:
374         utils.warn("[examine_package] Caught C-c; skipping.")
375     finally:
376         sys.stdout = save_stdout
377
378 ################################################################################
379
380 ## FIXME: horribly Debian specific
381
382 def do_bxa_notification(new, upload, session):
383     cnf = Config()
384
385     new = set([ o['package'] for o in new if o['type'] == 'deb' ])
386     if len(new) == 0:
387         return
388
389     key = session.query(MetadataKey).filter_by(key='Description').one()
390     summary = ""
391     for binary in upload.binaries:
392         if binary.package not in new:
393             continue
394         description = session.query(BinaryMetadata).filter_by(binary=binary, key=key).one().value
395         summary += "\n"
396         summary += "Package: {0}\n".format(binary.package)
397         summary += "Description: {0}\n".format(description)
398
399     subst = {
400         '__DISTRO__': cnf['Dinstall::MyDistribution'],
401         '__BCC__': 'X-DAK: dak process-new',
402         '__BINARY_DESCRIPTIONS__': summary,
403         }
404
405     bxa_mail = utils.TemplateSubst(subst,os.path.join(cnf["Dir::Templates"], "process-new.bxa_notification"))
406     utils.send_mail(bxa_mail)
407
408 ################################################################################
409
410 def add_overrides (new_overrides, suite, session):
411     if suite.overridesuite is not None:
412         suite = session.query(Suite).filter_by(suite_name=suite.overridesuite).one()
413
414     for override in new_overrides:
415         package = override['package']
416         priority = session.query(Priority).filter_by(priority=override['priority']).first()
417         section = session.query(Section).filter_by(section=override['section']).first()
418         component = get_mapped_component(override['component'], session)
419         overridetype = session.query(OverrideType).filter_by(overridetype=override['type']).one()
420
421         if priority is None:
422             raise Exception('Invalid priority {0} for package {1}'.format(priority, package))
423         if section is None:
424             raise Exception('Invalid section {0} for package {1}'.format(section, package))
425         if component is None:
426             raise Exception('Invalid component {0} for package {1}'.format(component, package))
427
428         o = Override(package=package, suite=suite, component=component, priority=priority, section=section, overridetype=overridetype)
429         session.add(o)
430
431     session.commit()
432
433 ################################################################################
434
435 def run_user_inspect_command(upload, upload_copy):
436     command = os.environ.get('DAK_INSPECT_UPLOAD')
437     if command is None:
438         return
439
440     directory = upload_copy.directory
441     if upload.source:
442         dsc = os.path.basename(upload.source.poolfile.filename)
443     else:
444         dsc = ''
445     changes = upload.changes.changesname
446
447     shell_command = command.format(
448             directory=directory,
449             dsc=dsc,
450             changes=changes,
451             )
452
453     subprocess.check_call(shell_command, shell=True)
454
455 ################################################################################
456
457 def get_reject_reason(reason=''):
458     """get reason for rejection
459
460     @rtype:  str
461     @return: string giving the reason for the rejection or C{None} if the
462              rejection should be cancelled
463     """
464     answer = 'E'
465     if Options['Automatic']:
466         answer = 'R'
467
468     while answer == 'E':
469         reason = utils.call_editor(reason)
470         print "Reject message:"
471         print utils.prefix_multi_line_string(reason, "  ", include_blank_lines=1)
472         prompt = "[R]eject, Edit, Abandon, Quit ?"
473         answer = "XXX"
474         while prompt.find(answer) == -1:
475             answer = utils.our_raw_input(prompt)
476             m = re_default_answer.search(prompt)
477             if answer == "":
478                 answer = m.group(1)
479             answer = answer[:1].upper()
480
481     if answer == 'Q':
482         sys.exit(0)
483
484     if answer == 'R':
485         return reason
486     return None
487
488 ################################################################################
489
490 def do_new(upload, upload_copy, handler, session):
491     cnf = Config()
492
493     run_user_inspect_command(upload, upload_copy)
494
495     # The main NEW processing loop
496     done = False
497     missing = []
498     while not done:
499         queuedir = upload.policy_queue.path
500         byhand = upload.byhand
501
502         missing = handler.missing_overrides(hints=missing)
503         broken = not check_valid(missing, session)
504
505         changesname = os.path.basename(upload.changes.changesname)
506
507         print
508         print changesname
509         print "-" * len(changesname)
510         print
511         print "   Target:     {0}".format(upload.target_suite.suite_name)
512         print "   Changed-By: {0}".format(upload.changes.changedby)
513         print
514
515         #if len(byhand) == 0 and len(missing) == 0:
516         #    break
517
518         if missing:
519             print "NEW\n"
520
521         answer = "XXX"
522         if Options["No-Action"] or Options["Automatic"]:
523             answer = 'S'
524
525         note = print_new(upload, missing, indexed=0, session=session)
526         prompt = ""
527
528         has_unprocessed_byhand = False
529         for f in byhand:
530             path = os.path.join(queuedir, f.filename)
531             if not f.processed and os.path.exists(path):
532                 print "W: {0} still present; please process byhand components and try again".format(f.filename)
533                 has_unprocessed_byhand = True
534
535         if not has_unprocessed_byhand and not broken and not note:
536             if len(missing) == 0:
537                 prompt = "Accept, "
538                 answer = 'A'
539             else:
540                 prompt = "Add overrides, "
541         if broken:
542             print "W: [!] marked entries must be fixed before package can be processed."
543         if note:
544             print "W: note must be removed before package can be processed."
545             prompt += "RemOve all notes, Remove note, "
546
547         prompt += "Edit overrides, Check, Manual reject, Note edit, Prod, [S]kip, Quit ?"
548
549         while prompt.find(answer) == -1:
550             answer = utils.our_raw_input(prompt)
551             m = re_default_answer.search(prompt)
552             if answer == "":
553                 answer = m.group(1)
554             answer = answer[:1].upper()
555
556         if answer in ( 'A', 'E', 'M', 'O', 'R' ) and Options["Trainee"]:
557             utils.warn("Trainees can't do that")
558             continue
559
560         if answer == 'A' and not Options["Trainee"]:
561             add_overrides(missing, upload.target_suite, session)
562             if Config().find_b("Dinstall::BXANotify"):
563                 do_bxa_notification(missing, upload, session)
564             handler.accept()
565             done = True
566             Logger.log(["NEW ACCEPT", upload.changes.changesname])
567         elif answer == 'C':
568             check_pkg(upload, upload_copy, session)
569         elif answer == 'E' and not Options["Trainee"]:
570             missing = edit_overrides (missing, upload, session)
571         elif answer == 'M' and not Options["Trainee"]:
572             reason = Options.get('Manual-Reject', '') + "\n"
573             reason = reason + "\n\n=====\n\n".join([n.comment for n in get_new_comments(upload.policy_queue, upload.changes.source, session=session)])
574             reason = get_reject_reason(reason)
575             if reason is not None:
576                 Logger.log(["NEW REJECT", upload.changes.changesname])
577                 handler.reject(reason)
578                 done = True
579         elif answer == 'N':
580             if edit_note(get_new_comments(upload.policy_queue, upload.changes.source, session=session),
581                          upload, session, bool(Options["Trainee"])) == 0:
582                 end()
583                 sys.exit(0)
584         elif answer == 'P' and not Options["Trainee"]:
585             if prod_maintainer(get_new_comments(upload.policy_queue, upload.changes.source, session=session),
586                                upload) == 0:
587                 end()
588                 sys.exit(0)
589             Logger.log(["NEW PROD", upload.changes.changesname])
590         elif answer == 'R' and not Options["Trainee"]:
591             confirm = utils.our_raw_input("Really clear note (y/N)? ").lower()
592             if confirm == "y":
593                 for c in get_new_comments(upload.policy_queue, upload.changes.source, upload.changes.version, session=session):
594                     session.delete(c)
595                 session.commit()
596         elif answer == 'O' and not Options["Trainee"]:
597             confirm = utils.our_raw_input("Really clear all notes (y/N)? ").lower()
598             if confirm == "y":
599                 for c in get_new_comments(upload.policy_queue, upload.changes.source, session=session):
600                     session.delete(c)
601                 session.commit()
602
603         elif answer == 'S':
604             done = True
605         elif answer == 'Q':
606             end()
607             sys.exit(0)
608
609         if handler.get_action():
610             print "PENDING %s\n" % handler.get_action()
611
612 ################################################################################
613 ################################################################################
614 ################################################################################
615
616 def usage (exit_code=0):
617     print """Usage: dak process-new [OPTION]... [CHANGES]...
618   -a, --automatic           automatic run
619   -b, --no-binaries         do not sort binary-NEW packages first
620   -c, --comments            show NEW comments
621   -h, --help                show this help and exit.
622   -m, --manual-reject=MSG   manual reject with `msg'
623   -n, --no-action           don't do anything
624   -q, --queue=QUEUE         operate on a different queue
625   -t, --trainee             FTP Trainee mode
626   -V, --version             display the version number and exit
627
628 ENVIRONMENT VARIABLES
629
630   DAK_INSPECT_UPLOAD: shell command to run to inspect a package
631       The command is automatically run in a shell when an upload
632       is checked.  The following substitutions are available:
633
634         {directory}: directory the upload is contained in
635         {dsc}:       name of the included dsc or the empty string
636         {changes}:   name of the changes file
637
638       Note that Python's 'format' method is used to format the command.
639
640       Example: run mc in a tmux session to inspect the upload
641
642       export DAK_INSPECT_UPLOAD='tmux new-session -d -s process-new 2>/dev/null; tmux new-window -n "{changes}" -t process-new:0 -k "cd {directory}; mc"'
643
644       and run
645
646       tmux attach -t process-new
647
648       in a separate terminal session.
649 """
650     sys.exit(exit_code)
651
652 ################################################################################
653
654 @contextlib.contextmanager
655 def lock_package(package):
656     """
657     Lock C{package} so that noone else jumps in processing it.
658
659     @type package: string
660     @param package: source package name to lock
661     """
662
663     cnf = Config()
664
665     path = os.path.join(cnf.get("Process-New::LockDir", cnf['Dir::Lock']), package)
666
667     try:
668         fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDONLY)
669     except OSError as e:
670         if e.errno == errno.EEXIST or e.errno == errno.EACCES:
671             user = pwd.getpwuid(os.stat(path)[stat.ST_UID])[4].split(',')[0].replace('.', '')
672             raise AlreadyLockedError(user)
673
674     try:
675         yield fd
676     finally:
677         os.unlink(path)
678
679 def do_pkg(upload, session):
680     # Try to get an included dsc
681     dsc = upload.source
682
683     cnf = Config()
684     group = cnf.get('Dinstall::UnprivGroup') or None
685
686     #bcc = "X-DAK: dak process-new"
687     #if cnf.has_key("Dinstall::Bcc"):
688     #    u.Subst["__BCC__"] = bcc + "\nBcc: %s" % (cnf["Dinstall::Bcc"])
689     #else:
690     #    u.Subst["__BCC__"] = bcc
691
692     try:
693       with lock_package(upload.changes.source):
694        with UploadCopy(upload, group=group) as upload_copy:
695         handler = PolicyQueueUploadHandler(upload, session)
696         if handler.get_action() is not None:
697             print "PENDING %s\n" % handler.get_action()
698             return
699
700         do_new(upload, upload_copy, handler, session)
701     except AlreadyLockedError as e:
702         print "Seems to be locked by %s already, skipping..." % (e)
703
704 def show_new_comments(uploads, session):
705     sources = [ upload.changes.source for upload in uploads ]
706     if len(sources) == 0:
707         return
708
709     query = """SELECT package, version, comment, author
710                FROM new_comments
711                WHERE package IN :sources
712                ORDER BY package, version"""
713
714     r = session.execute(query, params=dict(sources=tuple(sources)))
715
716     for i in r:
717         print "%s_%s\n%s\n(%s)\n\n\n" % (i[0], i[1], i[2], i[3])
718
719     session.rollback()
720
721 ################################################################################
722
723 def sort_uploads(new_queue, uploads, session, nobinaries=False):
724     sources = {}
725     sorteduploads = []
726     suitesrc = [s.source for s in session.query(DBSource.source). \
727       filter(DBSource.suites.any(Suite.suite_name.in_(['unstable', 'experimental'])))]
728     comments = [p.package for p in session.query(NewComment.package). \
729       filter_by(trainee=False, policy_queue=new_queue).distinct()]
730     for upload in uploads:
731         source = upload.changes.source
732         if not source in sources:
733             sources[source] = []
734         sources[source].append({'upload': upload,
735                                 'date': upload.changes.created,
736                                 'stack': 1,
737                                 'binary': True if source in suitesrc else False,
738                                 'comments': True if source in comments else False})
739     for src in sources:
740         if len(sources[src]) > 1:
741             changes = sources[src]
742             firstseen = sorted(changes, key=lambda k: (k['date']))[0]['date']
743             changes.sort(key=lambda item:item['date'])
744             for i in range (0, len(changes)):
745                 changes[i]['date'] = firstseen
746                 changes[i]['stack'] = i + 1
747         sorteduploads += sources[src]
748     if nobinaries:
749         sorteduploads = [u["upload"] for u in sorted(sorteduploads,
750                          key=lambda k: (k["comments"], k["binary"],
751                          k["date"], -k["stack"]))]
752     else:
753         sorteduploads = [u["upload"] for u in sorted(sorteduploads,
754                          key=lambda k: (k["comments"], -k["binary"],
755                          k["date"], -k["stack"]))]
756     return sorteduploads
757
758 ################################################################################
759
760 def end():
761     accept_count = SummaryStats().accept_count
762     accept_bytes = SummaryStats().accept_bytes
763
764     if accept_count:
765         sets = "set"
766         if accept_count > 1:
767             sets = "sets"
768         sys.stderr.write("Accepted %d package %s, %s.\n" % (accept_count, sets, utils.size_type(int(accept_bytes))))
769         Logger.log(["total",accept_count,accept_bytes])
770
771     if not Options["No-Action"] and not Options["Trainee"]:
772         Logger.close()
773
774 ################################################################################
775
776 def main():
777     global Options, Logger, Sections, Priorities
778
779     cnf = Config()
780     session = DBConn().session()
781
782     Arguments = [('a',"automatic","Process-New::Options::Automatic"),
783                  ('b',"no-binaries","Process-New::Options::No-Binaries"),
784                  ('c',"comments","Process-New::Options::Comments"),
785                  ('h',"help","Process-New::Options::Help"),
786                  ('m',"manual-reject","Process-New::Options::Manual-Reject", "HasArg"),
787                  ('t',"trainee","Process-New::Options::Trainee"),
788                  ('q','queue','Process-New::Options::Queue', 'HasArg'),
789                  ('n',"no-action","Process-New::Options::No-Action")]
790
791     changes_files = apt_pkg.parse_commandline(cnf.Cnf,Arguments,sys.argv)
792
793     for i in ["automatic", "no-binaries", "comments", "help", "manual-reject", "no-action", "version", "trainee"]:
794         if not cnf.has_key("Process-New::Options::%s" % (i)):
795             cnf["Process-New::Options::%s" % (i)] = ""
796
797     queue_name = cnf.get('Process-New::Options::Queue', 'new')
798     new_queue = session.query(PolicyQueue).filter_by(queue_name=queue_name).one()
799     if len(changes_files) == 0:
800         uploads = new_queue.uploads
801     else:
802         uploads = session.query(PolicyQueueUpload).filter_by(policy_queue=new_queue) \
803             .join(DBChange).filter(DBChange.changesname.in_(changes_files)).all()
804
805     Options = cnf.subtree("Process-New::Options")
806
807     if Options["Help"]:
808         usage()
809
810     if not Options["No-Action"]:
811         try:
812             Logger = daklog.Logger("process-new")
813         except CantOpenError as e:
814             Options["Trainee"] = "True"
815
816     Sections = Section_Completer(session)
817     Priorities = Priority_Completer(session)
818     readline.parse_and_bind("tab: complete")
819
820     if len(uploads) > 1:
821         sys.stderr.write("Sorting changes...\n")
822         uploads = sort_uploads(new_queue, uploads, session, Options["No-Binaries"])
823
824     if Options["Comments"]:
825         show_new_comments(uploads, session)
826     else:
827         for upload in uploads:
828             do_pkg (upload, session)
829
830     end()
831
832 ################################################################################
833
834 if __name__ == '__main__':
835     main()