make it a proper python/nix package

This commit is contained in:
Jörg Thalheim 2020-03-16 10:06:32 +00:00
parent 5e79543a6a
commit f341d1e982
No known key found for this signature in database
GPG Key ID: 003F2096411B5F92
14 changed files with 505 additions and 243 deletions

107
.gitignore vendored Normal file
View File

@ -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

7
LICENSE.rst Normal file
View File

@ -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.

View File

@ -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

38
README.rst Normal file
View File

@ -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 <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
::
$ 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

10
bin/nix-update Executable file
View File

@ -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()

26
default.nix Normal file
View File

@ -0,0 +1,26 @@
{ pkgs ? import <nixpkgs> {} }:
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; };
}

View File

@ -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()

52
nix_update/__init__.py Executable file
View File

@ -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()

6
nix_update/errors.py Normal file
View File

@ -0,0 +1,6 @@
class UpdateError(Exception):
pass
class VersionError(UpdateError):
pass

96
nix_update/update.py Normal file
View File

@ -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"])

31
nix_update/utils.py Normal file
View File

@ -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)

67
nix_update/version.py Normal file
View File

@ -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"
)

60
setup.cfg Normal file
View File

@ -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

5
setup.py Executable file
View File

@ -0,0 +1,5 @@
#!/usr/bin/env python
from setuptools import setup
setup()