@@ -25,18 +25,33 @@ INDEX = "https://pypi.io/pypi"
25EXTENSIONS = ['tar.gz', 'tar.bz2', 'tar', 'zip', '.whl']
25EXTENSIONS = ['tar.gz', 'tar.bz2', 'tar', 'zip', '.whl']
26"""Permitted file extensions. These are evaluated from left to right and the first occurance is returned."""
26"""Permitted file extensions. These are evaluated from left to right and the first occurance is returned."""
29+logging.basicConfig(level=logging.INFO)
28−def _get_value(attribute, text):
32+def _get_values(attribute, text):
29− """Match attribute in text and return it."""
33+ """Match attribute in text and return all matches.
35+ :returns: List of matches.
30 regex = '{}\s+=\s+"(.*)";'.format(attribute)
37 regex = '{}\s+=\s+"(.*)";'.format(attribute)
31 regex = re.compile(regex)
38 regex = re.compile(regex)
32− value = regex.findall(text)
39+ values = regex.findall(text)
42+def _get_unique_value(attribute, text):
43+ """Match attribute in text and return unique match.
45+ :returns: Single match.
47+ values = _get_values(attribute, text)
33− n = len(value)
48+ n = len(values)
35− raise ValueError("Found too many values for {}".format(attribute))
50+ raise ValueError("found too many values for {}".format(attribute))
36 elif n == 1:
51 elif n == 1:
37− return value[0]
52+ return values[0]
39− raise ValueError("No value found for {}".format(attribute))
54+ raise ValueError("no value found for {}".format(attribute))
41def _get_line_and_value(attribute, text):
56def _get_line_and_value(attribute, text):
42 """Match attribute in text. Return the line and the value of the attribute."""
57 """Match attribute in text. Return the line and the value of the attribute."""
@@ -45,11 +60,11 @@ def _get_line_and_value(attribute, text):
45 value = regex.findall(text)
60 value = regex.findall(text)
46 n = len(value)
61 n = len(value)
48− raise ValueError("Found too many values for {}".format(attribute))
63+ raise ValueError("found too many values for {}".format(attribute))
49 elif n == 1:
64 elif n == 1:
50 return value[0]
65 return value[0]
52− raise ValueError("No value found for {}".format(attribute))
67+ raise ValueError("no value found for {}".format(attribute))
55def _replace_value(attribute, value, text):
70def _replace_value(attribute, value, text):
@@ -64,175 +79,151 @@ def _fetch_page(url):
64 if r.status_code == requests.codes.ok:
79 if r.status_code == requests.codes.ok:
65 return r.json()
80 return r.json()
67− raise ValueError("Request for {} failed".format(url))
82+ raise ValueError("request for {} failed".format(url))
69−def _get_latest_version(package, extension):
84+def _get_latest_version_pypi(package, extension):
85+ """Get latest version and hash from PyPI."""
72 url = "{}/{}/json".format(INDEX, package)
86 url = "{}/{}/json".format(INDEX, package)
73 json = _fetch_page(url)
87 json = _fetch_page(url)
75− data = extract_relevant_nix_data(json, extension)[1]
89+ version = json['info']['version']
76−
90+ for release in json['releases'][version]:
77− version = data['latest_version']
91+ if release['filename'].endswith(extension):
78− if version in data['versions']:
92+ # TODO: In case of wheel we need to do further checks!
79− sha256 = data['versions'][version]['sha256']
93+ sha256 = release['digests']['sha256']
81− sha256 = None # Its possible that no file was uploaded to PyPI
83 return version, sha256
95 return version, sha256
86−def extract_relevant_nix_data(json, extension):
98+def _get_latest_version_github(package, extension):
87− """Extract relevant Nix data from the JSON of a package obtained from PyPI.
99+ raise ValueError("updating from GitHub is not yet supported.")
103+ 'fetchFromGitHub' : _get_latest_version_github,
104+ 'fetchPypi' : _get_latest_version_pypi,
105+ 'fetchurl' : _get_latest_version_pypi,
89− :param json: JSON obtained from PyPI
108+
109+DEFAULT_SETUPTOOLS_EXTENSION = 'tar.gz'
113+ 'setuptools' : DEFAULT_SETUPTOOLS_EXTENSION,
117+def _determine_fetcher(text):
118+ # Count occurences of fetchers.
119+ nfetchers = sum(text.count('src = {}'.format(fetcher)) for fetcher in FETCHERS.keys())
121+ raise ValueError("no fetcher.")
123+ raise ValueError("multiple fetchers.")
125+ # Then we check which fetcher to use.
126+ for fetcher in FETCHERS.keys():
127+ if 'src = {}'.format(fetcher) in text:
131+def _determine_extension(text, fetcher):
132+ """Determine what extension is used in the expression.
135+ - fetchPypi, we check if format is specified.
136+ - fetchurl, we determine the extension from the url.
137+ - fetchFromGitHub we simply use `.tar.gz`.
91− def _extract_license(json):
139+ if fetcher == 'fetchPypi':
92− """Extract license from JSON."""
140+ try:
93− return json['info']['license']
141+ format = _get_unique_value('format', text)
94−
142+ except ValueError as e:
95− def _available_versions(json):
143+ format = None # format was not given
96− return json['releases'].keys()
144+
98− def _extract_latest_version(json):
146+ extension = _get_unique_value('extension', text)
99− return json['info']['version']
147+ except ValueError as e:
100−
148+ extension = None # extension was not given
101− def _get_src_and_hash(json, version, extensions):
149+
102− """Obtain url and hash for a given version and list of allowable extensions."""
103− if not json['releases']:
104− msg = "Package {}: No releases available.".format(json['info']['name'])
105− raise ValueError(msg)
107− # We use ['releases'] and not ['urls'] because we want to have the possibility for different version.
108− for possible_file in json['releases'][version]:
109− for extension in extensions:
150+ if extension is None:
110− if possible_file['filename'].endswith(extension):
151+ if format is None:
111− src = {'url': str(possible_file['url']),
152+ format = 'setuptools'
112− 'sha256': str(possible_file['digests']['sha256']),
153+ extension = FORMATS[format]
114− return src
155+ elif fetcher == 'fetchurl':
115− else:
156+ url = _get_unique_value('url', text)
116− msg = "Package {}: No release with valid file extension available.".format(json['info']['name'])
157+ extension = os.path.splitext(url)[1]
117− logging.info(msg)
158+ if 'pypi' not in url:
118− return None
159+ raise ValueError('url does not point to PyPI.')
119− #raise ValueError(msg)
160+
120−
161+ elif fetcher == 'fetchFromGitHub':
121− def _get_sources(json, extensions):
162+ raise ValueError('updating from GitHub is not yet implemented.')
122− versions = _available_versions(json)
163+
123− releases = {version: _get_src_and_hash(json, version, extensions) for version in versions}
124− releases = toolz.itemfilter(lambda x: x[1] is not None, releases)
128− name = str(json['info']['name'])
129− latest_version = str(_extract_latest_version(json))
130− #src = _get_src_and_hash(json, latest_version, EXTENSIONS)
131− sources = _get_sources(json, [extension])
134− license = str(_extract_license(json))
135− license = license if license != "UNKNOWN" else None
136− summary = str(json['info'].get('summary')).strip('.')
137− summary = summary if summary != "UNKNOWN" else None
138− #description = str(json['info'].get('description'))
139− #description = description if description != "UNKNOWN" else None
140− homepage = json['info'].get('home_page')
143− 'latest_version' : latest_version,
144− 'versions' : sources,
147− 'description' : summary if summary else None,
148− #'longDescription' : description,
149− 'license' : license,
150− 'homepage' : homepage,
153− return name, data
164+ return extension
156def _update_package(path):
167def _update_package(path):
171+ # Read the expression
172+ with open(path, 'r') as f:
176+ pname = _get_unique_value('pname', text)
178+ # Determine version.
179+ version = _get_unique_value('version', text)
181+ # First we check how many fetchers are mentioned.
182+ fetcher = _determine_fetcher(text)
184+ extension = _determine_extension(text, fetcher)
186+ new_version, new_sha256 = _get_latest_version_pypi(pname, extension)
188+ if new_version == version:
189+ logging.info("Path {}: no update available for {}.".format(path, pname))
192+ raise ValueError("no file available for {}.".format(pname))
194+ text = _replace_value('version', new_version, text)
195+ text = _replace_value('sha256', new_sha256, text)
197+ with open(path, 'w') as f:
200+ logging.info("Path {}: updated {} from {} to {}".format(path, pname, version, new_version))
158 # We need to read and modify a Nix expression.
207 # We need to read and modify a Nix expression.
159 if os.path.isdir(path):
208 if os.path.isdir(path):
160 path = os.path.join(path, 'default.nix')
209 path = os.path.join(path, 'default.nix')
211+ # If a default.nix does not exist, we quit.
162 if not os.path.isfile(path):
212 if not os.path.isfile(path):
163− logging.warning("Path does not exist: {}".format(path))
213+ logging.info("Path {}: does not exist.".format(path))
164 return False
214 return False
216+ # If file is not a Nix expression, we quit.
166 if not path.endswith(".nix"):
217 if not path.endswith(".nix"):
167− logging.warning("Path does not end with `.nix`, skipping: {}".format(path))
218+ logging.info("Path {}: does not end with `.nix`.".format(path))
170− with open(path, 'r') as f:
174− pname = _get_value('pname', text)
175− except ValueError as e:
176− logging.warning("Path {}: {}".format(path, str(e)))
177 return False
219 return False
180− version = _get_value('version', text)
222+ return _update_package(path)
181 except ValueError as e:
223 except ValueError as e:
182− logging.warning("Path {}: {}".format(path, str(e)))
224+ logging.warning("Path {}: {}".format(path, e))
183 return False
225 return False
185− # If we use a wheel, then we need to request a wheel as well
187− format = _get_value('format', text)
188− except ValueError as e:
189− # No format mentioned, then we assume we have setuptools
191− logging.info("Path {}: {}".format(path, str(e)))
192− extension = ".tar.gz"
194− if format == 'wheel':
198− url = _get_value('url', text)
199− extension = os.path.splitext(url)[1]
200− if 'pypi' not in url:
201− logging.warning("Path {}: uses non-PyPI url, not updating.".format(path))
203− except ValueError as e:
204− logging.info("Path {}: {}".format(path, str(e)))
205− extension = ".tar.gz"
208− new_version, new_sha256 = _get_latest_version(pname, extension)
209− except ValueError as e:
210− logging.warning("Path {}: {}".format(path, str(e)))
213− logging.warning("Path has no valid file available: {}".format(path))
215− if new_version != version:
217− text = _replace_value('version', new_version, text)
218− except ValueError as e:
219− logging.warning("Path {}: {}".format(path, str(e)))
221− text = _replace_value('sha256', new_sha256, text)
222− except ValueError as e:
223− logging.warning("Path {}: {}".format(path, str(e)))
225− with open(path, 'w') as f:
228− logging.info("Updated {} from {} to {}".format(pname, version, new_version))
231− logging.info("No update available for {} at {}".format(pname, version))
236def main():
227def main():
238 parser = argparse.ArgumentParser()
229 parser = argparse.ArgumentParser()
@@ -240,11 +231,11 @@ def main():
241 args = parser.parse_args()
232 args = parser.parse_args()
243− packages = args.package
234+ packages = map(os.path.abspath, args.package)
245− count = list(map(_update_package, packages))
236+ count = list(map(_update, packages))
247− #logging.info("{} package(s) updated".format(sum(count)))
238+ logging.info("{} package(s) updated".format(sum(count)))
249if __name__ == '__main__':
240if __name__ == '__main__':