PackageInfo: Add Python 3 support (by Valentin Lorentz)

This commit is contained in:
Krytarik Raido 2017-05-28 02:56:04 +02:00
parent 11b6996639
commit 075b45ce9f
4 changed files with 50 additions and 44 deletions

View File

@ -1,6 +1,7 @@
# -*- Encoding: utf-8 -*- # -*- Encoding: utf-8 -*-
### ###
# Copyright (c) 2008-2010 Terence Simpson # Copyright (c) 2008-2010 Terence Simpson
# Copyright (c) 2017- Krytarik Raido
# #
# This program is free software; you can redistribute it and/or modify # This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as # it under the terms of version 2 of the GNU General Public License as
@ -19,25 +20,27 @@ Display information on packages using apt-cache and search for files in packages
import supybot import supybot
import supybot.world as world import supybot.world as world
from imp import reload
__version__ = "0.9.1" __version__ = "1.0.0"
__author__ = supybot.Author("Terence Simpson", "tsimpson", "tsimpson@ubuntu.com") __author__ = supybot.Author("Krytarik Raido", "krytarik", "krytarik@tuxgarage.com")
__contributors__ = { __contributors__ = {
supybot.Author("Dennis Kaarsemaker","Seveas","dennis@kaarsemaker.net"): ["Origional concept"] supybot.Author("Dennis Kaarsemaker", "Seveas", "dennis@kaarsemaker.net"): ['Original Concept'],
supybot.Author("Terence Simpson", "tsimpson", "tsimpson@ubuntu.com"): ['Original Author']
} }
__url__ = 'https://launchpad.net/ubuntu-bots/' __url__ = 'https://launchpad.net/ubuntu-bots'
import config from . import config
reload(config) reload(config)
import plugin from . import plugin
reload(plugin) # In case we're being reloaded. reload(plugin) # In case we're being reloaded.
import packages from . import packages
reload(packages) reload(packages)
# Add more reloads here if you add third-party modules and want them to be # Add more reloads here if you add third-party modules and want them to be
# reloaded when this plugin is reloaded. Don't forget to import them as well! # reloaded when this plugin is reloaded. Don't forget to import them as well!
if world.testing: if world.testing:
import test from . import test
Class = plugin.Class Class = plugin.Class
configure = config.configure configure = config.configure

View File

@ -1,6 +1,7 @@
# -*- Encoding: utf-8 -*- # -*- Encoding: utf-8 -*-
### ###
# Copyright (c) 2008-2010 Terence Simpson # Copyright (c) 2008-2010 Terence Simpson
# Copyright (c) 2017- Krytarik Raido
# #
# This program is free software; you can redistribute it and/or modify # This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as # it under the terms of version 2 of the GNU General Public License as
@ -28,7 +29,7 @@ deb-src http://archive.ubuntu.com/ubuntu/ %s main restricted universe multiverse
#""" #"""
from supybot.questions import output, expect, something, yn from supybot.questions import output, expect, something, yn
import commands import subprocess
import os import os
def anything(prompt, default=None): def anything(prompt, default=None):
@ -93,20 +94,20 @@ deb-src http://archive.ubuntu.com/ubuntu/ %s main restricted universe multiverse
fd.write("# Apt sources list for Ubuntu %s\n" % release) fd.write("# Apt sources list for Ubuntu %s\n" % release)
fd.write(makeSource(sub_release)) fd.write(makeSource(sub_release))
fd.close() fd.close()
except Exception, e: except Exception as e:
output("Error writing to %r: %r (%s)" % (filename, str(e), type(e))) output("Error writing to %r: %r (%s)" % (filename, str(e), type(e)))
if yn("In order for the plugin to use these sources, you must run the 'update_apt' script, do you want to do this now?", default=True): if yn("In order for the plugin to use these sources, you must run the 'update_apt' script, do you want to do this now?", default=True):
os.environ['DIR'] = aptdir # the update_apt script checks if DIR is set and uses it if it is os.environ['DIR'] = aptdir # the update_apt script checks if DIR is set and uses it if it is
if commands.getstatus(update_apt) != 0: if subprocess.getstatus(update_apt) != 0:
output("There was an error running update_apt, please run '%s -v' to get more information" % update_apt) output("There was an error running update_apt, please run '%s -v' to get more information" % update_apt)
if commands.getstatusoutput('which apt-file') != 0: if subprocess.getstatusoutput('which apt-file') != 0:
output("You need to install apt-file in order to use the !find command of this plugin") output("You need to install apt-file in order to use the !find command of this plugin")
else: else:
if yn("In order for the !find command to work, you must run the 'update_apt_file' script, do you want to do this now?", default=True): if yn("In order for the !find command to work, you must run the 'update_apt_file' script, do you want to do this now?", default=True):
os.environ['DIR'] = aptdir # the update_apt_file script checks if DIR is set and uses it if it is os.environ['DIR'] = aptdir # the update_apt_file script checks if DIR is set and uses it if it is
if commands.getstatusoutput(update_apt_file) != 0: if subprocess.getstatusoutput(update_apt_file) != 0:
output("There was an error running update_apt_file, please run '%s -v' to get more information" % update_apt_file) output("There was an error running update_apt_file, please run '%s -v' to get more information" % update_apt_file)
PackageInfo = conf.registerPlugin('PackageInfo') PackageInfo = conf.registerPlugin('PackageInfo')

View File

@ -3,6 +3,7 @@
### ###
# Copyright (c) 2006-2007 Dennis Kaarsemaker # Copyright (c) 2006-2007 Dennis Kaarsemaker
# Copyright (c) 2008-2010 Terence Simpson # Copyright (c) 2008-2010 Terence Simpson
# Copyright (c) 2017- Krytarik Raido
# #
# This program is free software; you can redistribute it and/or modify # This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as # it under the terms of version 2 of the GNU General Public License as
@ -15,11 +16,11 @@
# #
### ###
import exceptions
import warnings import warnings
warnings.filterwarnings("ignore", "apt API not stable yet", exceptions.FutureWarning) warnings.filterwarnings("ignore", "apt API not stable yet", FutureWarning)
import commands, os, apt, urllib import subprocess, os, apt
from email import FeedParser import supybot.utils as utils
from email.parser import FeedParser
def component(arg): def component(arg):
if '/' in arg: return arg[:arg.find('/')] if '/' in arg: return arg[:arg.find('/')]
@ -28,9 +29,9 @@ def component(arg):
def description(pkg): def description(pkg):
if not pkg: if not pkg:
return None return None
if pkg.has_key('Description-en'): if 'Description-en' in pkg:
return pkg['Description-en'].split('\n')[0] return pkg['Description-en'].split('\n')[0]
elif pkg.has_key('Description'): elif 'Description' in pkg:
return pkg['Description'].split('\n')[0] return pkg['Description'].split('\n')[0]
return None return None
@ -42,8 +43,7 @@ class Apt:
self.log = plugin.log self.log = plugin.log
os.environ["LANG"] = "C" os.environ["LANG"] = "C"
if self.aptdir: if self.aptdir:
self.distros = [x[:-5] for x in os.listdir(self.aptdir) if x.endswith('.list')] self.distros = sorted([x[:-5] for x in os.listdir(self.aptdir) if x.endswith('.list')])
self.distros.sort()
self.aptcommand = """apt-cache\\ self.aptcommand = """apt-cache\\
-o"Dir::State::Lists=%s/%%s"\\ -o"Dir::State::Lists=%s/%%s"\\
-o"Dir::etc::sourcelist=%s/%%s.list"\\ -o"Dir::etc::sourcelist=%s/%%s.list"\\
@ -65,10 +65,10 @@ class Apt:
return "%s is not a valid distribution: %s" % (distro, ", ".join(self.distros)) return "%s is not a valid distribution: %s" % (distro, ", ".join(self.distros))
pkg = _pkg pkg = _pkg
data = commands.getoutput(self.aptcommand % (distro, distro, distro, distro, 'search -n', pkg)) data = subprocess.getoutput(self.aptcommand % (distro, distro, distro, distro, 'search -n', pkg))
if not data: if not data:
if filelookup: if filelookup:
data = commands.getoutput(self.aptfilecommand % (distro, distro, pkg)).split() data = subprocess.getoutput(self.aptfilecommand % (distro, distro, pkg)).split()
if data: if data:
if data[0] == 'sh:': # apt-file isn't installed if data[0] == 'sh:': # apt-file isn't installed
self.log.error("PackageInfo/packages: apt-file is not installed") self.log.error("PackageInfo/packages: apt-file is not installed")
@ -77,16 +77,16 @@ class Apt:
self.log.error("PackageInfo/packages: Please run the 'update_apt_file' script") self.log.error("PackageInfo/packages: Please run the 'update_apt_file' script")
return "Cache out of date, please contact the administrator" return "Cache out of date, please contact the administrator"
if data[0] == "Use" and data[1] == "of": if data[0] == "Use" and data[1] == "of":
url = "http://packages.ubuntu.com/search?searchon=contents&keywords=%s&mode=&suite=%s&arch=any" % (urllib.quote(pkg), distro) url = "http://packages.ubuntu.com/search?searchon=contents&keywords=%s&mode=&suite=%s&arch=any" % (utils.web.urlquote(pkg), distro)
return url return url
if len(data) > 10: if len(data) > 10:
return "File %s found in %s (and %d others) http://packages.ubuntu.com/search?searchon=contents&keywords=%s&mode=&suite=%s&arch=any" % (pkg, ', '.join(data[:10]), len(data)-10, urllib.quote(pkg), distro) return "File %s found in %s (and %d others) http://packages.ubuntu.com/search?searchon=contents&keywords=%s&mode=&suite=%s&arch=any" % (pkg, ', '.join(data[:10]), len(data)-10, utils.web.urlquote(pkg), distro)
return "File %s found in %s" % (pkg, ', '.join(data)) return "File %s found in %s" % (pkg, ', '.join(data))
return 'Package/file %s does not exist in %s' % (pkg, distro) return 'Package/file %s does not exist in %s' % (pkg, distro)
return "No packages matching '%s' could be found" % pkg return "No packages matching '%s' could be found" % pkg
pkgs = [x.split()[0] for x in data.split('\n')] pkgs = [x.split()[0] for x in data.split('\n')]
if len(pkgs) > 10: if len(pkgs) > 10:
return "Found: %s (and %d others) http://packages.ubuntu.com/search?keywords=%s&searchon=names&suite=%s&section=all" % (', '.join(pkgs[:10]), len(pkgs)-10, urllib.quote(pkg), distro) return "Found: %s (and %d others) http://packages.ubuntu.com/search?keywords=%s&searchon=names&suite=%s&section=all" % (', '.join(pkgs[:10]), len(pkgs)-10, utils.web.urlquote(pkg), distro)
else: else:
return "Found: %s" % ', '.join(pkgs[:5]) return "Found: %s" % ', '.join(pkgs[:5])
@ -102,8 +102,8 @@ class Apt:
pkg = _pkg pkg = _pkg
data = commands.getoutput(self.aptcommand % (distro, distro, distro, distro, 'show', pkg)) data = subprocess.getoutput(self.aptcommand % (distro, distro, distro, distro, 'show', pkg))
data2 = commands.getoutput(self.aptcommand % (distro, distro, distro, distro, 'showsrc', pkg)) data2 = subprocess.getoutput(self.aptcommand % (distro, distro, distro, distro, 'showsrc', pkg))
if not data or 'E: No packages found' in data: if not data or 'E: No packages found' in data:
return 'Package %s does not exist in %s' % (pkg, distro) return 'Package %s does not exist in %s' % (pkg, distro)
maxp = {'Version': '0~'} maxp = {'Version': '0~'}
@ -111,7 +111,7 @@ class Apt:
for p in packages: for p in packages:
if not p.strip(): if not p.strip():
continue continue
parser = FeedParser.FeedParser() parser = FeedParser()
parser.feed(p) parser.feed(p)
p = parser.close() p = parser.close()
if type(p) == type(""): if type(p) == type(""):
@ -127,7 +127,7 @@ class Apt:
for p in packages2: for p in packages2:
if not p.strip(): if not p.strip():
continue continue
parser = FeedParser.FeedParser() parser = FeedParser()
parser.feed(p) parser.feed(p)
p = parser.close() p = parser.close()
if type(p) == type(""): if type(p) == type(""):
@ -139,7 +139,7 @@ class Apt:
maxp2 = p maxp2 = p
del parser del parser
archs = '' archs = ''
if maxp2.has_key('Architecture'): if 'Architecture' in maxp2:
archs = [_.strip() for _ in maxp2['Architecture'].split() if _.strip()] archs = [_.strip() for _ in maxp2['Architecture'].split() if _.strip()]
for arch in archs: for arch in archs:
if arch not in ('any', 'all'): if arch not in ('any', 'all'):
@ -162,10 +162,10 @@ if __name__ == "__main__":
argv = sys.argv argv = sys.argv
argc = len(argv) argc = len(argv)
if argc == 1: if argc == 1:
print "Need at least one arg" print("Need at least one arg")
sys.exit(1) sys.exit(1)
if argc > 3: if argc > 3:
print "Only takes 2 args" print("Only takes 2 args")
sys.exit(1) sys.exit(1)
class FakePlugin: class FakePlugin:
class FakeLog: class FakeLog:
@ -180,7 +180,7 @@ if __name__ == "__main__":
try: try:
lookup = argv[1].split(None, 1)[1] lookup = argv[1].split(None, 1)[1]
except: except:
print "Need something to lookup" print("Need something to lookup")
sys.exit(1) sys.exit(1)
dists = "hardy" dists = "hardy"
if argc == 3: if argc == 3:
@ -188,7 +188,7 @@ if __name__ == "__main__":
plugin = FakePlugin() plugin = FakePlugin()
aptlookup = Apt(plugin) aptlookup = Apt(plugin)
if command == "find": if command == "find":
print aptlookup.find(lookup, dists) print(aptlookup.find(lookup, dists))
else: else:
print aptlookup.info(lookup, dists) print(aptlookup.info(lookup, dists))

View File

@ -1,6 +1,7 @@
# -*- Encoding: utf-8 -*- # -*- Encoding: utf-8 -*-
### ###
# Copyright (c) 2008-2010 Terence Simpson # Copyright (c) 2008-2010 Terence Simpson
# Copyright (c) 2017- Krytarik Raido
# #
# This program is free software; you can redistribute it and/or modify # This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as # it under the terms of version 2 of the GNU General Public License as
@ -25,7 +26,8 @@ import supybot.conf as conf
import os import os
import re import re
import time import time
import packages from imp import reload
from . import packages
reload(packages) reload(packages)
def get_user(msg): def get_user(msg):
@ -46,7 +48,7 @@ def stripNick(nick):
msgcache = {} msgcache = {}
def queue(irc, to, msg): def queue(irc, to, msg):
now = time.time() now = time.time()
for m in msgcache.keys(): for m in list(msgcache.keys()):
if msgcache[m] < now - 30: if msgcache[m] < now - 30:
msgcache.pop(m) msgcache.pop(m)
for m in msgcache: for m in msgcache:
@ -130,7 +132,7 @@ class PackageInfo(callbacks.Plugin):
target = msg.nick target = msg.nick
queue(irc, reply_target, "%s: %s" % (target, reply)) queue(irc, reply_target, "%s: %s" % (target, reply))
return return
except Exception, e: except Exception as e:
self.log.info("PackageInfo: (info) Exception in pipe: %r" % e) self.log.info("PackageInfo: (info) Exception in pipe: %r" % e)
pass pass
elif rest[0] == '>': elif rest[0] == '>':
@ -142,10 +144,10 @@ class PackageInfo(callbacks.Plugin):
if target.lower() == "me": if target.lower() == "me":
target = msg.nick # redirect target = msg.nick # redirect
if not target: # Throw error if not target: # Throw error
raise Exception, 'No target' raise Exception('No target')
queue(irc, target, "<%s> wants you to know: %s" % (msg.nick, reply)) queue(irc, target, "<%s> wants you to know: %s" % (msg.nick, reply))
return return
except Exception, e: except Exception as e:
self.log.info("PackageInfo: (info) Exception in redirect: %r" % e) self.log.info("PackageInfo: (info) Exception in redirect: %r" % e)
pass pass
@ -175,7 +177,7 @@ class PackageInfo(callbacks.Plugin):
target = msg.nick target = msg.nick
queue(irc, reply_target, "%s: %s" % (target, reply)) queue(irc, reply_target, "%s: %s" % (target, reply))
return return
except Exception, e: except Exception as e:
self.log.info("PackageInfo: (find) Exception in pipe: %r" % e) self.log.info("PackageInfo: (find) Exception in pipe: %r" % e)
pass pass
elif rest[0] == '>': elif rest[0] == '>':
@ -187,10 +189,10 @@ class PackageInfo(callbacks.Plugin):
if target.lower() == "me": if target.lower() == "me":
target = msg.nick # redirect target = msg.nick # redirect
if not target: # Throw error if not target: # Throw error
raise Exception, 'No target' raise Exception('No target')
queue(irc, target, "<%s> wants you to know: %s" % (msg.nick, reply)) queue(irc, target, "<%s> wants you to know: %s" % (msg.nick, reply))
return return
except Exception, e: except Exception as e:
self.log.info("PackageInfo: (find) Exception in redirect: %r" % e) self.log.info("PackageInfo: (find) Exception in redirect: %r" % e)
pass pass