1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim: set noexpandtab tabstop=4 shiftwidth=4 autoindent smartindent:
# Searches over the network to find out which RPM package distributes
# a given file.
#
# Written by Lucas C. Villa Real <lucasvr@gobolinux.org>
# Released under the GNU GPL version 2 or above.
import os
import re
import sys
import argparse
import subprocess
from html.parser import HTMLParser
class VersionCmp:
def test(self, candidate, reference):
if candidate[0].isalpha() and reference[0].isalpha():
return self.compare(candidate, reference)
c_parts = candidate.split(".")
r_parts = reference.split(".")
while True:
if len(c_parts) <= 1 or len(r_parts) <= 1:
# Return a comparison of the major numbers
try:
a = int("".join(c for c in c_parts[0] if c.isdigit()))
b = int("".join(r for r in r_parts[0] if r.isdigit()))
a_chars = "".join(c for c in c_parts[0] if not c.isdigit())
b_chars = "".join(r for r in r_parts[0] if not r.isdigit())
if a == b and len(a_chars) and len(b_chars):
return self.compare(a_chars, b_chars)
except ValueError:
pass
return self.compare(".".join(c_parts), ".".join(r_parts))
else:
# compare 2 numbers
try:
a = int("".join(c for c in c_parts[0] if c.isdigit()))
b = int("".join(r for r in r_parts[0] if r.isdigit()))
ret = self.compare(a, b)
if ret != 0:
return ret
except ValueError:
return self.compare(".".join(c_parts), ".".join(r_parts))
c_parts = c_parts[1:]
r_parts = r_parts[1:]
def compare(self, a, b):
if a == b:
return 0
return -1 if a < b else 1
class RPMFind_Parser(HTMLParser):
'''
Parses the HTML data output by rpmfind.net
'''
def __init__(self):
self.tags = []
self.candidates = []
HTMLParser.__init__(self)
def handle_starttag(self, tag, attrs):
self.tags.append(tag)
def handle_endtag(self, tag):
self.tags.pop()
def handle_data(self, data):
if len(self.tags) and self.tags[-1] == "a" and data.find(".rpm") >= 0:
self.candidates.append(data)
def get_pkgnames(self):
if len(self.candidates) == 0:
return ""
return self.candidates
class RPMFinder:
def find(self, path, arch, distroname, distrocode):
'''
Searches rpmfind.net for a given file. Arch and distro can
be provided to narrow the search scope. Returns the package
name on success or an empty string if no matches were found.
'''
self.path = path
self.arch = arch
self.distroname = distroname.replace(" ", "+")
self.distrocode = distrocode
self.name = path
for token in [">=", ">", "<=", "<", "="]:
self.name = self.name.replace(token, " ")
self.name = self.name.split(" ")[0]
matches = self.__search_rpmfind_net()
if len(matches) == 0:
return []
if any(op in self.path for op in [">", "<", "="]):
op, version = self.__get_op_and_version()
return self.__filter(matches, op, version)
else:
return matches
def __filter(self, matches, op, version):
filtered = []
for match in matches:
pkg_version = match.replace(self.name, "").replace("{0}.{1}.rpm".format(self.distrocode, self.arch), "").strip("-").strip(".")
sys.stderr.write("package {0}: {1} {2} {3}?\n".format(match, pkg_version, op, version))
vcmp = VersionCmp()
if op == ">" and vcmp.test(pkg_version, version) > 0:
filtered.append(match)
elif op == ">=" and vcmp.test(pkg_version, version) >= 0:
filtered.append(match)
elif op == "=" and vcmp.test(pkg_version, version) == 0:
filtered.append(match)
elif op == "<" and vcmp.test(pkg_version, version) < 0:
filtered.append(match)
elif op == "<=" and vcmp.test(pkg_version, version) <= 0:
filtered.append(match)
return filtered
def __get_op_and_version(self):
if ">=" in self.path:
return ">=", self.path.split(">=")[1].strip()
elif ">" in self.path:
return ">", self.path.split(">")[1].strip()
elif "<=" in self.path:
return "<=", self.path.split("<=")[1].strip()
elif "<" in self.path:
return "<", self.path.split("<")[1].strip()
elif "=" in self.path:
return "=", self.path.split("=")[1].strip()
else:
sys.stderr.write("could not extract op and version from {}\n".format(self.path))
return None, None
def __search_rpmfind_net(self):
path = self.path.replace("/", "%2F")
baseuri = "http://rpmfind.net/linux/rpm2html/search.php"
query = "?query={0}&submit=Search+...&system={1}&arch={2}".format(path, self.distroname, self.arch)
html = subprocess.check_output(["wget", "--quiet", "{0}{1}".format(baseuri, query), "-O", "-"])
# Compile a regex that catches package names derived from the basename given by self.path.
# Example: perl-DBICx when perl-DBI is wanted.
regex = re.compile(r"{0}\-[0-9]+.*{1}.{2}.rpm".format(self.name, self.distrocode, self.arch))
htmlparser = RPMFind_Parser()
htmlparser.feed(str(html))
pkgnames = htmlparser.get_pkgnames()
result = []
for pkgname in pkgnames:
if regex.match(pkgname):
result.append(pkgname)
return result
def main():
argparser = argparse.ArgumentParser(argument_default="")
argparser.add_argument("--path", type=str, help="File name to search for in the remote RPM databases")
argparser.add_argument("--arch", type=str, help="Architecture (optional)")
argparser.add_argument("--distroname", type=str, help="Distribution name (optional)")
argparser.add_argument("--distrocode", type=str, help="Distribution code (optional)")
args = argparser.parse_args()
if len(args.path) == 0:
argparser.print_help()
sys.exit(1)
pkgname = RPMFinder().find(args.path, args.arch, args.distroname, args.distrocode)
if len(pkgname):
print(pkgname[0])
if __name__ == "__main__":
main()
|