axiom-developer
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Axiom-developer] bugzilla


From: Camm Maguire
Subject: Re: [Axiom-developer] bugzilla
Date: Fri, 26 Mar 2004 18:55:21 -0000
User-agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.2

Greetings!  OK -- alas it is in python:

=============================================================================
#!/usr/bin/python2.3 -S
# -*- python -*-
# reportbug - Report a bug in the Debian distribution.
#   Written by Chris Lawrence <address@hidden>
#   Copyright (C) 1999-2004 Chris Lawrence
#
# This program is freely distributable per the following license:
#
LICENSE="""\
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appears in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation.

I DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL I
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE."""
#
# Version 2.48; see changelog for revision history
# $Id: reportbug,v 1.20 2004/02/17 23:37:33 lawrencc Exp $

import site

VERSION = "reportbug 2.48"
COPYRIGHT = VERSION + '\nCopyright (C) 1999-2004 Chris Lawrence 
<address@hidden>'
DEBUGGER = 'address@hidden'
DEFAULT_BTS = 'debian'

import sys, os
sys.path = [os.curdir, '/usr/share/reportbug'] + sys.path

import optparse, re, os, pwd, time, locale, commands, checkversions
import rfc822, smtplib, reportbug, cStringIO, socket, debianbts, checkbuildd
import gettext, popen2

from rbtempfile import TempFile, open_write_safe

from reportbug import MODE_EXPERT, MODE_ADVANCED, MODE_NOVICE, MODE_STANDARD
from reportbug_exceptions import *
from optparse import OptionParser, OptionValueError
import textwrap

import email
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEAudio import MIMEAudio
from email.MIMEImage import MIMEImage
from email.MIMEBase import MIMEBase
from email.MIMEMessage import MIMEMessage
from email.Header import Header
from email import Encoders

# Ignore the f*cking deprecation warnings that slipped into a stable release
#import warnings
#warnings.filterwarnings("ignore", category=DeprecationWarning)

try:
    gettext.install('reportbug')
except IOError:
    pass

import reportbug_ui_text as ui

# Magic constant time
MIN_USER_ID = 250

quietly = False

# Lame empty exception used later to save some coding
class NoMessage(Exception):
    pass

# Cheat for now.
# ewrite() may put stuff on the status bar or in message boxes depending on UI
def ewrite(*args):
    return quietly or ui.log_message(*args)

# Lame message when we store a report as a temp file.
def stopmsg(filename):
    ui.long_message(
        'reportbug stopped; your incomplete report is stored as "%s".\n'
        'This file may be located in a temporary directory; if so, it might '
        'disappear without any further notice.\n', filename)

# Obscene hack :)
def system(cmdline):
    try:
        x = os.getcwd()
    except OSError:
        os.chdir('/')
    os.system(cmdline)

def show_report(text, use_pager=True):
    if not use_pager:
        ewrite(text)
        return

    pager = os.environ.get('PAGER', 'sensible-pager')
    os.popen(pager, 'w').write(text)

def spawn_editor(message, filename, default_editor=None):
    if not default_editor:
        editor = (os.environ.get('VISUAL') or os.environ.get('EDITOR') or
                  '/usr/bin/sensible-editor')
    else:
        editor = default_editor

    if not editor:
        ewrite('No editor found!\n')
        return (message, 0)

    edname = os.path.basename(editor.split()[0])

    # Move the cursor for lazy buggers like me; add your editor here...
    ourline = 0
    for (lineno, line) in enumerate(file(filename)):
        if line == '\n' and not ourline:
            ourline = lineno + 2
        elif line.strip() == reportbug.NEWBIELINE:
            ourline = lineno + 2

    opts = ''
    if 'vim' in edname:
        # Force *vim to edit the file in the foreground, instead of forking
        opts = '-f '
    
    if ourline:
        if edname in ('vi', 'nvi', 'vim', 'elvis', 'gvim', 'kvim'):
            opts = '-c :%d' % ourline
        elif (edname in ('elvis-tiny', 'gnuclient', 'ee', 'pico', 'nano') or
              'emacs' in edname):
            opts = '+%d' % ourline
        elif edname in ('jed', 'xjed'):
            opts = '-g %d' % ourline
        elif edname == 'kate':
            opts = '--line %d' % ourline

    if '&' in editor or edname == 'kate':
        ewrite("Spawning %s in background; please press Enter when done "
               "editing.\n", edname)
    else:
        ewrite("Spawning %s...\n", edname)

    result = system("%s %s '%s'" % (editor, opts, filename))

    if result:
        ewrite('Warning: possible error exit from %s: %d\n', edname, result)

    if not os.path.exists(filename):
        ewrite('Bug report file %s removed!', filename)
        sys.exit(1)

    if '&' in editor: return (None, 1)

    newmessage = file(filename).read()

    if newmessage == message:
        ewrite('No changes were made in the editor.\n')

    return (newmessage, newmessage != message)

def handle_editing(filename, dmessage, options, sendto, attachments, package,
                   editor=None):
    if not editor:
        editor = options.editor
    message = None
    skip_editing = False
    while 1:
        if not skip_editing:
            (message, changed) = spawn_editor(message or dmessage, filename,
                                              editor)
        skip_editing = False
        if not message:
            x = ''
            while x != 'y':
                x = ui.select_options('Done editing', 'Ynq',
                                      {'y': 'Continue (editing done).',
                                       'n': "Don't continue yet.",
                                       'q': 'Exit without sending report.'})
                if x == 'q':
                    stopmsg(filename)
                    sys.exit(1)

            message = file(filename).read()
            changed = True

        prompt = 'Submit this report on %s (e to edit)' % package
        if options.kudos:
            prompt = 'Send this message (e to edit)'
            ewrite("Message will be sent to %s\n", sendto)
        elif options.outfile:
            ewrite("Report will be saved as %s\n", options.outfile)
        else:
            ewrite("Report will be sent to %s\n", sendto)

        if attachments:
            ewrite('Attachments:\n')
            for name in attachments:
                ewrite(' %s\n', name)

        menuopts = "Ynaceilmp"
        if not changed: menuopts = "ynacEilmp"

        x = ui.select_options(prompt, menuopts,
                              {'y': 'Submit the bug report via email.',
                               'n': "Don't submit the bug report; instead, "
                               "save it in a temporary file.",
                               'a': "Attach a file.",
                               'i': "Include a text file.",
                               'c': "Change editor and re-edit.",
                               'e': 'Re-edit the bug report.',
                               'l': 'Pipe the message through the pager.',
                               'p': 'Print message to stdout.',
                               'm': "Choose a mailer to edit the report."})
        if x in ('a', 'i'):
            if x == 'i':
                attachfile = ui.get_filename('Choose a text file to include: ')
            else:
                attachfile = ui.get_filename('Choose a file to attach: ')
            if attachfile:
                attachfile = os.path.expanduser(attachfile)
                if os.path.exists(attachfile):
                    if x == 'i':
                        fp = file(attachfile)
                        message += '\n*** %s\n%s' % (attachfile, fp.read())
                        fp.close()
                        fp, filename2 = TempFile()
                        fp.write(message)
                        fp.close()
                        os.unlink(filename)
                        filename = filename2
                    else:
                        attachments.append(attachfile)
                        skip_editing = True
                else:
                    ewrite("Can't find %s to include!\n", attachfile)
        elif x == 'c':
            ed = ui.get_filename('Choose editor: ', default=options.editor)
            if ed:
                editor = ed
        elif x == 'm':
            mailers = [(x, "") for x in reportbug.MUA.keys()]
            mailers.sort()
            mailer = ui.menu('Choose a mailer for your report', mailers,
                             'Select mailer: ', default='', empty_ok=True)
            if mailer:
                mailer = reportbug.MUA.get(mailer)
                if mailer:
                    options.mua = mailer
                    break
            skip_editing = True
        elif x == 'n':
            stopmsg(filename)
            sys.exit(1)
        elif x in ('l', 'p'):
            skip_editing = True
            if x == 'l':
                pager = os.environ.get('PAGER', 'sensible-pager')
                os.popen(pager, 'w').write(message)
            else:
                sys.stdout.write(message)
        elif x == 'y':
            if message == dmessage:
                x = ui.select_options(
                    'Report is unchanged.  Edit this report or quit', 'Eqs',
                    {'q': "Don't submit the bug report; instead, save it "
                     "in a temporary file and quit.",
                     'e': 'Re-edit the bug report.',
                     's': 'Send report anyway.'})
                if x == 'q':
                    stopmsg(filename)
                    sys.exit(1)
                    break
                elif x == 's':
                    ewrite('Sending empty report anyway...\n')
                    break
            else:
                break

    return file(filename).read()

def find_package_for(filename, notatty=False, pathonly=False):
    ewrite("Finding package for '%s'...\n", filename)
    (newfilename, packages) = reportbug.find_package_for(filename, pathonly)
    if newfilename != filename:
        filename = newfilename
        ewrite("Resolved as '%s'.\n", filename)
    if not packages:
        ewrite("No packages match.\n")
        return (filename, None)
    elif len(packages) > 1:
        if notatty:
            print "Please re-run reportbug selecting one of these packages:"
            for package in packlist:
                print "  "+package
            sys.exit(1)

        packlist = packages.items()
        packlist.sort()
        packs = []
        for pkg, files in packlist:
            if len(files) > 3:
                files[3:] = ['...']
            packs.append( (pkg, ', '.join(files) ) )

        package = ui.menu("Multiple packages match: ", packs, 'Select one '
                          'of these packages: ', any_ok=True)
        return (filename, package)
    else:
        package = packages.keys()[0]
        ewrite("Using package '%s'.\n", package)
        return (filename, package)

def get_other_package_name(others):
    return ui.menu("Please enter the name of the package in which you "
                   "have found a problem, or choose one of these bug "
                   "categories:", others, "Enter a package: ", any_ok=True,
                   default='')

def get_package_name(bts='debian', mode=MODE_EXPERT):
    others = debianbts.SYSTEMS[bts]['otherpkgs']
    prompt = "Please enter the name of the package in which you have found "\
             "a problem"
    if others:
        prompt += ", or type 'other' to report a more general problem."
    else:
        prompt += '.'
    
    package = ui.get_string(prompt, force_prompt=True)
    if not package:
        return
    if others and package and package == 'other':
        package = get_other_package_name(others)

    if mode < MODE_EXPERT:
        if package in ('bugs.debian.org', 'debbugs'):
            if ui.yes_no('Are you reporting a problem with this program '
                         '(reportbug)', 'Yes, this is actually a bug in '
                         'reportbug.', 'No, this is really a problem in the '
                         'BTS itself.'):
                package = 'reportbug'

        if package in ('general', 'project', 'debian-general', 'base'):
            if not ui.yes_no(
                "Are you sure this bug doesn't apply to a specific package?",
                'Yes, this bug is truly general.',
                'No, this is not really a general bug.', False):
                return get_package_name(bts, mode)

        if package == 'wnpp':
            if not ui.yes_no(
                'Are you sure you want to file a WNPP report?',
                'Yes, I am a developer or know what I\'m doing.',
                'No, I am not a developer and I don\'t know what wnpp means.',
                False):
                return get_package_name(bts, mode)

    return package

def special_prompts(package, bts, ui):
    prompts = debianbts.SYSTEMS[bts].get('specials')
    if prompts:
        pkgprompts = prompts.get(package)
        if pkgprompts:
            return pkgprompts(package, bts, ui)
    return

def offer_configuration(options):
    if not options.configure:
        ui.long_message('Welcome to reportbug!  Since it looks like this is '
                        'the first time you have used reportbug, we are '
                        'configuring its behavior.  These settings will be '
                        'saved to the file "%s", which you will be free to '
                        'edit further.\n\n', reportbug.USERFILE)
    mode = ui.menu('Please choose the default operating mode for reportbug.',
                   reportbug.MODES, 'Select mode: ', options.mode,
                   order=reportbug.MODELIST)
    
    if 0: # Disabled since the others don't work
        interface = ui.menu('Please choose the default '
                            'interface for reportbug.', reportbug.UIS,
                            'Select interface: ', options.interface)
    else:
        interface = 'text'

    online = ui.yes_no('Will reportbug often have direct '
                       'Internet access?  (You should answer yes to this '
                       'question unless you know what you are doing and '
                       'plan to check whether duplicate reports have been '
                       'filed via some other channel.)',
                       'Yes, reportbug should assume it has access to the '
                       'network always.',
                       'No, I am only online occasionally to send and '
                       'receive mail.',
                       default=(not options.offline))

    def_realname, def_email = reportbug.get_email()
    realname = ui.get_string('What real name should be used for sending bug '
                             'reports? [%s]' %
                             (options.realname or def_realname),
                             options=[def_realname], force_prompt=True)
    from_addr = ui.get_string('Which of your email addresses should be used '
                              'when sending bug reports? [%s]' %
                              (options.email or def_email),options=[def_email],
                              force_prompt=True)

    stupidmode = not ui.yes_no(
        'Do you have a "mail transport agent" (MTA) like Exim, Postfix or '
        'SSMTP configured on this computer?',
        'Yes, I can run /usr/sbin/sendmail without horrible things happening. '
        'If you can send email from this machine without setting an SMTP Host '
        'in your mailer, you should choose this answer.',
        'No, I need to use an SMTP Host or I don\'t know if I have an MTA.',
        (not options.smtphost))

    smtphost = options.smtphost or ''
    if stupidmode:
        smtphost = ui.get_string(
            'Do you know your SMTP host? Usually it\'s called something like '
            'mail.example.org or smtp.example.org. '
            'Just press ENTER if you don\'t.',
            options=[smtphost], force_prompt=True)
        if smtphost:
            stupidmode = False
    else:
        smtphost = ''
    
    if os.path.exists(reportbug.USERFILE):
        try:
            os.rename(reportbug.USERFILE, reportbug.USERFILE+'~')
        except OSError:
            ewrite('Unable to rename %s as %s~\n', reportbug.USERFILE,
                   reportbug.USERFILE)

    fp = file(reportbug.USERFILE, 'w')
    print >> fp, '# reportbug preferences file'
    print >> fp, '# Version of reportbug this preferences file was written by'
    print >> fp, 'reportbug_version "2.48"'
    print >> fp, '# default operating mode: one of:',
    print >> fp, ', '.join(reportbug.MODELIST)
    print >> fp, 'mode %s' % mode
    print >> fp, '# default user interface'
    print >> fp, 'ui %s' % interface
    print >> fp, '# offline setting - comment out to be online'
    if not online:
        print >> fp, 'offline'
    else:
        print >> fp, '#offline'
    print >> fp, '# name and email setting (if non-default)'
    rn = 'realname "%s"'
    em = 'email "%s"'
    email_addy = (from_addr or options.email or def_email)
    print >> fp, rn % (realname or options.realname or def_realname)
    print >> fp, em % email_addy
    uid = os.getuid()
    if uid < MIN_USER_ID:
        print >> fp, '# Suppress user ID check for this user'
        print >> fp, 'no-check-uid'

    if smtphost:
        print >> fp, '# Send all outgoing mail via the following host'
        print >> fp, 'smtphost "%s"' % smtphost

    if stupidmode:
        print >> fp, '# Disable fallback mode by commenting out the following:'
        print >> fp, 'no-cc'
        print >> fp, 'header "X-Debbugs-CC: %s"' % email_addy
        print >> fp, 'smtphost master.debian.org'
    else:
        print >> fp, '# If nothing else works, remove the # at the beginning'
        print >> fp, '# of the following three lines:'
        print >> fp, '#no-cc'
        print >> fp, '#header "X-Debbugs-CC: %s"' % email_addy
        print >> fp, '#smtphost master.debian.org'
        
    print >> fp, '# You can add other settings after this line.  See'
    print >> fp, '# /etc/reportbug.conf for a full listing of options.'
    fp.close()
    ui.long_message('Default preferences file written.  To reconfigure, '
                    're-run reportbug with the "--configure" option.\n')

ascii_range = ''.join([chr(x) for x in range(32,127)])
notascii = re.compile(r'[^'+re.escape(ascii_range)+']')
notascii2 = re.compile(r'[^'+re.escape(ascii_range)+r'\s]')

# Wrapper for MIMEText
class BetterMIMEText(MIMEText):
    def __init__(self, _text, _subtype='plain', _charset=None):
        MIMEText.__init__(self, _text, _subtype, 'us-ascii')
        # Only set the charset paraemeter to non-ASCII if the body
        # includes unprintable characters
        if notascii2.search(_text):
            self.set_param('charset', _charset)

def encode_if_needed(text, charset, encoding='q'):
    needed = False
    
    if notascii.search(text):
        # Fall back on something vaguely sensible if there are high chars
        # and the encoding is us-ascii
        if charset == 'us-ascii':
            charset = 'iso-8859-15'
        return Header(text, charset)
    else:
        return Header(text, 'us-ascii')

def rfc2047_encode_address(addr, charset, mua=None):
    newlist = []
    addresses = rfc822.AddrlistClass(addr).getaddrlist()
    for (realname, address) in addresses:
        if realname:
            newlist.append( email.Utils.formataddr(
                (str(rfc2047_encode_header(realname, charset, mua)), address)))
        else:
            newlist.append( address )
    return ', '.join(newlist)

def rfc2047_encode_header(header, charset, mua=None):
    if mua: return header
    
    return encode_if_needed(header, charset)

def verify_option(option, opt, value, parser, *args):
    heading, valid = args
    if value == 'help':
        ewrite('%s:\n %s\n' % (heading, '\n '.join(valid)))
        sys.exit(1)
    elif value in valid:
        setattr(parser.values, option.dest, value)
    else:
        ewrite('Ignored bogus setting for %s: %s\n' % (opt, value))

def verify_append_option(option, opt, value, parser, *args):
    heading, valid = args
    if value == 'help':
        ewrite('%s:\n %s\n' % (heading, '\n '.join(valid)))
        sys.exit(1)
    elif value in valid:
        try:
            getattr(parser.values, option.dest).append(value)
        except AttributeError:
            setattr(parser.values, option.dest, [value])
    else:
        ewrite('Ignored bogus setting for %s: %s\n' % (opt, value))

def main():
    global quietly, ui

    try:
        locale.setlocale(locale.LC_ALL, '')
    except locale.Error, x:
        print >> sys.stderr, '*** Warning:', x
    
    charset = locale.nl_langinfo(locale.CODESET)
    # It would be nice if there were some canonical character set conversion
    if charset.lower() == 'ansi_x3.4-1968':
        charset = 'us-ascii'

    notatty = not ui.ISATTY
    body = ''
    filename = None

    defaults = {
        'sendto' : 'submit', 'mode' : 'novice', 'mta' : '/usr/sbin/sendmail',
        'check_available' : True, 'query_src' : True, 'debconf' : True,
        'editor' : '', 'offline' : False, 'verify' : True, 'check_uid' : True,
        'testmode' : False, 'attachments' : [], 'keyid' : '', 'body' : None,
        'bodyfile' : None }

    if not sys.stdin.isatty():
        defaults.update({ 'dontquery' : True, 'notatty' : True,
                          'printonly' : True })

    # Convention: consider `option.foo' names read-only; they always contain
    # the original value as determined by the cascade of command-line options
    # and configuration files.  When we need to adjust a value, we first say
    # "foo = options.foo" and then refer to just `foo'.
    args = reportbug.parse_config_files()
    for option, arg in args.items():
        if option in reportbug.CONFIG_ARGS:
            defaults[option] = arg
        else:
            sys.stderr.write('Warning: untranslated token "%s"\n' % option)
    
    parser = optparse.OptionParser(
        usage='%prog [options] <package | filename>', version=VERSION)
    parser.set_defaults(**defaults)
    parser.add_option('-c', '--no-config-files', action="store_true",
                      dest='noconf', help='do not include conffiles in report')
    parser.add_option('-C', '--class', action='callback', type='string',
                      callback=verify_option, dest="klass", metavar='CLASS',
                      callback_args=('Permitted report classes:',
                                     debianbts.CLASSLIST),
                      help='specify report class for GNATS BTSes')
    parser.add_option('-d', '--debug', action='store_const', const=DEBUGGER,
                      dest='sendto', help='send report only to '+DEBUGGER)
    parser.add_option('--test', action="store_true", default=False,
                      dest="testmode",
                      help="operate in test mode (maintainer use only)")
    parser.add_option('-e', '--editor', dest='editor',
                      help='specify an editor for your report')
    parser.add_option('-f', '--filename', dest='searchfor',
                      help='file to search for')
    parser.add_option('--path', dest='pathonly', action="store_true",
                      default=False, help='only search the path with -f')
    parser.add_option('-g', '--gnupg', '--gpg', action='store_const',
                      dest='sign', const='gpg',
                      help='sign report with GNU Privacy Guard')
    parser.add_option('-G', '--gnus', action='store_const', dest='mua',
                      const=reportbug.MUA['gnus'],
                      help='send the report using GNUS')
    parser.add_option('--pgp', action='store_const', dest='sign',
                      const='pgp', help='sign report with PGP')
    parser.add_option('-K', '--keyid', type="string", dest="keyid",
                      help="key ID to use for PGP/GnuPG signatures")
    parser.add_option('-H', '--header', action='append', dest='headers',
                      help='add a custom RFC822 header to your report')
    parser.add_option('--license', action='store_true', default=False,
                      help='show copyright and license information')
    parser.add_option('-m', '--maintonly', action='store_const',
                      dest='sendto', const='maintonly',
                      help='send the report to the maintainer only')
    parser.add_option('-M', '--mutt', action='store_const', dest='mua',
                      const=reportbug.MUA['mutt'],
                      help='send the report using mutt')
    parser.add_option('--mirror', action='append', help='add a BTS mirror',
                      dest='mirrors')
    parser.add_option('-a', '--af', action='store_const', dest='mua',
                      const=reportbug.MUA['af'],
                      help='send the report using af')
    parser.add_option('-n', '--mh', '--nmh', action='store_const', dest='mua',
                      help='send the report using mh/nmh',
                      const=reportbug.MUA['mh'])
    parser.add_option('--mua', dest='mua',
                      help='send the report using the specified mailer')
    parser.add_option('--mta', dest='mta', help='send the report using the '
                      'specified mail transport agent')
    parser.add_option('--list-cc', action='append', dest='listcc',
                      help='send a copy to the specified address')
    parser.add_option('-p', '--print', action='store_true', dest='printonly',
                      help='output the report to standard output only')
    parser.add_option('--report-quiet', action='store_const', dest='sendto',
                      const='quiet', help='file report without any mail to '
                      'the maintainer or tracking lists')
    parser.add_option('-q', '--quiet', action='store_true', dest='quietly',
                      help='reduce the verbosity of the output', default=False)
    parser.add_option('-s', '--subject', help='the subject for your report')
    parser.add_option('-x', '--no-cc', dest='nocc', action='store_true',
                      help='do not send a copy of the report to yourself')
    parser.add_option('-z', '--no-compress', dest='nocompress',
                      action='store_true', help='do not strip blank lines '
                      'and comments from config files')
    parser.add_option('-o', '--output', dest='outfile', help='output the '
                      'report to the specified file')
    parser.add_option('-O', '--offline', help='disable all external queries',
                      action='store_true')
    parser.add_option('-i', '--include', action='append',
                      help='include the specified file in the report')
    parser.add_option('-A', '--attach', action='append', dest='attachments',
                      help='attach the specified file to the report')
    parser.add_option('-b', '--no-query-bts', action='store_true',
                      dest='dontquery',help='do not query the BTS for reports')
    parser.add_option('--query-bts', action='store_false', dest='dontquery',
                      help='query the BTS for reports')
    parser.add_option('-T', '--tag', action='callback', dest='tags',
                      callback=verify_append_option,  type='string',
                      callback_args=('Permitted tags:',
                                     debianbts.TAGLIST+['none']),
                      help='add the specified tag to the report')
    parser.add_option('--http_proxy', '--proxy', help='use this proxy for '
                      'HTTP accesses')
    parser.add_option('--email', help='specify originating email address')
    parser.add_option('--realname', help='specify real name for your report')
    parser.add_option('--smtphost', help='specify SMTP server for mailing')
    parser.add_option('--replyto', '--reply-to', help='specify Reply-To '
                      'address for your report')
    parser.add_option('--query-source', action='store_true', dest='query_src',
                      help='query on source packages, not binary packages')
    parser.add_option('--no-query-source', action='store_false',
                      dest='query_src', help='query on binary packages only')
    parser.add_option('--debconf', action='store_true',
                      help='include debconf settings in your report')
    parser.add_option('--no-debconf', action='store_false', dest='debconf',
                      help='exclude debconf settings from your report')
    parser.add_option('-j', '--justification', help='include justification '
                      'for the severity of your report')
    parser.add_option('-V', '--package-version', dest='pkgversion',
                      help='specify the version number for the package')
    parser.add_option('-u', '--interface', '--ui', action='callback',
                      callback=verify_option, type='string', dest='interface',
                      callback_args=('Valid user interfaces',
                                     reportbug.VALID_UIS),
                      help='choose which user interface to use')
    parser.add_option('-Q', '--query-only', action='store_true',
                      dest='queryonly', help='only query the BTS')
    parser.add_option('-t', '--type', action='callback', dest='type',
                      callback=verify_option, type='string',
                      callback_args=('Valid types of report:',
                                     ('gnats', 'debbugs')),
                      help='choose the type of report to file')
    parser.add_option('-B', '--bts', action='callback', dest='bts',
                      callback=verify_option, type='string',
                      callback_args=('Valid bug tracking systems',
                                     debianbts.SYSTEMS.keys()),
                      help='choose BTS to file the report with')
    parser.add_option('-S', '--severity', action='callback',
                      callback=verify_option, type='string', dest='severity',
                      callback_args=('Valid severities', debianbts.SEVLIST),
                      help='identify the severity of the report')
    parser.add_option('--template', action='store_true',
                      help='output a template report only')
    parser.add_option('--configure', action='store_true',
                      help='reconfigure reportbug for this user')
    parser.add_option('--check-available', action='store_true',
                      help='check for new releases at packages.debian.org')
    parser.add_option('--no-check-available', action='store_false',
                      dest='check_available', help='do not check for new '
                      'releases')
    parser.add_option('--mode', action='callback', help='choose the operating '
                      'mode for reportbug', callback=verify_option,
                      type='string', dest='mode',
                      callback_args=('Permitted operating modes',
                                     reportbug.MODES.keys()))
    parser.add_option('-v', '--verify', action='store_true', help='verify '
                      'integrity of installed package using debsums')
    parser.add_option('--no-verify', action='store_false', dest='verify',
                      help='do not verify package installation')
    parser.add_option('-k', '--kudos', action='store_true', default=False,
                      help='send appreciative email to the maintainer, rather '
                      'than filing a bug report')
    parser.add_option('--check-installed', action='store_true',
                      dest='querydpkg', help='check whether the specified '
                      'package is installed when filing a report (default)')
    parser.add_option('--body', dest="body", type="string",
                      help="specify the body for the report as a string")
    parser.add_option('--body-file', '--bodyfile', dest="bodyfile",
                      type="string",
                      help="use the specified file as the body of the report")
    parser.add_option('-I', '--no-check-installed', action='store_false',
                      default=True, dest='querydpkg',
                      help='don\'t check whether the package is installed')
    (options, args) = parser.parse_args()

    if options.configure:
        offer_configuration(options)
        sys.exit(0)
    elif options.license:
        print COPYRIGHT
        print
        print LICENSE
        sys.exit(0)

    # These option values may get adjusted below, so give them a variable name.
    check_available = options.check_available
    dontquery = options.dontquery
    headers = options.headers or []
    mua = options.mua
    pkgversion = options.pkgversion
    quietly = options.quietly
    severity = options.severity
    smtphost = options.smtphost
    subject = options.subject
    sysinfo = debianbts.SYSTEMS[options.bts or 'debian']
    rtype = options.type or sysinfo['type']
    attachments = options.attachments
    pgp_addr = options.keyid

    if options.body:
        body = textwrap.fill(options.body)
    elif options.bodyfile:
        try:
            body = file(options.bodyfile).read()
        except:
            ewrite('Unable to read body from file %s.\n', options.bodyfile)
            sys.exit(1)

    if body and not body.endswith('\n'):
        body += '\n'

    if options.queryonly:
        check_available = False
    
    if options.offline:
        check_available = False
        dontquery = True

    if options.tags:
        taglist = options.tags
        if 'none' in taglist:
            taglist = []
    else:
        taglist = []

    if options.testmode:
        options.sendto = DEBUGGER
        options.tags = ['none']
        check_available = False
        dontquery = True
        severity = 'normal'
        subject = 'testing'
        taglist = []
    
    if options.template:
        check_available = False
        dontquery = quietly = notatty = True
        mua = smtphost = None
        severity = severity or 'wishlist'
        subject = subject or 'none'

    if options.outfile or options.printonly:
        mua = smtphost = None

    if attachments and mua:
        ewrite('Attachments are incompatible with using an MUA.  They will be 
ignored.\n')
        attachments = []

    if reportbug.first_run():
        if not args:
            offer_configuration(options)
            main()
            sys.exit(0)
        else:
            ewrite('Warning: no reportbug configuration found.  Proceeding in 
%s mode.\n' % options.mode)

    mode = reportbug.MODELIST.index(options.mode)

    # Disable signatures when in printonly or mua mode
    # (since they'll be bogus anyway)
    sign = options.sign
    if (options.mua or options.printonly) and sign:
        sign = ''

    uid = os.getuid()
    if uid < MIN_USER_ID:
        if notatty and not uid:
            ewrite("reportbug will not run as root non-interactively.\n")
            sys.exit(1)

        if not uid or options.check_uid:
            if not uid:
                message = "Running 'reportbug' as root is probably insecure!"
            else:
                message = "Running 'reportbug' as an administrative user "\
                          "is probably not a good idea!"
            message += '  Continue'

            if not ui.yes_no(message, 'Continue with reportbug.', 'Exit.',
                             False):
                ewrite("reportbug stopped.\n")
                sys.exit(1)

    # Fix up command line options for GNOME interface
    sys.argv = sys.argv[:1] + list(args)
    if options.interface:
        if options.interface in ('gnome', 'newt'):
            ui.long_message("The %s interface is not supported.  Unless you "
                            "are debugging reportbug, please do not use it.  "
                            "If you are debugging reportbug, please DO NOT "
                            "file bugs more serious than 'normal' that "
                            "indicate problems with this interface.\n",
                            options.interface)
                            
        iface = 'reportbug_ui_'+options.interface
        exec 'import '+iface
        ui = eval(iface)

    if (reportbug.first_run() and not args):
        offer_configuration(options)
        ewrite('To report a bug, please rerun reportbug.\n')
        sys.exit(0)

    foundfile = None
    package = None
    if not len(args) and not options.searchfor and not notatty:
        package = get_package_name(options.bts or 'debian', mode)
    elif len(args) > 1:
        ewrite("Please report one bug at a time.\n")
        ewrite("[Did you forget to put all switches before the "
               "package name?]\n")
        sys.exit(1)
    elif options.searchfor:
        (foundfile, package) = find_package_for(options.searchfor, notatty,
                                                options.pathonly)
    elif len(args):
        package = args[0]
        if package and package.startswith('/'):
            (foundfile, package) = find_package_for(package, notatty)

    if not package:
        ewrite("No package specified; stopping.\n")
        sys.exit(1)

    if options.interface == 'text':
        ewrite('*** Welcome to reportbug.  Use ? for help at prompts. ***\n')

    fromaddr = reportbug.get_user_id(options.email, options.realname)
    ewrite("Using '%s' as your from address.\n", fromaddr)


    try:
        blah = u'hello'.encode(charset)
    except LookupError:
        ui.long_message(
            'Unable to use specified character set "%s"; you probably need '
            'either cjkcodecs (for users of Asian locales) or iconvcodec '
            'installed.\nFalling back to ASCII encoding.\n', charset)
        charset = 'ascii'
    else:
        ewrite("Detected character set: %s\n"
               "Please change your locale if this is incorrect.\n\n", charset)

    buginfo = '/usr/share/bug/' + package
    bugexec = submitas = submitto = presubj = None
    if os.path.isfile(buginfo) and os.access(buginfo, os.X_OK):
        bugexec = buginfo
    elif os.path.isdir(buginfo):
        if os.path.isfile(buginfo+'/script') and os.access(buginfo+'/script', 
os.X_OK):
            bugexec = buginfo+'/script'

        if os.path.isfile(buginfo+'/presubj'):
            presubj = buginfo+'/presubj'

        if os.path.isfile(buginfo+'/control'):
            submitas, submitto = 
reportbug.parse_bug_control_file(buginfo+'/control')
    elif os.path.isfile('/usr/share/bug/default/'+package) \
         and os.access('/usr/share/bug/default/'+package, os.X_OK):
        bugexec = '/usr/share/bug/default/'+package
    elif os.path.isdir('/usr/share/bug/default/'+package):
        buginfo = '/usr/share/bug/default/'+package
        if os.path.isfile(buginfo+'/script') and os.access(buginfo+'/script',
                                                           os.X_OK):
            bugexec = buginfo+'/script'

        if os.path.isfile(buginfo+'/presubj'):
            presubj = buginfo+'/presubj'

        if os.path.isfile(buginfo+'/control'):
            submitas, submitto = reportbug.parse_bug_control_file(buginfo+
                                                                  '/control')

    incfiles = ""
    if options.include:
        for f in options.include:
            if os.path.exists(f):
                fp = file(f)
                incfiles = '%s\n*** %s\n%s' % (incfiles, f, fp.read())
                fp.close()
            else:
                ewrite("Can't find %s to include!\n", f)
                sys.exit(1)
        incfiles += '\n'

    pkgavail = maintainer = ''
    depends = []
    conffiles = []
    isvirtual = (package in sysinfo['otherpkgs'].keys() and
                 package not in sysinfo.get('nonvirtual', []))
    issource = installed = False
    
    if not pkgversion and options.querydpkg and sysinfo['query-dpkg']:
        ewrite("Getting status for %s...\n", package)
        status = reportbug.get_package_status(package)

        pkgavail, installed = status[1], status[5]
        # Packages that only exist to do weird dependency things
        deppkgs = sysinfo.get('deppkgs')
        if pkgavail and deppkgs:
            if installed and package in deppkgs:
                depends = status[2]
                if depends:
                    newdepends = []
                    for x in depends:
                        newdepends.extend(x)
                    depends = newdepends
                    if len(depends) == 1:
                        ewrite('Dependency package "%s" corresponds to '
                               'actual package "%s".\n', package, depends[0])
                        package = depends[0]
                    else:
                        opts = [(x, reportbug.get_package_status(x)[10])
                                for x in depends]
                        if mode >= MODE_ADVANCED:
                            opts += [(package,
                                      status[10]+' (dependency package)')]
                            
                        package = ui.menu('%s is a dependency package.  '
                                          'Which of the following '
                                          'packages is the bug in?' % package,
                                          opts,
                                          'Select one of these packages: ')
                    ewrite("Getting status for %s...\n", package)
                    status = reportbug.get_package_status(package)
                    pkgavail, installed = status[1], status[5]

        if not pkgavail and not isvirtual:
            # Look for a matching source package
            packages = reportbug.get_source_package(package)
            if len(packages) > 0:
                src = package
                if len(packages) == 1:
                    ewrite('Source package "%s" corresponds to '
                           'binary package "%s".\n', package, packages[0][0])
                    package = packages[0][0]
                elif len(packages) and not notatty:
                    packages.append( (src, 'Source package') )
                    package = ui.menu('Which of the following packages is the '
                                      'bug in?', packages, empty_ok=True,
                                      prompt='Select one of these packages: ')
                if not package:
                    ewrite("No package specified; stopping.\n")
                    sys.exit(1)

                if package != src:
                    ewrite("Getting status for %s...\n", package)
                    status = reportbug.get_package_status(package)
                else:
                    issource = True
            else:
                ewrite('No matching source or binary packages.\n')

        if not installed and not notatty and not isvirtual and not issource:
            packages = reportbug.packages_providing(package)
            tmp = pack = None
            if not packages:
                if ui.yes_no(
                    'A package named "%s" does not appear to be installed; do '
                    'you want to search for a similar-looking filename in '
                    'an installed package' % package,
                    'Look for a file with a similar filename.',
                    'Continue filing with this package name.', True):
                    pkgavail = False
                else:
                    pack = package
                    
            if not packages and not pkgavail and not pack:
                (tmp, pack) = find_package_for(package, notatty)
                if pack:
                    if not ui.yes_no(
                        "A package named '%s' does not appear to be installed "
                        "on your system; however, '%s' contains a file named "
                        "'%s'.  Do you want to file your report on the "
                        "package reportbug found" % (package, pack, tmp),
                        'Yes, use the package specified.',
                        'No, give up the search.'):
                        ewrite("Package not installed; stopping.\n")
                        sys.exit(1)

            if pack:
                foundfile, package = tmp, pack
                ewrite("Getting status for %s...\n", package)
                status = reportbug.get_package_status(package)
            elif not packages:
                if not ui.yes_no(
                    'This package does not appear to be installed; continue '
                    'with this report', 'Ignore this problem and continue.',
                    'Exit without filing a report.', False):
                    ewrite("Package not installed; stopping.\n")
                    sys.exit(1)
            elif (len(packages) > 1) or (packages[0][0] != package):
                this_package = [(package, 'Uninstalled/non-existent package')]
                package = ui.menu('Which of the following installed packages '
                                  'is the bug in?', packages + this_package,
                                  'Select one of these packages: ',
                                  empty_ok=True)
                if not package:
                    ewrite("No package specified; stopping.\n")
                    sys.exit(1)
                else:
                    ewrite("Getting status for %s...\n", package)
                    status = reportbug.get_package_status(package)
        elif not pkgavail and not notatty and not isvirtual and not issource:
            if not ui.yes_no(
                'This package does not appear to exist; continue',
                'Ignore this problem and continue.',
                'Exit without filing a report.', False):
                ewrite("Package does not exist; stopping.\n")
                sys.exit(1)

        (pkgversion, pkgavail, depends, conffiles, maintainer, installed,
         origin, vendor, reportinfo, priority, desc, src_name,
         fulldesc, state) = status

    if (pkgavail and options.verify and os.path.exists('/usr/bin/debsums')
        and not (notatty or options.kudos) and state == 'installed'):
        ewrite('Verifying package integrity...\n')
        rc, output = commands.getstatusoutput('/usr/bin/debsums -s'+
                                              commands.mkarg(package))
        if rc:
            if not ui.yes_no(
                'There may be a problem with your installation of '+package+
                ';\nthe following files appear to be missing or changed:\n'+
                output+'\nDo you still want to file a report',
                'Ignore this problem and continue.  This may be '
                'appropriate if you have fixed the package manually already.  '
                'This problem may also result from the use of localepurge.',
                'Exit without filing a report.', False, nowrap=True):
                ewrite("Package integrity check failed; stopping.\n")
                sys.exit(1)

    if not pkgversion:
        if not (isvirtual or issource or notatty):
            pkgversion = ui.get_string('Please enter the version of the '
                                       'package this report applies to '
                                       '(blank OK)', force_prompt=True)
    elif check_available and not (options.kudos or notatty or
                                  options.offline):
        ewrite('Checking for newer versions at packages.debian.org...\n')
        (avail, toonew) = checkversions.check_available(
            package, pkgversion, check_incoming=(mode > MODE_STANDARD),
            http_proxy=options.http_proxy)
        if toonew:
            if not ui.yes_no(
                '\nYour version of %s (%s) is newer than that in Debian!\n'
                'Do you still want to file a report' % (package, pkgversion),
                'Ignore this problem and continue.  This may be '
                'appropriate if you know this bug is present in older '
                'releases of the package, or you\'re running a mixed '
                'stable/testing installation.',
                'Exit without filing a report.', False):
                ewrite("Newer released version; stopping.\n")
                sys.exit(1)
                             
        if avail:
            availtext = ''
            availlist = avail.keys()
            availlist.sort()
            for rel in availlist:
                availtext += '  %s: %s\n' % (rel, avail[rel])

            if not ui.yes_no(
                ('\nYour version (%s) of %s appears to be out of date.\nThe '
                'following newer release(s) are available in the Debian '
                'archive:\n' % (pkgversion, package))+availtext+
                'Do you still want to file a report',
                'Ignore this problem and continue.  This may be '
                'appropriate if you know this bug is still present in more '
                'recent releases of the package.',
                'Exit without filing a report.', False, nowrap=True):
                ewrite("Newer released version; stopping.\n")
                sys.exit(1)

    bts = DEFAULT_BTS
    if options.bts:
        bts = options.bts
        ewrite("Will send report to %s.\n", debianbts.SYSTEMS[bts]['name'])
    elif origin:
        if origin == bts:
            ewrite("Package originates from %s.\n", vendor)
            reportinfo = None
        elif origin in debianbts.SYSTEMS.keys():
            ewrite("Package originates from %s; overriding your system "
                   "selection.\n", vendor)
            bts = origin
            reportinfo = None
        elif reportinfo:
            ewrite("Unknown origin %s; will send to %s.\n", origin,
                   reportinfo[1])
            rtype, submitto = reportinfo
        elif submitto:
            ewrite("Unknown origin %s; will send to %s.\n", origin, submitto)
        else:
            ewrite("Unknown origin %s; will send to %s.\n", origin, bts)
    elif reportinfo:
        rtype, submitto = reportinfo
        ewrite("Will use %s protocol talking to %s.\n", rtype, submitto)
        dontquery = True

    if rtype == 'mailto':
        rtype = 'debbugs'
        dontquery = True

    if options.listcc:
        headers.append('X-Debbugs-CC: '+', '.join(options.listcc))

    special = False
    if not body and not subject and not notatty:
        res = special_prompts(package, bts, ui)
        if res:
            (subject, severity, h, body, query) = res
            headers = headers + h
            if not query:
                dontquery = True
            special = True

    sendto = options.sendto
    exinfo = None
    if not (dontquery or notatty or options.kudos):
        pkg, src = package, issource
        if options.query_src:
            src = True
        try:
            exinfo = ui.handle_bts_query(pkg, bts, options.mirrors,
                                         options.http_proxy, source=src)
        except NotImplemented:
            exinfo = None
        except NoNetwork:
            ewrite('Unable to contact BTS; continuing anyway.\n')
        except NoPackage:
            if not options.queryonly and maintainer and ui.yes_no(
                'There is no record of this package in the bug tracking '
                'system.\nSend report directly to maintainer',
                'Send the report to the maintainer (%s).' % maintainer,
                'Send the report to the BTS anyway.'):
                rtype = 'debbugs'
                sendto = maintainer
        except NoBugs:
            ewrite('No bug reports found.\n')
        except NoReport:
            ewrite('Nothing new to report; exiting.\n')
            return
        
        if options.queryonly: return

    ccaddr = os.environ.get('MAILCC')
    if options.nocc:
        bccaddr = os.environ.get('MAILBCC')
    else:
        bccaddr = os.environ.get('MAILBCC', fromaddr)

    if maintainer:
        ewrite("Maintainer for %s is '%s'.\n", package, maintainer)
        if 'qa.debian.org' in maintainer:
            ui.long_message('''\
This package is currently "orphaned"; if you care a current or prospective
Debian developer, you might consider adopting it.  Please be aware that your
report may not be resolved for a while, and that packages that have been
orphaned for a long period of time are often removed from the archive.\n''')
            ui.ewrite('\nFor more details, please see: 
http://www.debian.org/devel/wnpp/\n')

    if options.kudos:
        if maintainer:
            sendto = maintainer
        else:
            ewrite('Unable to determine maintainer for %s; exiting.', package)
            sys.exit(1)

    depinfo = ""
    # Grab dependency list, removing version conditions.
    if depends and not options.kudos:
        ewrite("Getting dependency information for %s...\n", package)
        depinfo = reportbug.get_dependency_info(package, depends)

    confinfo = []
    conftext = ''
    remonly = False
    if conffiles and not options.kudos:
        ewrite("Getting changed configuration files...\n")
        confinfo, changed = reportbug.get_changed_config_files(conffiles,
                                                               nocompress)

    if not conffiles:
        pass
    elif options.noconf and changed:
        for f in changed:
            confinfo[f] = 'changed [not included]'
    elif changed and not notatty:
        while 1:
            x = ui.select_options(
                "*** WARNING: The following configuration files have been "
                "modified:\n"+ "\n".join(changed)+
                "\nSend modified configuration files", 'Ynd',
                {'y':'Send your modified configuration files.',
                 'n':"Don't send modified configuration files.",
                 'd':'Display modified configuration files.'})
            if x == 'n':
                for f in changed:
                    confinfo[f] = 'changed [not included]'
                break
            elif x == 'd':
                PAGER = os.environ.get('PAGER', '/usr/bin/sensible-pager')
                system(PAGER+' '+' '.join(changed))
            else:
                break

    if confinfo:
        conftext = '\n-- Configuration Files:\n'
        files = confinfo.keys()
        files.sort()
        for f in files:
            conftext = conftext + '%s %s\n' % (f, confinfo[f])

    if (options.debconf and os.path.exists('/usr/bin/debconf-show') and
        not options.kudos and installed):
        (status, output) = commands.getstatusoutput(
            'DEBCONF_SYSTEMRC=1 DEBCONF_NOWARNINGS=yes '
            '/usr/bin/debconf-show %s' % package)
        if status:
            conftext += '\n-- debconf-show failed\n'
        elif output:
            if (notatty or
                ui.yes_no("*** The following debconf settings were detected:\n"
                          +output+"\nInclude these settings in your report",
                          'Send your debconf settings.',
                          "Don't send your debconf settings.", nowrap=True)):
                conftext += '\n-- debconf information:\n%s\n' % output
            else:
                conftext += '\n-- debconf information excluded\n'
        else:
            conftext += '\n-- no debconf information\n'

    ewrite('\n')
    prompted = False
    if options.kudos:
        subject = subject or ('Thanks for packaging %s!' % package)
    elif exinfo:
        if special:
            body = ''
        prompted = True
        subject = ui.get_string('Please provide a subject for your response; '
                                'no subject will stop reportbug.',
                                force_prompt=True)
    elif not subject and not notatty:
        prompted = True
        if presubj:
            ewrite(file(presubj).read()+'\n')

        subject = ui.get_string(
            'Please briefly describe your problem (you can elaborate in '
            'a moment; an empty response will stop reportbug).  This '
            'should be a pithy summary of what is wrong with the package, '
            'for example, "fails to send email" or "does not start with -q '
            'option specified."', force_prompt=True)

    if not subject:
        ewrite("No subject specified; stopping.\n")
        sys.exit(1)

    if len(subject) > 100 and prompted and mode < MODE_EXPERT:
        subject = ui.get_string(
            'Your description is a bit long; please enter a shorter subject. '
            '(An empty response will retain the existing subject.)',
            force_prompt=True) or subject
    if package != 'wnpp' and prompted and mode < MODE_EXPERT:
        if foundfile:
            subject = foundfile + ": " + subject
            ewrite("Rewriting subject to '%s'\n", subject)
        elif (not re.match(r"\S+:\s", subject) and package not in subject):
            subject = package + ": " + subject
            ewrite("Rewriting subject to '%s'\n", subject)

    if severity and rtype:
        severity = debianbts.convert_severity(severity, rtype)

    klass = options.klass
    if not notatty and not (exinfo or options.kudos):
        if not severity:
            if rtype == 'gnats':
                severities = debianbts.SEVERITIES_gnats
                default = 'non-critical'
            else:
                if mode == MODE_NOVICE:
                    severities = {'normal' : debianbts.SEVERITIES['normal'],
                                  'minor': debianbts.SEVERITIES['minor'],
                                  'wishlist': debianbts.SEVERITIES['wishlist'],
                                  }
                else:
                    severities = debianbts.SEVERITIES
                default = 'normal'

            severity = ui.menu("How would you rate the severity of this "
                               "problem or report?", severities,
                               'Please select a severity level: ',
                               default=default, order=debianbts.SEVLIST)

        if rtype == 'gnats':
            # Class of report
            klass = ui.menu("What sort of problem are you reporting?",
                            debianbts.CLASSES, 'Please select a class: ',
                            default='sw-bug', order=debianbts.CLASSLIST)

    severity = severity or 'normal'

    justification = options.justification
    if rtype == 'debbugs' and package != 'wnpp' and mode < MODE_EXPERT:
        if severity in ('critical', 'grave'):
            justification = ui.menu(
                'You are reporting a ' +severity+' bug; which of the '
                'following criteria does it meet?',
                debianbts.JUSTIFICATIONS[severity],
                'Please select the impact of the bug: ', default='unknown')
        elif severity == 'serious':
            justification = ui.get_string(
                'You are reporting a serious bug; which section of the '
                'Debian Policy Manual contains the "must" or "required" '
                'directive that it violates?  (E.g., "1.2.3")  Just type '
                '"unknown" if you are not sure.', force_prompt=True)
            if re.match('[0-9]+\.[0-9.]+', justification):
                justification = 'Policy ' + justification
            elif not justification:
                justification = 'unknown'

        if justification == 'unknown':
            justification = ''
            severity = 'normal'
            ewrite('Severity downgraded to "normal".\n')

    if severity == 'does-not-build':
        if pkgversion and not src_name:
            src_name = package
        if src_name and check_available and not notatty:
            ewrite('Checking buildd.debian.org for past builds of %s...\n',
                   src_name)
            built = checkbuildd.check_built(src_name,
                                            http_proxy=options.http_proxy)

            if built:
                ewrite('Successful past builds... treating as serious.\n')
                severity = 'serious'
                justification = 'no longer builds from source'
            else:
                ewrite('No successful builds... treating as important.\n')
                severity = 'important'
                justification = 'fails to build from source'
        else:
            if notatty:
                severity = 'important'
                justification = 'fails to build from source'
            else:
                if ui.yes_no(
                    'Has this package successfully been built for this '
                    'architecture in the past (you can look this up at '
                    'buildd.debian.org)',
                    'Yes, this is a recently-introduced problem.',
                    'No, it has always been this way.'):
                    severity = 'serious'
                    justification = 'no longer builds from source'
                else:
                    severity = 'important'
                    justification = 'fails to build from source'

    TMPDIR = os.environ.get('TMPDIR', '/tmp')
    HOMEDIR = os.environ.get('HOME', '/')

    if (rtype == 'debbugs' and not options.tags and
        not (notatty or options.kudos or exinfo) and package != 'wnpp' and
        mode > MODE_NOVICE):
        # Multiple-choice checkbox
        taglist = ui.select_multiple(
            'Do any of the following apply to this report?', debianbts.TAGS,
            'Please select tags: ', order=debianbts.TAGLIST,
            extras=debianbts.EXTRA_TAGS)

    patch = ('patch' in taglist)

    if taglist:
        tags = ' '.join(taglist)
    else:
        tags = ''

    # Execute bug script
    if bugexec and not options.kudos:
        if os.path.exists('handle_bugscript'):
            handler = './handle_bugscript'
        else:
            handler = '/usr/share/reportbug/handle_bugscript'

        fh, filename = TempFile()
        fh.close()
        system(handler+' '+bugexec+' '+filename)

        addinfo = "\n-- Package-specific info:\n"+file(filename).read()
        os.unlink(filename)
        if addinfo and incfiles:
            incfiles = addinfo + "\n" + incfiles
        elif addinfo:
            incfiles = addinfo

    # Prepare bug report
    if options.kudos:
        message = '\n\n'
        if not mua:
            SIGFILE = os.path.join(HOMEDIR, '.signature')
            try:
                message = "\n\n-- \n"+file(SIGFILE).read()
            except IOError:
                pass
    else:
        message = reportbug.generate_blank_report(
            submitas or package, pkgversion, severity, justification, depinfo,
            conftext, foundfile, incfiles, bts, exinfo, rtype, klass, subject,
            tags, body, mode)

    # Substitute server email address
    if submitto and '@' not in sendto:
        if '@' in submitto:
            sendto = submitto
        else:
            if exinfo:
                if sendto != 'submit':
                    sendto = '%d-%s' % (exinfo, sendto)
                else:
                    sendto = str(exinfo)

            sendto = sendto+'@'+submitto
    elif '@' not in sendto:
        if exinfo:
            if sendto != 'submit':
                sendto = '%d-%s' % (exinfo, sendto)
            else:
                sendto = str(exinfo)

        try:
            sendto = sysinfo['email'] % sendto
        except TypeError:
            sendto = sysinfo['email']

        sendto = rfc822.dump_address_pair((sysinfo['name']+
                                           ' Bug Tracking System', sendto))

    mailing = not (mua or options.printonly or options.template)
    message = "Subject: %s\n%s" % (subject, message)

    if mailing:
        fh, filename = TempFile()
        fh.write(message)
        fh.close()
        oldmua = mua or options.mua
        if not options.body and not options.bodyfile:
            message = handle_editing(filename, message, options, sendto,
                                     attachments, package)
        if not oldmua and options.mua:
            mua = options.mua
        if mua:
            mailing = False
            if os.path.exists(filename):
                os.unlink(filename)
        elif not sendto:
            print message,
            # Remove the temporary file
            if os.path.exists(filename):
                os.unlink(filename)
            return

        if not mua and patch and not attachments and not notatty:
            while True:
                patchfile = ui.get_filename(
                    'What is the filename of the patch (if none, or you have '
                    'already included it, just press ENTER)?',
                    force_prompt=True)
                if patchfile:
                    attachfile = os.path.expanduser(patchfile)
                    if os.path.exists(attachfile):
                        attachments.append(attachfile)
                        break
                    else:
                        ewrite('%s not found!', attachfile)
                else:
                    break

    body, headers, pseudoheaders = reportbug.cleanup_msg(message,headers,rtype)

    if sign:
        ewrite('Passing message to %s for signature...\n', sign)
        if not pgp_addr:
            pgp_addr = reportbug.get_email_addr(fromaddr)[1]

        # Make the unsigned file first
        (unsigned, file1) = TempFile(
            prefix=('reportbug-unsigned-%s-%d-' % (package, os.getpid())) )
        unsigned.write(body)
        unsigned.close()

        # Now make the signed file
        (signed, file2) = TempFile(
            prefix=('reportbug-signed-%s-%d-' % (package, os.getpid())))
        signed.close()

        if sign == 'gpg':
            signcmd = "gpg --local-user '%s' --clearsign" % pgp_addr
        else:
            signcmd = "pgp -u '%s' -fast" % pgp_addr

        signcmd += '<'+commands.mkarg(file1)+' >'+commands.mkarg(file2)
        try:
            os.system(signcmd)
            x = file(file2, 'r')
            signedbody = x.read()
            x.close()

            if os.path.exists(file1):
                os.unlink(file1)
            if os.path.exists(file2):
                os.unlink(file2)

            if not signedbody:
                raise NoMessage
            body = signedbody
        except (NoMessage, IOError, OSError):
            fh, tmpfile2 = TempFile(prefix="reportbug-")
            fh.write(body)
            fh.close()
            ewrite('gpg/pgp failed; input file in %s\n', tmpfile2)
            sys.exit(1)

    if pseudoheaders:
        body = '\n'.join(pseudoheaders)+'\n\n'+body

    if attachments and not mua:
        import mimetypes
        mimetypes.init()
        
        message = MIMEMultipart('mixed')
        bodypart = BetterMIMEText(body, _charset=charset)
        bodypart.add_header('Content-Disposition', 'inline')
        message.preamble = 'This is a multi-part MIME message sent by 
reportbug.\n\n'
        message.epilogue = ''
        message.attach(bodypart)
        for attachment in attachments:
            if not os.path.isfile(attachment):
                ewrite("Warning: can't find attachment '%s'.\n", attachment)
                continue
            ctype = None
            cset = charset
            if os.path.exists('/usr/bin/file'):
                info = commands.getoutput('/usr/bin/file --mime --brief' +
                                           commands.mkarg(attachment) +
                                          ' 2>/dev/null')
                match = re.match(r'([^;, ]*)(,[^;]+)?(?:; )?(.*)', info)
                if match:
                    ctype, junk, extras = match.groups()
                    match = re.search(r'charset=([^,]+|"[^,"]+")', extras)
                    if match:
                        cset = match.group(1)
            # If file doesn't work, try to guess based on the extension
            if not ctype:
                ctype, encoding = mimetypes.guess_type(
                    attachment, strict=False)
            if not ctype:
                ctype = 'application/octet-stream'

            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                fp = file(attachment)
                part = BetterMIMEText(fp.read(), _subtype=subtype, 
                                      _charset=cset)
                fp.close()
            elif maintype == 'message':
                fp = file(attachment)
                part = MIMEMessage(email.message_from_file(fp),
                                   _subtype=subtype)
                fp.close()
            elif maintype == 'image':
                fp = file(attachment, 'rb')
                part = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'audio':
                fp = file(attachment, 'rb')
                part = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = file(attachment, 'rb')
                part = MIMEBase(maintype, subtype)
                part.set_payload(fp.read())
                fp.close()
                email.Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment',
                            filename=os.path.basename(attachment))
            message.attach(part)
    else:
        message = BetterMIMEText(body, _charset=charset)
    
    # Standard headers
    message['From'] = rfc2047_encode_address(fromaddr, charset, mua)
    message['To'] = rfc2047_encode_address(sendto, charset, mua)

    for (header, value) in headers:
        if header in ['From', 'To', 'Cc', 'Bcc', 'X-Debbugs-CC', 'Reply-To',
                      'Mail-Followup-To']:
            message[header] = rfc2047_encode_address(value, charset, mua)
        else:
            message[header] = rfc2047_encode_header(value, charset, mua)
    
    if ccaddr:
        message['Cc'] = rfc2047_encode_address(ccaddr, charset, mua)

    if bccaddr:
        message['Bcc'] = rfc2047_encode_address(bccaddr, charset, mua)

    replyto = os.environ.get("REPLYTO", options.replyto)
    if replyto:
        message['Reply-To'] = rfc2047_encode_address(replyto, charset, mua)

    if mailing:
        message['X-Mailer'] = VERSION
        message['Date'] = email.Utils.formatdate(localtime=True)
    elif mua and not (options.printonly or options.template):
        message['X-Reportbug-Version'] = "2.48"

    failed = using_sendmail = False
    msgname = ''
    # Disable smtphost if mua is set
    if mua and smtphost:
        smtphost = ''

    addrs = [str(x) for x in (message.get_all('To', []) +
                              message.get_all('Cc', []) +
                              message.get_all('Bcc', []))]
    alist = email.Utils.getaddresses(addrs)

    cclist = [str(x) for x in message.get_all('X-Debbugs-Cc', [])]
    debbugs_cc = email.Utils.getaddresses(cclist)
    if cclist:
        del message['X-Debbugs-Cc']
        addrlist = ', '.join(cclist)
        message['X-Debbugs-Cc'] = rfc2047_encode_address(addrlist, charset, mua)

    if options.template or options.printonly:
        pipe = sys.stdout
    elif mua:
        pipe, filename = TempFile()
    elif options.outfile or not os.path.exists(options.mta):
        msgname = options.outfile or ('/var/tmp/%s.bug' % package)
        if os.path.exists(msgname):
            try:
                os.rename(msgname, msgname+'~')
            except OSError:
                ewrite('Unable to rename existing %s as %s~\n',
                       msgname, msgname)
        try:
            pipe = open_write_safe(msgname, 'w')
        except OSError:
            fh, newmsgname = TempFile(prefix=('reportbug-%s-%d-' %
                                              (package, os.getpid())))
            fh.write(message.as_string())
            fh.close()
            ewrite('Writing to %s failed; '
                   'wrote bug report to %s\n', msgname, newmsgname)
            msgname = newmsgname
    elif not smtphost:
        try:
            x = os.getcwd()
        except OSError:
            os.chdir('/')
        pipe = os.popen(options.mta+' -t -oi -oem', 'w')
        using_sendmail = True

    message = message.as_string()
    if smtphost:
        toaddrs = [x[1] for x in alist]
        smtp_message = re.sub(r'(?m)^[.]', '..', message)

        ewrite("Connecting to %s...\n", smtphost)
        try:
            conn = smtplib.SMTP(smtphost)
            conn.sendmail(fromaddr, toaddrs, smtp_message)
            conn.quit()
        except (socket.error, smtplib.SMTPException), x:
            failed = True
            ewrite('SMTP send failure: %s\n', x)
            fh, msgname = TempFile(prefix=('reportbug-%s-%d-' %
                                           (package, os.getpid())))
            fh.write(message)
            fh.close()
            ewrite('Wrote bug report to %s\n', msgname)
    else:
        pipe.write(message)
        if msgname:
            ewrite("Bug report written as %s\n", msgname)

        if pipe.close() and using_sendmail:
            failed = True
            fh, msgname = TempFile(prefix=('reportbug-%s-%d-' %
                                           (package, os.getpid())))
            fh.write(message)
            fh.close()
            ewrite('Wrote bug report to %s\n', msgname)

    if mua:
        for bit in mua.split():
            if '%s' not in bit: break
        ewrite("Spawning %s...\n", bit or mua)
        if '%s' not in mua:
            mua += ' %s'
        system(mua % commands.mkarg(filename)[1:])
    elif not failed and (using_sendmail or smtphost):
        if options.kudos:
            ewrite('\nMessage sent to: %s\n', sendto)
        else:
            ewrite("\nBug report submitted to: %s\n", sendto)

        addresses = []
        for addr in alist:
            if addr[1] != rfc822.parseaddr(sendto)[1]:
                addresses.append(addr)

        if len(addresses):
            ewrite("Copies sent to:\n")
            for address in addresses:
                ewrite('  %s\n', rfc822.dump_address_pair(address))

        if debbugs_cc and rtype == 'debbugs':
            ewrite("Copies will be sent after processing to:\n")
            for address in debbugs_cc:
                ewrite('  %s\n', rfc822.dump_address_pair(address))

        if not (exinfo or options.kudos) and rtype == 'debbugs':
            ewrite('\n')
            ui.long_message(
"""If you want to provide additional information, please wait to
receive the bug tracking number via email; you may then send any extra
information to %s (e.g. %s), where n is the bug number.\n""",
            (sysinfo['email'] % 'n'), (sysinfo['email'] % '999999'))

    # If we've stored more than one copy of the message, delete the
    # one without the SMTP headers.
    if os.path.exists(msgname) and os.path.exists(filename):
        try:
            os.unlink(filename)
        except:
            pass

    if filename and os.path.exists(filename) and not mua:
        # Message is misleading if an MUA is used.
        ewrite("A copy of the report is stored as: %s\n" % filename)
    return

if __name__ == '__main__':
    sys.path.append('/usr/share/reportbug')
    try:
        main()
    except KeyboardInterrupt:
        ewrite("\nreportbug: exiting due to user interrupt.\n")
    except debianbts.Error, x:
        ewrite('error accessing BTS: %s\n' % x)
=============================================================================

root <address@hidden> writes:

> can you send me "reportbug"?
> 
> 
> _______________________________________________
> Axiom-developer mailing list
> address@hidden
> http://mail.nongnu.org/mailman/listinfo/axiom-developer
> 
> 
> 

-- 
Camm Maguire                                            address@hidden
==========================================================================
"The earth is but one country, and mankind its citizens."  --  Baha'u'llah




reply via email to

[Prev in Thread] Current Thread [Next in Thread]