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