Skip to content

Instantly share code, notes, and snippets.

@manvari
Last active December 29, 2015 01:09
Show Gist options
  • Save manvari/7591026 to your computer and use it in GitHub Desktop.
Save manvari/7591026 to your computer and use it in GitHub Desktop.
A simple Python script for the AUR. Uses the AUR API.
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# pyarchaur.py
import requests
import time
import datetime
import argparse
class APIClient:
def __init__(self):
''' Defines the AUR and the AUR API URLs. '''
self.aur_url = "https://aur.archlinux.org"
self.aur_api_url = "{}/rpc.php".format(self.aur_url)
def api_request(self, rqtype, pkgname):
'''
Sends a request to the AUR API.
Returns response as JSON.
'''
parameters = {'type': rqtype, 'arg': pkgname}
try:
api_response = requests.get(self.aur_api_url, params=parameters,
headers={"Accept": "application/json"})
return api_response.json()
except Exception as err:
print("Failed to look up the requested package on the AUR.")
raise SystemExit(err)
def convert_date(self, date):
'''
Converts the date returned by the AUR API.
Returns a date string formatted according to the locale's representation.
'''
try:
return datetime.datetime.fromtimestamp(int(date)).strftime('%a %d %b %Y, %H:%M:%S')
except ValueError:
print("Could not convert the date from the AUR API response.")
def convert_category(self, id):
'''
Converts the category ID returned by the AUR API.
Returns the category name.
'''
category_dict = {1: 'None', 2: 'daemons', 3: 'devel', 4: 'editors', 5: 'emulators',
6: 'games', 7: 'gnome', 8: 'i18n', 9: 'kde', 10: 'lib',
11: 'modules', 12: 'multimedia', 13: 'networking', 14: 'office',
15: 'science', 16: 'system', 17: 'x11', 18: 'xfce', 19: 'kernels',
20: 'fonts'}
try:
return category_dict[id]
except:
print("Category ID cannot be converted.")
def local_timezone(self):
''' Returns the name of the local timezone. '''
if time.localtime().tm_isdst == 0: # DST not in effect
return time.tzname[0]
else:
return time.tzname[1]
def pkg_info(self, rqtype, pkgname):
''' Prints information for the search. '''
# Retrieve API data for the package
api_response = self.api_request(rqtype, pkgname)
api_resultcount = api_response['resultcount'] # either 0 or >= 1
if not api_resultcount:
print("No package matching this name was found on the AUR.")
return 1
api_results = api_response['results']
if not isinstance(api_results, list):
api_results = [api_results,]
# Get local timezone
local_tz = self.local_timezone()
# Print info for results
for api_result in api_results:
# Format dates
if api_result['OutOfDate'] != 0:
ood_date = self.convert_date(api_result['OutOfDate'])
status = "Out of Date (flagged on {} {})".format(ood_date, local_tz)
else:
status = "Up-to-date"
lastmodified = "{} {}".format(self.convert_date(api_result['LastModified']), local_tz)
submitted = "{} {}".format(self.convert_date(api_result['FirstSubmitted']), local_tz)
# Format category
category = self.convert_category(int(api_result['CategoryID']))
# Format URLs
pkg_project_url = api_result['URL'].replace('\\', '')
pkg_aur_url = "{}/packages/{}/".format(self.aur_url, api_result['Name'])
pkg_dl_url = "{}{}".format(self.aur_url, api_result['URLPath'].replace("\\", ""))
# Print info
print("Name : {0}\n" \
"Version : {1}\n" \
"Status : {2}\n" \
"Project Page : {3}\n" \
"Description : {4}\n" \
"Category : {5}\n" \
"License : {6}\n" \
"Votes : {7}\n" \
"Maintainer : {8}\n" \
"Submitted : {9}\n" \
"Last Modified : {10}\n" \
"AUR Page : {11}\n" \
"DL URL : {12}\n".format(api_result['Name'], api_result['Version'],
status, api_result['URL'],
api_result['Description'], category,
api_result['License'], api_result['NumVotes'],
api_result['Maintainer'], submitted,
lastmodified, pkg_aur_url, pkg_dl_url))
if rqtype == 'search':
print("Search Result : {} package(s)".format(api_resultcount))
if __name__ == "__main__":
parser = argparse.ArgumentParser(prog="pyarchaur.py")
parser.add_argument("request", nargs=1, choices=("search", "info"), default="info",
help="Request type (search, info) for the given package name.")
parser.add_argument("package", help="Name of the package to look for on the AUR.")
args = parser.parse_args()
pkgname = args.package
api_query = APIClient()
if args.request == ['search']:
api_query.pkg_info('search', pkgname)
else:
api_query.pkg_info('info', pkgname)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment