From f341d1e98221cee65fbdce9dd6529ce3d67c3e77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Thalheim?= Date: Mon, 16 Mar 2020 10:06:32 +0000 Subject: [PATCH] make it a proper python/nix package --- .gitignore | 107 +++++++++++++++++++++ LICENSE.rst | 7 ++ README.md | 34 ------- README.rst | 38 ++++++++ bin/nix-update | 10 ++ default.nix | 26 +++++ nix-update.py | 209 ----------------------------------------- nix_update/__init__.py | 52 ++++++++++ nix_update/errors.py | 6 ++ nix_update/update.py | 96 +++++++++++++++++++ nix_update/utils.py | 31 ++++++ nix_update/version.py | 67 +++++++++++++ setup.cfg | 60 ++++++++++++ setup.py | 5 + 14 files changed, 505 insertions(+), 243 deletions(-) create mode 100644 .gitignore create mode 100644 LICENSE.rst delete mode 100644 README.md create mode 100644 README.rst create mode 100755 bin/nix-update create mode 100644 default.nix delete mode 100755 nix-update.py create mode 100755 nix_update/__init__.py create mode 100644 nix_update/errors.py create mode 100644 nix_update/update.py create mode 100644 nix_update/utils.py create mode 100644 nix_update/version.py create mode 100644 setup.cfg create mode 100755 setup.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..86a9924 --- /dev/null +++ b/.gitignore @@ -0,0 +1,107 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +# Nix artifacts +result \ No newline at end of file diff --git a/LICENSE.rst b/LICENSE.rst new file mode 100644 index 0000000..21427d9 --- /dev/null +++ b/LICENSE.rst @@ -0,0 +1,7 @@ +Copyright 2020 Jörg Thalheim + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md deleted file mode 100644 index 2cda635..0000000 --- a/README.md +++ /dev/null @@ -1,34 +0,0 @@ -# nix-update - -Update nix packages likes it is 2020. -This tool is still in early development. - -## Dependencies - -- python 3 -- [nix-prefetch](https://github.com/msteen/nix-prefetch/) - -## USAGE - -First change to your directory containing the nix expression (Could be a nixpkgs or your own repository). Than run `nix-update` as follows - -``` -$ python nix-update.py attribute [version] -``` - -This example will fetch the latest github release: - -``` -$ python nix-update.py nixpkgs-review -``` - -It is also possible to specify the version manually - -``` -$ python nix-update.py nixpkgs-review 2.1.1 -``` - -## TODO - -- [ ] make it a proper python/nix package -- [ ] optionally commit update diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..1c86f31 --- /dev/null +++ b/README.rst @@ -0,0 +1,38 @@ +nix-update +========== + +Update nix packages likes it is 2020. This tool is still in early +development. + +Dependencies +------------ + +- python 3 +- `nix-prefetch `__ + +USAGE +----- + +First change to your directory containing the nix expression (Could be a +nixpkgs or your own repository). Than run ``nix-update`` as follows + +:: + + $ nix-update attribute [version] + +This example will fetch the latest github release: + +:: + + $ nix-update nixpkgs-review + +It is also possible to specify the version manually + +:: + + $ nix-update nixpkgs-review 2.1.1 + +TODO +---- + +- ☐ optionally commit update diff --git a/bin/nix-update b/bin/nix-update new file mode 100755 index 0000000..0212631 --- /dev/null +++ b/bin/nix-update @@ -0,0 +1,10 @@ +#!/usr/bin/env python +import sys +import os +sys.path.insert(0, os.path.join( + os.path.dirname(os.path.dirname(os.path.realpath(__file__))))) + +from nix_update import main # NOQA + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/default.nix b/default.nix new file mode 100644 index 0000000..a16afa0 --- /dev/null +++ b/default.nix @@ -0,0 +1,26 @@ +{ pkgs ? import {} }: + + +with pkgs; +python3.pkgs.buildPythonApplication rec { + name = "nix-update"; + src = ./.; + buildInputs = [ makeWrapper ]; + checkInputs = [ mypy python3.pkgs.black python3.pkgs.flake8 glibcLocales ]; + checkPhase = '' + echo -e "\x1b[32m## run black\x1b[0m" + LC_ALL=en_US.utf-8 black --check . + echo -e "\x1b[32m## run flake8\x1b[0m" + flake8 nix_update + echo -e "\x1b[32m## run mypy\x1b[0m" + mypy nix_update + ''; + makeWrapperArgs = [ + "--prefix PATH" ":" (lib.makeBinPath [ nix nix-prefetch ]) + ]; + shellHook = '' + # workaround because `python setup.py develop` breaks for me + ''; + + passthru.env = buildEnv { inherit name; paths = buildInputs ++ checkInputs; }; +} diff --git a/nix-update.py b/nix-update.py deleted file mode 100755 index 2904f08..0000000 --- a/nix-update.py +++ /dev/null @@ -1,209 +0,0 @@ -#!/usr/bin/env python3 - -import argparse -import fileinput -import json -import re -import subprocess -import urllib.request -import xml.etree.ElementTree as ET -import tempfile -import sys -from typing import Optional, List, NoReturn -from urllib.parse import urlparse, ParseResult - - -def die(msg: str) -> NoReturn: - print(msg, file=sys.stderr) - sys.exit(1) - - -def fetch_latest_github_release(url: ParseResult) -> Optional[str]: - parts = url.path.split("/") - owner, repo = parts[1], parts[2] - # TODO fallback to tags? - resp = urllib.request.urlopen(f"https://github.com/{owner}/{repo}/releases.atom") - tree = ET.fromstring(resp.read()) - release = tree.find(".//{http://www.w3.org/2005/Atom}entry") - if release is None: - return None - link = release.find("{http://www.w3.org/2005/Atom}link") - assert link is not None - href = link.attrib["href"] - url = urlparse(href) - return url.path.split("/")[-1] - - -def fetch_latest_pypi_release(url: ParseResult) -> str: - parts = url.path.split("/") - package = parts[2] - resp = urllib.request.urlopen(f"https://pypi.org/pypi/{package}/json") - data = json.loads(resp.read()) - return data["info"]["version"] - - -def fetch_latest_gitlab_release(url: ParseResult) -> Optional[str]: - parts = url.path.split("/") - project_id = parts[4] - resp = urllib.request.urlopen(f"https://gitlab.com/api/v4/projects/{project_id}/repository/tags") - data = json.loads(resp.read()) - if len(data) == 0: - return None - return data[0]["name"] - - -def fetch_latest_release(url_str: str) -> Optional[str]: - url = urlparse(url_str) - - if url.netloc == "pypi": - return fetch_latest_pypi_release(url) - elif url.netloc == "github.com": - return fetch_latest_github_release(url) - elif url.netloc == "gitlab.com": - return fetch_latest_gitlab_release(url) - else: - die( - "Please specify the version. We can only get the latest version from github/pypi projects right now" - ) - - -# def find_repology_release(attr) -> str: -# resp = urllib.request.urlopen(f"https://repology.org/api/v1/projects/{attr}/") -# data = json.loads(resp.read()) -# for name, pkg in data.items(): -# for repo in pkg: -# if repo["status"] == "newest": -# return repo["version"] -# return None - - -def eval_attr(import_path: str, attr: str) -> str: - return f"""(with import {import_path} {{}}; - let - pkg = {attr}; - in {{ - name = pkg.name; - version = (builtins.parseDrvName pkg.name).version; - position = pkg.meta.position; - urls = pkg.src.urls; - hash = pkg.src.outputHash; - modSha256 = pkg.modSha256 or null; - cargoSha256 = pkg.cargoSha256 or null; - }})""" - - -def update_version(filename: str, current: str, target: str): - if target.startswith("v"): - target = target[1:] - - if current != target: - with fileinput.FileInput(filename, inplace=True) as f: - for line in f: - print(line.replace(current, target), end="") - - -def replace_hash(filename: str, current: str, target: str): - if current != target: - with fileinput.FileInput(filename, inplace=True) as f: - for line in f: - line = re.sub(current, target, line) - print(line, end="") - - -def nix_prefetch(cmd: List[str]) -> str: - res = subprocess.run( - ["nix-prefetch"] + cmd, text=True, stdout=subprocess.PIPE, check=True, - ) - return res.stdout.strip() - - -def update_src_hash(import_path: str, attr: str, filename: str, current_hash: str): - target_hash = nix_prefetch([f"(import {import_path} {{}}).{attr}"]) - replace_hash(filename, current_hash, target_hash) - - -def update_mod256_hash(import_path: str, attr: str, filename: str, current_hash: str): - expr = f"{{ sha256 }}: (import {import_path} {{}}).{attr}.go-modules.overrideAttrs (_: {{ modSha256 = sha256; }})" - target_hash = nix_prefetch([expr]) - replace_hash(filename, current_hash, target_hash) - - -def update_cargoSha256_hash(import_path: str, attr: str, filename: str, current_hash: str): - target_hash = nix_prefetch([f"{{ sha256 }}: (import {import_path} {{}}).{attr}.cargoDeps.overrideAttrs (_: {{ inherit sha256; }})"]) - replace_hash(filename, current_hash, target_hash) - - -def update(import_path: str, attr: str, target_version: Optional[str]) -> None: - res = subprocess.run( - ["nix", "eval", "--json", eval_attr(import_path, attr)], - text=True, - stdout=subprocess.PIPE, - ) - out = json.loads(res.stdout) - current_version: str = out["version"] - if current_version == "": - name = out["name"] - die(f"Nix's builtins.parseDrvName could not parse the version from {name}") - filename, line = out["position"].rsplit(":", 1) - - if not target_version: - # latest_version = find_repology_release(attr) - # if latest_version is None: - url = out["urls"][0] - target_version = fetch_latest_release(url) - if target_version is None: - die("No releases found") - update_version(filename, current_version, target_version) - - update_src_hash(import_path, attr, filename, out["hash"]) - - if out["modSha256"]: - update_mod256_hash(import_path, attr, filename, out["modSha256"]) - - if out["cargoSha256"]: - update_cargoSha256_hash(import_path, attr, filename, out["cargoSha256"]) - - -def parse_args(): - parser = argparse.ArgumentParser() - help = "File to import rather than default.nix. Examples, ./release.nix" - parser.add_argument("-f", "--file", default="./.", help=help) - parser.add_argument("--build", action="store_true", help="build the package") - parser.add_argument( - "--run", - action="store_true", - help="provide a shell based on `nix run` with the package in $PATH", - ) - parser.add_argument( - "--shell", action="store_true", help="provide a shell with the package" - ) - parser.add_argument("attribute", help="Attribute name within the file evaluated") - parser.add_argument("version", nargs="?", help="Version to update to") - return parser.parse_args() - - -def nix_shell(filename: str, attribute: str) -> None: - with tempfile.NamedTemporaryFile(mode="w") as f: - f.write( - f""" - with import {filename}; mkShell {{ buildInputs = [ {attribute} ]; }} - """ - ) - f.flush() - subprocess.run(["nix-shell", f.name]) - - -def main() -> None: - args = parse_args() - update(args.file, args.attribute, args.version) - if args.build: - subprocess.run(["nix", "build", "-f", args.file, args.attribute]) - if args.run: - subprocess.run(["nix", "run", "-f", args.file, args.attribute]) - - if args.shell: - nix_shell(args.file, args.attribute) - - -if __name__ == "__main__": - main() diff --git a/nix_update/__init__.py b/nix_update/__init__.py new file mode 100755 index 0000000..7b1cef7 --- /dev/null +++ b/nix_update/__init__.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 + +import argparse +import tempfile + +from .update import update +from .utils import run + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + help = "File to import rather than default.nix. Examples, ./release.nix" + parser.add_argument("-f", "--file", default="./.", help=help) + parser.add_argument("--build", action="store_true", help="build the package") + parser.add_argument( + "--run", + action="store_true", + help="provide a shell based on `nix run` with the package in $PATH", + ) + parser.add_argument( + "--shell", action="store_true", help="provide a shell with the package" + ) + parser.add_argument("attribute", help="Attribute name within the file evaluated") + parser.add_argument("version", nargs="?", help="Version to update to") + return parser.parse_args() + + +def nix_shell(filename: str, attribute: str) -> None: + with tempfile.NamedTemporaryFile(mode="w") as f: + f.write( + f""" + with import {filename}; mkShell {{ buildInputs = [ {attribute} ]; }} + """ + ) + f.flush() + run(["nix-shell", f.name], stdout=None) + + +def main() -> None: + args = parse_args() + update(args.file, args.attribute, args.version) + if args.build: + run(["nix", "build", "-f", args.file, args.attribute], stdout=None) + if args.run: + run(["nix", "run", "-f", args.file, args.attribute], stdout=None) + + if args.shell: + nix_shell(args.file, args.attribute) + + +if __name__ == "__main__": + main() diff --git a/nix_update/errors.py b/nix_update/errors.py new file mode 100644 index 0000000..d51f51e --- /dev/null +++ b/nix_update/errors.py @@ -0,0 +1,6 @@ +class UpdateError(Exception): + pass + + +class VersionError(UpdateError): + pass diff --git a/nix_update/update.py b/nix_update/update.py new file mode 100644 index 0000000..bb8ec1b --- /dev/null +++ b/nix_update/update.py @@ -0,0 +1,96 @@ +import fileinput +import re +import json +from typing import List, Optional + +from .utils import run +from .errors import UpdateError +from .version import fetch_latest_version + + +def eval_attr(import_path: str, attr: str) -> str: + return f"""(with import {import_path} {{}}; + let + pkg = {attr}; + in {{ + name = pkg.name; + version = (builtins.parseDrvName pkg.name).version; + position = pkg.meta.position; + urls = pkg.src.urls; + hash = pkg.src.outputHash; + modSha256 = pkg.modSha256 or null; + cargoSha256 = pkg.cargoSha256 or null; + }})""" + + +def update_version(filename: str, current: str, target: str) -> None: + if target.startswith("v"): + target = target[1:] + + if current != target: + with fileinput.FileInput(filename, inplace=True) as f: + for line in f: + print(line.replace(current, target), end="") + + +def replace_hash(filename: str, current: str, target: str) -> None: + if current != target: + with fileinput.FileInput(filename, inplace=True) as f: + for line in f: + line = re.sub(current, target, line) + print(line, end="") + + +def nix_prefetch(cmd: List[str]) -> str: + res = run(["nix-prefetch"] + cmd) + return res.stdout.strip() + + +def update_src_hash( + import_path: str, attr: str, filename: str, current_hash: str +) -> None: + target_hash = nix_prefetch([f"(import {import_path} {{}}).{attr}"]) + replace_hash(filename, current_hash, target_hash) + + +def update_mod256_hash( + import_path: str, attr: str, filename: str, current_hash: str +) -> None: + expr = f"{{ sha256 }}: (import {import_path} {{}}).{attr}.go-modules.overrideAttrs (_: {{ modSha256 = sha256; }})" + target_hash = nix_prefetch([expr]) + replace_hash(filename, current_hash, target_hash) + + +def update_cargoSha256_hash( + import_path: str, attr: str, filename: str, current_hash: str +) -> None: + expr = f"{{ sha256 }}: (import {import_path} {{}}).{attr}.cargoDeps.overrideAttrs (_: {{ inherit sha256; }})" + target_hash = nix_prefetch([expr]) + replace_hash(filename, current_hash, target_hash) + + +def update(import_path: str, attr: str, target_version: Optional[str]) -> None: + res = run(["nix", "eval", "--json", eval_attr(import_path, attr)]) + out = json.loads(res.stdout) + current_version: str = out["version"] + if current_version == "": + name = out["name"] + UpdateError( + f"Nix's builtins.parseDrvName could not parse the version from {name}" + ) + filename, line = out["position"].rsplit(":", 1) + + if not target_version: + # latest_version = find_repology_release(attr) + # if latest_version is None: + url = out["urls"][0] + target_version = fetch_latest_version(url) + update_version(filename, current_version, target_version) + + update_src_hash(import_path, attr, filename, out["hash"]) + + if out["modSha256"]: + update_mod256_hash(import_path, attr, filename, out["modSha256"]) + + if out["cargoSha256"]: + update_cargoSha256_hash(import_path, attr, filename, out["cargoSha256"]) diff --git a/nix_update/utils.py b/nix_update/utils.py new file mode 100644 index 0000000..4789c9b --- /dev/null +++ b/nix_update/utils.py @@ -0,0 +1,31 @@ +import os +import subprocess +import sys +from pathlib import Path +from typing import IO, Any, Callable, List, Optional, Union + +HAS_TTY = sys.stdout.isatty() +ROOT = Path(os.path.dirname(os.path.realpath(__file__))) + + +def color_text(code: int, file: IO[Any] = sys.stdout) -> Callable[[str], None]: + def wrapper(text: str) -> None: + if HAS_TTY: + print(f"\x1b[{code}m{text}\x1b[0m", file=file) + else: + print(text, file=file) + + return wrapper + + +warn = color_text(31, file=sys.stderr) +info = color_text(32) + + +def run( + command: List[str], + cwd: Optional[Union[Path, str]] = None, + stdout: Union[None, int, IO[Any]] = subprocess.PIPE, +) -> subprocess.CompletedProcess: + info("$ " + " ".join(command)) + return subprocess.run(command, cwd=cwd, check=True, text=True, stdout=stdout) diff --git a/nix_update/version.py b/nix_update/version.py new file mode 100644 index 0000000..f979de5 --- /dev/null +++ b/nix_update/version.py @@ -0,0 +1,67 @@ +import urllib.request +import xml.etree.ElementTree as ET +from urllib.parse import urlparse, ParseResult +import json + +from .errors import VersionError + + +def fetch_latest_github_version(url: ParseResult) -> str: + parts = url.path.split("/") + owner, repo = parts[1], parts[2] + # TODO fallback to tags? + resp = urllib.request.urlopen(f"https://github.com/{owner}/{repo}/releases.atom") + tree = ET.fromstring(resp.read()) + release = tree.find(".//{http://www.w3.org/2005/Atom}entry") + if release is None: + raise VersionError("No release found") + link = release.find("{http://www.w3.org/2005/Atom}link") + assert link is not None + href = link.attrib["href"] + url = urlparse(href) + return url.path.split("/")[-1] + + +def fetch_latest_pypi_version(url: ParseResult) -> str: + parts = url.path.split("/") + package = parts[2] + resp = urllib.request.urlopen(f"https://pypi.org/pypi/{package}/json") + data = json.loads(resp.read()) + return data["info"]["version"] + + +def fetch_latest_gitlab_version(url: ParseResult) -> str: + parts = url.path.split("/") + project_id = parts[4] + resp = urllib.request.urlopen( + f"https://gitlab.com/api/v4/projects/{project_id}/repository/tags" + ) + data = json.loads(resp.read()) + if len(data) == 0: + raise VersionError("No git tags found") + return data[0]["name"] + + +# def find_repology_release(attr) -> str: +# resp = urllib.request.urlopen(f"https://repology.org/api/v1/projects/{attr}/") +# data = json.loads(resp.read()) +# for name, pkg in data.items(): +# for repo in pkg: +# if repo["status"] == "newest": +# return repo["version"] +# return None + + +def fetch_latest_version(url_str: str) -> str: + url = urlparse(url_str) + + if url.netloc == "pypi": + return fetch_latest_pypi_version(url) + elif url.netloc == "github.com": + return fetch_latest_github_version(url) + elif url.netloc == "gitlab.com": + return fetch_latest_gitlab_version(url) + else: + raise VersionError( + "Please specify the version. We can only get the latest version from github/pypi projects right now" + ) diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..4dcac68 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,60 @@ +[metadata] +name = nix-update +version = 0.0.0 +author = Jörg Thalheim +author-email = joerg@thalheim.io +home-page = https://github.com/Mic92/nix-update +description = Update Nix packages like it is 2020 +long-description = file: README.rst +license = MIT +license-file = LICENSE.rst +platform = any +classifiers = + Development Status :: 5 - Production/Stable + Environment :: Console + Topic :: Utilities + License :: OSI Approved :: MIT License + Operating System :: OS Independent + Programming Language :: Python + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 + +[options] +zip_safe = true +include_package_data = true +python_requires = >= 3.6 +packages = nix_update +setup_requires = + setuptools + +[options.entry_points] +console_scripts = + nix-update = nix_update:main + +[bdist_wheel] +universal = true + +[check] +metadata = true +restructuredtext = true +strict = true[wheel] +universal = 1 + +[pycodestyle] +max-line-length = 88 +ignore = E501,E741,W503 + +[flake8] +max-line-length = 88 +ignore = E501,E741,W503 +exclude = .git,__pycache__,docs/source/conf.py,old,build,dist + +[mypy] +warn_redundant_casts = true +disallow_untyped_calls = true +disallow_untyped_defs = true +no_implicit_optional = true + +[mypy-setuptools.*] +ignore_missing_imports = True \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100755 index 0000000..beda28e --- /dev/null +++ b/setup.py @@ -0,0 +1,5 @@ +#!/usr/bin/env python + +from setuptools import setup + +setup()