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