poetry2nix: 1.7.1 -> 1.8.0

This commit is contained in:
adisbladis 2020-05-05 21:20:44 +01:00
parent 4ad2e1c92e
commit 36debc367e
No known key found for this signature in database
GPG Key ID: 110BFAD44C6249B7
13 changed files with 1328 additions and 1022 deletions

View File

@ -1,4 +1,4 @@
{ pkgs ? import <nixpkgs> {} { pkgs ? import <nixpkgs> { }
, lib ? pkgs.lib , lib ? pkgs.lib
, version , version
}: }:
@ -33,8 +33,8 @@ pkgs.stdenv.mkDerivation {
mv poetry2nix $out/bin mv poetry2nix $out/bin
wrapProgram $out/bin/poetry2nix --prefix PATH ":" ${lib.makeBinPath [ wrapProgram $out/bin/poetry2nix --prefix PATH ":" ${lib.makeBinPath [
pkgs.nix-prefetch-git pkgs.nix-prefetch-git
]} ]}
runHook postInstall runHook postInstall
''; '';

View File

@ -1,22 +1,20 @@
{ pkgs ? import <nixpkgs> {} { pkgs ? import <nixpkgs> { }
, lib ? pkgs.lib , lib ? pkgs.lib
, poetry ? null , poetry ? null
, poetryLib ? import ./lib.nix { inherit lib pkgs; } , poetryLib ? import ./lib.nix { inherit lib pkgs; }
}: }:
let let
inherit (poetryLib) isCompatible readTOML; inherit (poetryLib) isCompatible readTOML moduleName;
# Poetry2nix version # Poetry2nix version
version = "1.7.1"; version = "1.8.0";
/* The default list of poetry2nix override overlays */ /* The default list of poetry2nix override overlays */
defaultPoetryOverrides = (import ./overrides.nix { inherit pkgs lib; }); defaultPoetryOverrides = (import ./overrides.nix { inherit pkgs lib; });
mkEvalPep508 = import ./pep508.nix { mkEvalPep508 = import ./pep508.nix {
inherit lib poetryLib; inherit lib poetryLib;
stdenv = pkgs.stdenv; stdenv = pkgs.stdenv;
}; };
getFunctorFn = fn: if builtins.typeOf fn == "set" then fn.__functor else fn; getFunctorFn = fn: if builtins.typeOf fn == "set" then fn.__functor else fn;
# Map SPDX identifiers to license names # Map SPDX identifiers to license names
@ -34,95 +32,99 @@ let
, overrides ? [ defaultPoetryOverrides ] , overrides ? [ defaultPoetryOverrides ]
, python ? pkgs.python3 , python ? pkgs.python3
, pwd ? projectDir , pwd ? projectDir
, preferWheels ? false
}@attrs: }@attrs:
let let
poetryPkg = poetry.override { inherit python; }; poetryPkg = poetry.override { inherit python; };
pyProject = readTOML pyproject;
poetryLock = readTOML poetrylock;
lockFiles =
let
lockfiles = lib.getAttrFromPath [ "metadata" "files" ] poetryLock;
in
lib.listToAttrs (lib.mapAttrsToList (n: v: { name = moduleName n; value = v; }) lockfiles);
specialAttrs = [
"overrides"
"poetrylock"
"projectDir"
"pwd"
"preferWheels"
];
passedAttrs = builtins.removeAttrs attrs specialAttrs;
evalPep508 = mkEvalPep508 python;
pyProject = readTOML pyproject; # Filter packages by their PEP508 markers & pyproject interpreter version
poetryLock = readTOML poetrylock; partitions =
lockFiles = lib.getAttrFromPath [ "metadata" "files" ] poetryLock; let
specialAttrs = [
"overrides"
"poetrylock"
"projectDir"
"pwd"
];
passedAttrs = builtins.removeAttrs attrs specialAttrs;
evalPep508 = mkEvalPep508 python;
# Filter packages by their PEP508 markers & pyproject interpreter version
partitions = let
supportsPythonVersion = pkgMeta: if pkgMeta ? marker then (evalPep508 pkgMeta.marker) else true; supportsPythonVersion = pkgMeta: if pkgMeta ? marker then (evalPep508 pkgMeta.marker) else true;
in in
lib.partition supportsPythonVersion poetryLock.package; lib.partition supportsPythonVersion poetryLock.package;
compatible = partitions.right;
incompatible = partitions.wrong;
compatible = partitions.right; # Create an overriden version of pythonPackages
incompatible = partitions.wrong; #
# We need to avoid mixing multiple versions of pythonPackages in the same
# Create an overriden version of pythonPackages # closure as python can only ever have one version of a dependency
# baseOverlay = self: super:
# We need to avoid mixing multiple versions of pythonPackages in the same let
# closure as python can only ever have one version of a dependency getDep = depName: self.${depName};
baseOverlay = self: super: lockPkgs = builtins.listToAttrs
let (
getDep = depName: self.${depName}; builtins.map
(
lockPkgs = builtins.listToAttrs ( pkgMeta: rec {
builtins.map ( name = moduleName pkgMeta.name;
pkgMeta: rec { value = self.mkPoetryDep
name = pkgMeta.name; (
value = self.mkPoetryDep ( pkgMeta // {
pkgMeta // { inherit pwd preferWheels;
inherit pwd; source = pkgMeta.source or null;
source = pkgMeta.source or null; files = lockFiles.${name};
files = lockFiles.${name}; pythonPackages = self;
pythonPackages = self; sourceSpec = pyProject.tool.poetry.dependencies.${name} or pyProject.tool.poetry.dev-dependencies.${name};
sourceSpec = pyProject.tool.poetry.dependencies.${name} or pyProject.tool.poetry.dev-dependencies.${name}; }
} );
); }
} ) compatible
) compatible
); );
in in
lockPkgs; lockPkgs;
overlays = builtins.map getFunctorFn ( overlays = builtins.map getFunctorFn
(
[ [
( (
self: super: self: super:
let let
hooks = self.callPackage ./hooks {}; hooks = self.callPackage ./hooks { };
in in
{ {
mkPoetryDep = self.callPackage ./mk-poetry-dep.nix { mkPoetryDep = self.callPackage ./mk-poetry-dep.nix {
inherit pkgs lib python poetryLib; inherit pkgs lib python poetryLib;
}; };
poetry = poetryPkg; poetry = poetryPkg;
# The canonical name is setuptools-scm # The canonical name is setuptools-scm
setuptools-scm = super.setuptools_scm; setuptools-scm = super.setuptools_scm;
inherit (hooks) removePathDependenciesHook poetry2nixFixupHook; inherit (hooks) pipBuildHook removePathDependenciesHook poetry2nixFixupHook;
} }
) )
# Null out any filtered packages, we don't want python.pkgs from nixpkgs # Null out any filtered packages, we don't want python.pkgs from nixpkgs
(self: super: builtins.listToAttrs (builtins.map (x: { name = x.name; value = null; }) incompatible)) (self: super: builtins.listToAttrs (builtins.map (x: { name = moduleName x.name; value = null; }) incompatible))
# Create poetry2nix layer # Create poetry2nix layer
baseOverlay baseOverlay
] ++ # User provided overrides ] ++ # User provided overrides
overrides overrides
); );
packageOverrides = lib.foldr lib.composeExtensions (self: super: { }) overlays;
packageOverrides = lib.foldr lib.composeExtensions (self: super: {}) overlays; py = python.override { inherit packageOverrides; self = py; };
in
py = python.override { inherit packageOverrides; self = py; }; {
in python = py;
{ poetryPackages = map (pkg: py.pkgs.${moduleName pkg.name}) compatible;
python = py; poetryLock = poetryLock;
poetryPackages = map (pkg: py.pkgs.${pkg.name}) compatible; inherit pyProject;
poetryLock = poetryLock; };
inherit pyProject;
};
/* Returns a package with a python interpreter and all packages specified in the poetry.lock lock file. /* Returns a package with a python interpreter and all packages specified in the poetry.lock lock file.
@ -136,15 +138,17 @@ let
, overrides ? [ defaultPoetryOverrides ] , overrides ? [ defaultPoetryOverrides ]
, pwd ? projectDir , pwd ? projectDir
, python ? pkgs.python3 , python ? pkgs.python3
, preferWheels ? false
}: }:
let let
py = mkPoetryPackages ( py = mkPoetryPackages
(
{ {
inherit pyproject poetrylock overrides python pwd; inherit pyproject poetrylock overrides python pwd preferWheels;
} }
); );
in in
py.python.withPackages (_: py.poetryPackages); py.python.withPackages (_: py.poetryPackages);
/* Creates a Python application from pyproject.toml and poetry.lock */ /* Creates a Python application from pyproject.toml and poetry.lock */
mkPoetryApplication = mkPoetryApplication =
@ -153,79 +157,79 @@ let
, pyproject ? projectDir + "/pyproject.toml" , pyproject ? projectDir + "/pyproject.toml"
, poetrylock ? projectDir + "/poetry.lock" , poetrylock ? projectDir + "/poetry.lock"
, overrides ? [ defaultPoetryOverrides ] , overrides ? [ defaultPoetryOverrides ]
, meta ? {} , meta ? { }
, python ? pkgs.python3 , python ? pkgs.python3
, pwd ? projectDir , pwd ? projectDir
, preferWheels ? false
, ... , ...
}@attrs: }@attrs:
let let
poetryPython = mkPoetryPackages { poetryPython = mkPoetryPackages {
inherit pyproject poetrylock overrides python pwd; inherit pyproject poetrylock overrides python pwd preferWheels;
}; };
py = poetryPython.python; py = poetryPython.python;
inherit (poetryPython) pyProject; inherit (poetryPython) pyProject;
specialAttrs = [
"overrides"
"poetrylock"
"projectDir"
"pwd"
"pyproject"
"preferWheels"
];
passedAttrs = builtins.removeAttrs attrs specialAttrs;
specialAttrs = [ # Get dependencies and filter out depending on interpreter version
"overrides" getDeps = depAttr:
"poetrylock" let
"projectDir" compat = isCompatible (poetryLib.getPythonVersion py);
"pwd" deps = pyProject.tool.poetry.${depAttr} or { };
"pyproject" depAttrs = builtins.map (d: lib.toLower d) (builtins.attrNames deps);
]; in
passedAttrs = builtins.removeAttrs attrs specialAttrs; builtins.map
(
dep:
let
pkg = py.pkgs."${dep}";
constraints = deps.${dep}.python or "";
isCompat = compat constraints;
in if isCompat then pkg else null
) depAttrs;
getInputs = attr: attrs.${attr} or [ ];
mkInput = attr: extraInputs: getInputs attr ++ extraInputs;
buildSystemPkgs = poetryLib.getBuildSystemPkgs {
inherit pyProject;
pythonPackages = py.pkgs;
};
in
py.pkgs.buildPythonApplication
(
passedAttrs // {
pname = moduleName pyProject.tool.poetry.name;
version = pyProject.tool.poetry.version;
# Get dependencies and filter out depending on interpreter version inherit src;
getDeps = depAttr:
let
compat = isCompatible py.pythonVersion;
deps = pyProject.tool.poetry.${depAttr} or {};
depAttrs = builtins.map (d: lib.toLower d) (builtins.attrNames deps);
in
builtins.map (
dep:
let
pkg = py.pkgs."${dep}";
constraints = deps.${dep}.python or "";
isCompat = compat constraints;
in
if isCompat then pkg else null
) depAttrs;
getInputs = attr: attrs.${attr} or []; format = "pyproject";
mkInput = attr: extraInputs: getInputs attr ++ extraInputs;
buildSystemPkgs = poetryLib.getBuildSystemPkgs { buildInputs = mkInput "buildInputs" buildSystemPkgs;
inherit pyProject; propagatedBuildInputs = mkInput "propagatedBuildInputs" (getDeps "dependencies") ++ ([ py.pkgs.setuptools ]);
pythonPackages = py.pkgs; nativeBuildInputs = mkInput "nativeBuildInputs" [ pkgs.yj py.pkgs.removePathDependenciesHook ];
}; checkInputs = mkInput "checkInputs" (getDeps "dev-dependencies");
in
py.pkgs.buildPythonApplication (
passedAttrs // {
pname = pyProject.tool.poetry.name;
version = pyProject.tool.poetry.version;
inherit src; passthru = {
python = py;
};
format = "pyproject"; meta = meta // {
inherit (pyProject.tool.poetry) description homepage;
inherit (py.meta) platforms;
license = getLicenseBySpdxId (pyProject.tool.poetry.license or "unknown");
};
buildInputs = mkInput "buildInputs" buildSystemPkgs; }
propagatedBuildInputs = mkInput "propagatedBuildInputs" (getDeps "dependencies") ++ ([ py.pkgs.setuptools ]); );
nativeBuildInputs = mkInput "nativeBuildInputs" [ pkgs.yj py.pkgs.removePathDependenciesHook ];
checkInputs = mkInput "checkInputs" (getDeps "dev-dependencies");
passthru = {
python = py;
};
meta = meta // {
inherit (pyProject.tool.poetry) description homepage;
inherit (py.meta) platforms;
license = getLicenseBySpdxId (pyProject.tool.poetry.license or "unknown");
};
}
);
/* Poetry2nix CLI used to supplement SHA-256 hashes for git dependencies */ /* Poetry2nix CLI used to supplement SHA-256 hashes for git dependencies */
cli = import ./cli.nix { inherit pkgs lib version; }; cli = import ./cli.nix { inherit pkgs lib version; };
@ -247,7 +251,7 @@ in
defaultSet = defaultPoetryOverrides self super; defaultSet = defaultPoetryOverrides self super;
customSet = fn self super; customSet = fn self super;
in in
defaultSet // customSet; defaultSet // customSet;
}; };
/* /*

View File

@ -0,0 +1,24 @@
source $stdenv/setup
set -euo pipefail
curl="curl \
--location \
--max-redirs 20 \
--retry 2 \
--disable-epsv \
--cookie-jar cookies \
--insecure \
--speed-time 5 \
-# \
--fail \
$curlOpts \
$NIX_CURL_FLAGS"
echo "Trying to fetch wheel with predicted URL: $predictedURL"
$curl $predictedURL --output $out && exit 0
echo "Predicted URL '$predictedURL' failed, querying pypi.org"
$curl "https://pypi.org/pypi/$pname/json" | jq -r ".releases.\"$version\"[] | select(.filename == \"$file\") | .url" > url
url=$(cat url)
$curl -k $url --output $out

View File

@ -2,31 +2,48 @@
, callPackage , callPackage
, makeSetupHook , makeSetupHook
, yj , yj
, wheel
, pip
}: }:
let let
pythonInterpreter = python.pythonForBuild.interpreter; pythonInterpreter = python.pythonForBuild.interpreter;
pythonSitePackages = python.sitePackages;
in in
{ {
removePathDependenciesHook = callPackage ( removePathDependenciesHook = callPackage
{}: (
{}:
makeSetupHook { makeSetupHook {
name = "remove-path-dependencies.sh"; name = "remove-path-dependencies.sh";
deps = []; deps = [ ];
substitutions = { substitutions = {
inherit pythonInterpreter; inherit pythonInterpreter;
yj = "${yj}/bin/yj"; yj = "${yj}/bin/yj";
pyprojectPatchScript = "${./pyproject-without-path.py}"; pyprojectPatchScript = "${./pyproject-without-path.py}";
}; };
} ./remove-path-dependencies.sh } ./remove-path-dependencies.sh
) {}; ) { };
poetry2nixFixupHook = callPackage ( pipBuildHook = callPackage
{}: (
{ pip, wheel }:
makeSetupHook {
name = "pip-build-hook.sh";
deps = [ pip wheel ];
substitutions = {
inherit pythonInterpreter pythonSitePackages;
};
} ./pip-build-hook.sh
) { };
poetry2nixFixupHook = callPackage
(
{}:
makeSetupHook { makeSetupHook {
name = "fixup-hook.sh"; name = "fixup-hook.sh";
deps = []; deps = [ ];
} ./fixup-hook.sh } ./fixup-hook.sh
) {}; ) { };
} }

View File

@ -0,0 +1,50 @@
# Setup hook to use for pip projects
echo "Sourcing pip-build-hook"
pipBuildPhase() {
echo "Executing pipBuildPhase"
runHook preBuild
# Prefer using setup.py to avoid build-system dependencies if we have a setup.py
if [ -z "${dontPreferSetupPy-}" ]; then
if test -e setup.py && test -e pyproject.toml; then
echo "Removing pyproject.toml..."
rm -f pyproject.toml
fi
fi
mkdir -p dist
echo "Creating a wheel..."
@pythonInterpreter@ -m pip wheel --no-index --no-deps --no-clean --no-build-isolation --wheel-dir dist .
echo "Finished creating a wheel..."
runHook postBuild
echo "Finished executing pipBuildPhase"
}
pipShellHook() {
echo "Executing pipShellHook"
runHook preShellHook
# Long-term setup.py should be dropped.
if [ -e pyproject.toml ]; then
tmp_path=$(mktemp -d)
export PATH="$tmp_path/bin:$PATH"
export PYTHONPATH="$tmp_path/@pythonSitePackages@:$PYTHONPATH"
mkdir -p "$tmp_path/@pythonSitePackages@"
@pythonInterpreter@ -m pip install -e . --prefix "$tmp_path" >&2
fi
runHook postShellHook
echo "Finished executing pipShellHook"
}
if [ -z "${dontUsePipBuild-}" ] && [ -z "${buildPhase-}" ]; then
echo "Using pipBuildPhase"
buildPhase=pipBuildPhase
fi
if [ -z "${shellHook-}" ]; then
echo "Using pipShellHook"
shellHook=pipShellHook
fi

View File

@ -6,7 +6,14 @@ import sys
data = json.load(sys.stdin) data = json.load(sys.stdin)
for dep in data['tool']['poetry']['dependencies'].values():
def get_deep(o, path):
for p in path.split('.'):
o = o.get(p, {})
return o
for dep in get_deep(data, 'tool.poetry.dependencies').values():
if isinstance(dep, dict): if isinstance(dep, dict):
try: try:
del dep['path']; del dep['path'];

View File

@ -8,6 +8,20 @@ let
genList (i: if i == idx then value else (builtins.elemAt list i)) (length list) genList (i: if i == idx then value else (builtins.elemAt list i)) (length list)
); );
# Do some canonicalisation of module names
moduleName = name: lib.toLower (lib.replaceStrings [ "_" "." ] [ "-" "-" ] name);
# Get a full semver pythonVersion from a python derivation
getPythonVersion = python:
let
pyVer = lib.splitVersion python.pythonVersion ++ [ "0" ];
ver = lib.splitVersion python.version;
major = l: lib.elemAt l 0;
minor = l: lib.elemAt l 1;
joinVersion = v: lib.concatStringsSep "." v;
in
joinVersion ( if major pyVer == major ver && minor pyVer == minor ver then ver else pyVer);
# Compare a semver expression with a version # Compare a semver expression with a version
isCompatible = version: isCompatible = version:
let let
@ -18,41 +32,41 @@ let
}; };
splitRe = "(" + (builtins.concatStringsSep "|" (builtins.map (x: lib.replaceStrings [ "|" ] [ "\\|" ] x) (lib.attrNames operators))) + ")"; splitRe = "(" + (builtins.concatStringsSep "|" (builtins.map (x: lib.replaceStrings [ "|" ] [ "\\|" ] x) (lib.attrNames operators))) + ")";
in in
expr: expr:
let
tokens = builtins.filter (x: x != "") (builtins.split splitRe expr);
combine = acc: v:
let let
tokens = builtins.filter (x: x != "") (builtins.split splitRe expr); isOperator = builtins.typeOf v == "list";
combine = acc: v: operator = if isOperator then (builtins.elemAt v 0) else acc.operator;
let
isOperator = builtins.typeOf v == "list";
operator = if isOperator then (builtins.elemAt v 0) else acc.operator;
in
if isOperator then (acc // { inherit operator; }) else {
inherit operator;
state = operators."${operator}" acc.state (satisfiesSemver version v);
};
initial = { operator = "&&"; state = true; };
in in
if expr == "" then true else (builtins.foldl' combine initial tokens).state; if isOperator then (acc // { inherit operator; }) else {
inherit operator;
state = operators."${operator}" acc.state (satisfiesSemver version v);
};
initial = { operator = "&&"; state = true; };
in if expr == "" then true else (builtins.foldl' combine initial tokens).state;
fromTOML = builtins.fromTOML or fromTOML = builtins.fromTOML or
( (
toml: builtins.fromJSON ( toml: builtins.fromJSON
builtins.readFile ( (
pkgs.runCommand "from-toml" builtins.readFile
{ (
inherit toml; pkgs.runCommand "from-toml"
allowSubstitutes = false; {
preferLocalBuild = true; inherit toml;
} allowSubstitutes = false;
'' preferLocalBuild = true;
${pkgs.remarshal}/bin/remarshal \ }
-if toml \ ''
-i <(echo "$toml") \ ${pkgs.remarshal}/bin/remarshal \
-of json \ -if toml \
-o $out -i <(echo "$toml") \
'' -of json \
-o $out
''
)
) )
)
); );
readTOML = path: fromTOML (builtins.readFile path); readTOML = path: fromTOML (builtins.readFile path);
@ -63,10 +77,61 @@ let
let let
ml = pkgs.pythonManylinuxPackages; ml = pkgs.pythonManylinuxPackages;
in in
if lib.strings.hasInfix "manylinux1" f then { pkg = [ ml.manylinux1 ]; str = "1"; } if lib.strings.hasInfix "manylinux1" f then { pkg = [ ml.manylinux1 ]; str = "1"; }
else if lib.strings.hasInfix "manylinux2010" f then { pkg = [ ml.manylinux2010 ]; str = "2010"; } else if lib.strings.hasInfix "manylinux2010" f then { pkg = [ ml.manylinux2010 ]; str = "2010"; }
else if lib.strings.hasInfix "manylinux2014" f then { pkg = [ ml.manylinux2014 ]; str = "2014"; } else if lib.strings.hasInfix "manylinux2014" f then { pkg = [ ml.manylinux2014 ]; str = "2014"; }
else { pkg = []; str = null; }; else { pkg = [ ]; str = null; };
# Predict URL from the PyPI index.
# Args:
# pname: package name
# file: filename including extension
# hash: SRI hash
# kind: Language implementation and version tag
predictURLFromPypi = lib.makeOverridable
(
{ pname, file, hash, kind }:
"https://files.pythonhosted.org/packages/${kind}/${lib.toLower (builtins.substring 0 1 file)}/${pname}/${file}"
);
# Fetch the wheels from the PyPI index.
# We need to first get the proper URL to the wheel.
# Args:
# pname: package name
# file: filename including extension
# hash: SRI hash
# kind: Language implementation and version tag
fetchWheelFromPypi = lib.makeOverridable
(
{ pname, file, hash, kind, curlOpts ? "" }:
let
version = builtins.elemAt (builtins.split "-" file) 2;
in
(pkgs.stdenvNoCC.mkDerivation {
name = file;
nativeBuildInputs = [
pkgs.curl
pkgs.jq
];
isWheel = true;
system = "builtin";
preferLocalBuild = true;
impureEnvVars = lib.fetchers.proxyImpureEnvVars ++ [
"NIX_CURL_FLAGS"
];
predictedURL = predictURLFromPypi { inherit pname file hash kind; };
inherit pname file version curlOpts;
builder = ./fetch-wheel.sh;
outputHashMode = "flat";
outputHashAlgo = "sha256";
outputHash = hash;
})
);
# Fetch the artifacts from the PyPI index. Since we get all # Fetch the artifacts from the PyPI index. Since we get all
# info we need from the lock file we don't use nixpkgs' fetchPyPi # info we need from the lock file we don't use nixpkgs' fetchPyPi
@ -78,25 +143,27 @@ let
# file: filename including extension # file: filename including extension
# hash: SRI hash # hash: SRI hash
# kind: Language implementation and version tag https://www.python.org/dev/peps/pep-0427/#file-name-convention # kind: Language implementation and version tag https://www.python.org/dev/peps/pep-0427/#file-name-convention
fetchFromPypi = lib.makeOverridable ( fetchFromPypi = lib.makeOverridable
{ pname, file, hash, kind }: (
pkgs.fetchurl { { pname, file, hash, kind }:
url = "https://files.pythonhosted.org/packages/${kind}/${lib.toLower (builtins.substring 0 1 file)}/${pname}/${file}"; if lib.strings.hasSuffix "whl" file then fetchWheelFromPypi { inherit pname file hash kind; }
inherit hash; else
} pkgs.fetchurl {
); url = predictURLFromPypi { inherit pname file hash kind; };
inherit hash;
}
);
getBuildSystemPkgs = getBuildSystemPkgs =
{ pythonPackages { pythonPackages
, pyProject , pyProject
}: }:
let let
buildSystem = lib.getAttrFromPath [ "build-system" "build-backend" ] pyProject; buildSystem = lib.attrByPath [ "build-system" "build-backend" ] "" pyProject;
drvAttr = builtins.elemAt (builtins.split "\\.|:" buildSystem) 0; drvAttr = moduleName (builtins.elemAt (builtins.split "\\.|:" buildSystem) 0);
in in
if buildSystem == "" then [] else ( if buildSystem == "" then [ ] else (
[ pythonPackages.${drvAttr} or (throw "unsupported build system ${buildSystem}") ] [ pythonPackages.${drvAttr} or (throw "unsupported build system ${buildSystem}") ]
); );
# Find gitignore files recursively in parent directory stopping with .git # Find gitignore files recursively in parent directory stopping with .git
findGitIgnores = path: findGitIgnores = path:
@ -105,9 +172,9 @@ let
gitIgnore = path + "/.gitignore"; gitIgnore = path + "/.gitignore";
isGitRoot = builtins.pathExists (path + "/.git"); isGitRoot = builtins.pathExists (path + "/.git");
hasGitIgnore = builtins.pathExists gitIgnore; hasGitIgnore = builtins.pathExists gitIgnore;
gitIgnores = if hasGitIgnore then [ gitIgnore ] else []; gitIgnores = if hasGitIgnore then [ gitIgnore ] else [ ];
in in
lib.optionals (builtins.toString path != "/" && ! isGitRoot) (findGitIgnores parent) ++ gitIgnores; lib.optionals (builtins.toString path != "/" && ! isGitRoot) (findGitIgnores parent) ++ gitIgnores;
/* /*
Provides a source filtering mechanism that: Provides a source filtering mechanism that:
@ -124,22 +191,25 @@ let
|| (type == "regular" && ! lib.strings.hasSuffix ".pyc" name) || (type == "regular" && ! lib.strings.hasSuffix ".pyc" name)
; ;
in in
lib.cleanSourceWith { lib.cleanSourceWith {
filter = lib.cleanSourceFilter; filter = lib.cleanSourceFilter;
src = lib.cleanSourceWith { src = lib.cleanSourceWith {
filter = pkgs.nix-gitignore.gitignoreFilterPure pycacheFilter gitIgnores src; filter = pkgs.nix-gitignore.gitignoreFilterPure pycacheFilter gitIgnores src;
inherit src; inherit src;
};
}; };
};
in in
{ {
inherit inherit
fetchFromPypi fetchFromPypi
fetchWheelFromPypi
getManyLinuxDeps getManyLinuxDeps
isCompatible isCompatible
readTOML readTOML
getBuildSystemPkgs getBuildSystemPkgs
satisfiesSemver satisfiesSemver
cleanPythonSources cleanPythonSources
moduleName
getPythonVersion
; ;
} }

View File

@ -10,74 +10,68 @@
, version , version
, files , files
, source , source
, dependencies ? {} , dependencies ? { }
, pythonPackages , pythonPackages
, python-versions , python-versions
, pwd , pwd
, sourceSpec , sourceSpec
, supportedExtensions ? lib.importJSON ./extensions.json , supportedExtensions ? lib.importJSON ./extensions.json
, preferWheels ? false
, ... , ...
}: }:
pythonPackages.callPackage ( pythonPackages.callPackage
{ preferWheel ? false (
, ... { preferWheel ? preferWheels
}@args: , ...
}@args:
let let
inherit (poetryLib) isCompatible getManyLinuxDeps fetchFromPypi; inherit (poetryLib) isCompatible getManyLinuxDeps fetchFromPypi moduleName;
inherit (import ./pep425.nix { inherit (import ./pep425.nix {
inherit lib python; inherit lib python;
inherit (pkgs) stdenv; inherit (pkgs) stdenv;
}) selectWheel }) selectWheel
; ;
fileCandidates =
fileCandidates = let let
supportedRegex = ("^.*?(" + builtins.concatStringsSep "|" supportedExtensions + ")"); supportedRegex = ("^.*?(" + builtins.concatStringsSep "|" supportedExtensions + ")");
matchesVersion = fname: builtins.match ("^.*" + builtins.replaceStrings [ "." ] [ "\\." ] version + ".*$") fname != null; matchesVersion = fname: builtins.match ("^.*" + builtins.replaceStrings [ "." ] [ "\\." ] version + ".*$") fname != null;
hasSupportedExtension = fname: builtins.match supportedRegex fname != null; hasSupportedExtension = fname: builtins.match supportedRegex fname != null;
isCompatibleEgg = fname: ! lib.strings.hasSuffix ".egg" fname || lib.strings.hasSuffix "py${python.pythonVersion}.egg" fname; isCompatibleEgg = fname: ! lib.strings.hasSuffix ".egg" fname || lib.strings.hasSuffix "py${python.pythonVersion}.egg" fname;
in in
builtins.filter (f: matchesVersion f.file && hasSupportedExtension f.file && isCompatibleEgg f.file) files; builtins.filter (f: matchesVersion f.file && hasSupportedExtension f.file && isCompatibleEgg f.file) files;
toPath = s: pwd + "/${s}"; toPath = s: pwd + "/${s}";
isSource = source != null; isSource = source != null;
isGit = isSource && source.type == "git"; isGit = isSource && source.type == "git";
isLocal = isSource && source.type == "directory"; isLocal = isSource && source.type == "directory";
localDepPath = toPath source.url; localDepPath = toPath source.url;
pyProject = poetryLib.readTOML (localDepPath + "/pyproject.toml"); pyProject = poetryLib.readTOML (localDepPath + "/pyproject.toml");
buildSystemPkgs = poetryLib.getBuildSystemPkgs { buildSystemPkgs = poetryLib.getBuildSystemPkgs {
inherit pythonPackages pyProject; inherit pythonPackages pyProject;
}; };
fileInfo =
fileInfo = let let
isBdist = f: lib.strings.hasSuffix "whl" f.file; isBdist = f: lib.strings.hasSuffix "whl" f.file;
isSdist = f: ! isBdist f && ! isEgg f; isSdist = f: ! isBdist f && ! isEgg f;
isEgg = f: lib.strings.hasSuffix ".egg" f.file; isEgg = f: lib.strings.hasSuffix ".egg" f.file;
binaryDist = selectWheel fileCandidates;
binaryDist = selectWheel fileCandidates; sourceDist = builtins.filter isSdist fileCandidates;
sourceDist = builtins.filter isSdist fileCandidates; eggs = builtins.filter isEgg fileCandidates;
eggs = builtins.filter isEgg fileCandidates; entries = ( if preferWheel then binaryDist ++ sourceDist else sourceDist ++ binaryDist) ++ eggs;
lockFileEntry = builtins.head entries;
entries = (if preferWheel then binaryDist ++ sourceDist else sourceDist ++ binaryDist) ++ eggs; _isEgg = isEgg lockFileEntry;
in
lockFileEntry = builtins.head entries;
_isEgg = isEgg lockFileEntry;
in
rec { rec {
inherit (lockFileEntry) file hash; inherit (lockFileEntry) file hash;
name = file; name = file;
format = format =
if _isEgg then "egg" if _isEgg then "egg"
else if lib.strings.hasSuffix ".whl" name then "wheel" else if lib.strings.hasSuffix ".whl" name then "wheel"
else "setuptools"; else "pyproject";
kind = kind =
if _isEgg then python.pythonVersion if _isEgg then python.pythonVersion
else if format == "setuptools" then "source" else if format == "pyproject" then "source"
else (builtins.elemAt (lib.strings.splitString "-" name) 2); else (builtins.elemAt (lib.strings.splitString "-" name) 2);
}; };
@ -88,63 +82,65 @@ pythonPackages.callPackage (
"toml" # Toml is an extra for setuptools-scm "toml" # Toml is an extra for setuptools-scm
]; ];
baseBuildInputs = lib.optional (! lib.elem name skipSetupToolsSCM) pythonPackages.setuptools-scm; baseBuildInputs = lib.optional (! lib.elem name skipSetupToolsSCM) pythonPackages.setuptools-scm;
format = if isLocal then "pyproject" else if isGit then "pyproject" else fileInfo.format;
format = if isLocal then "pyproject" else if isGit then "setuptools" else fileInfo.format;
in in
buildPythonPackage {
pname = moduleName name;
version = version;
buildPythonPackage { inherit format;
pname = name;
version = version;
inherit format; doCheck = false; # We never get development deps
doCheck = false; # We never get development deps # Stripping pre-built wheels lead to `ELF load command address/offset not properly aligned`
dontStrip = format == "wheel";
# Stripping pre-built wheels lead to `ELF load command address/offset not properly aligned` nativeBuildInputs = [
dontStrip = format == "wheel"; pythonPackages.poetry2nixFixupHook
]
++ lib.optional (!isSource && (getManyLinuxDeps fileInfo.name).str != null) autoPatchelfHook
++ lib.optional (format == "pyproject") pythonPackages.removePathDependenciesHook
;
nativeBuildInputs = [ buildInputs = (
pythonPackages.poetry2nixFixupHook baseBuildInputs
] ++ lib.optional (!isSource) (getManyLinuxDeps fileInfo.name).pkg
++ lib.optional (!isSource && (getManyLinuxDeps fileInfo.name).str != null) autoPatchelfHook ++ lib.optional isLocal buildSystemPkgs
++ lib.optional (format == "pyproject") pythonPackages.removePathDependenciesHook );
;
buildInputs = ( propagatedBuildInputs =
baseBuildInputs let
++ lib.optional (!isSource) (getManyLinuxDeps fileInfo.name).pkg compat = isCompatible (poetryLib.getPythonVersion python);
++ lib.optional isLocal buildSystemPkgs deps = lib.filterAttrs (n: v: v)
); (
lib.mapAttrs
propagatedBuildInputs = let (
compat = isCompatible python.pythonVersion; n: v:
deps = lib.filterAttrs (n: v: v) ( let
lib.mapAttrs ( constraints = v.python or "";
n: v: in
let compat constraints
constraints = v.python or ""; ) dependencies
in );
compat constraints
) dependencies
);
depAttrs = lib.attrNames deps; depAttrs = lib.attrNames deps;
in in
builtins.map (n: pythonPackages.${lib.toLower n}) depAttrs; builtins.map (n: pythonPackages.${moduleName n}) depAttrs;
meta = { meta = {
broken = ! isCompatible python.pythonVersion python-versions; broken = ! isCompatible (poetryLib.getPythonVersion python) python-versions;
license = []; license = [ ];
inherit (python.meta) platforms; inherit (python.meta) platforms;
}; };
passthru = { passthru = {
inherit args; inherit args;
}; };
# We need to retrieve kind from the interpreter and the filename of the package # We need to retrieve kind from the interpreter and the filename of the package
# Interpreters should declare what wheel types they're compatible with (python type + ABI) # Interpreters should declare what wheel types they're compatible with (python type + ABI)
# Here we can then choose a file based on that info. # Here we can then choose a file based on that info.
src = if isGit then ( src =
if isGit then (
builtins.fetchGit { builtins.fetchGit {
inherit (source) url; inherit (source) url;
rev = source.reference; rev = source.reference;
@ -154,6 +150,5 @@ pythonPackages.callPackage (
pname = name; pname = name;
inherit (fileInfo) file hash kind; inherit (fileInfo) file hash kind;
}; };
} }
) { }
) {}

File diff suppressed because it is too large Load Diff

View File

@ -12,8 +12,7 @@ let
major = builtins.elemAt ver 0; major = builtins.elemAt ver 0;
minor = builtins.elemAt ver 1; minor = builtins.elemAt ver 1;
in in
"cp${major}${minor}"; "cp${major}${minor}";
abiTag = "${pythonTag}m"; abiTag = "${pythonTag}m";
# #
@ -24,13 +23,13 @@ let
entries = splitString "-" str; entries = splitString "-" str;
p = removeSuffix ".whl" (builtins.elemAt entries 4); p = removeSuffix ".whl" (builtins.elemAt entries 4);
in in
{ {
pkgName = builtins.elemAt entries 0; pkgName = builtins.elemAt entries 0;
pkgVer = builtins.elemAt entries 1; pkgVer = builtins.elemAt entries 1;
pyVer = builtins.elemAt entries 2; pyVer = builtins.elemAt entries 2;
abi = builtins.elemAt entries 3; abi = builtins.elemAt entries 3;
platform = p; platform = p;
}; };
# #
# Builds list of acceptable osx wheel files # Builds list of acceptable osx wheel files
@ -42,9 +41,9 @@ let
v = lib.lists.head versions; v = lib.lists.head versions;
vs = lib.lists.tail versions; vs = lib.lists.tail versions;
in in
if (builtins.length versions == 0) if (builtins.length versions == 0)
then [] then [ ]
else (builtins.filter (x: hasInfix v x.file) candidates) ++ (findBestMatches vs candidates); else (builtins.filter (x: hasInfix v x.file) candidates) ++ (findBestMatches vs candidates);
# pyver = "cpXX" # pyver = "cpXX"
# x = "cpXX" | "py2" | "py3" | "py2.py3" # x = "cpXX" | "py2" | "py3" | "py2.py3"
@ -53,7 +52,7 @@ let
normalize = y: ''cp${lib.strings.removePrefix "cp" (lib.strings.removePrefix "py" y)}''; normalize = y: ''cp${lib.strings.removePrefix "cp" (lib.strings.removePrefix "py" y)}'';
isCompat = p: x: lib.strings.hasPrefix (normalize x) p; isCompat = p: x: lib.strings.hasPrefix (normalize x) p;
in in
lib.lists.any (isCompat pyver) (lib.strings.splitString "." x); lib.lists.any (isCompat pyver) (lib.strings.splitString "." x);
# #
# Selects the best matching wheel file from a list of files # Selects the best matching wheel file from a list of files
@ -61,42 +60,37 @@ let
selectWheel = files: selectWheel = files:
let let
filesWithoutSources = (builtins.filter (x: hasSuffix ".whl" x.file) files); filesWithoutSources = (builtins.filter (x: hasSuffix ".whl" x.file) files);
isPyAbiCompatible = pyabi: x: x == "none" || pyabi == x; isPyAbiCompatible = pyabi: x: x == "none" || pyabi == x;
withPython = ver: abi: x: (isPyVersionCompatible ver x.pyVer) && (isPyAbiCompatible abi x.abi); withPython = ver: abi: x: (isPyVersionCompatible ver x.pyVer) && (isPyAbiCompatible abi x.abi);
withPlatform =
withPlatform = if isLinux if isLinux
then ( then (
x: x.platform == "manylinux1_${stdenv.platform.kernelArch}" x: x.platform == "manylinux1_${stdenv.platform.kernelArch}"
|| x.platform == "manylinux2010_${stdenv.platform.kernelArch}" || x.platform == "manylinux2010_${stdenv.platform.kernelArch}"
|| x.platform == "manylinux2014_${stdenv.platform.kernelArch}" || x.platform == "manylinux2014_${stdenv.platform.kernelArch}"
|| x.platform == "any" || x.platform == "any"
) )
else (x: hasInfix "macosx" x.platform || x.platform == "any"); else (x: hasInfix "macosx" x.platform || x.platform == "any");
filterWheel = x: filterWheel = x:
let let
f = toWheelAttrs x.file; f = toWheelAttrs x.file;
in in
(withPython pythonTag abiTag f) && (withPlatform f); (withPython pythonTag abiTag f) && (withPlatform f);
filtered = builtins.filter filterWheel filesWithoutSources; filtered = builtins.filter filterWheel filesWithoutSources;
choose = files: choose = files:
let let
osxMatches = [ "10_12" "10_11" "10_10" "10_9" "any" ]; osxMatches = [ "10_12" "10_11" "10_10" "10_9" "any" ];
linuxMatches = [ "manylinux1_" "manylinux2010_" "manylinux2014_" "any" ]; linuxMatches = [ "manylinux1_" "manylinux2010_" "manylinux2014_" "any" ];
chooseLinux = x: lib.singleton (builtins.head (findBestMatches linuxMatches x)); chooseLinux = x: lib.take 1 (findBestMatches linuxMatches x);
chooseOSX = x: lib.singleton (builtins.head (findBestMatches osxMatches x)); chooseOSX = x: lib.take 1 (findBestMatches osxMatches x);
in in
if isLinux if isLinux
then chooseLinux files then chooseLinux files
else chooseOSX files; else chooseOSX files;
in in
if (builtins.length filtered == 0) if (builtins.length filtered == 0)
then [] then [ ]
else choose (filtered); else choose (filtered);
in in
{ {
inherit selectWheel toWheelAttrs isPyVersionCompatible; inherit selectWheel toWheelAttrs isPyVersionCompatible;

View File

@ -7,7 +7,6 @@ let
# Strip leading/trailing whitespace from string # Strip leading/trailing whitespace from string
stripStr = s: lib.elemAt (builtins.split "^ *" (lib.elemAt (builtins.split " *$" s) 0)) 2; stripStr = s: lib.elemAt (builtins.split "^ *" (lib.elemAt (builtins.split " *$" s) 0)) 2;
findSubExpressionsFun = acc: c: ( findSubExpressionsFun = acc: c: (
if c == "(" then ( if c == "(" then (
let let
@ -15,23 +14,23 @@ let
isOpen = acc.openP == 0; isOpen = acc.openP == 0;
startPos = if isOpen then posNew else acc.startPos; startPos = if isOpen then posNew else acc.startPos;
in in
acc // { acc // {
inherit startPos; inherit startPos;
exprs = acc.exprs ++ [ (substr acc.exprPos (acc.pos - 1) acc.expr) ]; exprs = acc.exprs ++ [ (substr acc.exprPos (acc.pos - 1) acc.expr) ];
pos = posNew; pos = posNew;
openP = acc.openP + 1; openP = acc.openP + 1;
} }
) else if c == ")" then ( ) else if c == ")" then (
let let
openP = acc.openP - 1; openP = acc.openP - 1;
exprs = findSubExpressions (substr acc.startPos acc.pos acc.expr); exprs = findSubExpressions (substr acc.startPos acc.pos acc.expr);
in in
acc // { acc // {
inherit openP; inherit openP;
pos = acc.pos + 1; pos = acc.pos + 1;
exprs = if openP == 0 then acc.exprs ++ [ exprs ] else acc.exprs; exprs = if openP == 0 then acc.exprs ++ [ exprs ] else acc.exprs;
exprPos = if openP == 0 then acc.pos + 1 else acc.exprPos; exprPos = if openP == 0 then acc.pos + 1 else acc.exprPos;
} }
) else acc // { pos = acc.pos + 1; } ) else acc // { pos = acc.pos + 1; }
); );
@ -39,7 +38,7 @@ let
findSubExpressions = expr: findSubExpressions = expr:
let let
acc = builtins.foldl' findSubExpressionsFun { acc = builtins.foldl' findSubExpressionsFun {
exprs = []; exprs = [ ];
expr = expr; expr = expr;
pos = 0; pos = 0;
openP = 0; openP = 0;
@ -47,18 +46,16 @@ let
startPos = 0; startPos = 0;
} (lib.stringToCharacters expr); } (lib.stringToCharacters expr);
tailExpr = (substr acc.exprPos acc.pos expr); tailExpr = (substr acc.exprPos acc.pos expr);
tailExprs = if tailExpr != "" then [ tailExpr ] else []; tailExprs = if tailExpr != "" then [ tailExpr ] else [ ];
in in
acc.exprs ++ tailExprs; acc.exprs ++ tailExprs;
parseExpressions = exprs: parseExpressions = exprs:
let let
splitCond = ( splitCond = (
s: builtins.map s: builtins.map
(x: stripStr (if builtins.typeOf x == "list" then (builtins.elemAt x 0) else x)) (x: stripStr ( if builtins.typeOf x == "list" then (builtins.elemAt x 0) else x))
(builtins.split " (and|or) " (s + " ")) (builtins.split " (and|or) " (s + " "))
); );
mapfn = expr: ( mapfn = expr: (
if (builtins.match "^ ?$" expr != null) then null # Filter empty if (builtins.match "^ ?$" expr != null) then null # Filter empty
else if (builtins.elem expr [ "and" "or" ]) then { else if (builtins.elem expr [ "and" "or" ]) then {
@ -70,14 +67,12 @@ let
value = expr; value = expr;
} }
); );
parse = expr: builtins.filter (x: x != null) (builtins.map mapfn (splitCond expr)); parse = expr: builtins.filter (x: x != null) (builtins.map mapfn (splitCond expr));
in in
builtins.foldl' ( builtins.foldl'
acc: v: acc ++ ( (
if builtins.typeOf v == "string" then parse v else [ (parseExpressions v) ] acc: v: acc ++ ( if builtins.typeOf v == "string" then parse v else [ (parseExpressions v) ])
) ) [ ] exprs;
) [] exprs;
# Transform individual expressions to structured expressions # Transform individual expressions to structured expressions
# This function also performs variable substitution, replacing environment markers with their explicit values # This function also performs variable substitution, replacing environment markers with their explicit values
@ -94,9 +89,10 @@ let
else throw "Unsupported platform" else throw "Unsupported platform"
); );
platform_machine = stdenv.platform.kernelArch; platform_machine = stdenv.platform.kernelArch;
platform_python_implementation = let platform_python_implementation =
impl = python.passthru.implementation; let
in impl = python.passthru.implementation;
in
( (
if impl == "cpython" then "CPython" if impl == "cpython" then "CPython"
else if impl == "pypy" then "PyPy" else if impl == "pypy" then "PyPy"
@ -115,34 +111,32 @@ let
implementation_version = python.version; implementation_version = python.version;
extra = ""; extra = "";
}; };
substituteVar = value: if builtins.hasAttr value variables then (builtins.toJSON variables."${value}") else value; substituteVar = value: if builtins.hasAttr value variables then (builtins.toJSON variables."${value}") else value;
processVar = value: builtins.foldl' (acc: v: v acc) value [ processVar = value: builtins.foldl' (acc: v: v acc) value [
stripStr stripStr
substituteVar substituteVar
]; ];
in in
if builtins.typeOf exprs == "set" then ( if builtins.typeOf exprs == "set" then (
if exprs.type == "expr" then ( if exprs.type == "expr" then (
let let
mVal = ''[a-zA-Z0-9\'"_\. ]+''; mVal = ''[a-zA-Z0-9\'"_\. ]+'';
mOp = "in|[!=<>]+"; mOp = "in|[!=<>]+";
e = stripStr exprs.value; e = stripStr exprs.value;
m = builtins.map stripStr (builtins.match ''^(${mVal}) *(${mOp}) *(${mVal})$'' e); m = builtins.map stripStr (builtins.match ''^(${mVal}) *(${mOp}) *(${mVal})$'' e);
in in
{ {
type = "expr"; type = "expr";
value = { value = {
op = builtins.elemAt m 1; op = builtins.elemAt m 1;
values = [ values = [
(processVar (builtins.elemAt m 0)) (processVar (builtins.elemAt m 0))
(processVar (builtins.elemAt m 2)) (processVar (builtins.elemAt m 2))
]; ];
}; };
} }
) else exprs ) else exprs
) else builtins.map transformExpressions exprs; ) else builtins.map transformExpressions exprs;
# Recursively eval all expressions # Recursively eval all expressions
evalExpressions = exprs: evalExpressions = exprs:
@ -165,32 +159,33 @@ let
let let
parts = builtins.splitVersion c; parts = builtins.splitVersion c;
pruned = lib.take ((builtins.length parts) - 1) parts; pruned = lib.take ((builtins.length parts) - 1) parts;
upper = builtins.toString ( upper = builtins.toString
(lib.toInt (builtins.elemAt pruned (builtins.length pruned - 1))) + 1 (
); (lib.toInt (builtins.elemAt pruned (builtins.length pruned - 1))) + 1
);
upperConstraint = builtins.concatStringsSep "." (ireplace (builtins.length pruned - 1) upper pruned); upperConstraint = builtins.concatStringsSep "." (ireplace (builtins.length pruned - 1) upper pruned);
in in
op.">=" v c && op."<" v upperConstraint; op.">=" v c && op."<" v upperConstraint;
"===" = x: y: x == y; "===" = x: y: x == y;
"in" = x: y: "in" = x: y:
let let
values = builtins.filter (x: builtins.typeOf x == "string") (builtins.split " " (unmarshal y)); values = builtins.filter (x: builtins.typeOf x == "string") (builtins.split " " (unmarshal y));
in in
builtins.elem (unmarshal x) values; builtins.elem (unmarshal x) values;
}; };
in in
if builtins.typeOf exprs == "set" then ( if builtins.typeOf exprs == "set" then (
if exprs.type == "expr" then ( if exprs.type == "expr" then (
let let
expr = exprs; expr = exprs;
result = (op."${expr.value.op}") (builtins.elemAt expr.value.values 0) (builtins.elemAt expr.value.values 1); result = (op."${expr.value.op}") (builtins.elemAt expr.value.values 0) (builtins.elemAt expr.value.values 1);
in in
{ {
type = "value"; type = "value";
value = result; value = result;
} }
) else exprs ) else exprs
) else builtins.map evalExpressions exprs; ) else builtins.map evalExpressions exprs;
# Now that we have performed an eval all that's left to do is to concat the graph into a single bool # Now that we have performed an eval all that's left to do is to concat the graph into a single bool
reduceExpressions = exprs: reduceExpressions = exprs:
@ -217,18 +212,18 @@ let
cond = "and"; cond = "and";
} v; } v;
in in
acc // { acc // {
value = cond."${acc.cond}" acc.value ret.value; value = cond."${acc.cond}" acc.value ret.value;
} }
) else throw "Unsupported type" ) else throw "Unsupported type"
); );
in in
( (
builtins.foldl' reduceExpressionsFun { builtins.foldl' reduceExpressionsFun {
value = true; value = true;
cond = "and"; cond = "and";
} exprs } exprs
).value; ).value;
in in
e: builtins.foldl' (acc: v: v acc) e [ e: builtins.foldl' (acc: v: v acc) e [
findSubExpressions findSubExpressions

View File

@ -1,28 +1,28 @@
{ lib, ireplace }: { lib, ireplace }:
let let
inherit (builtins) elemAt match; inherit (builtins) elemAt match;
operators =
operators = let let
matchWildCard = s: match "([^\*])(\.[\*])" s; matchWildCard = s: match "([^\*])(\.[\*])" s;
mkComparison = ret: version: v: builtins.compareVersions version v == ret; mkComparison = ret: version: v: builtins.compareVersions version v == ret;
mkIdxComparison = idx: version: v: mkIdxComparison = idx: version: v:
let let
ver = builtins.splitVersion v; ver = builtins.splitVersion v;
minor = builtins.toString (lib.toInt (elemAt ver idx) + 1); minor = builtins.toString (lib.toInt (elemAt ver idx) + 1);
upper = builtins.concatStringsSep "." (ireplace idx minor ver); upper = builtins.concatStringsSep "." (ireplace idx minor ver);
in in
operators.">=" version v && operators."<" version upper; operators.">=" version v && operators."<" version upper;
dropWildcardPrecision = f: version: constraint: dropWildcardPrecision = f: version: constraint:
let let
m = matchWildCard constraint; m = matchWildCard constraint;
hasWildcard = m != null; hasWildcard = m != null;
c = if hasWildcard then (elemAt m 0) else constraint; c = if hasWildcard then (elemAt m 0) else constraint;
v = v =
if hasWildcard then (builtins.substring 0 (builtins.stringLength c) version) if hasWildcard then (builtins.substring 0 (builtins.stringLength c) version)
else version; else version;
in in
f v c; f v c;
in in
{ {
# Prefix operators # Prefix operators
"==" = dropWildcardPrecision (mkComparison 0); "==" = dropWildcardPrecision (mkComparison 0);
@ -39,24 +39,23 @@ let
# Prune constraint # Prune constraint
parts = builtins.splitVersion c; parts = builtins.splitVersion c;
pruned = lib.take ((builtins.length parts) - 1) parts; pruned = lib.take ((builtins.length parts) - 1) parts;
upper = builtins.toString ( upper = builtins.toString
(lib.toInt (builtins.elemAt pruned (builtins.length pruned - 1))) + 1 (
); (lib.toInt (builtins.elemAt pruned (builtins.length pruned - 1))) + 1
);
upperConstraint = builtins.concatStringsSep "." (ireplace (builtins.length pruned - 1) upper pruned); upperConstraint = builtins.concatStringsSep "." (ireplace (builtins.length pruned - 1) upper pruned);
in in
operators.">=" v c && operators."<" v upperConstraint; operators.">=" v c && operators."<" v upperConstraint;
# Infix operators # Infix operators
"-" = version: v: operators.">=" version v.vl && operators."<=" version v.vu; "-" = version: v: operators.">=" version v.vl && operators."<=" version v.vu;
# Arbitrary equality clause, just run simple comparison # Arbitrary equality clause, just run simple comparison
"===" = v: c: v == c; "===" = v: c: v == c;
# #
}; };
re = { re = {
operators = "([=><!~\^]+)"; operators = "([=><!~\^]+)";
version = "([0-9\.\*x]+)"; version = "([0-9\.\*x]+)";
}; };
parseConstraint = constraint: parseConstraint = constraint:
let let
constraintStr = builtins.replaceStrings [ " " ] [ "" ] constraint; constraintStr = builtins.replaceStrings [ " " ] [ "" ] constraint;
@ -65,26 +64,24 @@ let
# There is also an infix operator to match ranges # There is also an infix operator to match ranges
mIn = match "${re.version} *(-) *${re.version}" constraintStr; mIn = match "${re.version} *(-) *${re.version}" constraintStr;
in in
( (
if mPre != null then { if mPre != null then {
op = elemAt mPre 0; op = elemAt mPre 0;
v = elemAt mPre 1; v = elemAt mPre 1;
} }
# Infix operators are range matches # Infix operators are range matches
else if mIn != null then { else if mIn != null then {
op = elemAt mIn 1; op = elemAt mIn 1;
v = { v = {
vl = (elemAt mIn 0); vl = (elemAt mIn 0);
vu = (elemAt mIn 2); vu = (elemAt mIn 2);
}; };
} }
else throw "Constraint \"${constraintStr}\" could not be parsed" else throw "Constraint \"${constraintStr}\" could not be parsed"
); );
satisfiesSemver = version: constraint: satisfiesSemver = version: constraint:
let let
inherit (parseConstraint constraint) op v; inherit (parseConstraint constraint) op v;
in in if constraint == "*" then true else operators."${op}" version v;
if constraint == "*" then true else operators."${op}" version v;
in in
{ inherit satisfiesSemver; } { inherit satisfiesSemver; }

View File

@ -14,7 +14,7 @@ curl -L -s https://github.com/nix-community/poetry2nix/archive/master.tar.gz | t
mv poetry2nix-master/* . mv poetry2nix-master/* .
mkdir build mkdir build
cp *.nix *.json *.py build/ cp *.* build/
cp -r hooks bin build/ cp -r hooks bin build/
rm build/shell.nix build/generate.py build/overlay.nix build/flake.nix rm build/shell.nix build/generate.py build/overlay.nix build/flake.nix