From 0460bee94c68dcdbe366e81ff6056573f6a6daf2 Mon Sep 17 00:00:00 2001
From: Tom Prince <tom.prince@private.storage>
Date: Tue, 14 Sep 2021 15:28:20 -0600
Subject: [PATCH] Add a helper python function wrapping nix-prefetch-url.

---
 shell.nix                        | 17 +++++++++++++++-
 tools/pylib/README.rst           |  2 ++
 tools/pylib/ps_tools/__init__.py | 35 ++++++++++++++++++++++++++++++++
 3 files changed, 53 insertions(+), 1 deletion(-)
 create mode 100644 tools/pylib/README.rst
 create mode 100644 tools/pylib/ps_tools/__init__.py

diff --git a/shell.nix b/shell.nix
index ce1add06..97814a9c 100644
--- a/shell.nix
+++ b/shell.nix
@@ -1,12 +1,27 @@
 let
   release2105 = import ./nixpkgs-2105.nix { };
 in
-{ pkgs ? release2105 }:
+{ pkgs ? release2105, lib ? pkgs.lib, python ? pkgs.python3 }:
+let
+  # This is a python envionment that has the dependencies
+  # for the development python scripts we use, and the
+  # helper library.
+  python-env = python.buildEnv.override {
+    extraLibs = [ python.pkgs.httpx ];
+    # Add `.pth` file pointing at the directory containg our helper library.
+    # This will get added to `sys.path` by `site.py`.
+    # See https://docs.python.org/3/library/site.html
+    postBuild = ''
+      echo ${lib.escapeShellArg ./tools/pylib} > $out/${lib.escapeShellArg python.sitePackages}/tools.pth
+    '';
+  };
+in
 pkgs.mkShell {
   shellHook = ''
     export NIX_PATH="nixpkgs=${pkgs.path}";
   '';
   buildInputs = [
+    python-env
     pkgs.morph
     pkgs.jp
   ];
diff --git a/tools/pylib/README.rst b/tools/pylib/README.rst
new file mode 100644
index 00000000..083f6620
--- /dev/null
+++ b/tools/pylib/README.rst
@@ -0,0 +1,2 @@
+This directory contains a python package of helper functions used by the scripts in ``tools/``.
+To get this on the python path, run ``nix-shell`` in the root of the repository.
diff --git a/tools/pylib/ps_tools/__init__.py b/tools/pylib/ps_tools/__init__.py
new file mode 100644
index 00000000..278ef0f1
--- /dev/null
+++ b/tools/pylib/ps_tools/__init__.py
@@ -0,0 +1,35 @@
+"""
+Helpers for development and CI scripts.
+"""
+from __future__ import annotations
+
+import subprocess
+
+
+def get_url_hash(hash_type, name, url) -> dict[str, str]:
+    """
+    Get the nix hash of the given URL.
+
+    :returns: Dictionary of arguments suitable to pass to :nix:`pkgs.fetchzip`
+        or a function derived from it (such as :nix:`pkgs.fetchFromGitLab`)
+        to specify the hash.
+    """
+    output = subprocess.run(
+        [
+            "nix-prefetch-url",
+            "--type",
+            hash_type,
+            "--unpack",
+            "--name",
+            name,
+            url,
+        ],
+        capture_output=True,
+        check=True,
+        encoding="utf-8",
+    )
+
+    return {
+        "outputHashAlgo": hash_type,
+        "outputHash": output.stdout.strip(),
+    }
-- 
GitLab