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