diff --git a/.ci_support/linux_64_numpy1.22python3.10.____cpython.yaml b/.ci_support/linux_64_python3.10.____cpython.yaml
similarity index 76%
rename from .ci_support/linux_64_numpy1.22python3.10.____cpython.yaml
rename to .ci_support/linux_64_python3.10.____cpython.yaml
index 39b7953..121a649 100644
--- a/.ci_support/linux_64_numpy1.22python3.10.____cpython.yaml
+++ b/.ci_support/linux_64_python3.10.____cpython.yaml
@@ -1,25 +1,25 @@
c_compiler:
- gcc
c_compiler_version:
-- '12'
+- '13'
c_stdlib:
- sysroot
c_stdlib_version:
- '2.17'
cdt_name:
-- cos7
+- conda
channel_sources:
- conda-forge
channel_targets:
- ryanvolz main
docker_image:
-- quay.io/condaforge/linux-anvil-cos7-x86_64
+- quay.io/condaforge/linux-anvil-x86_64:alma9
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
numpy:
-- '1.22'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
@@ -29,7 +29,5 @@ python:
target_platform:
- linux-64
zip_keys:
-- - c_stdlib_version
- - cdt_name
- - python
- numpy
diff --git a/.ci_support/linux_64_numpy1.23python3.11.____cpython.yaml b/.ci_support/linux_64_python3.11.____cpython.yaml
similarity index 76%
rename from .ci_support/linux_64_numpy1.23python3.11.____cpython.yaml
rename to .ci_support/linux_64_python3.11.____cpython.yaml
index 46be447..db5e804 100644
--- a/.ci_support/linux_64_numpy1.23python3.11.____cpython.yaml
+++ b/.ci_support/linux_64_python3.11.____cpython.yaml
@@ -1,25 +1,25 @@
c_compiler:
- gcc
c_compiler_version:
-- '12'
+- '13'
c_stdlib:
- sysroot
c_stdlib_version:
- '2.17'
cdt_name:
-- cos7
+- conda
channel_sources:
- conda-forge
channel_targets:
- ryanvolz main
docker_image:
-- quay.io/condaforge/linux-anvil-cos7-x86_64
+- quay.io/condaforge/linux-anvil-x86_64:alma9
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
numpy:
-- '1.23'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
@@ -29,7 +29,5 @@ python:
target_platform:
- linux-64
zip_keys:
-- - c_stdlib_version
- - cdt_name
- - python
- numpy
diff --git a/.ci_support/linux_64_numpy1.26python3.12.____cpython.yaml b/.ci_support/linux_64_python3.12.____cpython.yaml
similarity index 76%
rename from .ci_support/linux_64_numpy1.26python3.12.____cpython.yaml
rename to .ci_support/linux_64_python3.12.____cpython.yaml
index e22631d..b735d10 100644
--- a/.ci_support/linux_64_numpy1.26python3.12.____cpython.yaml
+++ b/.ci_support/linux_64_python3.12.____cpython.yaml
@@ -1,25 +1,25 @@
c_compiler:
- gcc
c_compiler_version:
-- '12'
+- '13'
c_stdlib:
- sysroot
c_stdlib_version:
- '2.17'
cdt_name:
-- cos7
+- conda
channel_sources:
- conda-forge
channel_targets:
- ryanvolz main
docker_image:
-- quay.io/condaforge/linux-anvil-cos7-x86_64
+- quay.io/condaforge/linux-anvil-x86_64:alma9
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
numpy:
-- '1.26'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
@@ -29,7 +29,5 @@ python:
target_platform:
- linux-64
zip_keys:
-- - c_stdlib_version
- - cdt_name
- - python
- numpy
diff --git a/.ci_support/linux_64_numpy1.22python3.9.____cpython.yaml b/.ci_support/linux_64_python3.9.____cpython.yaml
similarity index 76%
rename from .ci_support/linux_64_numpy1.22python3.9.____cpython.yaml
rename to .ci_support/linux_64_python3.9.____cpython.yaml
index 4bb5251..b33af1b 100644
--- a/.ci_support/linux_64_numpy1.22python3.9.____cpython.yaml
+++ b/.ci_support/linux_64_python3.9.____cpython.yaml
@@ -1,25 +1,25 @@
c_compiler:
- gcc
c_compiler_version:
-- '12'
+- '13'
c_stdlib:
- sysroot
c_stdlib_version:
- '2.17'
cdt_name:
-- cos7
+- conda
channel_sources:
- conda-forge
channel_targets:
- ryanvolz main
docker_image:
-- quay.io/condaforge/linux-anvil-cos7-x86_64
+- quay.io/condaforge/linux-anvil-x86_64:alma9
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
numpy:
-- '1.22'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
@@ -29,7 +29,5 @@ python:
target_platform:
- linux-64
zip_keys:
-- - c_stdlib_version
- - cdt_name
- - python
- numpy
diff --git a/.ci_support/linux_aarch64_numpy1.22python3.10.____cpython.yaml b/.ci_support/linux_aarch64_numpy1.22python3.10.____cpython.yaml
deleted file mode 100644
index bfa6eb2..0000000
--- a/.ci_support/linux_aarch64_numpy1.22python3.10.____cpython.yaml
+++ /dev/null
@@ -1,39 +0,0 @@
-BUILD:
-- aarch64-conda_cos7-linux-gnu
-c_compiler:
-- gcc
-c_compiler_version:
-- '12'
-c_stdlib:
-- sysroot
-c_stdlib_version:
-- '2.17'
-cdt_arch:
-- aarch64
-cdt_name:
-- cos7
-channel_sources:
-- conda-forge
-channel_targets:
-- ryanvolz main
-docker_image:
-- quay.io/condaforge/linux-anvil-aarch64
-gnuradio_core:
-- 3.10.10
-hdf5:
-- 1.14.3
-numpy:
-- '1.22'
-pin_run_as_build:
- python:
- min_pin: x.x
- max_pin: x.x
-python:
-- 3.10.* *_cpython
-target_platform:
-- linux-aarch64
-zip_keys:
-- - c_stdlib_version
- - cdt_name
-- - python
- - numpy
diff --git a/.ci_support/linux_aarch64_numpy1.22python3.8.____cpython.yaml b/.ci_support/linux_aarch64_numpy1.22python3.8.____cpython.yaml
deleted file mode 100644
index 7d58668..0000000
--- a/.ci_support/linux_aarch64_numpy1.22python3.8.____cpython.yaml
+++ /dev/null
@@ -1,39 +0,0 @@
-BUILD:
-- aarch64-conda_cos7-linux-gnu
-c_compiler:
-- gcc
-c_compiler_version:
-- '12'
-c_stdlib:
-- sysroot
-c_stdlib_version:
-- '2.17'
-cdt_arch:
-- aarch64
-cdt_name:
-- cos7
-channel_sources:
-- conda-forge
-channel_targets:
-- ryanvolz main
-docker_image:
-- quay.io/condaforge/linux-anvil-aarch64
-gnuradio_core:
-- 3.10.10
-hdf5:
-- 1.14.3
-numpy:
-- '1.22'
-pin_run_as_build:
- python:
- min_pin: x.x
- max_pin: x.x
-python:
-- 3.8.* *_cpython
-target_platform:
-- linux-aarch64
-zip_keys:
-- - c_stdlib_version
- - cdt_name
-- - python
- - numpy
diff --git a/.ci_support/linux_aarch64_numpy1.22python3.9.____cpython.yaml b/.ci_support/linux_aarch64_numpy1.22python3.9.____cpython.yaml
deleted file mode 100644
index 622d15e..0000000
--- a/.ci_support/linux_aarch64_numpy1.22python3.9.____cpython.yaml
+++ /dev/null
@@ -1,39 +0,0 @@
-BUILD:
-- aarch64-conda_cos7-linux-gnu
-c_compiler:
-- gcc
-c_compiler_version:
-- '12'
-c_stdlib:
-- sysroot
-c_stdlib_version:
-- '2.17'
-cdt_arch:
-- aarch64
-cdt_name:
-- cos7
-channel_sources:
-- conda-forge
-channel_targets:
-- ryanvolz main
-docker_image:
-- quay.io/condaforge/linux-anvil-aarch64
-gnuradio_core:
-- 3.10.10
-hdf5:
-- 1.14.3
-numpy:
-- '1.22'
-pin_run_as_build:
- python:
- min_pin: x.x
- max_pin: x.x
-python:
-- 3.9.* *_cpython
-target_platform:
-- linux-aarch64
-zip_keys:
-- - c_stdlib_version
- - cdt_name
-- - python
- - numpy
diff --git a/.ci_support/linux_aarch64_numpy1.23python3.11.____cpython.yaml b/.ci_support/linux_aarch64_numpy1.23python3.11.____cpython.yaml
deleted file mode 100644
index 9c9b39f..0000000
--- a/.ci_support/linux_aarch64_numpy1.23python3.11.____cpython.yaml
+++ /dev/null
@@ -1,39 +0,0 @@
-BUILD:
-- aarch64-conda_cos7-linux-gnu
-c_compiler:
-- gcc
-c_compiler_version:
-- '12'
-c_stdlib:
-- sysroot
-c_stdlib_version:
-- '2.17'
-cdt_arch:
-- aarch64
-cdt_name:
-- cos7
-channel_sources:
-- conda-forge
-channel_targets:
-- ryanvolz main
-docker_image:
-- quay.io/condaforge/linux-anvil-aarch64
-gnuradio_core:
-- 3.10.10
-hdf5:
-- 1.14.3
-numpy:
-- '1.23'
-pin_run_as_build:
- python:
- min_pin: x.x
- max_pin: x.x
-python:
-- 3.11.* *_cpython
-target_platform:
-- linux-aarch64
-zip_keys:
-- - c_stdlib_version
- - cdt_name
-- - python
- - numpy
diff --git a/.ci_support/linux_aarch64_numpy1.26python3.12.____cpython.yaml b/.ci_support/linux_aarch64_numpy1.26python3.12.____cpython.yaml
deleted file mode 100644
index 564f074..0000000
--- a/.ci_support/linux_aarch64_numpy1.26python3.12.____cpython.yaml
+++ /dev/null
@@ -1,39 +0,0 @@
-BUILD:
-- aarch64-conda_cos7-linux-gnu
-c_compiler:
-- gcc
-c_compiler_version:
-- '12'
-c_stdlib:
-- sysroot
-c_stdlib_version:
-- '2.17'
-cdt_arch:
-- aarch64
-cdt_name:
-- cos7
-channel_sources:
-- conda-forge
-channel_targets:
-- ryanvolz main
-docker_image:
-- quay.io/condaforge/linux-anvil-aarch64
-gnuradio_core:
-- 3.10.10
-hdf5:
-- 1.14.3
-numpy:
-- '1.26'
-pin_run_as_build:
- python:
- min_pin: x.x
- max_pin: x.x
-python:
-- 3.12.* *_cpython
-target_platform:
-- linux-aarch64
-zip_keys:
-- - c_stdlib_version
- - cdt_name
-- - python
- - numpy
diff --git a/.ci_support/linux_64_numpy1.22python3.8.____cpython.yaml b/.ci_support/linux_aarch64_python3.10.____cpython.yaml
similarity index 69%
rename from .ci_support/linux_64_numpy1.22python3.8.____cpython.yaml
rename to .ci_support/linux_aarch64_python3.10.____cpython.yaml
index 930c1d4..eaffab8 100644
--- a/.ci_support/linux_64_numpy1.22python3.8.____cpython.yaml
+++ b/.ci_support/linux_aarch64_python3.10.____cpython.yaml
@@ -1,35 +1,33 @@
c_compiler:
- gcc
c_compiler_version:
-- '12'
+- '13'
c_stdlib:
- sysroot
c_stdlib_version:
- '2.17'
cdt_name:
-- cos7
+- conda
channel_sources:
- conda-forge
channel_targets:
- ryanvolz main
docker_image:
-- quay.io/condaforge/linux-anvil-cos7-x86_64
+- quay.io/condaforge/linux-anvil-aarch64:alma9
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
numpy:
-- '1.22'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
max_pin: x.x
python:
-- 3.8.* *_cpython
+- 3.10.* *_cpython
target_platform:
-- linux-64
+- linux-aarch64
zip_keys:
-- - c_stdlib_version
- - cdt_name
- - python
- numpy
diff --git a/.ci_support/linux_aarch64_python3.11.____cpython.yaml b/.ci_support/linux_aarch64_python3.11.____cpython.yaml
new file mode 100644
index 0000000..a868b6d
--- /dev/null
+++ b/.ci_support/linux_aarch64_python3.11.____cpython.yaml
@@ -0,0 +1,33 @@
+c_compiler:
+- gcc
+c_compiler_version:
+- '13'
+c_stdlib:
+- sysroot
+c_stdlib_version:
+- '2.17'
+cdt_name:
+- conda
+channel_sources:
+- conda-forge
+channel_targets:
+- ryanvolz main
+docker_image:
+- quay.io/condaforge/linux-anvil-aarch64:alma9
+gnuradio_core:
+- 3.10.11
+hdf5:
+- 1.14.3
+numpy:
+- '2.0'
+pin_run_as_build:
+ python:
+ min_pin: x.x
+ max_pin: x.x
+python:
+- 3.11.* *_cpython
+target_platform:
+- linux-aarch64
+zip_keys:
+- - python
+ - numpy
diff --git a/.ci_support/linux_aarch64_python3.12.____cpython.yaml b/.ci_support/linux_aarch64_python3.12.____cpython.yaml
new file mode 100644
index 0000000..98ad0fa
--- /dev/null
+++ b/.ci_support/linux_aarch64_python3.12.____cpython.yaml
@@ -0,0 +1,33 @@
+c_compiler:
+- gcc
+c_compiler_version:
+- '13'
+c_stdlib:
+- sysroot
+c_stdlib_version:
+- '2.17'
+cdt_name:
+- conda
+channel_sources:
+- conda-forge
+channel_targets:
+- ryanvolz main
+docker_image:
+- quay.io/condaforge/linux-anvil-aarch64:alma9
+gnuradio_core:
+- 3.10.11
+hdf5:
+- 1.14.3
+numpy:
+- '2.0'
+pin_run_as_build:
+ python:
+ min_pin: x.x
+ max_pin: x.x
+python:
+- 3.12.* *_cpython
+target_platform:
+- linux-aarch64
+zip_keys:
+- - python
+ - numpy
diff --git a/.ci_support/linux_aarch64_python3.9.____cpython.yaml b/.ci_support/linux_aarch64_python3.9.____cpython.yaml
new file mode 100644
index 0000000..9b9faa1
--- /dev/null
+++ b/.ci_support/linux_aarch64_python3.9.____cpython.yaml
@@ -0,0 +1,33 @@
+c_compiler:
+- gcc
+c_compiler_version:
+- '13'
+c_stdlib:
+- sysroot
+c_stdlib_version:
+- '2.17'
+cdt_name:
+- conda
+channel_sources:
+- conda-forge
+channel_targets:
+- ryanvolz main
+docker_image:
+- quay.io/condaforge/linux-anvil-aarch64:alma9
+gnuradio_core:
+- 3.10.11
+hdf5:
+- 1.14.3
+numpy:
+- '2.0'
+pin_run_as_build:
+ python:
+ min_pin: x.x
+ max_pin: x.x
+python:
+- 3.9.* *_cpython
+target_platform:
+- linux-aarch64
+zip_keys:
+- - python
+ - numpy
diff --git a/.ci_support/migrations/numpy2.yaml b/.ci_support/migrations/numpy2.yaml
new file mode 100644
index 0000000..d70edeb
--- /dev/null
+++ b/.ci_support/migrations/numpy2.yaml
@@ -0,0 +1,74 @@
+__migrator:
+ build_number: 1
+ kind: version
+ commit_message: |
+ Rebuild for numpy 2.0
+
+ TL;DR: The way we build against numpy has changed as of numpy 2.0. This bot
+ PR has updated the recipe to account for the changes (see below for details).
+ The numpy 2.0 package itself is currently only available from a special release
+ channel (`conda-forge/label/numpy_rc`) and will not be available on the main
+ `conda-forge` channel until the release of numpy 2.0 GA.
+
+ The biggest change is that we no longer need to use the oldest available numpy
+ version at build time in order to support old numpy version at runtime - numpy
+ will by default use a compatible ABI for the oldest still-supported numpy versions.
+
+ Additionally, we no longer need to use `{{ pin_compatible("numpy") }}` as a
+ run requirement - this has been handled for more than two years now by a
+ run-export on the numpy package itself. The migrator will therefore remove
+ any occurrences of this.
+
+ However, by default, building against numpy 2.0 will assume that the package
+ is compatible with numpy 2.0, which is not necessarily the case. You should
+ check that the upstream package explicitly supports numpy 2.0, otherwise you
+ need to add a `- numpy <2.0dev0` run requirement until that happens (check numpy
+ issue 26191 for an overview of the most important packages).
+
+ Note that the numpy release candidate promises to be ABI-compatible with the
+ final 2.0 release. This means that building against 2.0.0rc1 produces packages
+ that can be published to our main channels.
+
+ If you already want to use the numpy 2.0 release candidate yourself, you can do
+ ```
+ conda config --add channels conda-forge/label/numpy_rc
+ ```
+ or add this channel to your `.condarc` file directly.
+
+ ### To-Dos:
+ * [ ] Match run-requirements for numpy (i.e. check upstream `pyproject.toml` or however the project specifies numpy compatibility)
+ * If upstream is not yet compatible with numpy 2.0, add `numpy <2.0dev0` upper bound under `run:`.
+ * If upstream is already compatible with numpy 2.0, nothing else should be necessary in most cases.
+ * If upstream requires a minimum numpy version newer than 1.19, you can add `numpy >=x.y` under `run:`.
+ * [ ] Remove any remaining occurrences of `{{ pin_compatible("numpy") }}` that the bot may have missed.
+
+ PS. If the build does not compile anymore, this is almost certainly a sign that
+ the upstream project is not yet ready for numpy 2.0; do not close this PR until
+ a version compatible with numpy 2.0 has been released upstream and on this
+ feedstock (in the meantime, you can keep the bot from reopening this PR in
+ case of git conflicts by marking it as a draft).
+
+ migration_number: 1
+ exclude:
+ # needs local overrides that get stomped on by the migrator, which then fails
+ - scipy
+ # already done, but thinks its unsolvable
+ - pandas
+ ordering:
+ # prefer channels including numpy_rc (otherwise smithy doesn't
+ # know which of the two values should be taken on merge)
+ channel_sources:
+ - conda-forge
+ - conda-forge/label/numpy_rc,conda-forge
+
+# needs to match length of zip {python, python_impl, numpy}
+# as it is in global CBC in order to override it
+numpy:
+ - 1.22 # no py38 support for numpy 2.0
+ - 2.0
+ - 2.0
+ - 2.0
+ - 2.0
+channel_sources:
+ - conda-forge/label/numpy_rc,conda-forge
+migrator_ts: 1713572489.295986
diff --git a/.ci_support/osx_64_numpy1.22python3.8.____cpython.yaml b/.ci_support/osx_64_numpy1.22python3.8.____cpython.yaml
deleted file mode 100644
index d3805e9..0000000
--- a/.ci_support/osx_64_numpy1.22python3.8.____cpython.yaml
+++ /dev/null
@@ -1,35 +0,0 @@
-MACOSX_DEPLOYMENT_TARGET:
-- '10.13'
-MACOSX_SDK_VERSION:
-- '10.13'
-c_compiler:
-- clang
-c_compiler_version:
-- '16'
-c_stdlib:
-- macosx_deployment_target
-c_stdlib_version:
-- '10.13'
-channel_sources:
-- conda-forge
-channel_targets:
-- ryanvolz main
-gnuradio_core:
-- 3.10.10
-hdf5:
-- 1.14.3
-macos_machine:
-- x86_64-apple-darwin13.4.0
-numpy:
-- '1.22'
-pin_run_as_build:
- python:
- min_pin: x.x
- max_pin: x.x
-python:
-- 3.8.* *_cpython
-target_platform:
-- osx-64
-zip_keys:
-- - python
- - numpy
diff --git a/.ci_support/osx_64_numpy1.22python3.10.____cpython.yaml b/.ci_support/osx_64_python3.10.____cpython.yaml
similarity index 94%
rename from .ci_support/osx_64_numpy1.22python3.10.____cpython.yaml
rename to .ci_support/osx_64_python3.10.____cpython.yaml
index dbd9f4b..c4cac36 100644
--- a/.ci_support/osx_64_numpy1.22python3.10.____cpython.yaml
+++ b/.ci_support/osx_64_python3.10.____cpython.yaml
@@ -5,7 +5,7 @@ MACOSX_SDK_VERSION:
c_compiler:
- clang
c_compiler_version:
-- '16'
+- '18'
c_stdlib:
- macosx_deployment_target
c_stdlib_version:
@@ -15,13 +15,13 @@ channel_sources:
channel_targets:
- ryanvolz main
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
macos_machine:
- x86_64-apple-darwin13.4.0
numpy:
-- '1.22'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
diff --git a/.ci_support/osx_64_numpy1.23python3.11.____cpython.yaml b/.ci_support/osx_64_python3.11.____cpython.yaml
similarity index 94%
rename from .ci_support/osx_64_numpy1.23python3.11.____cpython.yaml
rename to .ci_support/osx_64_python3.11.____cpython.yaml
index 475c3ea..35c039b 100644
--- a/.ci_support/osx_64_numpy1.23python3.11.____cpython.yaml
+++ b/.ci_support/osx_64_python3.11.____cpython.yaml
@@ -5,7 +5,7 @@ MACOSX_SDK_VERSION:
c_compiler:
- clang
c_compiler_version:
-- '16'
+- '18'
c_stdlib:
- macosx_deployment_target
c_stdlib_version:
@@ -15,13 +15,13 @@ channel_sources:
channel_targets:
- ryanvolz main
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
macos_machine:
- x86_64-apple-darwin13.4.0
numpy:
-- '1.23'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
diff --git a/.ci_support/osx_64_numpy1.26python3.12.____cpython.yaml b/.ci_support/osx_64_python3.12.____cpython.yaml
similarity index 94%
rename from .ci_support/osx_64_numpy1.26python3.12.____cpython.yaml
rename to .ci_support/osx_64_python3.12.____cpython.yaml
index 7a99926..bc41e06 100644
--- a/.ci_support/osx_64_numpy1.26python3.12.____cpython.yaml
+++ b/.ci_support/osx_64_python3.12.____cpython.yaml
@@ -5,7 +5,7 @@ MACOSX_SDK_VERSION:
c_compiler:
- clang
c_compiler_version:
-- '16'
+- '18'
c_stdlib:
- macosx_deployment_target
c_stdlib_version:
@@ -15,13 +15,13 @@ channel_sources:
channel_targets:
- ryanvolz main
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
macos_machine:
- x86_64-apple-darwin13.4.0
numpy:
-- '1.26'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
diff --git a/.ci_support/osx_64_numpy1.22python3.9.____cpython.yaml b/.ci_support/osx_64_python3.9.____cpython.yaml
similarity index 94%
rename from .ci_support/osx_64_numpy1.22python3.9.____cpython.yaml
rename to .ci_support/osx_64_python3.9.____cpython.yaml
index c7adfae..14f6ca4 100644
--- a/.ci_support/osx_64_numpy1.22python3.9.____cpython.yaml
+++ b/.ci_support/osx_64_python3.9.____cpython.yaml
@@ -5,7 +5,7 @@ MACOSX_SDK_VERSION:
c_compiler:
- clang
c_compiler_version:
-- '16'
+- '18'
c_stdlib:
- macosx_deployment_target
c_stdlib_version:
@@ -15,13 +15,13 @@ channel_sources:
channel_targets:
- ryanvolz main
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
macos_machine:
- x86_64-apple-darwin13.4.0
numpy:
-- '1.22'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
diff --git a/.ci_support/osx_arm64_numpy1.22python3.8.____cpython.yaml b/.ci_support/osx_arm64_numpy1.22python3.8.____cpython.yaml
deleted file mode 100644
index 387de10..0000000
--- a/.ci_support/osx_arm64_numpy1.22python3.8.____cpython.yaml
+++ /dev/null
@@ -1,35 +0,0 @@
-MACOSX_DEPLOYMENT_TARGET:
-- '11.0'
-MACOSX_SDK_VERSION:
-- '11.0'
-c_compiler:
-- clang
-c_compiler_version:
-- '16'
-c_stdlib:
-- macosx_deployment_target
-c_stdlib_version:
-- '11.0'
-channel_sources:
-- conda-forge
-channel_targets:
-- ryanvolz main
-gnuradio_core:
-- 3.10.10
-hdf5:
-- 1.14.3
-macos_machine:
-- arm64-apple-darwin20.0.0
-numpy:
-- '1.22'
-pin_run_as_build:
- python:
- min_pin: x.x
- max_pin: x.x
-python:
-- 3.8.* *_cpython
-target_platform:
-- osx-arm64
-zip_keys:
-- - python
- - numpy
diff --git a/.ci_support/osx_arm64_numpy1.22python3.10.____cpython.yaml b/.ci_support/osx_arm64_python3.10.____cpython.yaml
similarity index 94%
rename from .ci_support/osx_arm64_numpy1.22python3.10.____cpython.yaml
rename to .ci_support/osx_arm64_python3.10.____cpython.yaml
index 0e0c708..44451f4 100644
--- a/.ci_support/osx_arm64_numpy1.22python3.10.____cpython.yaml
+++ b/.ci_support/osx_arm64_python3.10.____cpython.yaml
@@ -5,7 +5,7 @@ MACOSX_SDK_VERSION:
c_compiler:
- clang
c_compiler_version:
-- '16'
+- '18'
c_stdlib:
- macosx_deployment_target
c_stdlib_version:
@@ -15,13 +15,13 @@ channel_sources:
channel_targets:
- ryanvolz main
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
macos_machine:
- arm64-apple-darwin20.0.0
numpy:
-- '1.22'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
diff --git a/.ci_support/osx_arm64_numpy1.23python3.11.____cpython.yaml b/.ci_support/osx_arm64_python3.11.____cpython.yaml
similarity index 94%
rename from .ci_support/osx_arm64_numpy1.23python3.11.____cpython.yaml
rename to .ci_support/osx_arm64_python3.11.____cpython.yaml
index 200c204..a781667 100644
--- a/.ci_support/osx_arm64_numpy1.23python3.11.____cpython.yaml
+++ b/.ci_support/osx_arm64_python3.11.____cpython.yaml
@@ -5,7 +5,7 @@ MACOSX_SDK_VERSION:
c_compiler:
- clang
c_compiler_version:
-- '16'
+- '18'
c_stdlib:
- macosx_deployment_target
c_stdlib_version:
@@ -15,13 +15,13 @@ channel_sources:
channel_targets:
- ryanvolz main
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
macos_machine:
- arm64-apple-darwin20.0.0
numpy:
-- '1.23'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
diff --git a/.ci_support/osx_arm64_numpy1.26python3.12.____cpython.yaml b/.ci_support/osx_arm64_python3.12.____cpython.yaml
similarity index 94%
rename from .ci_support/osx_arm64_numpy1.26python3.12.____cpython.yaml
rename to .ci_support/osx_arm64_python3.12.____cpython.yaml
index 3e40079..fc2d5d5 100644
--- a/.ci_support/osx_arm64_numpy1.26python3.12.____cpython.yaml
+++ b/.ci_support/osx_arm64_python3.12.____cpython.yaml
@@ -5,7 +5,7 @@ MACOSX_SDK_VERSION:
c_compiler:
- clang
c_compiler_version:
-- '16'
+- '18'
c_stdlib:
- macosx_deployment_target
c_stdlib_version:
@@ -15,13 +15,13 @@ channel_sources:
channel_targets:
- ryanvolz main
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
macos_machine:
- arm64-apple-darwin20.0.0
numpy:
-- '1.26'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
diff --git a/.ci_support/osx_arm64_numpy1.22python3.9.____cpython.yaml b/.ci_support/osx_arm64_python3.9.____cpython.yaml
similarity index 94%
rename from .ci_support/osx_arm64_numpy1.22python3.9.____cpython.yaml
rename to .ci_support/osx_arm64_python3.9.____cpython.yaml
index bc6672e..61bd0c2 100644
--- a/.ci_support/osx_arm64_numpy1.22python3.9.____cpython.yaml
+++ b/.ci_support/osx_arm64_python3.9.____cpython.yaml
@@ -5,7 +5,7 @@ MACOSX_SDK_VERSION:
c_compiler:
- clang
c_compiler_version:
-- '16'
+- '18'
c_stdlib:
- macosx_deployment_target
c_stdlib_version:
@@ -15,13 +15,13 @@ channel_sources:
channel_targets:
- ryanvolz main
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
macos_machine:
- arm64-apple-darwin20.0.0
numpy:
-- '1.22'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
diff --git a/.ci_support/win_64_numpy1.22python3.8.____cpython.yaml b/.ci_support/win_64_numpy1.22python3.8.____cpython.yaml
deleted file mode 100644
index 2d0adf7..0000000
--- a/.ci_support/win_64_numpy1.22python3.8.____cpython.yaml
+++ /dev/null
@@ -1,25 +0,0 @@
-c_compiler:
-- vs2019
-c_stdlib:
-- vs
-channel_sources:
-- conda-forge
-channel_targets:
-- ryanvolz main
-gnuradio_core:
-- 3.10.10
-hdf5:
-- 1.14.3
-numpy:
-- '1.22'
-pin_run_as_build:
- python:
- min_pin: x.x
- max_pin: x.x
-python:
-- 3.8.* *_cpython
-target_platform:
-- win-64
-zip_keys:
-- - python
- - numpy
diff --git a/.ci_support/win_64_numpy1.22python3.10.____cpython.yaml b/.ci_support/win_64_python3.10.____cpython.yaml
similarity index 93%
rename from .ci_support/win_64_numpy1.22python3.10.____cpython.yaml
rename to .ci_support/win_64_python3.10.____cpython.yaml
index a0bdf3c..f2c3c1f 100644
--- a/.ci_support/win_64_numpy1.22python3.10.____cpython.yaml
+++ b/.ci_support/win_64_python3.10.____cpython.yaml
@@ -7,11 +7,11 @@ channel_sources:
channel_targets:
- ryanvolz main
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
numpy:
-- '1.22'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
diff --git a/.ci_support/win_64_numpy1.23python3.11.____cpython.yaml b/.ci_support/win_64_python3.11.____cpython.yaml
similarity index 93%
rename from .ci_support/win_64_numpy1.23python3.11.____cpython.yaml
rename to .ci_support/win_64_python3.11.____cpython.yaml
index c76cb77..adc63ae 100644
--- a/.ci_support/win_64_numpy1.23python3.11.____cpython.yaml
+++ b/.ci_support/win_64_python3.11.____cpython.yaml
@@ -7,11 +7,11 @@ channel_sources:
channel_targets:
- ryanvolz main
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
numpy:
-- '1.23'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
diff --git a/.ci_support/win_64_numpy1.26python3.12.____cpython.yaml b/.ci_support/win_64_python3.12.____cpython.yaml
similarity index 93%
rename from .ci_support/win_64_numpy1.26python3.12.____cpython.yaml
rename to .ci_support/win_64_python3.12.____cpython.yaml
index af46ee6..c06cee9 100644
--- a/.ci_support/win_64_numpy1.26python3.12.____cpython.yaml
+++ b/.ci_support/win_64_python3.12.____cpython.yaml
@@ -7,11 +7,11 @@ channel_sources:
channel_targets:
- ryanvolz main
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
numpy:
-- '1.26'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
diff --git a/.ci_support/win_64_numpy1.22python3.9.____cpython.yaml b/.ci_support/win_64_python3.9.____cpython.yaml
similarity index 93%
rename from .ci_support/win_64_numpy1.22python3.9.____cpython.yaml
rename to .ci_support/win_64_python3.9.____cpython.yaml
index 57cc652..8f7c1fe 100644
--- a/.ci_support/win_64_numpy1.22python3.9.____cpython.yaml
+++ b/.ci_support/win_64_python3.9.____cpython.yaml
@@ -7,11 +7,11 @@ channel_sources:
channel_targets:
- ryanvolz main
gnuradio_core:
-- 3.10.10
+- 3.10.11
hdf5:
- 1.14.3
numpy:
-- '1.22'
+- '2.0'
pin_run_as_build:
python:
min_pin: x.x
diff --git a/.git_archival.txt b/.git_archival.txt
new file mode 100644
index 0000000..7c51009
--- /dev/null
+++ b/.git_archival.txt
@@ -0,0 +1,3 @@
+node: $Format:%H$
+node-date: $Format:%cI$
+describe-name: $Format:%(describe:tags=true,match=*[0-9]*)$
diff --git a/.gitattributes b/.gitattributes
index 5b88b4b..8702f9e 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,3 +1,5 @@
+.git_archival.txt export-subst
+
# Auto detect text files and perform LF normalization
# http://davidlaing.com/2012/09/19/customise-your-gitattributes-to-become-a-git-ninja/
* text=auto
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000..6c4b369
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,11 @@
+version: 2
+updates:
+ # Maintain dependencies for GitHub Actions
+ - package-ecosystem: "github-actions"
+ directory: "/"
+ schedule:
+ interval: "weekly"
+ groups:
+ actions:
+ patterns:
+ - "*"
diff --git a/.github/release.yml b/.github/release.yml
new file mode 100644
index 0000000..9d1e098
--- /dev/null
+++ b/.github/release.yml
@@ -0,0 +1,5 @@
+changelog:
+ exclude:
+ authors:
+ - dependabot
+ - pre-commit-ci
diff --git a/.github/workflows/automerge.yml b/.github/workflows/automerge.yml
deleted file mode 100644
index f79fe85..0000000
--- a/.github/workflows/automerge.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-on:
- status: {}
- check_suite:
- types:
- - completed
-
-jobs:
- automerge-action:
- runs-on: ubuntu-latest
- name: automerge
- steps:
- - name: checkout
- uses: actions/checkout@v2
- - name: automerge-action
- id: automerge-action
- uses: conda-forge/automerge-action@master
- with:
- github_token: ${{ secrets.GITHUB_TOKEN }}
- rerendering_github_token: ${{ secrets.RERENDERING_GITHUB_TOKEN }}
diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml
new file mode 100644
index 0000000..01e58f1
--- /dev/null
+++ b/.github/workflows/cd.yml
@@ -0,0 +1,88 @@
+name: wheels
+
+on:
+ workflow_dispatch:
+ release:
+ types:
+ - published
+ pull_request:
+ paths:
+ - .github/workflows/cd.yml
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+env:
+ # Many color libraries just need this to be set to any value, but at least
+ # one distinguishes color depth, where "3" -> "256-bit color".
+ FORCE_COLOR: 3
+
+jobs:
+ make_sdist:
+ name: Make SDist
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+
+ - name: Build SDist
+ run: pipx run build --sdist
+
+ - uses: actions/upload-artifact@v4
+ with:
+ name: cibw-sdist
+ path: dist/*.tar.gz
+
+ build_wheels:
+ name: Wheel on ${{ matrix.os }}
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-latest, macos-13, macos-14]
+
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+
+ - uses: pypa/cibuildwheel@v2.20
+ env:
+ # limited at least by availability of h5py, which skips pypy and musl
+ CIBW_SKIP: pp* *musllinux* *i686 *win32
+
+ - name: Upload wheels
+ uses: actions/upload-artifact@v4
+ with:
+ name: cibw-wheels-${{ matrix.os }}-${{ strategy.job-index }}
+ path: wheelhouse/*.whl
+
+ upload_all:
+ needs: [build_wheels, make_sdist]
+ environment: pypi
+ permissions:
+ id-token: write
+ attestations: write
+ contents: read
+ runs-on: ubuntu-latest
+ if: github.event_name == 'release' && github.event.action == 'published'
+
+ steps:
+ - uses: actions/download-artifact@v4
+ with:
+ pattern: cibw-*
+ path: dist
+ merge-multiple: true
+
+ - name: Generate artifact attestations
+ uses: actions/attest-build-provenance@v1.4.1
+ with:
+ subject-path: "dist/*"
+
+ - uses: pypa/gh-action-pypi-publish@release/v1
+ with:
+ # Remember to tell (test-)pypi about this repo before publishing
+ # Remove this line to publish to PyPI
+ repository-url: https://test.pypi.org/legacy/
diff --git a/.github/workflows/conda-build.yml b/.github/workflows/conda-build.yml
index 39234d2..43f57fe 100644
--- a/.github/workflows/conda-build.yml
+++ b/.github/workflows/conda-build.yml
@@ -23,138 +23,111 @@ jobs:
fail-fast: false
matrix:
include:
- - CONFIG: linux_64_numpy1.22python3.10.____cpython
- SHORT_CONFIG: linux_64_numpy1.22python3.10.____cpython
+ - CONFIG: linux_64_python3.10.____cpython
+ SHORT_CONFIG: linux_64_python3.10.____cpython
UPLOAD_PACKAGES: True
os: ubuntu
runs_on: ['ubuntu-latest']
- DOCKER_IMAGE: quay.io/condaforge/linux-anvil-cos7-x86_64
- - CONFIG: linux_64_numpy1.22python3.8.____cpython
- SHORT_CONFIG: linux_64_numpy1.22python3.8.____cpython
+ DOCKER_IMAGE: quay.io/condaforge/linux-anvil-x86_64:alma9
+ - CONFIG: linux_64_python3.11.____cpython
+ SHORT_CONFIG: linux_64_python3.11.____cpython
UPLOAD_PACKAGES: True
os: ubuntu
runs_on: ['ubuntu-latest']
- DOCKER_IMAGE: quay.io/condaforge/linux-anvil-cos7-x86_64
- - CONFIG: linux_64_numpy1.22python3.9.____cpython
- SHORT_CONFIG: linux_64_numpy1.22python3.9.____cpython
+ DOCKER_IMAGE: quay.io/condaforge/linux-anvil-x86_64:alma9
+ - CONFIG: linux_64_python3.12.____cpython
+ SHORT_CONFIG: linux_64_python3.12.____cpython
UPLOAD_PACKAGES: True
os: ubuntu
runs_on: ['ubuntu-latest']
- DOCKER_IMAGE: quay.io/condaforge/linux-anvil-cos7-x86_64
- - CONFIG: linux_64_numpy1.23python3.11.____cpython
- SHORT_CONFIG: linux_64_numpy1.23python3.11.____cpython
+ DOCKER_IMAGE: quay.io/condaforge/linux-anvil-x86_64:alma9
+ - CONFIG: linux_64_python3.9.____cpython
+ SHORT_CONFIG: linux_64_python3.9.____cpython
UPLOAD_PACKAGES: True
os: ubuntu
runs_on: ['ubuntu-latest']
- DOCKER_IMAGE: quay.io/condaforge/linux-anvil-cos7-x86_64
- - CONFIG: linux_64_numpy1.26python3.12.____cpython
- SHORT_CONFIG: linux_64_numpy1.26python3.12.____cpython
+ DOCKER_IMAGE: quay.io/condaforge/linux-anvil-x86_64:alma9
+ - CONFIG: linux_aarch64_python3.10.____cpython
+ SHORT_CONFIG: linux_aarch64_python3.10.____cpython
UPLOAD_PACKAGES: True
os: ubuntu
runs_on: ['ubuntu-latest']
- DOCKER_IMAGE: quay.io/condaforge/linux-anvil-cos7-x86_64
- - CONFIG: linux_aarch64_numpy1.22python3.10.____cpython
- SHORT_CONFIG: linux_aarch64_numpy1.22python3.10.____cpython
+ DOCKER_IMAGE: quay.io/condaforge/linux-anvil-aarch64:alma9
+ - CONFIG: linux_aarch64_python3.11.____cpython
+ SHORT_CONFIG: linux_aarch64_python3.11.____cpython
UPLOAD_PACKAGES: True
os: ubuntu
runs_on: ['ubuntu-latest']
- DOCKER_IMAGE: quay.io/condaforge/linux-anvil-aarch64
- - CONFIG: linux_aarch64_numpy1.22python3.8.____cpython
- SHORT_CONFIG: linux_aarch64_numpy1.22python3.8.____cpython
+ DOCKER_IMAGE: quay.io/condaforge/linux-anvil-aarch64:alma9
+ - CONFIG: linux_aarch64_python3.12.____cpython
+ SHORT_CONFIG: linux_aarch64_python3.12.____cpython
UPLOAD_PACKAGES: True
os: ubuntu
runs_on: ['ubuntu-latest']
- DOCKER_IMAGE: quay.io/condaforge/linux-anvil-aarch64
- - CONFIG: linux_aarch64_numpy1.22python3.9.____cpython
- SHORT_CONFIG: linux_aarch64_numpy1.22python3.9.____cpython
+ DOCKER_IMAGE: quay.io/condaforge/linux-anvil-aarch64:alma9
+ - CONFIG: linux_aarch64_python3.9.____cpython
+ SHORT_CONFIG: linux_aarch64_python3.9.____cpython
UPLOAD_PACKAGES: True
os: ubuntu
runs_on: ['ubuntu-latest']
- DOCKER_IMAGE: quay.io/condaforge/linux-anvil-aarch64
- - CONFIG: linux_aarch64_numpy1.23python3.11.____cpython
- SHORT_CONFIG: linux_aarch64_numpy1.23python3.11.____cpython
- UPLOAD_PACKAGES: True
- os: ubuntu
- runs_on: ['ubuntu-latest']
- DOCKER_IMAGE: quay.io/condaforge/linux-anvil-aarch64
- - CONFIG: linux_aarch64_numpy1.26python3.12.____cpython
- SHORT_CONFIG: linux_aarch64_numpy1.26python3.12.____cpython
- UPLOAD_PACKAGES: True
- os: ubuntu
- runs_on: ['ubuntu-latest']
- DOCKER_IMAGE: quay.io/condaforge/linux-anvil-aarch64
- - CONFIG: osx_64_numpy1.22python3.10.____cpython
- SHORT_CONFIG: osx_64_numpy1.22python3.10.____cpython
- UPLOAD_PACKAGES: True
- os: macos
- runs_on: ['macos-13']
- - CONFIG: osx_64_numpy1.22python3.8.____cpython
- SHORT_CONFIG: osx_64_numpy1.22python3.8.____cpython
+ DOCKER_IMAGE: quay.io/condaforge/linux-anvil-aarch64:alma9
+ - CONFIG: osx_64_python3.10.____cpython
+ SHORT_CONFIG: osx_64_python3.10.____cpython
UPLOAD_PACKAGES: True
os: macos
runs_on: ['macos-13']
- - CONFIG: osx_64_numpy1.22python3.9.____cpython
- SHORT_CONFIG: osx_64_numpy1.22python3.9.____cpython
+ - CONFIG: osx_64_python3.11.____cpython
+ SHORT_CONFIG: osx_64_python3.11.____cpython
UPLOAD_PACKAGES: True
os: macos
runs_on: ['macos-13']
- - CONFIG: osx_64_numpy1.23python3.11.____cpython
- SHORT_CONFIG: osx_64_numpy1.23python3.11.____cpython
+ - CONFIG: osx_64_python3.12.____cpython
+ SHORT_CONFIG: osx_64_python3.12.____cpython
UPLOAD_PACKAGES: True
os: macos
runs_on: ['macos-13']
- - CONFIG: osx_64_numpy1.26python3.12.____cpython
- SHORT_CONFIG: osx_64_numpy1.26python3.12.____cpython
+ - CONFIG: osx_64_python3.9.____cpython
+ SHORT_CONFIG: osx_64_python3.9.____cpython
UPLOAD_PACKAGES: True
os: macos
runs_on: ['macos-13']
- - CONFIG: osx_arm64_numpy1.22python3.10.____cpython
- SHORT_CONFIG: osx_arm64_numpy1.22python3.10.____cpython
+ - CONFIG: osx_arm64_python3.10.____cpython
+ SHORT_CONFIG: osx_arm64_python3.10.____cpython
UPLOAD_PACKAGES: True
os: macos
runs_on: ['macos-13']
- - CONFIG: osx_arm64_numpy1.22python3.8.____cpython
- SHORT_CONFIG: osx_arm64_numpy1.22python3.8.____cpython
+ - CONFIG: osx_arm64_python3.11.____cpython
+ SHORT_CONFIG: osx_arm64_python3.11.____cpython
UPLOAD_PACKAGES: True
os: macos
runs_on: ['macos-13']
- - CONFIG: osx_arm64_numpy1.22python3.9.____cpython
- SHORT_CONFIG: osx_arm64_numpy1.22python3.9.____cpython
+ - CONFIG: osx_arm64_python3.12.____cpython
+ SHORT_CONFIG: osx_arm64_python3.12.____cpython
UPLOAD_PACKAGES: True
os: macos
runs_on: ['macos-13']
- - CONFIG: osx_arm64_numpy1.23python3.11.____cpython
- SHORT_CONFIG: osx_arm64_numpy1.23python3.11.____cpython
+ - CONFIG: osx_arm64_python3.9.____cpython
+ SHORT_CONFIG: osx_arm64_python3.9.____cpython
UPLOAD_PACKAGES: True
os: macos
runs_on: ['macos-13']
- - CONFIG: osx_arm64_numpy1.26python3.12.____cpython
- SHORT_CONFIG: osx_arm64_numpy1.26python3.12.____cpython
- UPLOAD_PACKAGES: True
- os: macos
- runs_on: ['macos-13']
- - CONFIG: win_64_numpy1.22python3.10.____cpython
- SHORT_CONFIG: win_64_numpy1.22python3.10.____cpython
+ - CONFIG: win_64_python3.10.____cpython
+ SHORT_CONFIG: win_64_python3.10.____cpython
UPLOAD_PACKAGES: True
os: windows
runs_on: ['windows-latest']
- - CONFIG: win_64_numpy1.22python3.8.____cpython
- SHORT_CONFIG: win_64_numpy1.22python3.8.____cpython
+ - CONFIG: win_64_python3.11.____cpython
+ SHORT_CONFIG: win_64_python3.11.____cpython
UPLOAD_PACKAGES: True
os: windows
runs_on: ['windows-latest']
- - CONFIG: win_64_numpy1.22python3.9.____cpython
- SHORT_CONFIG: win_64_numpy1.22python3.9.____cpython
+ - CONFIG: win_64_python3.12.____cpython
+ SHORT_CONFIG: win_64_python3.12.____cpython
UPLOAD_PACKAGES: True
os: windows
runs_on: ['windows-latest']
- - CONFIG: win_64_numpy1.23python3.11.____cpython
- SHORT_CONFIG: win_64_numpy1.23python3.11.____cpython
- UPLOAD_PACKAGES: True
- os: windows
- runs_on: ['windows-latest']
- - CONFIG: win_64_numpy1.26python3.12.____cpython
- SHORT_CONFIG: win_64_numpy1.26python3.12.____cpython
+ - CONFIG: win_64_python3.9.____cpython
+ SHORT_CONFIG: win_64_python3.9.____cpython
UPLOAD_PACKAGES: True
os: windows
runs_on: ['windows-latest']
@@ -214,12 +187,6 @@ jobs:
fi
./.scripts/run_osx_build.sh
- - name: Install Miniconda for windows
- uses: conda-incubator/setup-miniconda@a4260408e20b96e80095f42ff7f1a15b27dd94ca # v3.0.4
- with:
- miniforge-version: latest
- if: matrix.os == 'windows'
-
- name: Build on windows
shell: cmd
run: |
@@ -228,6 +195,7 @@ jobs:
set "sha=%GITHUB_SHA%"
call ".scripts\run_win_build.bat"
env:
+ MINIFORGE_HOME: D:\Miniforge
PYTHONUNBUFFERED: 1
CONFIG: ${{ matrix.CONFIG }}
CI: github_actions
@@ -243,6 +211,7 @@ jobs:
CONFIG: ${{ matrix.CONFIG }}
SHORT_CONFIG: ${{ matrix.SHORT_CONFIG }}
OS: ${{ matrix.os }}
+ MINIFORGE_HOME_WIN: D:\Miniforge
run: |
export CI=github_actions
export CI_RUN_ID=$GITHUB_RUN_ID
@@ -251,7 +220,7 @@ jobs:
if [ $OS == "macos" ]; then
export CONDA_BLD_DIR="${MINIFORGE_HOME:-${HOME}/miniforge3}/conda-bld"
elif [ $OS == "windows" ]; then
- export CONDA_BLD_DIR="${CONDA//\\//}/conda-bld"
+ export CONDA_BLD_DIR="${MINIFORGE_HOME_WIN//\\//}/conda-bld"
else
export CONDA_BLD_DIR="build_artifacts"
fi
@@ -270,7 +239,7 @@ jobs:
continue-on-error: true
- name: Store conda build artifacts
- uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3
+ uses: actions/upload-artifact@6f51ac03b9356f520e9adb1b1b7802705f340c2b # v4.5.0
if: ${{ always() && steps.prepare-artifacts.outcome == 'success' }}
with:
name: ${{ steps.prepare-artifacts.outputs.BLD_ARTIFACT_NAME }}
@@ -279,7 +248,7 @@ jobs:
continue-on-error: true
- name: Store conda build environment artifacts
- uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3
+ uses: actions/upload-artifact@6f51ac03b9356f520e9adb1b1b7802705f340c2b # v4.5.0
if: ${{ failure() && steps.prepare-artifacts.outcome == 'success' }}
with:
name: ${{ steps.prepare-artifacts.outputs.ENV_ARTIFACT_NAME }}
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index 7c5ffea..39b99bd 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -16,9 +16,9 @@ jobs:
run: |
pip install flake8
# stop the build if there are Python syntax errors or undefined names
- flake8 python --config python/setup.cfg --count --select=E9,F63,F7,F82 --show-source --statistics
+ flake8 python --ignore C812,C815,D101,E203,N803,N806,W503 --max-line-length 88 --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings.
- flake8 python --config python/setup.cfg --count --exit-zero --max-complexity=10 --statistics
+ flake8 python --ignore C812,C815,D101,E203,N803,N806,W503 --max-line-length 88 --count --exit-zero --max-complexity=10 --statistics
- name: Check formatting with black
run: |
pip install black
diff --git a/.github/workflows/webservices.yml b/.github/workflows/webservices.yml
deleted file mode 100644
index 2e5fe71..0000000
--- a/.github/workflows/webservices.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-on: repository_dispatch
-
-jobs:
- webservices:
- runs-on: ubuntu-latest
- name: webservices
- steps:
- - name: webservices
- id: webservices
- uses: conda-forge/webservices-dispatch-action@master
- with:
- github_token: ${{ secrets.GITHUB_TOKEN }}
- rerendering_github_token: ${{ secrets.RERENDERING_GITHUB_TOKEN }}
diff --git a/.gitignore b/.gitignore
index b988ea2..c29982f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,7 +9,6 @@ __pycache__/
# Distribution / packaging
.Python
-env/
build/
develop-eggs/
dist/
@@ -20,9 +19,11 @@ parts/
sdist/
var/
wheels/
+share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
+MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
@@ -37,13 +38,17 @@ pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
+.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
-*,cover
+*.cover
+*.py,cover
.hypothesis/
+.pytest_cache/
+cover/
# Translations
*.mo
@@ -52,6 +57,8 @@ coverage.xml
# Django stuff:
*.log
local_settings.py
+db.sqlite3
+db.sqlite3-journal
# Flask stuff:
instance/
@@ -64,16 +71,34 @@ instance/
docs/_build/
# PyBuilder
+.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
+# IPython
+profile_default/
+ipython_config.py
+
# pyenv
+# For a library or package, you might want to ignore these files since the code is
+# intended to run in multiple environments; otherwise, check them in:
.python-version
-# celery beat schedule file
+# pipenv
+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+# However, in case of collaboration, if having platform-specific dependencies or dependencies
+# having no cross-platform support, pipenv may install dependencies that don't work, or not
+# install all needed dependencies.
+#Pipfile.lock
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow
+__pypackages__/
+
+# Celery stuff
celerybeat-schedule
+celerybeat.pid
# SageMath parsed files
*.sage.py
@@ -81,13 +106,18 @@ celerybeat-schedule
# dotenv
.env
-# virtualenv
+# Environments
+.env
.venv
+env/
venv/
ENV/
+env.bak/
+venv.bak/
# Spyder project settings
.spyderproject
+.spyproject
# Rope project settings
.ropeproject
@@ -95,6 +125,40 @@ ENV/
# mkdocs documentation
/site
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# Cython debug symbols
+cython_debug/
+
+# setuptools_scm
+python/*/_version.py
+
+
+# ruff
+.ruff_cache/
+
+# OS specific stuff
+.DS_Store
+.DS_Store?
+._*
+.Spotlight-V100
+.Trashes
+ehthumbs.db
+Thumbs.db
+
+# Common editor files
+*~
+*.swp
+
## C
# Prerequisites
diff --git a/.scripts/build_steps.sh b/.scripts/build_steps.sh
index cd9b205..352d052 100755
--- a/.scripts/build_steps.sh
+++ b/.scripts/build_steps.sh
@@ -31,18 +31,20 @@ pkgs_dirs:
solver: libmamba
CONDARC
+mv /opt/conda/conda-meta/history /opt/conda/conda-meta/history.$(date +%Y-%m-%d-%H-%M-%S)
+echo > /opt/conda/conda-meta/history
+micromamba install --root-prefix ~/.conda --prefix /opt/conda \
+ --yes --override-channels --channel conda-forge --strict-channel-priority \
+ pip python=3.12 conda-build conda-forge-ci-setup=4 "conda-build>=24.1"
export CONDA_LIBMAMBA_SOLVER_NO_CHANNELS_FROM_INSTALLED=1
-mamba install --update-specs --yes --quiet --channel conda-forge --strict-channel-priority \
- pip mamba conda-build conda-forge-ci-setup=4 "conda-build>=24.1"
-mamba update --update-specs --yes --quiet --channel conda-forge --strict-channel-priority \
- pip mamba conda-build conda-forge-ci-setup=4 "conda-build>=24.1"
-
# set up the condarc
setup_conda_rc "${FEEDSTOCK_ROOT}" "${RECIPE_ROOT}" "${CONFIG_FILE}"
source run_conda_forge_build_setup
+
+
# make the build number clobber
make_build_number "${FEEDSTOCK_ROOT}" "${RECIPE_ROOT}" "${CONFIG_FILE}"
@@ -74,8 +76,8 @@ else
--extra-meta flow_run_id="${flow_run_id:-}" remote_url="${remote_url:-}" sha="${sha:-}"
( startgroup "Inspecting artifacts" ) 2> /dev/null
- # inspect_artifacts was only added in conda-forge-ci-setup 4.6.0
- command -v inspect_artifacts >/dev/null 2>&1 && inspect_artifacts || echo "inspect_artifacts needs conda-forge-ci-setup >=4.6.0"
+ # inspect_artifacts was only added in conda-forge-ci-setup 4.9.4
+ command -v inspect_artifacts >/dev/null 2>&1 && inspect_artifacts --recipe-dir "${RECIPE_ROOT}" -m "${CONFIG_FILE}" || echo "inspect_artifacts needs conda-forge-ci-setup >=4.9.4"
( endgroup "Inspecting artifacts" ) 2> /dev/null
diff --git a/.scripts/run_osx_build.sh b/.scripts/run_osx_build.sh
index 14cb5c9..53dd6a9 100755
--- a/.scripts/run_osx_build.sh
+++ b/.scripts/run_osx_build.sh
@@ -6,29 +6,41 @@ source .scripts/logging_utils.sh
set -xe
-MINIFORGE_HOME=${MINIFORGE_HOME:-${HOME}/miniforge3}
-
-( startgroup "Installing a fresh version of Miniforge" ) 2> /dev/null
-
-MINIFORGE_URL="https://github.com/conda-forge/miniforge/releases/latest/download"
-MINIFORGE_FILE="Miniforge3-MacOSX-$(uname -m).sh"
-curl -L -O "${MINIFORGE_URL}/${MINIFORGE_FILE}"
-rm -rf ${MINIFORGE_HOME}
-bash $MINIFORGE_FILE -b -p ${MINIFORGE_HOME}
-
-( endgroup "Installing a fresh version of Miniforge" ) 2> /dev/null
+MINIFORGE_HOME="${MINIFORGE_HOME:-${HOME}/miniforge3}"
+MINIFORGE_HOME="${MINIFORGE_HOME%/}" # remove trailing slash
+export CONDA_BLD_PATH="${CONDA_BLD_PATH:-${MINIFORGE_HOME}/conda-bld}"
+
+( startgroup "Provisioning base env with micromamba" ) 2> /dev/null
+MICROMAMBA_VERSION="1.5.10-0"
+if [[ "$(uname -m)" == "arm64" ]]; then
+ osx_arch="osx-arm64"
+else
+ osx_arch="osx-64"
+fi
+MICROMAMBA_URL="https://github.com/mamba-org/micromamba-releases/releases/download/${MICROMAMBA_VERSION}/micromamba-${osx_arch}"
+MAMBA_ROOT_PREFIX="${MINIFORGE_HOME}-micromamba-$(date +%s)"
+echo "Downloading micromamba ${MICROMAMBA_VERSION}"
+micromamba_exe="$(mktemp -d)/micromamba"
+curl -L -o "${micromamba_exe}" "${MICROMAMBA_URL}"
+chmod +x "${micromamba_exe}"
+echo "Creating environment"
+"${micromamba_exe}" create --yes --root-prefix "${MAMBA_ROOT_PREFIX}" --prefix "${MINIFORGE_HOME}" \
+ --channel conda-forge \
+ pip python=3.12 conda-build conda-forge-ci-setup=4 "conda-build>=24.1"
+echo "Moving pkgs cache from ${MAMBA_ROOT_PREFIX} to ${MINIFORGE_HOME}"
+mv "${MAMBA_ROOT_PREFIX}/pkgs" "${MINIFORGE_HOME}"
+echo "Cleaning up micromamba"
+rm -rf "${MAMBA_ROOT_PREFIX}" "${micromamba_exe}" || true
+( endgroup "Provisioning base env with micromamba" ) 2> /dev/null
( startgroup "Configuring conda" ) 2> /dev/null
-
-source ${MINIFORGE_HOME}/etc/profile.d/conda.sh
+echo "Activating environment"
+source "${MINIFORGE_HOME}/etc/profile.d/conda.sh"
conda activate base
export CONDA_SOLVER="libmamba"
export CONDA_LIBMAMBA_SOLVER_NO_CHANNELS_FROM_INSTALLED=1
-mamba install --update-specs --quiet --yes --channel conda-forge --strict-channel-priority \
- pip mamba conda-build conda-forge-ci-setup=4 "conda-build>=24.1"
-mamba update --update-specs --yes --quiet --channel conda-forge --strict-channel-priority \
- pip mamba conda-build conda-forge-ci-setup=4 "conda-build>=24.1"
+
@@ -88,8 +100,8 @@ else
( startgroup "Inspecting artifacts" ) 2> /dev/null
- # inspect_artifacts was only added in conda-forge-ci-setup 4.6.0
- command -v inspect_artifacts >/dev/null 2>&1 && inspect_artifacts || echo "inspect_artifacts needs conda-forge-ci-setup >=4.6.0"
+ # inspect_artifacts was only added in conda-forge-ci-setup 4.9.4
+ command -v inspect_artifacts >/dev/null 2>&1 && inspect_artifacts --recipe-dir ./recipes/conda -m ./.ci_support/${CONFIG}.yaml || echo "inspect_artifacts needs conda-forge-ci-setup >=4.9.4"
( endgroup "Inspecting artifacts" ) 2> /dev/null
diff --git a/.scripts/run_win_build.bat b/.scripts/run_win_build.bat
index 44d19c8..602821d 100755
--- a/.scripts/run_win_build.bat
+++ b/.scripts/run_win_build.bat
@@ -3,30 +3,51 @@
:: changes to this script, consider a proposal to conda-smithy so that other feedstocks can also
:: benefit from the improvement.
-:: Note: we assume a Miniforge installation is available
-
:: INPUTS (required environment variables)
:: CONFIG: name of the .ci_support/*.yaml file for this job
:: CI: azure, github_actions, or unset
+:: MINIFORGE_HOME: where to install the base conda environment
:: UPLOAD_PACKAGES: true or false
:: UPLOAD_ON_BRANCH: true or false
setlocal enableextensions enabledelayedexpansion
+FOR %%A IN ("%~dp0.") DO SET "REPO_ROOT=%%~dpA"
+if "%MINIFORGE_HOME%"=="" set "MINIFORGE_HOME=%USERPROFILE%\Miniforge3"
+:: Remove trailing backslash, if present
+if "%MINIFORGE_HOME:~-1%"=="\" set "MINIFORGE_HOME=%MINIFORGE_HOME:~0,-1%"
+call :start_group "Provisioning base env with micromamba"
+set "MAMBA_ROOT_PREFIX=%MINIFORGE_HOME%-micromamba-%RANDOM%"
+set "MICROMAMBA_VERSION=1.5.10-0"
+set "MICROMAMBA_URL=https://github.com/mamba-org/micromamba-releases/releases/download/%MICROMAMBA_VERSION%/micromamba-win-64"
+set "MICROMAMBA_TMPDIR=%TMP%\micromamba-%RANDOM%"
+set "MICROMAMBA_EXE=%MICROMAMBA_TMPDIR%\micromamba.exe"
+
+echo Downloading micromamba %MICROMAMBA_VERSION%
+if not exist "%MICROMAMBA_TMPDIR%" mkdir "%MICROMAMBA_TMPDIR%"
+certutil -urlcache -split -f "%MICROMAMBA_URL%" "%MICROMAMBA_EXE%"
+if !errorlevel! neq 0 exit /b !errorlevel!
+
+echo Creating environment
+call "%MICROMAMBA_EXE%" create --yes --root-prefix "%MAMBA_ROOT_PREFIX%" --prefix "%MINIFORGE_HOME%" ^
+ --channel conda-forge ^
+ pip python=3.12 conda-build conda-forge-ci-setup=4 "conda-build>=24.1"
+if !errorlevel! neq 0 exit /b !errorlevel!
+echo Removing %MAMBA_ROOT_PREFIX%
+del /S /Q "%MAMBA_ROOT_PREFIX%" >nul
+del /S /Q "%MICROMAMBA_TMPDIR%" >nul
+call :end_group
+
call :start_group "Configuring conda"
:: Activate the base conda environment
-call activate base
+echo Activating environment
+call "%MINIFORGE_HOME%\Scripts\activate.bat"
:: Configure the solver
set "CONDA_SOLVER=libmamba"
if !errorlevel! neq 0 exit /b !errorlevel!
set "CONDA_LIBMAMBA_SOLVER_NO_CHANNELS_FROM_INSTALLED=1"
-:: Provision the necessary dependencies to build the recipe later
-echo Installing dependencies
-mamba.exe install "python=3.10" pip mamba conda-build conda-forge-ci-setup=4 "conda-build>=24.1" -c conda-forge --strict-channel-priority --yes
-if !errorlevel! neq 0 exit /b !errorlevel!
-
:: Set basic configuration
echo Setting up configuration
setup_conda_rc .\ ".\recipes/conda" .\.ci_support\%CONFIG%.yaml
@@ -48,7 +69,7 @@ if NOT [%HOST_PLATFORM%] == [%BUILD_PLATFORM%] (
)
if NOT [%flow_run_id%] == [] (
- set "EXTRA_CB_OPTIONS=%EXTRA_CB_OPTIONS% --extra-meta flow_run_id=%flow_run_id% remote_url=%remote_url% sha=%sha%"
+ set "EXTRA_CB_OPTIONS=%EXTRA_CB_OPTIONS% --extra-meta flow_run_id=%flow_run_id% remote_url=%remote_url% sha=%sha%"
)
call :end_group
@@ -59,8 +80,8 @@ conda-build.exe "recipes/conda" -m .ci_support\%CONFIG%.yaml --suppress-variable
if !errorlevel! neq 0 exit /b !errorlevel!
call :start_group "Inspecting artifacts"
-:: inspect_artifacts was only added in conda-forge-ci-setup 4.6.0
-WHERE inspect_artifacts >nul 2>nul && inspect_artifacts || echo "inspect_artifacts needs conda-forge-ci-setup >=4.6.0"
+:: inspect_artifacts was only added in conda-forge-ci-setup 4.9.4
+WHERE inspect_artifacts >nul 2>nul && inspect_artifacts --recipe-dir ".\recipes/conda" -m .ci_support\%CONFIG%.yaml || echo "inspect_artifacts needs conda-forge-ci-setup >=4.9.4"
call :end_group
:: Prepare some environment variables for the upload step
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 9a8f916..87bcad9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,16 +1,20 @@
-cmake_minimum_required(VERSION 3.0)
+cmake_minimum_required(VERSION 3.20)
cmake_policy(SET CMP0048 NEW)
+cmake_policy(SET CMP0079 NEW)
+cmake_policy(SET CMP0094 NEW)
-project(digital_rf_project LANGUAGES C)
+if(SKBUILD)
+ set(digital_rf_VERSION ${SKBUILD_PROJECT_VERSION})
+else()
+ set(digital_rf_VERSION 2.6.9)
+endif(SKBUILD)
+project(digital_rf LANGUAGES C VERSION ${digital_rf_VERSION})
include(GNUInstallDirs)
enable_testing()
# create targets that sub-projects will add dependencies to
-add_custom_target(source)
-add_custom_target(sdist)
add_custom_target(build)
-add_custom_target(wheel)
# include sub-projects
add_subdirectory(c)
@@ -34,4 +38,4 @@ configure_file(
add_custom_target(uninstall
COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake
)
-add_dependencies(uninstall libdigital_rf_uninstall digital_rf_uninstall)
+add_dependencies(uninstall libdigital_rf_uninstall)
diff --git a/README.rst b/README.rst
index 374921c..657f9bc 100644
--- a/README.rst
+++ b/README.rst
@@ -54,18 +54,19 @@ Build
-----
all
- * cmake >= 3.0 (``cmake``)
+ * cmake >= 3.20 (``cmake``)
c
* hdf5 >= 1.8 (``libhdf5-dev``)
python
+ * build (``python3-build`` or ``pip install build``)
* hdf5 >= 1.8 (``libhdf5-dev``)
* mako (``python-mako``)
* numpy (``python-numpy``)
- * pkgconfig (``python-pkgconfig``)
- * python 2.7 or 3.5+ (``python-dev``)
- * setuptools (``python-setuptools``)
+ * python 3.8+ (``python-dev``)
+ * scikit-build-core (``python3-scikit-build-core`` or ``pip install scikit-build-core``)
+ * setuptools-scm (``python3-setuptools-scm`` or ``pip install setuptools-scm``)
matlab
* cmake >= 3.0 (``cmake``)
@@ -82,9 +83,8 @@ python
* hdf5 >= 1.8 (``libhdf5``)
* numpy (``python-numpy``)
* packaging (``python-packaging``)
- * python 2.7 or 3.5+ (``python``)
+ * python 3.8+ (``python``)
* python-dateutil (``python-dateutil``)
- * pytz (``python-tz``)
* six (``python-six``)
matlab
@@ -110,11 +110,26 @@ python
Installation
============
-If you're just getting started with Digital RF, we recommend using the Python package. The easiest way to install it is through PyPI_ with `pip`::
+If you're just getting started with Digital RF, we recommend using the Conda_ binary package. It is available in the `conda-forge `_ distribution of community-maintained packages.
+
+In an existing Conda environment, run the following to install ``digital_rf`` and its dependencies::
+
+ conda config --add channels conda-forge
+ conda config --set channel_priority strict
+ conda install digital_rf
+
+You may also want to install the ``gnuradio-core`` package in order to make use of ``gr_digital_rf``::
+
+ conda install gnuradio-core
+
+Using PyPI package (wheel)
+--------------------------
+
+Alternatively, you can most likely install Digital RF through PyPI_ with `pip` using a pre-built wheel::
pip install digital_rf
-This will install the ``digital_rf`` and ``gr_digital_rf`` Python packages and GNU Radio Companion (GRC) blocks. If you're interested in the C library or development, see below for ways to install the full project package.
+This will install the ``digital_rf`` and ``gr_digital_rf`` Python packages and GNU Radio Companion (GRC) blocks. (If you're interested in the C library or development, see other installation methods for ways to install the full project package.)
If you plan on using Digital RF with GNU Radio, make sure to run the `pip` command in the same Python environment that your GNU Radio installation uses so that GNU Radio can find the packages. Depending on your GNU Radio installation, it may be necessary to add the Digital RF blocks to your GRC blocks path by creating or editing the GRC configuration file
@@ -130,21 +145,6 @@ to contain::
(replacing ``{PIP_PREFIX}`` with the pip installation prefix, "/usr/local" for example).
-Using Conda package
--------------------
-
-Alternatively, you can install digital_rf using our Conda_ binary package. It is available in the `conda-forge `_ distribution of community-maintained packages.
-
-In an existing Conda environment, run the following to install ``digital_rf`` and its dependencies::
-
- conda config --add channels conda-forge
- conda config --set channel_priority strict
- conda install digital_rf
-
-You may also want to install the ``gnuradio-core`` package in order to make use of ``gr_digital_rf``::
-
- conda install gnuradio-core
-
Using MacPorts
--------------
@@ -175,14 +175,15 @@ Build and install::
make
sudo make install
-CMake will attempt to find your Python installation in the usual places, preferring Python 3. If this fails or you need to specify a Python 2 installation (e.g. for GNU Radio older than version 3.8), specify a particular Python interpreter by adding ``-DPython_EXECUTABLE={PATH}`` (replacing ``{PATH}`` with the interpreter path) to the cmake command.
+CMake will attempt to find your Python installation in the usual places. If this fails, you can specify a particular Python interpreter by adding ``-DPython_EXECUTABLE={PATH}`` (replacing ``{PATH}`` with the interpreter path) to the cmake command.
Finally, you may need to update the library cache so the newly-installed ``libdigital_rf`` is found::
sudo ldconfig
-Note that it is also possible to build the different language libraries separately by following the CMake build procedure from within the `c`, `matlab`, and `python` directories.
+Note that it is also possible to build the different language libraries separately by following the CMake build procedure from within the `c` and `matlab` directories. The `python` package can be built and installed on its own using any Python build frontend compatible with `pyproject.toml`, e.g.::
+ python -m build
The MATLAB toolbox is not created by default. If you have MATLAB R2016a or higher and want to create an installable toolbox package, run the following from the build directory::
diff --git a/c/CMakeLists.txt b/c/CMakeLists.txt
index fea8192..85e7ba4 100644
--- a/c/CMakeLists.txt
+++ b/c/CMakeLists.txt
@@ -35,43 +35,62 @@ else(UNIX)
set(MATH_LIB)
endif(UNIX)
-find_package(HDF5 REQUIRED COMPONENTS C)
-# HDF5 can have Threads::Threads target, otherwise undefined without Threads
-find_package(Threads QUIET)
-# use imported targets from HDF5_LIBRARIES or take the supplied library path
-# and turn it into an imported target if it is an hdf5 library
set(HDF5_LIB_TARGETS)
-foreach(LIB IN LISTS HDF5_LIBRARIES)
- if(TARGET ${LIB})
- list(APPEND HDF5_LIB_TARGETS ${LIB})
- else(TARGET ${LIB})
- # name of library file with directory and extension stripped
- get_filename_component(LIBNAME ${LIB} NAME_WE)
- # strip leading lib (if it exists) to get target name
- string(REGEX REPLACE "^lib(.*)" "\\1" TGT ${LIBNAME})
- # exclude non-hdf5 libraries (libs that HDF5 linked against)
- if(${TGT} MATCHES ".*hdf5.*")
- # unknown library type so we don't have to find dll on windows
- add_library(digital_rf::${TGT} UNKNOWN IMPORTED)
- set_target_properties(digital_rf::${TGT} PROPERTIES
- IMPORTED_LOCATION ${LIB}
- )
- if(HDF5_INCLUDE_DIRS)
- set_property(TARGET digital_rf::${TGT} APPEND PROPERTY
- INTERFACE_INCLUDE_DIRECTORIES ${HDF5_INCLUDE_DIRS}
+option(DRF_FORCE_INTREE_HDF5 "Force in-tree HDF5 build using static library" OFF)
+if(SKBUILD OR DRF_FORCE_INTREE_HDF5)
+ include(FetchContent)
+ FetchContent_Declare(
+ HDF5
+ URL https://support.hdfgroup.org/releases/hdf5/v1_14/v1_14_5/downloads/hdf5-1.14.5.tar.gz
+ URL_HASH SHA256=ec2e13c52e60f9a01491bb3158cb3778c985697131fc6a342262d32a26e58e44
+ )
+ FetchContent_MakeAvailable(HDF5)
+ # don't build all of the HDF5 targets by default
+ set_property(DIRECTORY ${HDF5_SOURCE_DIR} PROPERTY EXCLUDE_FROM_ALL ON)
+ # use the static HDF5 library as the dependency when doing an skbuild build
+ list(APPEND HDF5_LIB_TARGETS hdf5-static)
+ # since we're using it, target needs to be installed in the export group
+ install(TARGETS hdf5-static
+ EXPORT libdigital_rfTargets
+ )
+else()
+ find_package(HDF5 REQUIRED COMPONENTS C)
+ # HDF5 can have Threads::Threads target, otherwise undefined without Threads
+ find_package(Threads QUIET)
+ # use imported targets from HDF5_LIBRARIES or take the supplied library path
+ # and turn it into an imported target if it is an hdf5 library
+ foreach(LIB IN LISTS HDF5_LIBRARIES)
+ if(TARGET ${LIB})
+ list(APPEND HDF5_LIB_TARGETS ${LIB})
+ else(TARGET ${LIB})
+ # name of library file with directory and extension stripped
+ get_filename_component(LIBNAME ${LIB} NAME_WE)
+ # strip leading lib (if it exists) to get target name
+ string(REGEX REPLACE "^lib(.*)" "\\1" TGT ${LIBNAME})
+ # exclude non-hdf5 libraries (libs that HDF5 linked against)
+ if(${TGT} MATCHES ".*hdf5.*")
+ # unknown library type so we don't have to find dll on windows
+ add_library(digital_rf::${TGT} UNKNOWN IMPORTED)
+ set_target_properties(digital_rf::${TGT} PROPERTIES
+ IMPORTED_LOCATION ${LIB}
)
- endif(HDF5_INCLUDE_DIRS)
- if(HDF5_DEFINITIONS)
- string(REGEX REPLACE "-D" " " HDF5_DEFINES ${HDF5_DEFINITIONS})
- separate_arguments(HDF5_DEFINES UNIX_COMMAND "${HDF5_DEFINES}")
- set_property(TARGET digital_rf::${TGT} APPEND PROPERTY
- INTERFACE_COMPILE_DEFINITIONS ${HDF5_DEFINES}
- )
- endif(HDF5_DEFINITIONS)
- list(APPEND HDF5_LIB_TARGETS digital_rf::${TGT})
- endif(${TGT} MATCHES ".*hdf5.*")
- endif(TARGET ${LIB})
-endforeach(LIB)
+ if(HDF5_INCLUDE_DIRS)
+ set_property(TARGET digital_rf::${TGT} APPEND PROPERTY
+ INTERFACE_INCLUDE_DIRECTORIES ${HDF5_INCLUDE_DIRS}
+ )
+ endif(HDF5_INCLUDE_DIRS)
+ if(HDF5_DEFINITIONS)
+ string(REGEX REPLACE "-D" " " HDF5_DEFINES ${HDF5_DEFINITIONS})
+ separate_arguments(HDF5_DEFINES UNIX_COMMAND "${HDF5_DEFINES}")
+ set_property(TARGET digital_rf::${TGT} APPEND PROPERTY
+ INTERFACE_COMPILE_DEFINITIONS ${HDF5_DEFINES}
+ )
+ endif(HDF5_DEFINITIONS)
+ list(APPEND HDF5_LIB_TARGETS digital_rf::${TGT})
+ endif(${TGT} MATCHES ".*hdf5.*")
+ endif(TARGET ${LIB})
+ endforeach(LIB)
+endif(SKBUILD OR DRF_FORCE_INTREE_HDF5)
# build/install libdigital_rf
configure_file(include/digital_rf.h include/digital_rf.h COPYONLY)
@@ -87,6 +106,9 @@ if(NOT TARGET build)
add_custom_target(build)
endif(NOT TARGET build)
add_dependencies(build digital_rf)
+target_compile_definitions(digital_rf PUBLIC
+ "$<$>:digital_rf_STATIC_DEFINE>"
+)
target_include_directories(digital_rf PUBLIC
$
$
@@ -105,18 +127,21 @@ set_target_properties(digital_rf PROPERTIES
install(TARGETS digital_rf
EXPORT libdigital_rfTargets
+ COMPONENT C
)
install(FILES
${CMAKE_CURRENT_BINARY_DIR}/include/digital_rf.h
${CMAKE_CURRENT_BINARY_DIR}/include/digital_rf_version.h
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/digital_rf
+ COMPONENT C
)
# build/install pkgconfig configuration files
configure_file(lib/pkgconfig/digital_rf.pc.in lib/pkgconfig/digital_rf.pc @ONLY)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/lib/pkgconfig/digital_rf.pc
DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig
+ COMPONENT C
)
# add targets to the build-tree export set
@@ -145,12 +170,14 @@ set(ConfigPackageLocation ${CMAKE_INSTALL_LIBDIR}/cmake/libdigital_rf)
install(EXPORT libdigital_rfTargets
NAMESPACE digital_rf::
DESTINATION ${ConfigPackageLocation}
+ COMPONENT C
)
install(
FILES
cmake/libdigital_rfConfig.cmake
"${CMAKE_CURRENT_BINARY_DIR}/libdigital_rfConfigVersion.cmake"
DESTINATION ${ConfigPackageLocation}
+ COMPONENT C
)
# examples, tests
diff --git a/c/include/digital_rf.h b/c/include/digital_rf.h
index 05d6b46..d0c4b46 100644
--- a/c/include/digital_rf.h
+++ b/c/include/digital_rf.h
@@ -49,10 +49,14 @@
#include "digital_rf_version.h"
#ifdef _WIN32
-# ifdef digital_rf_EXPORTS
-# define EXPORT __declspec(dllexport)
+# ifdef digital_rf_STATIC_DEFINE
+# define EXPORT
# else
-# define EXPORT __declspec(dllimport)
+# ifdef digital_rf_EXPORTS
+# define EXPORT __declspec(dllexport)
+# else
+# define EXPORT __declspec(dllimport)
+# endif
# endif
#else
# define EXPORT
diff --git a/cmake/create_metadata_dir.py.in b/cmake/create_metadata_dir.py.in
new file mode 100644
index 0000000..236d2a6
--- /dev/null
+++ b/cmake/create_metadata_dir.py.in
@@ -0,0 +1,41 @@
+#!/usr/bin/env python3
+
+import argparse
+import pathlib
+import shutil
+
+import build
+
+parser = argparse.ArgumentParser()
+parser.add_argument("--build", action="store_true")
+parser.add_argument("--install", action="store_true")
+args = parser.parse_args()
+
+source_dir = pathlib.Path('${PROJECT_SOURCE_DIR}')
+output_dir = pathlib.Path('${CMAKE_CURRENT_BINARY_DIR}')
+install_dir = pathlib.Path('${INSTALL_PLATLIB_DIR}')
+build_artifact = output_dir / "dist-info-created"
+
+if args.build and not build_artifact.exists():
+ builder = build.ProjectBuilder(source_dir)
+ try:
+ distinfo_dir = builder.prepare('wheel', output_dir)
+ except build.BuildBackendException:
+ # create isolated env since dependencies are not already met
+ with build.env.DefaultIsolatedEnv(installer=build.env.Installer) as env:
+ builder = build.ProjectBuilder.from_isolated_env(env, source_dir)
+ env.install(builder.build_system_requires)
+ env.install(builder.get_requires_for_build('wheel'))
+ distinfo_dir = builder.prepare('wheel', output_dir)
+
+ with open(build_artifact, "w") as f:
+ f.write(str(distinfo_dir))
+
+if args.install:
+ with open(build_artifact, "r") as f:
+ distinfo_dir = pathlib.Path(f.read())
+ shutil.copytree(
+ distinfo_dir,
+ install_dir / distinfo_dir.name,
+ dirs_exist_ok=True,
+ )
diff --git a/news/cibuildwheel.rst b/news/cibuildwheel.rst
new file mode 100644
index 0000000..76d65f2
--- /dev/null
+++ b/news/cibuildwheel.rst
@@ -0,0 +1,24 @@
+**Added:**
+
+* Building of Python package wheels using `cibuildwheel` has been added as a GitHub Actions workflow, making use of the change in build system (see below).
+
+**Changed:**
+
+* The build system has been updated to use pyproject.toml + scikit-build-core for the Python package, replacing the legacy setup.py + setuptools system of yore. As a result, the CMake build procedure has changed a bit, notably in that building a Python wheel using CMake is no longer supported. Use `python -m build` or an equivalent frontend from the source root to build Python wheels instead. The Python package can still be built and installed as before using CMake, just not as a wheel.
+
+**Deprecated:**
+
+*
+
+**Removed:**
+
+* Python 2 and Python < 3.8 will no longer be supported, and the README and build system has been updated accordingly.
+* The dependency on `pytz` has been removed in favor of equivalent functionality now in the Python standard library.
+
+**Fixed:**
+
+* Replace deprecated use of Python datetime's `utcnow()` and `utcfromtimestamp()`.
+
+**Security:**
+
+*
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..8acac03
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,196 @@
+[build-system]
+requires = [
+ "mako",
+ "oldest-supported-numpy; python_version<='3.8'",
+ "numpy>=2.0,<3; python_version>'3.8'",
+ "scikit-build-core>=0.10",
+]
+build-backend = "scikit_build_core.build"
+
+[project]
+name = "digital_rf"
+maintainers = [
+ { name = "Ryan Volz", email = "rvolz@mit.edu" },
+]
+authors = [
+ { name = "Bill Rideout", email = "brideout@mit.edu" },
+ { name = "Juha Vierinen", email = "jvi019@uit.no" },
+ { name = "Frank Lind", email = "fdlind@mit.edu" },
+ { name = "Ryan Volz", email = "rvolz@mit.edu" },
+ { name = "John Swoboda", email = "swoboj@mit.edu" },
+]
+description = "Library for reading and writing time-tagged RF data in the Digital RF format"
+readme = "python/README.rst"
+license.file = "LICENSE"
+requires-python = ">=3.8"
+classifiers = [
+ "Development Status :: 5 - Production/Stable",
+ "Environment :: Console",
+ "Intended Audience :: Science/Research",
+ "Intended Audience :: Developers",
+ "License :: OSI Approved :: BSD License",
+ "Operating System :: OS Independent",
+ "Programming Language :: C",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3 :: Only",
+ "Programming Language :: Python :: 3.8",
+ "Programming Language :: Python :: 3.9",
+ "Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
+ "Topic :: Scientific/Engineering",
+]
+keywords = ["hdf5", "radio", "rf"]
+dynamic = ["version"]
+dependencies = [
+ "h5py",
+ "numpy",
+ "packaging",
+ "python-dateutil",
+ "six",
+ "watchdog",
+]
+
+[project.optional-dependencies]
+test = [
+ "pytest >=6",
+ "pytest-cov >=3",
+]
+dev = [
+ "pytest >=6",
+ "pytest-cov >=3",
+]
+dataframe = [
+ "pandas",
+]
+plot = [
+ "matplotlib",
+ "scipy",
+]
+sound = [
+ "sounddevice"
+]
+all = [
+ "matplotlib",
+ "pandas",
+ "scipy",
+ "sounddevice",
+]
+
+[project.urls]
+Homepage = "https://github.com/MITHaystack/digital_rf"
+"Bug Tracker" = "https://github.com/MITHaystack/digital_rf/issues"
+Discussions = "https://github.com/MITHaystack/digital_rf/discussions"
+Changelog = "https://github.com/MITHaystack/digital_rf/releases"
+
+[project.scripts]
+drf = "digital_rf.drf_command:main"
+
+
+[tool.scikit-build]
+minimum-version = "build-system.requires"
+build-dir = "build/{wheel_tag}"
+metadata.version.provider = "scikit_build_core.metadata.setuptools_scm"
+sdist.include = ["python/digital_rf/_version.py"]
+sdist.exclude = []
+build.targets = ["digital_rf_python"]
+install.components = ["python"]
+wheel.packages = ["python/digital_rf", "python/gr_digital_rf"]
+experimental = true
+wheel.install-dir = "/data"
+
+[tool.scikit-build.cmake.define]
+BUILD_SHARED_LIBS = false
+CMAKE_INSTALL_LIBDIR = "lib"
+HDF5_ENABLE_SZIP_SUPPORT = false
+
+
+[tool.setuptools_scm]
+write_to = "python/digital_rf/_version.py"
+
+
+[tool.cibuildwheel]
+build-frontend = "build"
+test-command = "pytest {project}/python/tests"
+test-extras = ["test"]
+
+
+[tool.pytest.ini_options]
+minversion = "6.0"
+addopts = ["-ra", "--showlocals", "--strict-markers", "--strict-config", "--maxfail=10"]
+markers = ["firstonly"]
+xfail_strict = true
+filterwarnings = [
+ "error",
+]
+log_cli_level = "INFO"
+testpaths = [
+ "python/tests",
+]
+
+
+[tool.coverage]
+run.source = ["digital_rf"]
+report.exclude_also = [
+ '\.\.\.',
+ 'if typing.TYPE_CHECKING:',
+]
+
+
+[tool.ruff]
+line-length = 88
+
+[tool.ruff.lint]
+extend-select = [
+ "B", # flake8-bugbear
+ "I", # isort
+ "ARG", # flake8-unused-arguments
+ "C4", # flake8-comprehensions
+ "EM", # flake8-errmsg
+ "ICN", # flake8-import-conventions
+ "G", # flake8-logging-format
+ "PGH", # pygrep-hooks
+ "PIE", # flake8-pie
+ "PL", # pylint
+ "PT", # flake8-pytest-style
+ "PTH", # flake8-use-pathlib
+ "RET", # flake8-return
+ "RUF", # Ruff-specific
+ "SIM", # flake8-simplify
+ "T20", # flake8-print
+ "UP", # pyupgrade
+ "YTT", # flake8-2020
+ "EXE", # flake8-executable
+ "NPY", # NumPy specific rules
+ "PD", # pandas-vet
+]
+ignore = [
+ "PLR09", # Too many <...>
+ "PLR2004", # Magic value used in comparison
+ "ISC001", # Conflicts with formatter
+]
+isort.required-imports = ["from __future__ import annotations"]
+# Uncomment if using a _compat.typing backport
+# typing-modules = ["digital_rf._compat.typing"]
+
+[tool.ruff.lint.per-file-ignores]
+"tests/**" = ["T20"]
+"noxfile.py" = ["T20"]
+
+
+[tool.pylint]
+py-version = "3.8"
+ignore-paths = [".*/_version.py"]
+extension-pkg-allow-list = ["digital_rf.digital_rf_hdf5"]
+reports.output-format = "colorized"
+similarities.ignore-imports = "yes"
+messages_control.disable = [
+ "design",
+ "fixme",
+ "line-too-long",
+ "missing-module-docstring",
+ "missing-function-docstring",
+ "wrong-import-position",
+]
diff --git a/python/.gitattributes b/python/.gitattributes
deleted file mode 100644
index 7a702ff..0000000
--- a/python/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-digital_rf/_version.py export-subst
diff --git a/python/CMakeLists.txt b/python/CMakeLists.txt
index a499451..70b3a73 100644
--- a/python/CMakeLists.txt
+++ b/python/CMakeLists.txt
@@ -1,107 +1,36 @@
-cmake_minimum_required(VERSION 3.0)
-cmake_policy(SET CMP0048 NEW)
-if(${CMAKE_VERSION} GREATER_EQUAL "3.15")
- cmake_policy(SET CMP0094 NEW)
-endif(${CMAKE_VERSION} GREATER_EQUAL "3.15")
-
-# can't do binary dir == source dir because of file copying
-if(CMAKE_BINARY_DIR STREQUAL CMAKE_SOURCE_DIR)
- message(FATAL_ERROR "Must use a build/binary directory different from the\
- source directory.")
-endif(CMAKE_BINARY_DIR STREQUAL CMAKE_SOURCE_DIR)
-
-if(PYTHON_EXECUTABLE)
- # handle setting python executable by old variable name
- set(Python_EXECUTABLE ${PYTHON_EXECUTABLE})
-endif(PYTHON_EXECUTABLE)
-if(Python_EXECUTABLE)
- message(STATUS "User set python executable: ${Python_EXECUTABLE}")
-else()
- find_package(Python QUIET MODULE)
- if(Python_FOUND)
- message(STATUS "Found Python: ${Python_EXECUTABLE} (found version \"${Python_VERSION}\")")
- else()
- # fall back to older FindPythonInterp CMake module
- find_package(PythonInterp REQUIRED)
- set(Python_EXECUTABLE ${PYTHON_EXECUTABLE})
- endif(Python_FOUND)
-endif(Python_EXECUTABLE)
-
-set(digital_rf_VERSION 2.6.9)
-project(digital_rf LANGUAGES C VERSION ${digital_rf_VERSION})
-
-include(GNUInstallDirs)
-
-# variables to allow for different install locations for python package
-set(DRF_INSTALL_PREFIX_PYTHON CACHE PATH
- "Installation prefix for python package"
-)
-set(DRF_DATA_PREFIX_PYTHON CACHE PATH
- "Data installation prefix for python package"
-)
-set(DRF_SCRIPT_PREFIX_PYTHON CACHE PATH
- "Script installation prefix for python package"
-)
-
-# get compiler settings for digital_rf interface libraries (i.e. HDF5)
-# to pass to setup.py
-find_package(HDF5 REQUIRED COMPONENTS C)
-# need to set HDF5_LIBRARY_DIRS ourselves because FindHDF5 dropped it
-foreach(LIB IN LISTS HDF5_LIBRARIES)
- if(TARGET ${LIB})
- list(APPEND HDF5_LIBRARY_DIRS $)
- else(TARGET ${LIB})
- # name of library file with directory and extension stripped
- get_filename_component(LIBDIR ${LIB} DIRECTORY)
- list(APPEND HDF5_LIBRARY_DIRS ${LIBDIR})
- endif(TARGET ${LIB})
-endforeach(LIB)
-# make the lists still be semicolon-separated after generator expansion
-string(REGEX REPLACE ";" "\\\\;" HDF5_LIBRARY_DIRS "${HDF5_LIBRARY_DIRS}")
-# no matter what the find_package sets, we only care about the "hdf5" library
-set(HDF5_LIBRARIES hdf5)
-# make list out of space-separated HDF5_DEFINITIONS
-separate_arguments(HDF5_DEFINE UNIX_COMMAND "${HDF5_DEFINITIONS}")
-
-# copy files from root directory that we want in the python package
-set(ROOT_SRCS AUTHORS CHANGELOG.rst LICENSE)
-file(GLOB_RECURSE DATA_FILES
- RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/.." "../data/*"
-)
-foreach(SRCFILE ${ROOT_SRCS} ${DATA_FILES})
- configure_file(../${SRCFILE} ${SRCFILE} COPYONLY)
-endforeach(SRCFILE)
-
-# copy C source files from libdigital_rf into build directory
-set(C_SRCS
- include/digital_rf.h
- include/digital_rf_version.h
- include/windows/inttypes.h
- include/windows/stdint.h
- include/windows/wincompat.h
- lib/rf_write_hdf5.c
+find_package(
+ Python
+ COMPONENTS Interpreter Development.Module NumPy
+ REQUIRED
)
-foreach(SRCFILE ${C_SRCS})
- configure_file(../c/${SRCFILE} ${SRCFILE} COPYONLY)
-endforeach(SRCFILE)
-# get list of python source files by generating egg info
-set(EGG_INFO_OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/temp_egg/${PROJECT_NAME}.egg-info)
-file(MAKE_DIRECTORY ${EGG_INFO_OUTPUT})
+# check for mako, needed to create gr_digital_rf source/sink blocks from templates
execute_process(
- COMMAND ${Python_EXECUTABLE} setup.py -q
- egg_info -e ${CMAKE_CURRENT_BINARY_DIR}/temp_egg
- WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
- ERROR_QUIET
+ COMMAND ${Python_EXECUTABLE} -c "import mako"
+ RESULT_VARIABLE MAKO_CHECK_RESULT
+ OUTPUT_QUIET
)
-file(READ ${EGG_INFO_OUTPUT}/SOURCES.txt PYSOURCES)
-string(REGEX REPLACE ";" "\\\\;" PYSOURCES "${PYSOURCES}")
-string(REGEX REPLACE "\n" ";" PYSOURCES "${PYSOURCES}")
+if(MAKO_CHECK_RESULT EQUAL 0)
+ message(STATUS "Python checking for `mako` - found")
+ set(MAKO_FOUND TRUE)
+else()
+ message(STATUS "Python checking for `mako` - not found")
+ set(MAKO_FOUND FALSE)
+endif()
+if(NOT MAKO_FOUND)
+ message(SEND_ERROR "Could not find required build dependency: Python package `mako`")
+endif()
+
+add_custom_target(digital_rf_python ALL)
+if(NOT TARGET build)
+ add_custom_target(build)
+endif(NOT TARGET build)
-# copy python source files to build directory so we can run setup.py from there
-foreach(SRCFILE ${PYSOURCES})
- configure_file(${SRCFILE} ${SRCFILE} COPYONLY)
-endforeach(SRCFILE)
+python_add_library(digital_rf_python_module MODULE lib/py_rf_write_hdf5.c WITH_SOABI)
+target_link_libraries(digital_rf_python_module PUBLIC digital_rf PRIVATE Python::NumPy)
+set_target_properties(digital_rf_python_module PROPERTIES OUTPUT_NAME _py_rf_write_hdf5)
+add_dependencies(digital_rf_python digital_rf_python_module)
+add_dependencies(build digital_rf_python_module)
# build requires generating some of the gnuradio-companion blocks
macro(gen_block _generator _tmpl _out)
@@ -135,89 +64,127 @@ gen_block(
grc/gr_digital_rf_digital_rf_source.block.yml.tmpl
grc/gr_digital_rf_digital_rf_source.block.yml
)
-add_custom_target(gr_digital_rf_grc_generated_blocks ALL
+add_custom_target(gr_digital_rf_grc_generated_blocks
DEPENDS ${GENERATED_BLOCKS}
)
+add_dependencies(digital_rf_python gr_digital_rf_grc_generated_blocks)
-add_custom_target(digital_rf_source)
-add_dependencies(digital_rf_source gr_digital_rf_grc_generated_blocks)
-if(NOT TARGET source)
- add_custom_target(source)
-endif(NOT TARGET source)
-add_dependencies(source digital_rf_source)
+if(SKBUILD)
+ # skbuild should be set up to have CMAKE_INSTALL_PREFIX point to the "DATA"
+ # directory in the built wheel, so we need the installation directories for
+ # the extension module and scripts which are separate from that root
+ set(INSTALL_PLATLIB_DIR ${SKBUILD_PLATLIB_DIR})
+ set(INSTALL_SCRIPTS_DIR ${SKBUILD_SCRIPTS_DIR})
+else()
+ # set the installation directories when skbuild is not used
+ if(WIN32)
+ set(_SCRIPTS_DIR ${CMAKE_INSTALL_PREFIX}/Scripts)
+ else()
+ set(_SCRIPTS_DIR ${CMAKE_INSTALL_BINDIR})
+ endif()
+ set(DRF_INSTALL_PLATLIB ${Python_SITEARCH} CACHE STRING
+ "Python platlib (site-packages) path to use for installation"
+ )
+ set(DRF_INSTALL_SCRIPTS ${_SCRIPTS_DIR} CACHE STRING
+ "Python scripts (bin) path to use for installation"
+ )
+ cmake_path(
+ ABSOLUTE_PATH DRF_INSTALL_PLATLIB
+ BASE_DIRECTORY ${CMAKE_INSTALL_PREFIX}
+ NORMALIZE
+ OUTPUT_VARIABLE INSTALL_PLATLIB_DIR
+ )
+ cmake_path(
+ ABSOLUTE_PATH DRF_INSTALL_SCRIPTS
+ BASE_DIRECTORY ${CMAKE_INSTALL_PREFIX}
+ NORMALIZE
+ OUTPUT_VARIABLE INSTALL_SCRIPTS_DIR
+ )
+ cmake_path(IS_PREFIX
+ CMAKE_INSTALL_PREFIX ${INSTALL_PLATLIB_DIR}
+ NORMALIZE PLATLIB_IS_IN_PREFIX
+ )
+ if(NOT PLATLIB_IS_IN_PREFIX)
+ message(WARNING "Python DRF_INSTALL_PLATLIB (${DRF_INSTALL_PLATLIB}) is not relative or prefixed by CMAKE_INSTALL_PREFIX (${CMAKE_INSTALL_PREFIX}). This is unusual and might not be intended. Check and/or set these variables accordingly.")
+ endif()
+ cmake_path(IS_PREFIX
+ CMAKE_INSTALL_PREFIX ${INSTALL_SCRIPTS_DIR}
+ NORMALIZE SCRIPTS_IS_IN_PREFIX
+ )
+ if(NOT SCRIPTS_IS_IN_PREFIX)
+ message(WARNING "Python DRF_INSTALL_SCRIPTS (${DRF_INSTALL_SCRIPTS}) is not relative or prefixed by CMAKE_INSTALL_PREFIX (${CMAKE_INSTALL_PREFIX}). This is unusual and might not be intended. Check and/or set these variables accordingly.")
+ endif()
+
+ # check for Python build package, which is used to create/install valid
+ # metadata for the Python package
+ execute_process(
+ COMMAND ${Python_EXECUTABLE} -c "import build"
+ RESULT_VARIABLE PYTHON_BUILD_CHECK_RESULT
+ OUTPUT_QUIET
+ )
+ if(PYTHON_BUILD_CHECK_RESULT EQUAL 0)
+ message(STATUS "Python checking for `build` - found")
+ set(PYTHON_BUILD_FOUND TRUE)
+ else()
+ message(STATUS "Python checking for `build` - not found")
+ set(PYTHON_BUILD_FOUND FALSE)
+ endif()
+ if(NOT PYTHON_BUILD_FOUND)
+ message(SEND_ERROR "Could not find required build dependency: Python package `build`")
+ endif()
+
+ # create the Python package metadata directory using the `build` frontend
+ set(DRF_DIST_INFO_DIR_NAME digital_rf-${digital_rf_VERSION}.dist-info)
+ set(DIST_INFO_ARTIFACT_FILE ${CMAKE_CURRENT_BINARY_DIR}/dist-info-created)
+ configure_file(
+ ${PROJECT_SOURCE_DIR}/cmake/create_metadata_dir.py.in
+ ${CMAKE_CURRENT_BINARY_DIR}/create_metadata_dir.py
+ )
+ add_custom_command(
+ OUTPUT ${DIST_INFO_ARTIFACT_FILE}
+ COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/create_metadata_dir.py --build
+ DEPENDS ${PROJECT_SOURCE_DIR}/pyproject.toml
+ ${PROJECT_SOURCE_DIR}/cmake/create_metadata_dir.py.in
+ )
+ add_custom_target(digital_rf_python_package_metadata
+ DEPENDS ${DIST_INFO_ARTIFACT_FILE}
+ )
+ add_dependencies(digital_rf_python digital_rf_python_package_metadata)
-add_custom_target(digital_rf_sdist
- COMMAND ${Python_EXECUTABLE} setup.py sdist -d ${CMAKE_BINARY_DIR}/dist
- DEPENDS ${PYSOURCES}
- WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
-)
-add_dependencies(digital_rf_sdist digital_rf_source)
-if(NOT TARGET sdist)
- add_custom_target(sdist)
-endif(NOT TARGET sdist)
-add_dependencies(sdist digital_rf_sdist)
+ install(
+ CODE "execute_process(COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/create_metadata_dir.py --install)"
+ COMPONENT python
+ )
-# build and install python package with setup.py
-set(PYBUILD_OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/build)
-add_custom_command(
- OUTPUT ${PYBUILD_OUTPUT}
- COMMAND ${CMAKE_COMMAND} -E env HDF5_INCLUDE_DIRS="${HDF5_INCLUDE_DIRS}"
- HDF5_LIBRARY_DIRS="${HDF5_LIBRARY_DIRS}"
- HDF5_LIBRARIES="${HDF5_LIBRARIES}"
- HDF5_DEFINE="${HDF5_DEFINE}"
- ${Python_EXECUTABLE} setup.py build
- COMMAND ${Python_EXECUTABLE} setup.py egg_info
- COMMAND ${CMAKE_COMMAND} -E touch ${PYBUILD_OUTPUT}
- DEPENDS ${PYSOURCES}
- WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
-)
-add_custom_target(digital_rf_python ALL
- DEPENDS ${PYBUILD_OUTPUT}
-)
-add_dependencies(digital_rf_python digital_rf_source)
-if(NOT TARGET build)
- add_custom_target(build)
-endif(NOT TARGET build)
-add_dependencies(build digital_rf_python)
-add_custom_target(digital_rf_wheel
- COMMAND ${Python_EXECUTABLE} setup.py bdist_wheel -d ${CMAKE_BINARY_DIR}/dist
- DEPENDS ${PYBUILD_OUTPUT}
- WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
+ # skbuild installs the pure python packages itself, but without it we
+ # need to do that here
+ install(
+ DIRECTORY digital_rf gr_digital_rf
+ DESTINATION ${INSTALL_PLATLIB_DIR}
+ COMPONENT python
+ )
+endif(SKBUILD)
+
+
+install(TARGETS digital_rf_python_module DESTINATION ${INSTALL_PLATLIB_DIR}/digital_rf COMPONENT python)
+
+install(
+ FILES ${GENERATED_BLOCKS}
+ DESTINATION ${CMAKE_INSTALL_DATADIR}/gnuradio/grc/blocks
+ COMPONENT python
)
-if(NOT TARGET wheel)
- add_custom_target(wheel)
-endif(NOT TARGET wheel)
-add_dependencies(wheel digital_rf_wheel)
-# make sure paths on Windows use a double backslash in order to survive
-# setup.py (distutils) parsing when used later
-if(WIN32)
- macro(NORMALIZE_PATH PATHVARNAME)
- file(TO_NATIVE_PATH "${${PATHVARNAME}}" ${PATHVARNAME})
- string(REPLACE "\\" "\\\\" ${PATHVARNAME} "${${PATHVARNAME}}")
- endmacro()
- NORMALIZE_PATH(DRF_INSTALL_PREFIX_PYTHON)
- NORMALIZE_PATH(DRF_DATA_PREFIX_PYTHON)
- NORMALIZE_PATH(DRF_SCRIPT_PREFIX_PYTHON)
-endif(WIN32)
-file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/drf_install_python.cmake
- CONTENT "execute_process(COMMAND ${Python_EXECUTABLE} setup.py install\
-$<$: --prefix=${DRF_INSTALL_PREFIX_PYTHON}>\
-$<$: --install-data=${DRF_DATA_PREFIX_PYTHON}>\
-$<$: --install-scripts=${DRF_SCRIPT_PREFIX_PYTHON}>\
- --root=\$ENV{DESTDIR}/\
- --single-version-externally-managed\
- --record=${CMAKE_CURRENT_BINARY_DIR}/install_${PROJECT_NAME}_manifest.txt\
- WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})\
-")
-install(SCRIPT ${CMAKE_CURRENT_BINARY_DIR}/drf_install_python.cmake)
-# uninstall target
-configure_file(
- ../cmake/cmake_uninstall.cmake.in
- cmake_uninstall.cmake
- IMMEDIATE @ONLY
+install(
+ DIRECTORY grc/
+ DESTINATION ${CMAKE_INSTALL_DATADIR}/gnuradio/grc/blocks
+ COMPONENT python
+ FILES_MATCHING PATTERN "*.yml" PATTERN "*.xml"
)
-add_custom_target(digital_rf_uninstall
- COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake
+install(
+ DIRECTORY tools/
+ DESTINATION ${INSTALL_SCRIPTS_DIR}
+ FILE_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
+ COMPONENT python
+ FILES_MATCHING PATTERN "*.py"
)
diff --git a/python/MANIFEST.in b/python/MANIFEST.in
deleted file mode 100644
index 5b61db5..0000000
--- a/python/MANIFEST.in
+++ /dev/null
@@ -1,29 +0,0 @@
-include AUTHORS
-include CHANGELOG.rst
-include LICENSE
-include MANIFEST.md
-include pyproject.toml
-include README.rst
-include setup.py
-include setup.cfg
-
-recursive-include data *
-include examples/beacon/*.py
-include examples/beacon/config/*.ini
-include examples/sounder/*.py
-include examples/sounder/*.txt
-include examples/sounder/waveforms/*.py
-include examples/sounder/waveforms/*.bin
-include examples/*.py
-include include/*.h
-include include/windows/*.h
-include tests/*.py
-
-# manually include data_files because setuptools doesn't do it automatically
-include grc/*.xml
-include grc/*.block.yml
-include grc/*.tree.yml
-
-# versioneer
-include versioneer.py
-include digital_rf/_version.py
diff --git a/python/dev_requirements.txt b/python/dev_requirements.txt
deleted file mode 100644
index 4008138..0000000
--- a/python/dev_requirements.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-# required python packages for build from git source
-pkgconfig
-mako
-numpy
-setuptools
diff --git a/python/digital_rf/__init__.py b/python/digital_rf/__init__.py
index f3b4bed..290fc1e 100644
--- a/python/digital_rf/__init__.py
+++ b/python/digital_rf/__init__.py
@@ -8,7 +8,7 @@
from . import list_drf # noqa: F401
from .list_drf import ilsdrf, lsdrf # noqa: F401
from . import util # noqa: F401
-from . import _version
+from ._version import __version__, __version_tuple__
_logging.basicConfig(
level=_os.environ.get(
@@ -30,5 +30,3 @@
" those modules."
)
_logger.info(watchdog_msg, exc_info=True)
-
-__version__ = _version.get_versions()["version"]
diff --git a/python/digital_rf/_version.py b/python/digital_rf/_version.py
deleted file mode 100644
index 2bcec60..0000000
--- a/python/digital_rf/_version.py
+++ /dev/null
@@ -1,716 +0,0 @@
-# This file helps to compute a version number in source trees obtained from
-# git-archive tarball (such as those provided by githubs download-from-tag
-# feature). Distribution tarballs (built by setup.py sdist) and build
-# directories (produced by setup.py build) will contain a much shorter file
-# that just contains the computed version number.
-
-# This file is released into the public domain.
-# Generated by versioneer-0.29
-# https://github.com/python-versioneer/python-versioneer
-
-"""Git implementation of _version.py."""
-
-import errno
-import os
-import re
-import subprocess
-import sys
-from typing import Any, Callable, Dict, List, Optional, Tuple
-import functools
-
-
-def get_keywords() -> Dict[str, str]:
- """Get the keywords needed to look up the version information."""
- # these strings will be replaced by git during git-archive.
- # setup.py/versioneer.py will grep for the variable names, so they must
- # each be defined on a line of their own. _version.py will just call
- # get_keywords().
- git_refnames = "$Format:%d$"
- git_full = "$Format:%H$"
- git_date = "$Format:%ci$"
- keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
- return keywords
-
-
-class VersioneerConfig:
- """Container for Versioneer configuration parameters."""
-
- VCS: str
- style: str
- tag_prefix: str
- parentdir_prefix: str
- versionfile_source: str
- verbose: bool
-
-
-def get_config() -> VersioneerConfig:
- """Create, populate and return the VersioneerConfig() object."""
- # these strings are filled in when 'setup.py versioneer' creates
- # _version.py
- cfg = VersioneerConfig()
- cfg.VCS = "git"
- cfg.style = "pep440"
- cfg.tag_prefix = ""
- cfg.parentdir_prefix = "None"
- cfg.versionfile_source = "digital_rf/_version.py"
- cfg.verbose = False
- return cfg
-
-
-class NotThisMethod(Exception):
- """Exception raised if a method is not valid for the current scenario."""
-
-
-LONG_VERSION_PY: Dict[str, str] = {}
-HANDLERS: Dict[str, Dict[str, Callable]] = {}
-
-
-def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator
- """Create decorator to mark a method as the handler of a VCS."""
-
- def decorate(f: Callable) -> Callable:
- """Store f in HANDLERS[vcs][method]."""
- if vcs not in HANDLERS:
- HANDLERS[vcs] = {}
- HANDLERS[vcs][method] = f
- return f
-
- return decorate
-
-
-def run_command(
- commands: List[str],
- args: List[str],
- cwd: Optional[str] = None,
- verbose: bool = False,
- hide_stderr: bool = False,
- env: Optional[Dict[str, str]] = None,
-) -> Tuple[Optional[str], Optional[int]]:
- """Call the given command(s)."""
- assert isinstance(commands, list)
- process = None
-
- popen_kwargs: Dict[str, Any] = {}
- if sys.platform == "win32":
- # This hides the console window if pythonw.exe is used
- startupinfo = subprocess.STARTUPINFO()
- startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
- popen_kwargs["startupinfo"] = startupinfo
-
- for command in commands:
- try:
- dispcmd = str([command] + args)
- # remember shell=False, so use git.cmd on windows, not just git
- process = subprocess.Popen(
- [command] + args,
- cwd=cwd,
- env=env,
- stdout=subprocess.PIPE,
- stderr=(subprocess.PIPE if hide_stderr else None),
- **popen_kwargs,
- )
- break
- except OSError as e:
- if e.errno == errno.ENOENT:
- continue
- if verbose:
- print("unable to run %s" % dispcmd)
- print(e)
- return None, None
- else:
- if verbose:
- print("unable to find command, tried %s" % (commands,))
- return None, None
- stdout = process.communicate()[0].strip().decode()
- if process.returncode != 0:
- if verbose:
- print("unable to run %s (error)" % dispcmd)
- print("stdout was %s" % stdout)
- return None, process.returncode
- return stdout, process.returncode
-
-
-def versions_from_parentdir(
- parentdir_prefix: str,
- root: str,
- verbose: bool,
-) -> Dict[str, Any]:
- """Try to determine the version from the parent directory name.
-
- Source tarballs conventionally unpack into a directory that includes both
- the project name and a version string. We will also support searching up
- two directory levels for an appropriately named parent directory
- """
- rootdirs = []
-
- for _ in range(3):
- dirname = os.path.basename(root)
- if dirname.startswith(parentdir_prefix):
- return {
- "version": dirname[len(parentdir_prefix) :],
- "full-revisionid": None,
- "dirty": False,
- "error": None,
- "date": None,
- }
- rootdirs.append(root)
- root = os.path.dirname(root) # up a level
-
- if verbose:
- print(
- "Tried directories %s but none started with prefix %s"
- % (str(rootdirs), parentdir_prefix)
- )
- raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
-
-
-@register_vcs_handler("git", "get_keywords")
-def git_get_keywords(versionfile_abs: str) -> Dict[str, str]:
- """Extract version information from the given file."""
- # the code embedded in _version.py can just fetch the value of these
- # keywords. When used from setup.py, we don't want to import _version.py,
- # so we do it with a regexp instead. This function is not used from
- # _version.py.
- keywords: Dict[str, str] = {}
- try:
- with open(versionfile_abs, "r") as fobj:
- for line in fobj:
- if line.strip().startswith("git_refnames ="):
- mo = re.search(r'=\s*"(.*)"', line)
- if mo:
- keywords["refnames"] = mo.group(1)
- if line.strip().startswith("git_full ="):
- mo = re.search(r'=\s*"(.*)"', line)
- if mo:
- keywords["full"] = mo.group(1)
- if line.strip().startswith("git_date ="):
- mo = re.search(r'=\s*"(.*)"', line)
- if mo:
- keywords["date"] = mo.group(1)
- except OSError:
- pass
- return keywords
-
-
-@register_vcs_handler("git", "keywords")
-def git_versions_from_keywords(
- keywords: Dict[str, str],
- tag_prefix: str,
- verbose: bool,
-) -> Dict[str, Any]:
- """Get version information from git keywords."""
- if "refnames" not in keywords:
- raise NotThisMethod("Short version file found")
- date = keywords.get("date")
- if date is not None:
- # Use only the last line. Previous lines may contain GPG signature
- # information.
- date = date.splitlines()[-1]
-
- # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
- # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
- # -like" string, which we must then edit to make compliant), because
- # it's been around since git-1.5.3, and it's too difficult to
- # discover which version we're using, or to work around using an
- # older one.
- date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
- refnames = keywords["refnames"].strip()
- if refnames.startswith("$Format"):
- if verbose:
- print("keywords are unexpanded, not using")
- raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
- refs = {r.strip() for r in refnames.strip("()").split(",")}
- # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
- # just "foo-1.0". If we see a "tag: " prefix, prefer those.
- TAG = "tag: "
- tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)}
- if not tags:
- # Either we're using git < 1.8.3, or there really are no tags. We use
- # a heuristic: assume all version tags have a digit. The old git %d
- # expansion behaves like git log --decorate=short and strips out the
- # refs/heads/ and refs/tags/ prefixes that would let us distinguish
- # between branches and tags. By ignoring refnames without digits, we
- # filter out many common branch names like "release" and
- # "stabilization", as well as "HEAD" and "master".
- tags = {r for r in refs if re.search(r"\d", r)}
- if verbose:
- print("discarding '%s', no digits" % ",".join(refs - tags))
- if verbose:
- print("likely tags: %s" % ",".join(sorted(tags)))
- for ref in sorted(tags):
- # sorting will prefer e.g. "2.0" over "2.0rc1"
- if ref.startswith(tag_prefix):
- r = ref[len(tag_prefix) :]
- # Filter out refs that exactly match prefix or that don't start
- # with a number once the prefix is stripped (mostly a concern
- # when prefix is '')
- if not re.match(r"\d", r):
- continue
- if verbose:
- print("picking %s" % r)
- return {
- "version": r,
- "full-revisionid": keywords["full"].strip(),
- "dirty": False,
- "error": None,
- "date": date,
- }
- # no suitable tags, so version is "0+unknown", but full hex is still there
- if verbose:
- print("no suitable tags, using unknown + full revision id")
- return {
- "version": "0+unknown",
- "full-revisionid": keywords["full"].strip(),
- "dirty": False,
- "error": "no suitable tags",
- "date": None,
- }
-
-
-@register_vcs_handler("git", "pieces_from_vcs")
-def git_pieces_from_vcs(
- tag_prefix: str, root: str, verbose: bool, runner: Callable = run_command
-) -> Dict[str, Any]:
- """Get version from 'git describe' in the root of the source tree.
-
- This only gets called if the git-archive 'subst' keywords were *not*
- expanded, and _version.py hasn't already been rewritten with a short
- version string, meaning we're inside a checked out source tree.
- """
- GITS = ["git"]
- if sys.platform == "win32":
- GITS = ["git.cmd", "git.exe"]
-
- # GIT_DIR can interfere with correct operation of Versioneer.
- # It may be intended to be passed to the Versioneer-versioned project,
- # but that should not change where we get our version from.
- env = os.environ.copy()
- env.pop("GIT_DIR", None)
- runner = functools.partial(runner, env=env)
-
- _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose)
- if rc != 0:
- if verbose:
- print("Directory %s not under git control" % root)
- raise NotThisMethod("'git rev-parse --git-dir' returned error")
-
- # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
- # if there isn't one, this yields HEX[-dirty] (no NUM)
- describe_out, rc = runner(
- GITS,
- [
- "describe",
- "--tags",
- "--dirty",
- "--always",
- "--long",
- "--match",
- f"{tag_prefix}[[:digit:]]*",
- ],
- cwd=root,
- )
- # --long was added in git-1.5.5
- if describe_out is None:
- raise NotThisMethod("'git describe' failed")
- describe_out = describe_out.strip()
- full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root)
- if full_out is None:
- raise NotThisMethod("'git rev-parse' failed")
- full_out = full_out.strip()
-
- pieces: Dict[str, Any] = {}
- pieces["long"] = full_out
- pieces["short"] = full_out[:7] # maybe improved later
- pieces["error"] = None
-
- branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
- # --abbrev-ref was added in git-1.6.3
- if rc != 0 or branch_name is None:
- raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
- branch_name = branch_name.strip()
-
- if branch_name == "HEAD":
- # If we aren't exactly on a branch, pick a branch which represents
- # the current commit. If all else fails, we are on a branchless
- # commit.
- branches, rc = runner(GITS, ["branch", "--contains"], cwd=root)
- # --contains was added in git-1.5.4
- if rc != 0 or branches is None:
- raise NotThisMethod("'git branch --contains' returned error")
- branches = branches.split("\n")
-
- # Remove the first line if we're running detached
- if "(" in branches[0]:
- branches.pop(0)
-
- # Strip off the leading "* " from the list of branches.
- branches = [branch[2:] for branch in branches]
- if "master" in branches:
- branch_name = "master"
- elif not branches:
- branch_name = None
- else:
- # Pick the first branch that is returned. Good or bad.
- branch_name = branches[0]
-
- pieces["branch"] = branch_name
-
- # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
- # TAG might have hyphens.
- git_describe = describe_out
-
- # look for -dirty suffix
- dirty = git_describe.endswith("-dirty")
- pieces["dirty"] = dirty
- if dirty:
- git_describe = git_describe[: git_describe.rindex("-dirty")]
-
- # now we have TAG-NUM-gHEX or HEX
-
- if "-" in git_describe:
- # TAG-NUM-gHEX
- mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
- if not mo:
- # unparsable. Maybe git-describe is misbehaving?
- pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
- return pieces
-
- # tag
- full_tag = mo.group(1)
- if not full_tag.startswith(tag_prefix):
- if verbose:
- fmt = "tag '%s' doesn't start with prefix '%s'"
- print(fmt % (full_tag, tag_prefix))
- pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
- full_tag,
- tag_prefix,
- )
- return pieces
- pieces["closest-tag"] = full_tag[len(tag_prefix) :]
-
- # distance: number of commits since tag
- pieces["distance"] = int(mo.group(2))
-
- # commit: short hex revision ID
- pieces["short"] = mo.group(3)
-
- else:
- # HEX: no tags
- pieces["closest-tag"] = None
- out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root)
- pieces["distance"] = len(out.split()) # total number of commits
-
- # commit date: see ISO-8601 comment in git_versions_from_keywords()
- date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip()
- # Use only the last line. Previous lines may contain GPG signature
- # information.
- date = date.splitlines()[-1]
- pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
-
- return pieces
-
-
-def plus_or_dot(pieces: Dict[str, Any]) -> str:
- """Return a + if we don't already have one, else return a ."""
- if "+" in pieces.get("closest-tag", ""):
- return "."
- return "+"
-
-
-def render_pep440(pieces: Dict[str, Any]) -> str:
- """Build up version string, with post-release "local version identifier".
-
- Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
- get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
-
- Exceptions:
- 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += plus_or_dot(pieces)
- rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- else:
- # exception #1
- rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- return rendered
-
-
-def render_pep440_branch(pieces: Dict[str, Any]) -> str:
- """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
-
- The ".dev0" means not master branch. Note that .dev0 sorts backwards
- (a feature branch will appear "older" than the master branch).
-
- Exceptions:
- 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- if pieces["branch"] != "master":
- rendered += ".dev0"
- rendered += plus_or_dot(pieces)
- rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- else:
- # exception #1
- rendered = "0"
- if pieces["branch"] != "master":
- rendered += ".dev0"
- rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- return rendered
-
-
-def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]:
- """Split pep440 version string at the post-release segment.
-
- Returns the release segments before the post-release and the
- post-release version number (or -1 if no post-release segment is present).
- """
- vc = str.split(ver, ".post")
- return vc[0], int(vc[1] or 0) if len(vc) == 2 else None
-
-
-def render_pep440_pre(pieces: Dict[str, Any]) -> str:
- """TAG[.postN.devDISTANCE] -- No -dirty.
-
- Exceptions:
- 1: no tags. 0.post0.devDISTANCE
- """
- if pieces["closest-tag"]:
- if pieces["distance"]:
- # update the post release segment
- tag_version, post_version = pep440_split_post(pieces["closest-tag"])
- rendered = tag_version
- if post_version is not None:
- rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"])
- else:
- rendered += ".post0.dev%d" % (pieces["distance"])
- else:
- # no commits, use the tag as the version
- rendered = pieces["closest-tag"]
- else:
- # exception #1
- rendered = "0.post0.dev%d" % pieces["distance"]
- return rendered
-
-
-def render_pep440_post(pieces: Dict[str, Any]) -> str:
- """TAG[.postDISTANCE[.dev0]+gHEX] .
-
- The ".dev0" means dirty. Note that .dev0 sorts backwards
- (a dirty tree will appear "older" than the corresponding clean one),
- but you shouldn't be releasing software with -dirty anyways.
-
- Exceptions:
- 1: no tags. 0.postDISTANCE[.dev0]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += ".post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- rendered += plus_or_dot(pieces)
- rendered += "g%s" % pieces["short"]
- else:
- # exception #1
- rendered = "0.post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- rendered += "+g%s" % pieces["short"]
- return rendered
-
-
-def render_pep440_post_branch(pieces: Dict[str, Any]) -> str:
- """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] .
-
- The ".dev0" means not master branch.
-
- Exceptions:
- 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += ".post%d" % pieces["distance"]
- if pieces["branch"] != "master":
- rendered += ".dev0"
- rendered += plus_or_dot(pieces)
- rendered += "g%s" % pieces["short"]
- if pieces["dirty"]:
- rendered += ".dirty"
- else:
- # exception #1
- rendered = "0.post%d" % pieces["distance"]
- if pieces["branch"] != "master":
- rendered += ".dev0"
- rendered += "+g%s" % pieces["short"]
- if pieces["dirty"]:
- rendered += ".dirty"
- return rendered
-
-
-def render_pep440_old(pieces: Dict[str, Any]) -> str:
- """TAG[.postDISTANCE[.dev0]] .
-
- The ".dev0" means dirty.
-
- Exceptions:
- 1: no tags. 0.postDISTANCE[.dev0]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += ".post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- else:
- # exception #1
- rendered = "0.post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- return rendered
-
-
-def render_git_describe(pieces: Dict[str, Any]) -> str:
- """TAG[-DISTANCE-gHEX][-dirty].
-
- Like 'git describe --tags --dirty --always'.
-
- Exceptions:
- 1: no tags. HEX[-dirty] (note: no 'g' prefix)
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"]:
- rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
- else:
- # exception #1
- rendered = pieces["short"]
- if pieces["dirty"]:
- rendered += "-dirty"
- return rendered
-
-
-def render_git_describe_long(pieces: Dict[str, Any]) -> str:
- """TAG-DISTANCE-gHEX[-dirty].
-
- Like 'git describe --tags --dirty --always -long'.
- The distance/hash is unconditional.
-
- Exceptions:
- 1: no tags. HEX[-dirty] (note: no 'g' prefix)
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
- else:
- # exception #1
- rendered = pieces["short"]
- if pieces["dirty"]:
- rendered += "-dirty"
- return rendered
-
-
-def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]:
- """Render the given version pieces into the requested style."""
- if pieces["error"]:
- return {
- "version": "unknown",
- "full-revisionid": pieces.get("long"),
- "dirty": None,
- "error": pieces["error"],
- "date": None,
- }
-
- if not style or style == "default":
- style = "pep440" # the default
-
- if style == "pep440":
- rendered = render_pep440(pieces)
- elif style == "pep440-branch":
- rendered = render_pep440_branch(pieces)
- elif style == "pep440-pre":
- rendered = render_pep440_pre(pieces)
- elif style == "pep440-post":
- rendered = render_pep440_post(pieces)
- elif style == "pep440-post-branch":
- rendered = render_pep440_post_branch(pieces)
- elif style == "pep440-old":
- rendered = render_pep440_old(pieces)
- elif style == "git-describe":
- rendered = render_git_describe(pieces)
- elif style == "git-describe-long":
- rendered = render_git_describe_long(pieces)
- else:
- raise ValueError("unknown style '%s'" % style)
-
- return {
- "version": rendered,
- "full-revisionid": pieces["long"],
- "dirty": pieces["dirty"],
- "error": None,
- "date": pieces.get("date"),
- }
-
-
-def get_versions() -> Dict[str, Any]:
- """Get version information or return default if unable to do so."""
- # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
- # __file__, we can work backwards from there to the root. Some
- # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
- # case we can only use expanded keywords.
-
- cfg = get_config()
- verbose = cfg.verbose
-
- try:
- return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose)
- except NotThisMethod:
- pass
-
- try:
- root = os.path.realpath(__file__)
- # versionfile_source is the relative path from the top of the source
- # tree (where the .git directory might live) to this file. Invert
- # this to find the root from __file__.
- for _ in cfg.versionfile_source.split("/"):
- root = os.path.dirname(root)
- except NameError:
- return {
- "version": "0+unknown",
- "full-revisionid": None,
- "dirty": None,
- "error": "unable to find root of source tree",
- "date": None,
- }
-
- try:
- pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
- return render(pieces, cfg.style)
- except NotThisMethod:
- pass
-
- try:
- if cfg.parentdir_prefix:
- return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
- except NotThisMethod:
- pass
-
- return {
- "version": "0+unknown",
- "full-revisionid": None,
- "dirty": None,
- "error": "unable to compute version",
- "date": None,
- }
diff --git a/python/digital_rf/digital_metadata.py b/python/digital_rf/digital_metadata.py
index 18469cf..6a8a2ed 100644
--- a/python/digital_rf/digital_metadata.py
+++ b/python/digital_rf/digital_metadata.py
@@ -39,16 +39,13 @@
# local imports
from . import list_drf
-from ._version import get_versions
+from ._version import __version__, __version_tuple__
try:
import pandas
except ImportError:
pass
-__version__ = get_versions()["version"]
-del get_versions
-
__all__ = ("DigitalMetadataReader", "DigitalMetadataWriter")
@@ -348,7 +345,9 @@ def _sample_group_generator(self, samples):
start_sub_ts = (
file_ts // self._subdir_cadence_secs
) * self._subdir_cadence_secs
- sub_dt = datetime.datetime.utcfromtimestamp(start_sub_ts)
+ sub_dt = datetime.datetime.fromtimestamp(
+ start_sub_ts, tz=datetime.timezone.utc
+ )
subdir = os.path.join(
self._metadata_dir, sub_dt.strftime("%Y-%m-%dT%H-%M-%S")
)
@@ -1039,7 +1038,9 @@ def _get_file_list(self, sample0, sample1):
end_sub_ts + self._subdir_cadence_secs,
self._subdir_cadence_secs,
):
- sub_datetime = datetime.datetime.utcfromtimestamp(sub_ts)
+ sub_datetime = datetime.datetime.fromtimestamp(
+ sub_ts, tz=datetime.timezone.utc
+ )
subdir = sub_datetime.strftime("%Y-%m-%dT%H-%M-%S")
# create numpy array of all file TS in subdir
file_ts_in_subdir = np.arange(
diff --git a/python/digital_rf/digital_rf_hdf5.py b/python/digital_rf/digital_rf_hdf5.py
index 57f40e1..f79215a 100644
--- a/python/digital_rf/digital_rf_hdf5.py
+++ b/python/digital_rf/digital_rf_hdf5.py
@@ -35,10 +35,7 @@
# local imports
from . import _py_rf_write_hdf5, digital_metadata, list_drf
-from ._version import get_versions
-
-__version__ = get_versions()["version"]
-del get_versions
+from ._version import __version__, __version_tuple__
__all__ = (
"get_unix_time",
@@ -1668,7 +1665,9 @@ def _get_file_list(
int(end_sub_ts + subdir_cadence_seconds),
subdir_cadence_seconds,
):
- sub_datetime = datetime.datetime.utcfromtimestamp(sub_ts)
+ sub_datetime = datetime.datetime.fromtimestamp(
+ sub_ts, tz=datetime.timezone.utc
+ )
subdir = sub_datetime.strftime("%Y-%m-%dT%H-%M-%S")
# create numpy array of all file TS in subdir
file_msts_in_subdir = np.arange(
diff --git a/python/digital_rf/list_drf.py b/python/digital_rf/list_drf.py
index 7f92d3d..d77819d 100644
--- a/python/digital_rf/list_drf.py
+++ b/python/digital_rf/list_drf.py
@@ -15,8 +15,6 @@
import re
import shutil
-import pytz
-
from . import util
__all__ = (
@@ -188,7 +186,7 @@ def _yield_matching_files(
hour=int(m.group("hour")),
minute=int(m.group("minute")),
second=int(m.group("second")),
- tzinfo=pytz.utc,
+ tzinfo=datetime.timezone.utc,
)
time = dt - util.epoch
dec_subdirs.append((time, d))
@@ -312,11 +310,11 @@ def ilsdrf(
# convert starttime and endtime to timedeltas for comparison
if starttime is not None:
if starttime.tzinfo is None:
- starttime = pytz.utc.localize(starttime)
+ starttime = starttime.replace(tzinfo=datetime.timezone.utc)
starttime = starttime - util.epoch
if endtime is not None:
if endtime.tzinfo is None:
- endtime = pytz.utc.localize(endtime)
+ endtime = endtime.replace(tzinfo=datetime.timezone.utc)
endtime = endtime - util.epoch
if include_drf_properties is None:
diff --git a/python/digital_rf/mirror.py b/python/digital_rf/mirror.py
index c2bf060..d54e8bc 100644
--- a/python/digital_rf/mirror.py
+++ b/python/digital_rf/mirror.py
@@ -101,8 +101,10 @@ def mirror_to_dest(self, src_path):
os.makedirs(dest_dir)
if not os.path.exists(dest_path) or not filecmp.cmp(src_path, dest_path):
if self.verbose:
- now = datetime.datetime.utcnow().replace(microsecond=0)
- print("{0} | Mirroring {1}".format(now, src_path))
+ now = datetime.datetime.now(tz=datetime.timezone.utc).replace(
+ microsecond=0
+ )
+ print(f"{now} | Mirroring {src_path}")
else:
sys.stdout.write(".")
sys.stdout.flush()
@@ -328,12 +330,8 @@ def start(self):
# start observer to mirror new and modified files
self.observer.start()
- now = datetime.datetime.utcnow().replace(microsecond=0)
- print(
- "{0} | Mirroring ({1}) {2} to {3}:".format(
- now, self.method, self.src, self.dest
- )
- )
+ now = datetime.datetime.now(tz=datetime.timezone.utc).replace(microsecond=0)
+ print(f"{now} | Mirroring ({self.method}) {self.src} to {self.dest}:")
sys.stdout.flush()
if os.path.isdir(self.src):
diff --git a/python/digital_rf/ringbuffer.py b/python/digital_rf/ringbuffer.py
index 6710116..5b4455f 100644
--- a/python/digital_rf/ringbuffer.py
+++ b/python/digital_rf/ringbuffer.py
@@ -161,8 +161,8 @@ def _expire_oldest_from_group(self, group):
self._remove_from_queue(rec)
if self.verbose:
- now = datetime.datetime.utcnow().replace(microsecond=0)
- print("{0} | Expired {1}".format(now, rec.path))
+ now = datetime.datetime.now(tz=datetime.timezone.utc).replace(microsecond=0)
+ print(f"{now} | Expired {rec.path}")
# delete file
if not self.dryrun:
@@ -209,8 +209,10 @@ def _add_record(self, rec):
self._add_to_queue(rec)
if self.verbose:
- now = datetime.datetime.utcnow().replace(microsecond=0)
- print("{0} | Added {1}".format(now, rec.path))
+ now = datetime.datetime.now(tz=datetime.timezone.utc).replace(
+ microsecond=0
+ )
+ print(f"{now} | Added {rec.path}")
# expire oldest files until size constraint is met
self._expire(rec.group)
@@ -243,8 +245,8 @@ def _remove_record(self, path):
self._remove_from_queue(rec)
if self.verbose:
- now = datetime.datetime.utcnow().replace(microsecond=0)
- print("{0} | Removed {1}".format(now, rec.path))
+ now = datetime.datetime.now(tz=datetime.timezone.utc).replace(microsecond=0)
+ print(f"{now} | Removed {rec.path}")
def add_files(self, paths, sort=True):
"""Create file records from paths and add to ringbuffer."""
@@ -400,8 +402,10 @@ def _modify_record(self, rec):
self.active_size += rec.size
if self.verbose:
- now = datetime.datetime.utcnow().replace(microsecond=0)
- print("{0} | Updated {1}".format(now, rec.path))
+ now = datetime.datetime.now(tz=datetime.timezone.utc).replace(
+ microsecond=0
+ )
+ print(f"{now} | Updated {rec.path}")
class TimeExpirer(object):
@@ -704,15 +708,17 @@ def _add_existing_files(self):
def start(self):
"""Start ringbuffer process."""
- self._start_time = datetime.datetime.utcnow().replace(microsecond=0)
+ self._start_time = datetime.datetime.now(tz=datetime.timezone.utc).replace(
+ microsecond=0
+ )
# start observer to add new files
self.observer.start()
if self.dryrun:
print("DRY RUN (files will not be deleted):")
- now = datetime.datetime.utcnow().replace(microsecond=0)
- print("{0} | Starting {1}:".format(now, self))
+ now = datetime.datetime.now(tz=datetime.timezone.utc).replace(microsecond=0)
+ print(f"{now} | Starting {self}:")
sys.stdout.flush()
# add files that already existed before the observer started
@@ -779,11 +785,13 @@ def join(self):
"""Wait until a KeyboardInterrupt is received to stop ringbuffer."""
try:
while True:
- now = datetime.datetime.utcnow().replace(microsecond=0)
+ now = datetime.datetime.now(tz=datetime.timezone.utc).replace(
+ microsecond=0
+ )
interval = int((now - self._start_time).total_seconds())
if (interval % self.status_interval) == 0:
status = self.event_handler.status()
- print("{0} | ({1})".format(now, status))
+ print(f"{now} | ({status})")
sys.stdout.flush()
if not self.observer.all_alive():
diff --git a/python/digital_rf/util.py b/python/digital_rf/util.py
index 4069c23..641cab5 100644
--- a/python/digital_rf/util.py
+++ b/python/digital_rf/util.py
@@ -14,7 +14,6 @@
import dateutil.parser
import numpy as np
-import pytz
import six
@@ -29,7 +28,7 @@
)
-epoch = datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)
+epoch = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
def time_to_sample(time, samples_per_second):
@@ -58,7 +57,7 @@ def time_to_sample(time, samples_per_second):
if isinstance(time, datetime.datetime):
if time.tzinfo is None:
# assume UTC if timezone was not specified
- time = pytz.utc.localize(time)
+ time = time.replace(tzinfo=datetime.timezone.utc)
td = time - epoch
tsec = int(td.total_seconds())
tfrac = 1e-6 * td.microseconds
@@ -138,7 +137,7 @@ def datetime_to_timestamp(dt):
"""
if dt.tzinfo is None:
# assume UTC if timezone was not specified
- dt = pytz.utc.localize(dt)
+ dt = dt.replace(tzinfo=datetime.timezone.utc)
return (dt - epoch).total_seconds()
@@ -195,7 +194,7 @@ def parse_identifier_to_sample(iden, samples_per_second=None, ref_index=None):
'"+" identifier must be followed by an integer or float.'
)
if iden.lower().startswith("now"):
- dt = pytz.utc.localize(datetime.datetime.utcnow())
+ dt = datetime.datetime.now(tz=datetime.timezone.utc)
if iden.lower().endswith("ish"):
dt = dt.replace(microsecond=0) + datetime.timedelta(seconds=1)
iden = dt
@@ -273,7 +272,7 @@ def parse_identifier_to_time(iden, samples_per_second=None, ref_datetime=None):
'"+" identifier must be followed by an integer or float.'
)
if iden.lower().startswith("now"):
- dt = pytz.utc.localize(datetime.datetime.utcnow())
+ dt = datetime.datetime.now(tz=datetime.timezone.utc)
if iden.lower().endswith("ish"):
dt = dt.replace(microsecond=0) + datetime.timedelta(seconds=1)
else:
@@ -281,7 +280,7 @@ def parse_identifier_to_time(iden, samples_per_second=None, ref_datetime=None):
dt = dateutil.parser.parse(iden)
if dt.tzinfo is None:
# assume UTC if timezone was not specified in the string
- dt = pytz.utc.localize(dt)
+ dt = dt.replace(tzinfo=datetime.timezone.utc)
return dt
if isinstance(iden, float) or samples_per_second is None:
diff --git a/python/digital_rf/watchdog_drf.py b/python/digital_rf/watchdog_drf.py
index 5309afd..085f89c 100644
--- a/python/digital_rf/watchdog_drf.py
+++ b/python/digital_rf/watchdog_drf.py
@@ -15,7 +15,6 @@
import sys
import time
-import pytz
from watchdog.events import (
DirCreatedEvent,
FileCreatedEvent,
@@ -93,12 +92,12 @@ def __init__(
# convert starttime and endtime to timedeltas for comparison
if starttime is not None:
if starttime.tzinfo is None:
- starttime = pytz.utc.localize(starttime)
+ starttime = starttime.replace(tzinfo=datetime.timezone.utc)
starttime = starttime - util.epoch
self.starttime = starttime
if endtime is not None:
if endtime.tzinfo is None:
- endtime = pytz.utc.localize(endtime)
+ endtime = endtime.replace(tzinfo=datetime.timezone.utc)
endtime = endtime - util.epoch
self.endtime = endtime
@@ -397,7 +396,7 @@ def schedule(self, event_handler, path=None, recursive=False):
def start(self):
"""Start watching and enable handlers."""
- now = datetime.datetime.utcnow().replace(microsecond=0)
+ now = datetime.datetime.now(tz=datetime.timezone.utc).replace(microsecond=0)
msg = "{0} | Starting watchdog observer(s)."
print(msg.format(now))
sys.stdout.flush()
@@ -505,23 +504,23 @@ def __init__(self, dir, force_polling=None, **kwargs):
super(DigitalRFPrint, self).__init__(**kwargs)
def on_created(self, event):
- now = datetime.datetime.utcnow().replace(microsecond=0)
+ now = datetime.datetime.now(tz=datetime.timezone.utc).replace(microsecond=0)
path = os.path.relpath(event.src_path, self.root_dir)
- print("{0} | Created {1}".format(now, path))
+ print(f"{now} | Created {path}")
def on_deleted(self, event):
- now = datetime.datetime.utcnow().replace(microsecond=0)
+ now = datetime.datetime.now(tz=datetime.timezone.utc).replace(microsecond=0)
path = os.path.relpath(event.src_path, self.root_dir)
- print("{0} | Deleted {1}".format(now, path))
+ print(f"{now} | Deleted {path}")
def on_modified(self, event):
- now = datetime.datetime.utcnow().replace(microsecond=0)
+ now = datetime.datetime.now(tz=datetime.timezone.utc).replace(microsecond=0)
path = os.path.relpath(event.src_path, self.root_dir)
- print("{0} | Modified {1}".format(now, path))
+ print(f"{now} | Modified {path}")
def on_moved(self, event):
msg = "{0} | Moved {1} to {2}"
- now = datetime.datetime.utcnow().replace(microsecond=0)
+ now = datetime.datetime.now(tz=datetime.timezone.utc).replace(microsecond=0)
src_path = os.path.relpath(event.src_path, self.root_dir)
dest_path = os.path.relpath(event.dest_path, self.root_dir)
print(msg.format(now, src_path, dest_path))
@@ -533,8 +532,8 @@ def on_moved(self, event):
observer.schedule(event_handler, args.dir, recursive=True)
print("Type Ctrl-C to quit.")
observer.start()
- now = datetime.datetime.utcnow().replace(microsecond=0)
- print("{0} | Monitoring {1}:".format(now, args.dir))
+ now = datetime.datetime.now(tz=datetime.timezone.utc).replace(microsecond=0)
+ print(f"{now} | Monitoring {args.dir}:")
sys.stdout.flush()
try:
while True:
diff --git a/python/examples/beacon/beacon_record.py b/python/examples/beacon/beacon_record.py
index 4ea213b..6174054 100644
--- a/python/examples/beacon/beacon_record.py
+++ b/python/examples/beacon/beacon_record.py
@@ -28,7 +28,6 @@
import dateutil.parser
import ephem
import numpy as np
-import pytz
from digital_rf import DigitalMetadataWriter
from six.moves import configparser
@@ -431,7 +430,7 @@ def get_next_object(opt, site, objects, ctime):
obj_tle1 = obj_info["tle1"][1:-1]
obj_tle2 = obj_info["tle2"][1:-1]
obj_freqs = np.array(string.split(obj_info["frequencies"], ","), np.float32)
- c_dtime = datetime.datetime.utcfromtimestamp(ctime)
+ c_dtime = datetime.datetime.fromtimestamp(ctime, tz=datetime.timezone.utc)
c_ephem_time = ephem.Date(c_dtime)
(sat_rise, sat_transit, sat_set) = satellite_rise_and_set(
@@ -517,7 +516,7 @@ def ephemeris_passes(opt, st0, et0):
obj_tle1 = obj_info["tle1"][1:-1]
obj_tle2 = obj_info["tle2"][1:-1]
obj_freqs = np.array(string.split(obj_info["frequencies"], ","), np.float32)
- c_dtime = datetime.datetime.utcfromtimestamp(ctime)
+ c_dtime = datetime.datetime.fromtimestamp(ctime, tz=datetime.timezone.utc)
c_ephem_time = ephem.Date(c_dtime)
try:
@@ -783,12 +782,18 @@ def ephemeris_passes(opt, st0, et0):
dtstop0 = dateutil.parser.parse(offset_set_time)
start0 = int(
(
- dtstart0 - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)
+ dtstart0
+ - datetime.datetime(
+ 1970, 1, 1, tzinfo=datetime.timezone.utc
+ )
).total_seconds()
)
stop0 = int(
(
- dtstop0 - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)
+ dtstop0
+ - datetime.datetime(
+ 1970, 1, 1, tzinfo=datetime.timezone.utc
+ )
).total_seconds()
)
@@ -995,7 +1000,9 @@ def parse_command_line():
else:
dtst0 = dateutil.parser.parse(op.starttime)
st0 = int(
- (dtst0 - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
+ (
+ dtst0 - datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
+ ).total_seconds()
)
print("Start time: %s (%d)" % (dtst0.strftime("%a %b %d %H:%M:%S %Y"), st0))
@@ -1006,7 +1013,9 @@ def parse_command_line():
else:
dtet0 = dateutil.parser.parse(op.endtime)
et0 = int(
- (dtet0 - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
+ (
+ dtet0 - datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
+ ).total_seconds()
)
print("End time: %s (%d)" % (dtet0.strftime("%a %b %d %H:%M:%S %Y"), et0))
diff --git a/python/examples/sounder/prc_analyze.py b/python/examples/sounder/prc_analyze.py
index 4612d0a..db44af2 100755
--- a/python/examples/sounder/prc_analyze.py
+++ b/python/examples/sounder/prc_analyze.py
@@ -258,9 +258,9 @@ def analyze_prc(
plt.colorbar()
plt.title(
- datetime.datetime.utcfromtimestamp(idx / sr).strftime(
- "%Y-%m-%d %H:%M:%S"
- )
+ datetime.datetime.fromtimestamp(
+ idx / sr, tz=datetime.timezone.utc
+ ).strftime("%Y-%m-%d %H:%M:%S")
)
plt.savefig(
os.path.join(
diff --git a/python/examples/sounder/tx.py b/python/examples/sounder/tx.py
index 1f0a94e..7292854 100755
--- a/python/examples/sounder/tx.py
+++ b/python/examples/sounder/tx.py
@@ -24,7 +24,6 @@
import digital_rf as drf
import numpy as np
-import pytz
from gnuradio import analog, blocks, gr, uhd
from six.moves import configparser
@@ -551,8 +550,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
st = drf.util.parse_identifier_to_time(starttime)
if st is not None:
# find next suitable start time by cycle repeat period
- now = datetime.utcnow()
- now = now.replace(tzinfo=pytz.utc)
+ now = datetime.now(tz=datetime.timezone.utc)
soon = now + timedelta(seconds=SETUP_TIME)
diff = max(soon - st, timedelta(0)).total_seconds()
periods_until_next = (diff - 1) // period + 1
@@ -572,7 +570,10 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
if (
et
- < (pytz.utc.localize(datetime.utcnow()) + timedelta(seconds=SETUP_TIME))
+ < (
+ datetime.now(tz=datetime.timezone.utc)
+ + timedelta(seconds=SETUP_TIME)
+ )
) or (st is not None and et <= st):
raise ValueError("End time is before launch time!")
@@ -587,9 +588,10 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
# wait for the start time if it is not past
while (st is not None) and (
- (st - pytz.utc.localize(datetime.utcnow())) > timedelta(seconds=SETUP_TIME)
+ (st - datetime.now(tz=datetime.timezone.utc))
+ > timedelta(seconds=SETUP_TIME)
):
- ttl = int((st - pytz.utc.localize(datetime.utcnow())).total_seconds())
+ ttl = int((st - datetime.now(tz=datetime.timezone.utc)).total_seconds())
if (ttl % 10) == 0:
print("Standby {0} s remaining...".format(ttl))
sys.stdout.flush()
@@ -626,7 +628,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
if st is not None:
lt = st
else:
- now = pytz.utc.localize(datetime.utcnow())
+ now = datetime.now(tz=datetime.timezone.utc)
# launch on integer second by default for convenience (ceil + 1)
lt = now.replace(microsecond=0) + timedelta(seconds=2)
ltts = (lt - drf.util.epoch).total_seconds()
@@ -662,7 +664,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
# start the flowgraph once we are near the launch time
# (start too soon and device buffers might not yet be flushed)
# (start too late and device might not be able to start in time)
- while (lt - pytz.utc.localize(datetime.utcnow())) > timedelta(seconds=1.2):
+ while (lt - datetime.now(tz=datetime.timezone.utc)) > timedelta(seconds=1.2):
time.sleep(0.1)
fg.start()
@@ -674,7 +676,9 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
fg.wait()
else:
# sleep until end time nears
- while pytz.utc.localize(datetime.utcnow()) < et - timedelta(seconds=2):
+ while datetime.now(tz=datetime.timezone.utc) < et - timedelta(
+ seconds=2
+ ):
time.sleep(1)
else:
# issue stream stop command at end time
diff --git a/python/gr_digital_rf/__init__.py b/python/gr_digital_rf/__init__.py
index da1ee08..8dd49f7 100644
--- a/python/gr_digital_rf/__init__.py
+++ b/python/gr_digital_rf/__init__.py
@@ -5,7 +5,4 @@
from .raster import *
from .vector import *
-from digital_rf._version import get_versions
-
-__version__ = get_versions()["version"]
-del get_versions
+from digital_rf._version import __version__, __version_tuple__
diff --git a/python/grc/gen_gr_digital_rf_digital_rf_sourcesink.py b/python/grc/gen_gr_digital_rf_digital_rf_sourcesink.py
index b9e4129..a41ec74 100644
--- a/python/grc/gen_gr_digital_rf_digital_rf_sourcesink.py
+++ b/python/grc/gen_gr_digital_rf_digital_rf_sourcesink.py
@@ -7,15 +7,24 @@
# The full license is in the LICENSE file, distributed with this software.
# ----------------------------------------------------------------------------
if __name__ == "__main__":
- import os
+ import pathlib
from argparse import ArgumentParser
from mako.template import Template
desc = "Generate Digital RF Source/Sink GRC block file from template."
parser = ArgumentParser(description=desc)
- parser.add_argument("template", help="Template source/sink file.")
- parser.add_argument("output", nargs="?", help="Output file path.")
+ parser.add_argument(
+ "template",
+ type=pathlib.Path,
+ help="Template source/sink file.",
+ )
+ parser.add_argument(
+ "output",
+ nargs="?",
+ type=pathlib.Path,
+ help="Output file path.",
+ )
parser.add_argument(
"-n",
"--max_channels",
@@ -27,8 +36,8 @@
args = parser.parse_args()
if args.output is None:
- args.output = os.path.basename(os.path.splitext(args.template)[0])
-
- tmpl = Template(filename=args.template)
+ args.output = pathlib.Path(args.template.stem).resolve()
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ tmpl = Template(filename=str(args.template))
with open(args.output, "w") as f:
f.write(tmpl.render(max_num_channels=args.max_channels))
diff --git a/python/pyproject.toml b/python/pyproject.toml
deleted file mode 100644
index 1f54e80..0000000
--- a/python/pyproject.toml
+++ /dev/null
@@ -1,7 +0,0 @@
-[build-system]
-requires = [
- "oldest-supported-numpy",
- "pkgconfig",
- "setuptools",
- "wheel",
-]
diff --git a/python/setup.cfg b/python/setup.cfg
deleted file mode 100644
index b309c6c..0000000
--- a/python/setup.cfg
+++ /dev/null
@@ -1,13 +0,0 @@
-[aliases]
-test=pytest
-
-[flake8]
-ignore = C812,C815,D101,E203,N803,N806,W503
-max-line-length = 88
-
-[versioneer]
-VCS = git
-style = pep440
-versionfile_source = digital_rf/_version.py
-versionfile_build = digital_rf/_version.py
-tag_prefix =
diff --git a/python/setup.py b/python/setup.py
deleted file mode 100644
index f8bbf25..0000000
--- a/python/setup.py
+++ /dev/null
@@ -1,308 +0,0 @@
-# ----------------------------------------------------------------------------
-# Copyright (c) 2017 Massachusetts Institute of Technology (MIT)
-# All rights reserved.
-#
-# Distributed under the terms of the BSD 3-clause license.
-#
-# The full license is in the LICENSE file, distributed with this software.
-# ----------------------------------------------------------------------------
-"""Setup file for the digital_rf package."""
-import os
-import re
-import sys
-
-# to use a consistent encoding
-from codecs import open
-
-from setuptools import Extension, setup
-from setuptools.command.build_ext import build_ext as _build_ext
-
-import versioneer
-
-
-def localpath(*args):
- return os.path.abspath(os.path.join(os.path.dirname(__file__), *args))
-
-
-# Get the long description from the README file
-with open(localpath("README.rst"), encoding="utf-8") as f:
- long_description = f.read()
-
-needs_pytest = {"pytest", "test", "ptr"}.intersection(sys.argv)
-pytest_runner = ["pytest-runner"] if needs_pytest else []
-
-# library files to include in a binary distribution
-# (rely on specifying this with environment variables when it's needed)
-external_libs = []
-external_libs_env = os.getenv("DRF_PACKAGE_EXTERNAL_LIBS", None)
-if sys.platform.startswith("win") and external_libs_env is not None:
- external_lib_list = list(filter(None, external_libs_env.split(";")))
- external_libs.extend([("Lib/site-packages/digital_rf", external_lib_list)])
- if external_lib_list:
- istr = (
- "INFO: external libraries included by DRF_PACKAGE_EXTERNAL_LIBS:" " {0}"
- ).format(external_lib_list)
- print(istr)
-
-# h5py spec to require (helpful for Windows where we rely on the hdf5.dll
-# provided by h5py since we require h5py anyway, but in order to make sure
-# versions match we need to require a specific h5py version)
-h5py_spec_env = os.getenv("DRF_H5PY_SPEC", None)
-if h5py_spec_env is None:
- h5py_spec = "h5py"
-else:
- h5py_spec = h5py_spec_env
- print("INFO: h5py specified by DRF_H5PY_SPEC: {0}".format(h5py_spec))
-
-
-# subclass build_ext so we only add build settings for dependencies
-# at build time
-class build_ext(_build_ext):
- def _add_build_settings(self):
- # get numpy settings for extension (importing numpy)
- try:
- import numpy
-
- np_includes = numpy.get_include()
- except (ImportError, AttributeError):
- # if numpy is not installed get the headers from the .egg directory
- import numpy.core
-
- np_includes = os.path.join(os.path.dirname(numpy.core.__file__), "include")
- np_config = dict(include_dirs=[np_includes])
-
- # get hdf5 settings for extension (importing pkgconfig)
- HDF5_ROOT = os.getenv("HDF5_ROOT", sys.prefix)
- hdf5_config = dict(
- include_dirs=[os.path.join(HDF5_ROOT, "include")],
- library_dirs=[os.path.join(HDF5_ROOT, "lib")],
- libraries=["hdf5"],
- define=[],
- )
- if sys.platform.startswith("win"):
- hdf5_config["define"].extend(
- [("_HDF5USEDLL_", None), ("H5_BUILT_AS_DYNAMIC_LIB", None)]
- )
- else:
- hdf5_config["include_dirs"].extend(
- ["/opt/local/include", "/usr/local/include", "/usr/include"]
- )
- hdf5_config["library_dirs"].extend(
- ["/opt/local/lib", "/usr/local/lib", "/usr/lib"]
- )
- # try pkg-config to override default settings
- try:
- import pkgconfig
- except ImportError:
- infostr = (
- "INFO: python-pkgconfig not installed. Defaulting to" ' HDF5_ROOT="{0}"'
- )
- print(infostr.format(HDF5_ROOT))
- else:
- try:
- hdf5_exists = pkgconfig.exists("hdf5")
- except EnvironmentError:
- infostr = (
- "INFO: pkg-config not installed. Defaulting to" ' HDF5_ROOT="{0}"'
- )
- print(infostr.format(HDF5_ROOT))
- else:
- if hdf5_exists:
- hdf5_pkgconfig = pkgconfig.parse("hdf5")
- for k in ("include_dirs", "library_dirs", "libraries"):
- hdf5_config[k] = list(hdf5_pkgconfig[k])
- else:
- infostr = (
- "INFO: pkgconfig cannot find HDF5. Defaulting to"
- ' HDF5_ROOT="{0}"'
- )
- print(infostr.format(HDF5_ROOT))
- # use environment variables to override discovered settings
- hdf5_env_config = dict(
- include_dirs="HDF5_INCLUDE_DIRS",
- library_dirs="HDF5_LIBRARY_DIRS",
- libraries="HDF5_LIBRARIES",
- define="HDF5_DEFINE",
- )
- for k, e in hdf5_env_config.items():
- env_val = os.getenv(e, None)
- if env_val is not None:
- val_list = list(filter(None, env_val.split(";")))
- used = set()
- vals = []
- for v in val_list:
- if v not in used:
- used.add(v)
- if k == "define":
- items = v.split("=", 2)
- if items[0].startswith("-D"):
- items[0] = items[0][2:]
- if len(items) == 1:
- vals.append((items[0], None))
- else:
- vals.append(tuple(items))
- else:
- vals.append(v)
- # update hdf5_config
- hdf5_config[k] = vals
- print("INFO: {0}={1}".format(e, vals))
-
- # update extension settings
- for c in (np_config, hdf5_config):
- for k, v in c.items():
- cur = getattr(self, k)
- if cur is not None:
- cur.extend(i for i in v if i not in cur)
- else:
- setattr(self, k, v)
-
- def _convert_abspath_libraries(self):
- if sys.platform.startswith("win"):
- libname_re = re.compile("(?P.*)")
- else:
- libname_re = re.compile("^lib(?P.*)")
- for k, lib in enumerate(self.libraries):
- if os.path.isabs(lib):
- libdir, libfile = os.path.split(lib)
- libfilename, _ = os.path.splitext(libfile)
- libname = libname_re.sub(r"\g", libfilename)
- # replace library entry with its name and add dir to path
- self.libraries[k] = libname
- if libdir not in self.library_dirs:
- self.library_dirs.append(libdir)
-
- def run(self):
- self._add_build_settings()
- self._convert_abspath_libraries()
- _build_ext.run(self)
-
-
-cmdclass = versioneer.get_cmdclass()
-cmdclass.update(build_ext=build_ext)
-
-setup(
- name="digital_rf",
- version=versioneer.get_version(),
- description="Python tools to read/write Digital RF data in HDF5 format",
- long_description=long_description,
- url="https://github.com/MITHaystack/digital_rf",
- author="MIT Haystack Observatory",
- author_email="openradar-developers@openradar.org",
- license="BSD-3-Clause",
- classifiers=[
- "Development Status :: 5 - Production/Stable",
- "Environment :: Console",
- "Intended Audience :: Science/Research",
- "License :: OSI Approved :: BSD License",
- "Operating System :: MacOS :: MacOS X",
- "Operating System :: Microsoft :: Windows",
- "Operating System :: POSIX :: Linux",
- "Operating System :: Unix",
- "Programming Language :: C",
- "Programming Language :: Python :: 2",
- "Programming Language :: Python :: 2.7",
- "Programming Language :: Python :: 3",
- "Programming Language :: Python :: 3.5",
- "Programming Language :: Python :: 3.6",
- "Topic :: Scientific/Engineering",
- ],
- keywords="hdf5 radio rf",
- install_requires=[
- h5py_spec,
- "numpy",
- "packaging",
- "python-dateutil",
- "pytz",
- "six",
- "watchdog",
- ],
- setup_requires=pytest_runner,
- tests_require=["pytest>=3"],
- extras_require={
- "all": ["matplotlib", "pandas", "sounddevice", "scipy"],
- "dataframe": ["pandas"],
- "plot": ["matplotlib", "scipy"],
- "sound": ["sounddevice"],
- },
- packages=["digital_rf", "gr_digital_rf"],
- data_files=[
- (
- "share/gnuradio/grc/blocks",
- [
- "grc/gr_digital_rf_digital_rf_channel_sink.xml",
- "grc/gr_digital_rf_digital_rf_channel_source.xml",
- "grc/gr_digital_rf_digital_rf_sink.xml",
- "grc/gr_digital_rf_digital_rf_source.xml",
- "grc/gr_digital_rf_raster_aggregate.xml",
- "grc/gr_digital_rf_raster_chunk.xml",
- "grc/gr_digital_rf_raster_select.xml",
- "grc/gr_digital_rf_raster_tag.xml",
- "grc/gr_digital_rf_vector_aggregate.xml",
- "grc/gr_digital_rf_digital_rf_channel_sink.block.yml",
- "grc/gr_digital_rf_digital_rf_channel_source.block.yml",
- "grc/gr_digital_rf_digital_rf_sink.block.yml",
- "grc/gr_digital_rf_digital_rf_source.block.yml",
- "grc/gr_digital_rf_raster_aggregate.block.yml",
- "grc/gr_digital_rf_raster_chunk.block.yml",
- "grc/gr_digital_rf_raster_select.block.yml",
- "grc/gr_digital_rf_raster_tag.block.yml",
- "grc/gr_digital_rf_vector_aggregate.block.yml",
- "grc/gr_digital_rf.tree.yml",
- ],
- )
- ]
- + external_libs,
- ext_modules=[
- # extension settings without external dependencies
- Extension(
- name="digital_rf._py_rf_write_hdf5",
- sources=["lib/py_rf_write_hdf5.c", "lib/rf_write_hdf5.c"],
- include_dirs=list(
- filter(
- None,
- [
- localpath("include"),
- (
- localpath("include/windows")
- if sys.platform.startswith("win")
- else None
- ),
- ],
- )
- ),
- library_dirs=[],
- libraries=list(
- filter(None, ["m" if not sys.platform.startswith("win") else None])
- ),
- define_macros=list(
- filter(
- None,
- [
- (
- ("digital_rf_EXPORTS", None)
- if sys.platform.startswith("win")
- else None
- )
- ],
- )
- ),
- )
- ],
- entry_points={"console_scripts": ["drf=digital_rf.drf_command:main"]},
- scripts=[
- "tools/digital_metadata_archive.py",
- "tools/digital_rf_archive.py",
- "tools/digital_rf_upconvert.py",
- "tools/digital_rf_update_properties.py",
- "tools/drf_cross_sti.py",
- "tools/drf_plot.py",
- "tools/drf_sti.py",
- "tools/drf_sound.py",
- "tools/thor.py",
- "tools/thorosmo.py",
- "tools/thorpluto.py",
- "tools/uhdtodrf.py",
- "tools/verify_digital_rf_upconvert.py",
- ],
- cmdclass=cmdclass,
-)
diff --git a/python/tests/test_digital_rf_hdf5.py b/python/tests/test_digital_rf_hdf5.py
index 7e7e60b..84461a8 100644
--- a/python/tests/test_digital_rf_hdf5.py
+++ b/python/tests/test_digital_rf_hdf5.py
@@ -336,13 +336,13 @@ def data(bounds, data_block_slices, dtype, num_subchannels):
# start off with data array containing its appropriate fill value
if np.issubdtype(dtype, np.inexact):
- fill_value = np.nan * np.ones(1, dtype=dtype)[0]
+ fill_value = np.nan
elif dtype.names is not None:
fill_value = np.empty(1, dtype=dtype)[0]
fill_value["r"] = np.iinfo(dtype["r"]).min
fill_value["i"] = np.iinfo(dtype["i"]).min
else:
- fill_value = np.iinfo(dtype).min * np.ones(1, dtype=dtype)[0]
+ fill_value = np.iinfo(dtype).min
data = np.full(shape, fill_value, dtype=dtype)
rdata = generate_rf_data(shape, dtype, 0)
diff --git a/python/tools/digital_metadata_archive.py b/python/tools/digital_metadata_archive.py
index b337b13..8075b2b 100644
--- a/python/tools/digital_metadata_archive.py
+++ b/python/tools/digital_metadata_archive.py
@@ -1,4 +1,4 @@
-#!python
+#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2017 Massachusetts Institute of Technology (MIT)
# All rights reserved.
@@ -138,7 +138,9 @@ def _get_file_list(self, sample0, sample1):
end_sub_ts + self._subdir_cadence_secs,
self._subdir_cadence_secs,
):
- sub_datetime = datetime.datetime.utcfromtimestamp(sub_ts)
+ sub_datetime = datetime.datetime.fromtimestamp(
+ sub_ts, tz=datetime.timezone.utc
+ )
subdir = sub_datetime.strftime("%Y-%m-%dT%H-%M-%S")
# create numpy array of all file TS in subdir
file_ts_in_subdir = np.arange(
diff --git a/python/tools/digital_rf_archive.py b/python/tools/digital_rf_archive.py
index 02da8d6..474abca 100644
--- a/python/tools/digital_rf_archive.py
+++ b/python/tools/digital_rf_archive.py
@@ -1,4 +1,4 @@
-#!python
+#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2017 Massachusetts Institute of Technology (MIT)
# All rights reserved.
@@ -128,8 +128,9 @@ def archive_subdirectory_local_local(args):
archive_files.sort() # allows us to stop checking when a file moves out of time range
for archive_file in archive_files:
basename = os.path.basename(archive_file)
- ts = datetime.datetime.utcfromtimestamp(
- float(basename[basename.find("@") + 1 : -3])
+ ts = datetime.datetime.fromtimestamp(
+ float(basename[basename.find("@") + 1 : -3]),
+ tz=datetime.timezone.utc,
)
if ts >= startDT and ts <= endDT:
# check if we need to compress it
@@ -283,8 +284,9 @@ def archive_subdirectory_local_remote(args):
archive_files.sort() # allows us to stop checking when a file moves out of time range
for archive_file in archive_files:
basename = os.path.basename(archive_file)
- ts = datetime.datetime.utcfromtimestamp(
- float(basename[basename.find("@") + 1 : -3])
+ ts = datetime.datetime.fromtimestamp(
+ float(basename[basename.find("@") + 1 : -3]),
+ tz=datetime.timezone.utc,
)
if ts >= startDT and ts <= endDT:
# if we need to compress it, make a copy first
@@ -884,14 +886,18 @@ def get_chan_dict_remote(self):
# create datetimes
try:
- startDT = datetime.datetime.strptime(args.startDT, "%Y-%m-%dT%H:%M:%S")
+ startDT = datetime.datetime.strptime(args.startDT, "%Y-%m-%dT%H:%M:%S").replace(
+ tzinfo=datetime.timezone.utc
+ )
except:
print(
"startDT <%s> not in expected YYYY-MM-DDTHH:MM:SS format" % (args.startDT)
)
sys.exit(-1)
try:
- endDT = datetime.datetime.strptime(args.endDT, "%Y-%m-%dT%H:%M:%S")
+ endDT = datetime.datetime.strptime(args.endDT, "%Y-%m-%dT%H:%M:%S").replace(
+ tzinfo=datetime.timezone.utc
+ )
except:
print("endDT <%s> not in expected YYYY-MM-DDTHH:MM:SS format" % (args.endDT))
sys.exit(-1)
diff --git a/python/tools/digital_rf_upconvert.py b/python/tools/digital_rf_upconvert.py
index 12bb137..16f6948 100644
--- a/python/tools/digital_rf_upconvert.py
+++ b/python/tools/digital_rf_upconvert.py
@@ -1,4 +1,4 @@
-#!python
+#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2017 Massachusetts Institute of Technology (MIT)
# All rights reserved.
diff --git a/python/tools/digital_rf_update_properties.py b/python/tools/digital_rf_update_properties.py
index 1dfb15c..86643b5 100644
--- a/python/tools/digital_rf_update_properties.py
+++ b/python/tools/digital_rf_update_properties.py
@@ -1,4 +1,4 @@
-#!python
+#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2017 Massachusetts Institute of Technology (MIT)
# All rights reserved.
diff --git a/python/tools/drf_cross_sti.py b/python/tools/drf_cross_sti.py
index c2ec778..80dc310 100644
--- a/python/tools/drf_cross_sti.py
+++ b/python/tools/drf_cross_sti.py
@@ -1,4 +1,4 @@
-#!python
+#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2017 Massachusetts Institute of Technology (MIT)
# All rights reserved.
@@ -30,7 +30,6 @@
import matplotlib.mlab
import matplotlib.pyplot
import numpy as np
-import pytz
import scipy
import scipy.signal
@@ -159,7 +158,7 @@ def plot(self):
if self.control.start:
dtst0 = dateutil.parser.parse(self.control.start)
st0 = (
- dtst0 - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)
+ dtst0 - datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
).total_seconds()
st0 = int(st0 * sr)
else:
@@ -168,7 +167,7 @@ def plot(self):
if self.control.end:
dtst0 = dateutil.parser.parse(self.control.end)
et0 = (
- dtst0 - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)
+ dtst0 - datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
).total_seconds()
et0 = int(et0 * sr)
else:
diff --git a/python/tools/drf_plot.py b/python/tools/drf_plot.py
index b824529..9fdd45e 100644
--- a/python/tools/drf_plot.py
+++ b/python/tools/drf_plot.py
@@ -1,4 +1,4 @@
-#!python
+#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2017 Massachusetts Institute of Technology (MIT)
# All rights reserved.
diff --git a/python/tools/drf_sound.py b/python/tools/drf_sound.py
index 9bfead7..aa083e9 100644
--- a/python/tools/drf_sound.py
+++ b/python/tools/drf_sound.py
@@ -1,4 +1,4 @@
-#!python
+#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2017 Massachusetts Institute of Technology (MIT)
# All rights reserved.
@@ -25,7 +25,6 @@
import dateutil
import digital_rf as drf
import numpy as np
-import pytz
import scipy
import scipy.io.wavfile
import scipy.signal
@@ -70,7 +69,7 @@ def makeasound(self):
if self.control.start:
dtst0 = dateutil.parser.parse(self.control.start)
st0 = (
- dtst0 - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)
+ dtst0 - datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
).total_seconds()
st0 = int(st0 * sr)
else:
@@ -79,7 +78,7 @@ def makeasound(self):
if self.control.end:
dtst0 = dateutil.parser.parse(self.control.end)
et0 = (
- dtst0 - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)
+ dtst0 - datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
).total_seconds()
et0 = int(et0 * sr)
else:
diff --git a/python/tools/drf_sti.py b/python/tools/drf_sti.py
index 5557c57..4699e0d 100644
--- a/python/tools/drf_sti.py
+++ b/python/tools/drf_sti.py
@@ -1,4 +1,4 @@
-#!python
+#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2017 Massachusetts Institute of Technology (MIT)
# All rights reserved.
@@ -23,7 +23,6 @@
import matplotlib.mlab
import matplotlib.pyplot
import numpy as np
-import pytz
import scipy
import scipy.signal
@@ -89,15 +88,16 @@ def __init__(self, opt):
self.sr = self.dio.get_properties(self.channels[0])["samples_per_second"]
self.bounds = self.dio.get_bounds(self.channels[0])
- self.dt_start = datetime.datetime.utcfromtimestamp(
- int(self.bounds[0] / self.sr)
+ self.dt_start = datetime.datetime.fromtimestamp(
+ int(self.bounds[0] / self.sr),
+ tz=datetime.timezone.utc,
+ )
+ self.dt_stop = datetime.datetime.fromtimestamp(
+ int(self.bounds[1] / self.sr), tz=datetime.timezone.utc
)
- self.dt_stop = datetime.datetime.utcfromtimestamp(int(self.bounds[1] / self.sr))
print(
- "bound times {0} to {1} UTC".format(
- self.dt_start.utcnow().isoformat(), self.dt_stop.utcnow().isoformat()
- )
+ f"bound times {self.dt_start.isoformat()} to {self.dt_stop.isoformat()} UTC"
)
if self.opt.verbose:
@@ -148,7 +148,7 @@ def plot(self):
if self.opt.start:
dtst0 = dateutil.parser.parse(self.opt.start)
st0 = (
- dtst0 - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)
+ dtst0 - datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
).total_seconds()
st0 = int(st0 * self.sr)
else:
@@ -157,7 +157,7 @@ def plot(self):
if self.opt.end:
dtst0 = dateutil.parser.parse(self.opt.end)
et0 = (
- dtst0 - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)
+ dtst0 - datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
).total_seconds()
et0 = int(et0 * self.sr)
else:
diff --git a/python/tools/thor.py b/python/tools/thor.py
index c9f39cc..aa209e8 100644
--- a/python/tools/thor.py
+++ b/python/tools/thor.py
@@ -1,4 +1,4 @@
-#!python
+#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2017 Massachusetts Institute of Technology (MIT)
# All rights reserved.
@@ -26,7 +26,6 @@
import digital_rf as drf
import gr_digital_rf as gr_drf
import numpy as np
-import pytz
from gnuradio import blocks
from gnuradio import filter as grfilter
from gnuradio import gr, uhd
@@ -793,8 +792,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
st = drf.util.parse_identifier_to_time(starttime)
if st is not None:
# find next suitable start time by cycle repeat period
- now = datetime.utcnow()
- now = now.replace(tzinfo=pytz.utc)
+ now = datetime.now(tz=datetime.timezone.utc)
soon = now + timedelta(seconds=SETUP_TIME)
diff = max(soon - st, timedelta(0)).total_seconds()
periods_until_next = (diff - 1) // period + 1
@@ -814,7 +812,10 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
if (
et
- < (pytz.utc.localize(datetime.utcnow()) + timedelta(seconds=SETUP_TIME))
+ < (
+ datetime.now(tz=datetime.timezone.utc)
+ + timedelta(seconds=SETUP_TIME)
+ )
) or (st is not None and et <= st):
raise ValueError("End time is before launch time!")
@@ -834,9 +835,10 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
# wait for the start time if it is not past
while (st is not None) and (
- (st - pytz.utc.localize(datetime.utcnow())) > timedelta(seconds=SETUP_TIME)
+ (st - datetime.now(tz=datetime.timezone.utc))
+ > timedelta(seconds=SETUP_TIME)
):
- ttl = int((st - pytz.utc.localize(datetime.utcnow())).total_seconds())
+ ttl = int((st - datetime.now(tz=datetime.timezone.utc)).total_seconds())
if (ttl % 10) == 0:
print("Standby {0} s remaining...".format(ttl))
sys.stdout.flush()
@@ -883,7 +885,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
if st is not None:
lt = st
else:
- now = pytz.utc.localize(datetime.utcnow())
+ now = datetime.now(tz=datetime.timezone.utc)
# launch on integer second by default for convenience (ceil + 2)
lt = now.replace(microsecond=0) + timedelta(seconds=3)
ltts = (lt - drf.util.epoch).total_seconds()
@@ -1092,7 +1094,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
resampling_filter_taps=op.resampling_filter_taps[ko],
scaling=op.ch_scalings[ko],
),
- **op.metadata
+ **op.metadata,
),
is_continuous=True,
compression_level=0,
@@ -1129,7 +1131,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
# check that we get samples after launch
while not u.nitems_written(0):
- if (pytz.utc.localize(datetime.utcnow())) - lt > timedelta(seconds=5):
+ if (datetime.now(tz=datetime.timezone.utc)) - lt > timedelta(seconds=5):
fg.stop()
# need to wait for the flowgraph to clean up,
# otherwise it won't exit
@@ -1146,14 +1148,15 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
fg.wait()
else:
# sleep until end time
- while pytz.utc.localize(datetime.utcnow()) < et - timedelta(seconds=2):
+ while datetime.now(tz=datetime.timezone.utc) < et - timedelta(
+ seconds=2
+ ):
time.sleep(1)
- else:
- # (actually a little after to allow for inexact computer time)
- while pytz.utc.localize(datetime.utcnow()) < et + timedelta(
- seconds=0.2
- ):
- time.sleep(0.1)
+ # (actually a little after to allow for inexact computer time)
+ while datetime.now(tz=datetime.timezone.utc) < et + timedelta(
+ seconds=0.2
+ ):
+ time.sleep(0.1)
except KeyboardInterrupt:
# catch keyboard interrupt and simply exit
pass
diff --git a/python/tools/thorosmo.py b/python/tools/thorosmo.py
index b61a6e9..9083560 100644
--- a/python/tools/thorosmo.py
+++ b/python/tools/thorosmo.py
@@ -1,4 +1,4 @@
-#!python
+#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2020 Massachusetts Institute of Technology (MIT)
# All rights reserved.
@@ -22,7 +22,6 @@
from subprocess import call
from textwrap import dedent, fill, TextWrapper
import numpy as np
-import pytz
import digital_rf as drf
import gr_digital_rf as gr_drf
@@ -549,8 +548,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
st = drf.util.parse_identifier_to_time(starttime)
if st is not None:
# find next suitable start time by cycle repeat period
- now = datetime.utcnow()
- now = now.replace(tzinfo=pytz.utc)
+ now = datetime.now(tz=datetime.timezone.utc)
soon = now + timedelta(seconds=SETUP_TIME)
diff = max(soon - st, timedelta(0)).total_seconds()
periods_until_next = (diff - 1) // period + 1
@@ -570,7 +568,10 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
if (
et
- < (pytz.utc.localize(datetime.utcnow()) + timedelta(seconds=SETUP_TIME))
+ < (
+ datetime.now(tz=datetime.timezone.utc)
+ + timedelta(seconds=SETUP_TIME)
+ )
) or (st is not None and et <= st):
raise ValueError("End time is before launch time!")
@@ -590,9 +591,10 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
# wait for the start time if it is not past
while (st is not None) and (
- (st - pytz.utc.localize(datetime.utcnow())) > timedelta(seconds=SETUP_TIME)
+ (st - datetime.now(tz=datetime.timezone.utc))
+ > timedelta(seconds=SETUP_TIME)
):
- ttl = int((st - pytz.utc.localize(datetime.utcnow())).total_seconds())
+ ttl = int((st - datetime.now(tz=datetime.timezone.utc)).total_seconds())
if (ttl % 10) == 0:
print("Standby {0} s remaining...".format(ttl))
sys.stdout.flush()
@@ -633,7 +635,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
if st is not None:
lt = st
else:
- now = pytz.utc.localize(datetime.utcnow())
+ now = datetime.now(tz=datetime.timezone.utc)
# launch on integer second by default for convenience (ceil + 2)
lt = now.replace(microsecond=0) + timedelta(seconds=3)
ltts = (lt - drf.util.epoch).total_seconds()
@@ -829,7 +831,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
resampling_filter_taps=op.resampling_filter_taps[ko],
scaling=op.ch_scalings[ko],
),
- **op.metadata
+ **op.metadata,
),
is_continuous=True,
compression_level=0,
@@ -856,7 +858,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
graph.append(connections)
# start the flowgraph once we are near the launch time
- while (lt - pytz.utc.localize(datetime.utcnow())) > timedelta(seconds=0.5):
+ while (lt - datetime.now(tz=datetime.timezone.utc)) > timedelta(seconds=0.5):
time.sleep(0.1)
# start the flowgraph, samples should start at launch time
@@ -869,14 +871,15 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
fg.wait()
else:
# sleep until end time
- while pytz.utc.localize(datetime.utcnow()) < et - timedelta(seconds=2):
+ while datetime.now(tz=datetime.timezone.utc) < et - timedelta(
+ seconds=2
+ ):
time.sleep(1)
- else:
- # (actually a little after to allow for inexact computer time)
- while pytz.utc.localize(datetime.utcnow()) < et + timedelta(
- seconds=0.2
- ):
- time.sleep(0.1)
+ # (actually a little after to allow for inexact computer time)
+ while datetime.now(tz=datetime.timezone.utc) < et + timedelta(
+ seconds=0.2
+ ):
+ time.sleep(0.1)
except KeyboardInterrupt:
# catch keyboard interrupt and simply exit
pass
diff --git a/python/tools/thorpluto.py b/python/tools/thorpluto.py
old mode 100755
new mode 100644
index df28a17..907c176
--- a/python/tools/thorpluto.py
+++ b/python/tools/thorpluto.py
@@ -1,4 +1,4 @@
-#!python
+#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2020 Massachusetts Institute of Technology (MIT)
# All rights reserved.
@@ -23,7 +23,6 @@
from subprocess import call
from textwrap import dedent, fill, TextWrapper
import numpy as np
-import pytz
import digital_rf as drf
import gr_digital_rf as gr_drf
@@ -516,8 +515,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
st = drf.util.parse_identifier_to_time(starttime)
if st is not None:
# find next suitable start time by cycle repeat period
- now = datetime.utcnow()
- now = now.replace(tzinfo=pytz.utc)
+ now = datetime.now(tz=datetime.timezone.utc)
soon = now + timedelta(seconds=SETUP_TIME)
diff = max(soon - st, timedelta(0)).total_seconds()
periods_until_next = (diff - 1) // period + 1
@@ -537,7 +535,10 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
if (
et
- < (pytz.utc.localize(datetime.utcnow()) + timedelta(seconds=SETUP_TIME))
+ < (
+ datetime.now(tz=datetime.timezone.utc)
+ + timedelta(seconds=SETUP_TIME)
+ )
) or (st is not None and et <= st):
raise ValueError("End time is before launch time!")
@@ -557,9 +558,10 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
# wait for the start time if it is not past
while (st is not None) and (
- (st - pytz.utc.localize(datetime.utcnow())) > timedelta(seconds=SETUP_TIME)
+ (st - datetime.now(tz=datetime.timezone.utc))
+ > timedelta(seconds=SETUP_TIME)
):
- ttl = int((st - pytz.utc.localize(datetime.utcnow())).total_seconds())
+ ttl = int((st - datetime.now(tz=datetime.timezone.utc)).total_seconds())
if (ttl % 10) == 0:
print("Standby {0} s remaining...".format(ttl))
sys.stdout.flush()
@@ -602,7 +604,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
if st is not None:
lt = st
else:
- now = pytz.utc.localize(datetime.utcnow())
+ now = datetime.now(tz=datetime.timezone.utc)
# launch on integer second by default for convenience (ceil + 2)
lt = now.replace(microsecond=0) + timedelta(seconds=3)
ltts = (lt - drf.util.epoch).total_seconds()
@@ -793,7 +795,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
resampling_filter_taps=op.resampling_filter_taps[ko],
scaling=op.ch_scalings[ko],
),
- **op.metadata
+ **op.metadata,
),
is_continuous=True,
compression_level=0,
@@ -820,7 +822,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
graph.append(connections)
# start the flowgraph once we are near the launch time
- while (lt - pytz.utc.localize(datetime.utcnow())) > timedelta(seconds=0.5):
+ while (lt - datetime.now(tz=datetime.timezone.utc)) > timedelta(seconds=0.5):
time.sleep(0.1)
# start the flowgraph, samples should start at launch time
@@ -833,14 +835,15 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
fg.wait()
else:
# sleep until end time
- while pytz.utc.localize(datetime.utcnow()) < et - timedelta(seconds=2):
+ while datetime.now(tz=datetime.timezone.utc) < et - timedelta(
+ seconds=2
+ ):
time.sleep(1)
- else:
- # (actually a little after to allow for inexact computer time)
- while pytz.utc.localize(datetime.utcnow()) < et + timedelta(
- seconds=0.2
- ):
- time.sleep(0.1)
+ # (actually a little after to allow for inexact computer time)
+ while datetime.now(tz=datetime.timezone.utc) < et + timedelta(
+ seconds=0.2
+ ):
+ time.sleep(0.1)
except KeyboardInterrupt:
# catch keyboard interrupt and simply exit
pass
diff --git a/python/tools/uhdtodrf.py b/python/tools/uhdtodrf.py
index 6af4519..86a5263 100644
--- a/python/tools/uhdtodrf.py
+++ b/python/tools/uhdtodrf.py
@@ -1,4 +1,4 @@
-#!python
+#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2020 Massachusetts Institute of Technology (MIT)
# All rights reserved.
@@ -25,7 +25,6 @@
import digital_rf as drf
import numpy as np
-import pytz
import scipy.signal as sig
from six.moves import queue
import uhd
@@ -816,8 +815,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
st = drf.util.parse_identifier_to_time(starttime)
if st is not None:
# find next suitable start time by cycle repeat period
- now = datetime.utcnow()
- now = now.replace(tzinfo=pytz.utc)
+ now = datetime.now(tz=datetime.timezone.utc)
soon = now + timedelta(seconds=SETUP_TIME)
diff = max(soon - st, timedelta(0)).total_seconds()
periods_until_next = (diff - 1) // period + 1
@@ -837,7 +835,10 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
if (
et
- < (pytz.utc.localize(datetime.utcnow()) + timedelta(seconds=SETUP_TIME))
+ < (
+ datetime.now(tz=datetime.timezone.utc)
+ + timedelta(seconds=SETUP_TIME)
+ )
) or (st is not None and et <= st):
raise ValueError("End time is before launch time!")
@@ -857,9 +858,10 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
# wait for the start time if it is not past
while (st is not None) and (
- (st - pytz.utc.localize(datetime.utcnow())) > timedelta(seconds=SETUP_TIME)
+ (st - datetime.now(tz=datetime.timezone.utc))
+ > timedelta(seconds=SETUP_TIME)
):
- ttl = int((st - pytz.utc.localize(datetime.utcnow())).total_seconds())
+ ttl = int((st - datetime.now(tz=datetime.timezone.utc)).total_seconds())
if (ttl % 10) == 0:
print("Standby {0} s remaining...".format(ttl))
sys.stdout.flush()
@@ -892,7 +894,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
if st is not None:
lt = st
else:
- now = pytz.utc.localize(datetime.utcnow())
+ now = datetime.now(tz=datetime.timezone.utc)
# launch on integer second by default for convenience (ceil + 2)
lt = now.replace(microsecond=0) + timedelta(seconds=3)
ltts = (lt - drf.util.epoch).total_seconds()
@@ -1043,7 +1045,7 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
resampling_filter_taps=op.resampling_filter_taps[ko],
scaling=op.ch_scalings[ko],
),
- **op.metadata
+ **op.metadata,
)
# Metadata writer and write at first record sample
mdata_path = os.path.join(cpath, "metadata")
@@ -1096,9 +1098,9 @@ def run(self, starttime=None, endtime=None, duration=None, period=10):
stream.issue_stream_cmd(stream_cmd)
while not end_rec.is_set():
if et is not None:
- stop_bool = pytz.utc.localize(datetime.utcnow()) >= et - timedelta(
- seconds=1
- )
+ stop_bool = datetime.now(
+ tz=datetime.timezone.utc
+ ) >= et - timedelta(seconds=1)
if stop_bool:
end_rec.set()
diff --git a/python/tools/verify_digital_rf_upconvert.py b/python/tools/verify_digital_rf_upconvert.py
index ce593a3..6799abc 100644
--- a/python/tools/verify_digital_rf_upconvert.py
+++ b/python/tools/verify_digital_rf_upconvert.py
@@ -1,4 +1,4 @@
-#!python
+#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2017 Massachusetts Institute of Technology (MIT)
# All rights reserved.
diff --git a/python/versioneer.py b/python/versioneer.py
deleted file mode 100644
index de97d90..0000000
--- a/python/versioneer.py
+++ /dev/null
@@ -1,2334 +0,0 @@
-# Version: 0.29
-
-"""The Versioneer - like a rocketeer, but for versions.
-
-The Versioneer
-==============
-
-* like a rocketeer, but for versions!
-* https://github.com/python-versioneer/python-versioneer
-* Brian Warner
-* License: Public Domain (Unlicense)
-* Compatible with: Python 3.7, 3.8, 3.9, 3.10, 3.11 and pypy3
-* [![Latest Version][pypi-image]][pypi-url]
-* [![Build Status][travis-image]][travis-url]
-
-This is a tool for managing a recorded version number in setuptools-based
-python projects. The goal is to remove the tedious and error-prone "update
-the embedded version string" step from your release process. Making a new
-release should be as easy as recording a new tag in your version-control
-system, and maybe making new tarballs.
-
-
-## Quick Install
-
-Versioneer provides two installation modes. The "classic" vendored mode installs
-a copy of versioneer into your repository. The experimental build-time dependency mode
-is intended to allow you to skip this step and simplify the process of upgrading.
-
-### Vendored mode
-
-* `pip install versioneer` to somewhere in your $PATH
- * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is
- available, so you can also use `conda install -c conda-forge versioneer`
-* add a `[tool.versioneer]` section to your `pyproject.toml` or a
- `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md))
- * Note that you will need to add `tomli; python_version < "3.11"` to your
- build-time dependencies if you use `pyproject.toml`
-* run `versioneer install --vendor` in your source tree, commit the results
-* verify version information with `python setup.py version`
-
-### Build-time dependency mode
-
-* `pip install versioneer` to somewhere in your $PATH
- * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is
- available, so you can also use `conda install -c conda-forge versioneer`
-* add a `[tool.versioneer]` section to your `pyproject.toml` or a
- `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md))
-* add `versioneer` (with `[toml]` extra, if configuring in `pyproject.toml`)
- to the `requires` key of the `build-system` table in `pyproject.toml`:
- ```toml
- [build-system]
- requires = ["setuptools", "versioneer[toml]"]
- build-backend = "setuptools.build_meta"
- ```
-* run `versioneer install --no-vendor` in your source tree, commit the results
-* verify version information with `python setup.py version`
-
-## Version Identifiers
-
-Source trees come from a variety of places:
-
-* a version-control system checkout (mostly used by developers)
-* a nightly tarball, produced by build automation
-* a snapshot tarball, produced by a web-based VCS browser, like github's
- "tarball from tag" feature
-* a release tarball, produced by "setup.py sdist", distributed through PyPI
-
-Within each source tree, the version identifier (either a string or a number,
-this tool is format-agnostic) can come from a variety of places:
-
-* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows
- about recent "tags" and an absolute revision-id
-* the name of the directory into which the tarball was unpacked
-* an expanded VCS keyword ($Id$, etc)
-* a `_version.py` created by some earlier build step
-
-For released software, the version identifier is closely related to a VCS
-tag. Some projects use tag names that include more than just the version
-string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool
-needs to strip the tag prefix to extract the version identifier. For
-unreleased software (between tags), the version identifier should provide
-enough information to help developers recreate the same tree, while also
-giving them an idea of roughly how old the tree is (after version 1.2, before
-version 1.3). Many VCS systems can report a description that captures this,
-for example `git describe --tags --dirty --always` reports things like
-"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the
-0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has
-uncommitted changes).
-
-The version identifier is used for multiple purposes:
-
-* to allow the module to self-identify its version: `myproject.__version__`
-* to choose a name and prefix for a 'setup.py sdist' tarball
-
-## Theory of Operation
-
-Versioneer works by adding a special `_version.py` file into your source
-tree, where your `__init__.py` can import it. This `_version.py` knows how to
-dynamically ask the VCS tool for version information at import time.
-
-`_version.py` also contains `$Revision$` markers, and the installation
-process marks `_version.py` to have this marker rewritten with a tag name
-during the `git archive` command. As a result, generated tarballs will
-contain enough information to get the proper version.
-
-To allow `setup.py` to compute a version too, a `versioneer.py` is added to
-the top level of your source tree, next to `setup.py` and the `setup.cfg`
-that configures it. This overrides several distutils/setuptools commands to
-compute the version when invoked, and changes `setup.py build` and `setup.py
-sdist` to replace `_version.py` with a small static file that contains just
-the generated version data.
-
-## Installation
-
-See [INSTALL.md](./INSTALL.md) for detailed installation instructions.
-
-## Version-String Flavors
-
-Code which uses Versioneer can learn about its version string at runtime by
-importing `_version` from your main `__init__.py` file and running the
-`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can
-import the top-level `versioneer.py` and run `get_versions()`.
-
-Both functions return a dictionary with different flavors of version
-information:
-
-* `['version']`: A condensed version string, rendered using the selected
- style. This is the most commonly used value for the project's version
- string. The default "pep440" style yields strings like `0.11`,
- `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section
- below for alternative styles.
-
-* `['full-revisionid']`: detailed revision identifier. For Git, this is the
- full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac".
-
-* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the
- commit date in ISO 8601 format. This will be None if the date is not
- available.
-
-* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that
- this is only accurate if run in a VCS checkout, otherwise it is likely to
- be False or None
-
-* `['error']`: if the version string could not be computed, this will be set
- to a string describing the problem, otherwise it will be None. It may be
- useful to throw an exception in setup.py if this is set, to avoid e.g.
- creating tarballs with a version string of "unknown".
-
-Some variants are more useful than others. Including `full-revisionid` in a
-bug report should allow developers to reconstruct the exact code being tested
-(or indicate the presence of local changes that should be shared with the
-developers). `version` is suitable for display in an "about" box or a CLI
-`--version` output: it can be easily compared against release notes and lists
-of bugs fixed in various releases.
-
-The installer adds the following text to your `__init__.py` to place a basic
-version in `YOURPROJECT.__version__`:
-
- from ._version import get_versions
- __version__ = get_versions()['version']
- del get_versions
-
-## Styles
-
-The setup.cfg `style=` configuration controls how the VCS information is
-rendered into a version string.
-
-The default style, "pep440", produces a PEP440-compliant string, equal to the
-un-prefixed tag name for actual releases, and containing an additional "local
-version" section with more detail for in-between builds. For Git, this is
-TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags
---dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the
-tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and
-that this commit is two revisions ("+2") beyond the "0.11" tag. For released
-software (exactly equal to a known tag), the identifier will only contain the
-stripped tag, e.g. "0.11".
-
-Other styles are available. See [details.md](details.md) in the Versioneer
-source tree for descriptions.
-
-## Debugging
-
-Versioneer tries to avoid fatal errors: if something goes wrong, it will tend
-to return a version of "0+unknown". To investigate the problem, run `setup.py
-version`, which will run the version-lookup code in a verbose mode, and will
-display the full contents of `get_versions()` (including the `error` string,
-which may help identify what went wrong).
-
-## Known Limitations
-
-Some situations are known to cause problems for Versioneer. This details the
-most significant ones. More can be found on Github
-[issues page](https://github.com/python-versioneer/python-versioneer/issues).
-
-### Subprojects
-
-Versioneer has limited support for source trees in which `setup.py` is not in
-the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are
-two common reasons why `setup.py` might not be in the root:
-
-* Source trees which contain multiple subprojects, such as
- [Buildbot](https://github.com/buildbot/buildbot), which contains both
- "master" and "slave" subprojects, each with their own `setup.py`,
- `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI
- distributions (and upload multiple independently-installable tarballs).
-* Source trees whose main purpose is to contain a C library, but which also
- provide bindings to Python (and perhaps other languages) in subdirectories.
-
-Versioneer will look for `.git` in parent directories, and most operations
-should get the right version string. However `pip` and `setuptools` have bugs
-and implementation details which frequently cause `pip install .` from a
-subproject directory to fail to find a correct version string (so it usually
-defaults to `0+unknown`).
-
-`pip install --editable .` should work correctly. `setup.py install` might
-work too.
-
-Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in
-some later version.
-
-[Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking
-this issue. The discussion in
-[PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the
-issue from the Versioneer side in more detail.
-[pip PR#3176](https://github.com/pypa/pip/pull/3176) and
-[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve
-pip to let Versioneer work correctly.
-
-Versioneer-0.16 and earlier only looked for a `.git` directory next to the
-`setup.cfg`, so subprojects were completely unsupported with those releases.
-
-### Editable installs with setuptools <= 18.5
-
-`setup.py develop` and `pip install --editable .` allow you to install a
-project into a virtualenv once, then continue editing the source code (and
-test) without re-installing after every change.
-
-"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a
-convenient way to specify executable scripts that should be installed along
-with the python package.
-
-These both work as expected when using modern setuptools. When using
-setuptools-18.5 or earlier, however, certain operations will cause
-`pkg_resources.DistributionNotFound` errors when running the entrypoint
-script, which must be resolved by re-installing the package. This happens
-when the install happens with one version, then the egg_info data is
-regenerated while a different version is checked out. Many setup.py commands
-cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into
-a different virtualenv), so this can be surprising.
-
-[Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes
-this one, but upgrading to a newer version of setuptools should probably
-resolve it.
-
-
-## Updating Versioneer
-
-To upgrade your project to a new release of Versioneer, do the following:
-
-* install the new Versioneer (`pip install -U versioneer` or equivalent)
-* edit `setup.cfg` and `pyproject.toml`, if necessary,
- to include any new configuration settings indicated by the release notes.
- See [UPGRADING](./UPGRADING.md) for details.
-* re-run `versioneer install --[no-]vendor` in your source tree, to replace
- `SRC/_version.py`
-* commit any changed files
-
-## Future Directions
-
-This tool is designed to make it easily extended to other version-control
-systems: all VCS-specific components are in separate directories like
-src/git/ . The top-level `versioneer.py` script is assembled from these
-components by running make-versioneer.py . In the future, make-versioneer.py
-will take a VCS name as an argument, and will construct a version of
-`versioneer.py` that is specific to the given VCS. It might also take the
-configuration arguments that are currently provided manually during
-installation by editing setup.py . Alternatively, it might go the other
-direction and include code from all supported VCS systems, reducing the
-number of intermediate scripts.
-
-## Similar projects
-
-* [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time
- dependency
-* [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of
- versioneer
-* [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools
- plugin
-
-## License
-
-To make Versioneer easier to embed, all its code is dedicated to the public
-domain. The `_version.py` that it creates is also in the public domain.
-Specifically, both are released under the "Unlicense", as described in
-https://unlicense.org/.
-
-[pypi-image]: https://img.shields.io/pypi/v/versioneer.svg
-[pypi-url]: https://pypi.python.org/pypi/versioneer/
-[travis-image]:
-https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg
-[travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer
-
-"""
-# pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring
-# pylint:disable=missing-class-docstring,too-many-branches,too-many-statements
-# pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error
-# pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with
-# pylint:disable=attribute-defined-outside-init,too-many-arguments
-
-import configparser
-import errno
-import json
-import os
-import re
-import subprocess
-import sys
-from pathlib import Path
-from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union
-from typing import NoReturn
-import functools
-
-have_tomllib = True
-if sys.version_info >= (3, 11):
- import tomllib
-else:
- try:
- import tomli as tomllib
- except ImportError:
- have_tomllib = False
-
-
-class VersioneerConfig:
- """Container for Versioneer configuration parameters."""
-
- VCS: str
- style: str
- tag_prefix: str
- versionfile_source: str
- versionfile_build: Optional[str]
- parentdir_prefix: Optional[str]
- verbose: Optional[bool]
-
-
-def get_root() -> str:
- """Get the project root directory.
-
- We require that all commands are run from the project root, i.e. the
- directory that contains setup.py, setup.cfg, and versioneer.py .
- """
- root = os.path.realpath(os.path.abspath(os.getcwd()))
- setup_py = os.path.join(root, "setup.py")
- pyproject_toml = os.path.join(root, "pyproject.toml")
- versioneer_py = os.path.join(root, "versioneer.py")
- if not (
- os.path.exists(setup_py)
- or os.path.exists(pyproject_toml)
- or os.path.exists(versioneer_py)
- ):
- # allow 'python path/to/setup.py COMMAND'
- root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0])))
- setup_py = os.path.join(root, "setup.py")
- pyproject_toml = os.path.join(root, "pyproject.toml")
- versioneer_py = os.path.join(root, "versioneer.py")
- if not (
- os.path.exists(setup_py)
- or os.path.exists(pyproject_toml)
- or os.path.exists(versioneer_py)
- ):
- err = (
- "Versioneer was unable to run the project root directory. "
- "Versioneer requires setup.py to be executed from "
- "its immediate directory (like 'python setup.py COMMAND'), "
- "or in a way that lets it use sys.argv[0] to find the root "
- "(like 'python path/to/setup.py COMMAND')."
- )
- raise VersioneerBadRootError(err)
- try:
- # Certain runtime workflows (setup.py install/develop in a setuptools
- # tree) execute all dependencies in a single python process, so
- # "versioneer" may be imported multiple times, and python's shared
- # module-import table will cache the first one. So we can't use
- # os.path.dirname(__file__), as that will find whichever
- # versioneer.py was first imported, even in later projects.
- my_path = os.path.realpath(os.path.abspath(__file__))
- me_dir = os.path.normcase(os.path.splitext(my_path)[0])
- vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0])
- if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals():
- print(
- "Warning: build in %s is using versioneer.py from %s"
- % (os.path.dirname(my_path), versioneer_py)
- )
- except NameError:
- pass
- return root
-
-
-def get_config_from_root(root: str) -> VersioneerConfig:
- """Read the project setup.cfg file to determine Versioneer config."""
- # This might raise OSError (if setup.cfg is missing), or
- # configparser.NoSectionError (if it lacks a [versioneer] section), or
- # configparser.NoOptionError (if it lacks "VCS="). See the docstring at
- # the top of versioneer.py for instructions on writing your setup.cfg .
- root_pth = Path(root)
- pyproject_toml = root_pth / "pyproject.toml"
- setup_cfg = root_pth / "setup.cfg"
- section: Union[Dict[str, Any], configparser.SectionProxy, None] = None
- if pyproject_toml.exists() and have_tomllib:
- try:
- with open(pyproject_toml, "rb") as fobj:
- pp = tomllib.load(fobj)
- section = pp["tool"]["versioneer"]
- except (tomllib.TOMLDecodeError, KeyError) as e:
- print(f"Failed to load config from {pyproject_toml}: {e}")
- print("Try to load it from setup.cfg")
- if not section:
- parser = configparser.ConfigParser()
- with open(setup_cfg) as cfg_file:
- parser.read_file(cfg_file)
- parser.get("versioneer", "VCS") # raise error if missing
-
- section = parser["versioneer"]
-
- # `cast`` really shouldn't be used, but its simplest for the
- # common VersioneerConfig users at the moment. We verify against
- # `None` values elsewhere where it matters
-
- cfg = VersioneerConfig()
- cfg.VCS = section["VCS"]
- cfg.style = section.get("style", "")
- cfg.versionfile_source = cast(str, section.get("versionfile_source"))
- cfg.versionfile_build = section.get("versionfile_build")
- cfg.tag_prefix = cast(str, section.get("tag_prefix"))
- if cfg.tag_prefix in ("''", '""', None):
- cfg.tag_prefix = ""
- cfg.parentdir_prefix = section.get("parentdir_prefix")
- if isinstance(section, configparser.SectionProxy):
- # Make sure configparser translates to bool
- cfg.verbose = section.getboolean("verbose")
- else:
- cfg.verbose = section.get("verbose")
-
- return cfg
-
-
-class NotThisMethod(Exception):
- """Exception raised if a method is not valid for the current scenario."""
-
-
-# these dictionaries contain VCS-specific tools
-LONG_VERSION_PY: Dict[str, str] = {}
-HANDLERS: Dict[str, Dict[str, Callable]] = {}
-
-
-def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator
- """Create decorator to mark a method as the handler of a VCS."""
-
- def decorate(f: Callable) -> Callable:
- """Store f in HANDLERS[vcs][method]."""
- HANDLERS.setdefault(vcs, {})[method] = f
- return f
-
- return decorate
-
-
-def run_command(
- commands: List[str],
- args: List[str],
- cwd: Optional[str] = None,
- verbose: bool = False,
- hide_stderr: bool = False,
- env: Optional[Dict[str, str]] = None,
-) -> Tuple[Optional[str], Optional[int]]:
- """Call the given command(s)."""
- assert isinstance(commands, list)
- process = None
-
- popen_kwargs: Dict[str, Any] = {}
- if sys.platform == "win32":
- # This hides the console window if pythonw.exe is used
- startupinfo = subprocess.STARTUPINFO()
- startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
- popen_kwargs["startupinfo"] = startupinfo
-
- for command in commands:
- try:
- dispcmd = str([command] + args)
- # remember shell=False, so use git.cmd on windows, not just git
- process = subprocess.Popen(
- [command] + args,
- cwd=cwd,
- env=env,
- stdout=subprocess.PIPE,
- stderr=(subprocess.PIPE if hide_stderr else None),
- **popen_kwargs,
- )
- break
- except OSError as e:
- if e.errno == errno.ENOENT:
- continue
- if verbose:
- print("unable to run %s" % dispcmd)
- print(e)
- return None, None
- else:
- if verbose:
- print("unable to find command, tried %s" % (commands,))
- return None, None
- stdout = process.communicate()[0].strip().decode()
- if process.returncode != 0:
- if verbose:
- print("unable to run %s (error)" % dispcmd)
- print("stdout was %s" % stdout)
- return None, process.returncode
- return stdout, process.returncode
-
-
-LONG_VERSION_PY[
- "git"
-] = r'''
-# This file helps to compute a version number in source trees obtained from
-# git-archive tarball (such as those provided by githubs download-from-tag
-# feature). Distribution tarballs (built by setup.py sdist) and build
-# directories (produced by setup.py build) will contain a much shorter file
-# that just contains the computed version number.
-
-# This file is released into the public domain.
-# Generated by versioneer-0.29
-# https://github.com/python-versioneer/python-versioneer
-
-"""Git implementation of _version.py."""
-
-import errno
-import os
-import re
-import subprocess
-import sys
-from typing import Any, Callable, Dict, List, Optional, Tuple
-import functools
-
-
-def get_keywords() -> Dict[str, str]:
- """Get the keywords needed to look up the version information."""
- # these strings will be replaced by git during git-archive.
- # setup.py/versioneer.py will grep for the variable names, so they must
- # each be defined on a line of their own. _version.py will just call
- # get_keywords().
- git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s"
- git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s"
- git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s"
- keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
- return keywords
-
-
-class VersioneerConfig:
- """Container for Versioneer configuration parameters."""
-
- VCS: str
- style: str
- tag_prefix: str
- parentdir_prefix: str
- versionfile_source: str
- verbose: bool
-
-
-def get_config() -> VersioneerConfig:
- """Create, populate and return the VersioneerConfig() object."""
- # these strings are filled in when 'setup.py versioneer' creates
- # _version.py
- cfg = VersioneerConfig()
- cfg.VCS = "git"
- cfg.style = "%(STYLE)s"
- cfg.tag_prefix = "%(TAG_PREFIX)s"
- cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s"
- cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s"
- cfg.verbose = False
- return cfg
-
-
-class NotThisMethod(Exception):
- """Exception raised if a method is not valid for the current scenario."""
-
-
-LONG_VERSION_PY: Dict[str, str] = {}
-HANDLERS: Dict[str, Dict[str, Callable]] = {}
-
-
-def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator
- """Create decorator to mark a method as the handler of a VCS."""
- def decorate(f: Callable) -> Callable:
- """Store f in HANDLERS[vcs][method]."""
- if vcs not in HANDLERS:
- HANDLERS[vcs] = {}
- HANDLERS[vcs][method] = f
- return f
- return decorate
-
-
-def run_command(
- commands: List[str],
- args: List[str],
- cwd: Optional[str] = None,
- verbose: bool = False,
- hide_stderr: bool = False,
- env: Optional[Dict[str, str]] = None,
-) -> Tuple[Optional[str], Optional[int]]:
- """Call the given command(s)."""
- assert isinstance(commands, list)
- process = None
-
- popen_kwargs: Dict[str, Any] = {}
- if sys.platform == "win32":
- # This hides the console window if pythonw.exe is used
- startupinfo = subprocess.STARTUPINFO()
- startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
- popen_kwargs["startupinfo"] = startupinfo
-
- for command in commands:
- try:
- dispcmd = str([command] + args)
- # remember shell=False, so use git.cmd on windows, not just git
- process = subprocess.Popen([command] + args, cwd=cwd, env=env,
- stdout=subprocess.PIPE,
- stderr=(subprocess.PIPE if hide_stderr
- else None), **popen_kwargs)
- break
- except OSError as e:
- if e.errno == errno.ENOENT:
- continue
- if verbose:
- print("unable to run %%s" %% dispcmd)
- print(e)
- return None, None
- else:
- if verbose:
- print("unable to find command, tried %%s" %% (commands,))
- return None, None
- stdout = process.communicate()[0].strip().decode()
- if process.returncode != 0:
- if verbose:
- print("unable to run %%s (error)" %% dispcmd)
- print("stdout was %%s" %% stdout)
- return None, process.returncode
- return stdout, process.returncode
-
-
-def versions_from_parentdir(
- parentdir_prefix: str,
- root: str,
- verbose: bool,
-) -> Dict[str, Any]:
- """Try to determine the version from the parent directory name.
-
- Source tarballs conventionally unpack into a directory that includes both
- the project name and a version string. We will also support searching up
- two directory levels for an appropriately named parent directory
- """
- rootdirs = []
-
- for _ in range(3):
- dirname = os.path.basename(root)
- if dirname.startswith(parentdir_prefix):
- return {"version": dirname[len(parentdir_prefix):],
- "full-revisionid": None,
- "dirty": False, "error": None, "date": None}
- rootdirs.append(root)
- root = os.path.dirname(root) # up a level
-
- if verbose:
- print("Tried directories %%s but none started with prefix %%s" %%
- (str(rootdirs), parentdir_prefix))
- raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
-
-
-@register_vcs_handler("git", "get_keywords")
-def git_get_keywords(versionfile_abs: str) -> Dict[str, str]:
- """Extract version information from the given file."""
- # the code embedded in _version.py can just fetch the value of these
- # keywords. When used from setup.py, we don't want to import _version.py,
- # so we do it with a regexp instead. This function is not used from
- # _version.py.
- keywords: Dict[str, str] = {}
- try:
- with open(versionfile_abs, "r") as fobj:
- for line in fobj:
- if line.strip().startswith("git_refnames ="):
- mo = re.search(r'=\s*"(.*)"', line)
- if mo:
- keywords["refnames"] = mo.group(1)
- if line.strip().startswith("git_full ="):
- mo = re.search(r'=\s*"(.*)"', line)
- if mo:
- keywords["full"] = mo.group(1)
- if line.strip().startswith("git_date ="):
- mo = re.search(r'=\s*"(.*)"', line)
- if mo:
- keywords["date"] = mo.group(1)
- except OSError:
- pass
- return keywords
-
-
-@register_vcs_handler("git", "keywords")
-def git_versions_from_keywords(
- keywords: Dict[str, str],
- tag_prefix: str,
- verbose: bool,
-) -> Dict[str, Any]:
- """Get version information from git keywords."""
- if "refnames" not in keywords:
- raise NotThisMethod("Short version file found")
- date = keywords.get("date")
- if date is not None:
- # Use only the last line. Previous lines may contain GPG signature
- # information.
- date = date.splitlines()[-1]
-
- # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant
- # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601
- # -like" string, which we must then edit to make compliant), because
- # it's been around since git-1.5.3, and it's too difficult to
- # discover which version we're using, or to work around using an
- # older one.
- date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
- refnames = keywords["refnames"].strip()
- if refnames.startswith("$Format"):
- if verbose:
- print("keywords are unexpanded, not using")
- raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
- refs = {r.strip() for r in refnames.strip("()").split(",")}
- # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
- # just "foo-1.0". If we see a "tag: " prefix, prefer those.
- TAG = "tag: "
- tags = {r[len(TAG):] for r in refs if r.startswith(TAG)}
- if not tags:
- # Either we're using git < 1.8.3, or there really are no tags. We use
- # a heuristic: assume all version tags have a digit. The old git %%d
- # expansion behaves like git log --decorate=short and strips out the
- # refs/heads/ and refs/tags/ prefixes that would let us distinguish
- # between branches and tags. By ignoring refnames without digits, we
- # filter out many common branch names like "release" and
- # "stabilization", as well as "HEAD" and "master".
- tags = {r for r in refs if re.search(r'\d', r)}
- if verbose:
- print("discarding '%%s', no digits" %% ",".join(refs - tags))
- if verbose:
- print("likely tags: %%s" %% ",".join(sorted(tags)))
- for ref in sorted(tags):
- # sorting will prefer e.g. "2.0" over "2.0rc1"
- if ref.startswith(tag_prefix):
- r = ref[len(tag_prefix):]
- # Filter out refs that exactly match prefix or that don't start
- # with a number once the prefix is stripped (mostly a concern
- # when prefix is '')
- if not re.match(r'\d', r):
- continue
- if verbose:
- print("picking %%s" %% r)
- return {"version": r,
- "full-revisionid": keywords["full"].strip(),
- "dirty": False, "error": None,
- "date": date}
- # no suitable tags, so version is "0+unknown", but full hex is still there
- if verbose:
- print("no suitable tags, using unknown + full revision id")
- return {"version": "0+unknown",
- "full-revisionid": keywords["full"].strip(),
- "dirty": False, "error": "no suitable tags", "date": None}
-
-
-@register_vcs_handler("git", "pieces_from_vcs")
-def git_pieces_from_vcs(
- tag_prefix: str,
- root: str,
- verbose: bool,
- runner: Callable = run_command
-) -> Dict[str, Any]:
- """Get version from 'git describe' in the root of the source tree.
-
- This only gets called if the git-archive 'subst' keywords were *not*
- expanded, and _version.py hasn't already been rewritten with a short
- version string, meaning we're inside a checked out source tree.
- """
- GITS = ["git"]
- if sys.platform == "win32":
- GITS = ["git.cmd", "git.exe"]
-
- # GIT_DIR can interfere with correct operation of Versioneer.
- # It may be intended to be passed to the Versioneer-versioned project,
- # but that should not change where we get our version from.
- env = os.environ.copy()
- env.pop("GIT_DIR", None)
- runner = functools.partial(runner, env=env)
-
- _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root,
- hide_stderr=not verbose)
- if rc != 0:
- if verbose:
- print("Directory %%s not under git control" %% root)
- raise NotThisMethod("'git rev-parse --git-dir' returned error")
-
- # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
- # if there isn't one, this yields HEX[-dirty] (no NUM)
- describe_out, rc = runner(GITS, [
- "describe", "--tags", "--dirty", "--always", "--long",
- "--match", f"{tag_prefix}[[:digit:]]*"
- ], cwd=root)
- # --long was added in git-1.5.5
- if describe_out is None:
- raise NotThisMethod("'git describe' failed")
- describe_out = describe_out.strip()
- full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root)
- if full_out is None:
- raise NotThisMethod("'git rev-parse' failed")
- full_out = full_out.strip()
-
- pieces: Dict[str, Any] = {}
- pieces["long"] = full_out
- pieces["short"] = full_out[:7] # maybe improved later
- pieces["error"] = None
-
- branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
- cwd=root)
- # --abbrev-ref was added in git-1.6.3
- if rc != 0 or branch_name is None:
- raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
- branch_name = branch_name.strip()
-
- if branch_name == "HEAD":
- # If we aren't exactly on a branch, pick a branch which represents
- # the current commit. If all else fails, we are on a branchless
- # commit.
- branches, rc = runner(GITS, ["branch", "--contains"], cwd=root)
- # --contains was added in git-1.5.4
- if rc != 0 or branches is None:
- raise NotThisMethod("'git branch --contains' returned error")
- branches = branches.split("\n")
-
- # Remove the first line if we're running detached
- if "(" in branches[0]:
- branches.pop(0)
-
- # Strip off the leading "* " from the list of branches.
- branches = [branch[2:] for branch in branches]
- if "master" in branches:
- branch_name = "master"
- elif not branches:
- branch_name = None
- else:
- # Pick the first branch that is returned. Good or bad.
- branch_name = branches[0]
-
- pieces["branch"] = branch_name
-
- # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
- # TAG might have hyphens.
- git_describe = describe_out
-
- # look for -dirty suffix
- dirty = git_describe.endswith("-dirty")
- pieces["dirty"] = dirty
- if dirty:
- git_describe = git_describe[:git_describe.rindex("-dirty")]
-
- # now we have TAG-NUM-gHEX or HEX
-
- if "-" in git_describe:
- # TAG-NUM-gHEX
- mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
- if not mo:
- # unparsable. Maybe git-describe is misbehaving?
- pieces["error"] = ("unable to parse git-describe output: '%%s'"
- %% describe_out)
- return pieces
-
- # tag
- full_tag = mo.group(1)
- if not full_tag.startswith(tag_prefix):
- if verbose:
- fmt = "tag '%%s' doesn't start with prefix '%%s'"
- print(fmt %% (full_tag, tag_prefix))
- pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'"
- %% (full_tag, tag_prefix))
- return pieces
- pieces["closest-tag"] = full_tag[len(tag_prefix):]
-
- # distance: number of commits since tag
- pieces["distance"] = int(mo.group(2))
-
- # commit: short hex revision ID
- pieces["short"] = mo.group(3)
-
- else:
- # HEX: no tags
- pieces["closest-tag"] = None
- out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root)
- pieces["distance"] = len(out.split()) # total number of commits
-
- # commit date: see ISO-8601 comment in git_versions_from_keywords()
- date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip()
- # Use only the last line. Previous lines may contain GPG signature
- # information.
- date = date.splitlines()[-1]
- pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
-
- return pieces
-
-
-def plus_or_dot(pieces: Dict[str, Any]) -> str:
- """Return a + if we don't already have one, else return a ."""
- if "+" in pieces.get("closest-tag", ""):
- return "."
- return "+"
-
-
-def render_pep440(pieces: Dict[str, Any]) -> str:
- """Build up version string, with post-release "local version identifier".
-
- Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
- get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
-
- Exceptions:
- 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += plus_or_dot(pieces)
- rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- else:
- # exception #1
- rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"],
- pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- return rendered
-
-
-def render_pep440_branch(pieces: Dict[str, Any]) -> str:
- """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
-
- The ".dev0" means not master branch. Note that .dev0 sorts backwards
- (a feature branch will appear "older" than the master branch).
-
- Exceptions:
- 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- if pieces["branch"] != "master":
- rendered += ".dev0"
- rendered += plus_or_dot(pieces)
- rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- else:
- # exception #1
- rendered = "0"
- if pieces["branch"] != "master":
- rendered += ".dev0"
- rendered += "+untagged.%%d.g%%s" %% (pieces["distance"],
- pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- return rendered
-
-
-def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]:
- """Split pep440 version string at the post-release segment.
-
- Returns the release segments before the post-release and the
- post-release version number (or -1 if no post-release segment is present).
- """
- vc = str.split(ver, ".post")
- return vc[0], int(vc[1] or 0) if len(vc) == 2 else None
-
-
-def render_pep440_pre(pieces: Dict[str, Any]) -> str:
- """TAG[.postN.devDISTANCE] -- No -dirty.
-
- Exceptions:
- 1: no tags. 0.post0.devDISTANCE
- """
- if pieces["closest-tag"]:
- if pieces["distance"]:
- # update the post release segment
- tag_version, post_version = pep440_split_post(pieces["closest-tag"])
- rendered = tag_version
- if post_version is not None:
- rendered += ".post%%d.dev%%d" %% (post_version + 1, pieces["distance"])
- else:
- rendered += ".post0.dev%%d" %% (pieces["distance"])
- else:
- # no commits, use the tag as the version
- rendered = pieces["closest-tag"]
- else:
- # exception #1
- rendered = "0.post0.dev%%d" %% pieces["distance"]
- return rendered
-
-
-def render_pep440_post(pieces: Dict[str, Any]) -> str:
- """TAG[.postDISTANCE[.dev0]+gHEX] .
-
- The ".dev0" means dirty. Note that .dev0 sorts backwards
- (a dirty tree will appear "older" than the corresponding clean one),
- but you shouldn't be releasing software with -dirty anyways.
-
- Exceptions:
- 1: no tags. 0.postDISTANCE[.dev0]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += ".post%%d" %% pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- rendered += plus_or_dot(pieces)
- rendered += "g%%s" %% pieces["short"]
- else:
- # exception #1
- rendered = "0.post%%d" %% pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- rendered += "+g%%s" %% pieces["short"]
- return rendered
-
-
-def render_pep440_post_branch(pieces: Dict[str, Any]) -> str:
- """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] .
-
- The ".dev0" means not master branch.
-
- Exceptions:
- 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += ".post%%d" %% pieces["distance"]
- if pieces["branch"] != "master":
- rendered += ".dev0"
- rendered += plus_or_dot(pieces)
- rendered += "g%%s" %% pieces["short"]
- if pieces["dirty"]:
- rendered += ".dirty"
- else:
- # exception #1
- rendered = "0.post%%d" %% pieces["distance"]
- if pieces["branch"] != "master":
- rendered += ".dev0"
- rendered += "+g%%s" %% pieces["short"]
- if pieces["dirty"]:
- rendered += ".dirty"
- return rendered
-
-
-def render_pep440_old(pieces: Dict[str, Any]) -> str:
- """TAG[.postDISTANCE[.dev0]] .
-
- The ".dev0" means dirty.
-
- Exceptions:
- 1: no tags. 0.postDISTANCE[.dev0]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += ".post%%d" %% pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- else:
- # exception #1
- rendered = "0.post%%d" %% pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- return rendered
-
-
-def render_git_describe(pieces: Dict[str, Any]) -> str:
- """TAG[-DISTANCE-gHEX][-dirty].
-
- Like 'git describe --tags --dirty --always'.
-
- Exceptions:
- 1: no tags. HEX[-dirty] (note: no 'g' prefix)
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"]:
- rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"])
- else:
- # exception #1
- rendered = pieces["short"]
- if pieces["dirty"]:
- rendered += "-dirty"
- return rendered
-
-
-def render_git_describe_long(pieces: Dict[str, Any]) -> str:
- """TAG-DISTANCE-gHEX[-dirty].
-
- Like 'git describe --tags --dirty --always -long'.
- The distance/hash is unconditional.
-
- Exceptions:
- 1: no tags. HEX[-dirty] (note: no 'g' prefix)
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"])
- else:
- # exception #1
- rendered = pieces["short"]
- if pieces["dirty"]:
- rendered += "-dirty"
- return rendered
-
-
-def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]:
- """Render the given version pieces into the requested style."""
- if pieces["error"]:
- return {"version": "unknown",
- "full-revisionid": pieces.get("long"),
- "dirty": None,
- "error": pieces["error"],
- "date": None}
-
- if not style or style == "default":
- style = "pep440" # the default
-
- if style == "pep440":
- rendered = render_pep440(pieces)
- elif style == "pep440-branch":
- rendered = render_pep440_branch(pieces)
- elif style == "pep440-pre":
- rendered = render_pep440_pre(pieces)
- elif style == "pep440-post":
- rendered = render_pep440_post(pieces)
- elif style == "pep440-post-branch":
- rendered = render_pep440_post_branch(pieces)
- elif style == "pep440-old":
- rendered = render_pep440_old(pieces)
- elif style == "git-describe":
- rendered = render_git_describe(pieces)
- elif style == "git-describe-long":
- rendered = render_git_describe_long(pieces)
- else:
- raise ValueError("unknown style '%%s'" %% style)
-
- return {"version": rendered, "full-revisionid": pieces["long"],
- "dirty": pieces["dirty"], "error": None,
- "date": pieces.get("date")}
-
-
-def get_versions() -> Dict[str, Any]:
- """Get version information or return default if unable to do so."""
- # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
- # __file__, we can work backwards from there to the root. Some
- # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
- # case we can only use expanded keywords.
-
- cfg = get_config()
- verbose = cfg.verbose
-
- try:
- return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
- verbose)
- except NotThisMethod:
- pass
-
- try:
- root = os.path.realpath(__file__)
- # versionfile_source is the relative path from the top of the source
- # tree (where the .git directory might live) to this file. Invert
- # this to find the root from __file__.
- for _ in cfg.versionfile_source.split('/'):
- root = os.path.dirname(root)
- except NameError:
- return {"version": "0+unknown", "full-revisionid": None,
- "dirty": None,
- "error": "unable to find root of source tree",
- "date": None}
-
- try:
- pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
- return render(pieces, cfg.style)
- except NotThisMethod:
- pass
-
- try:
- if cfg.parentdir_prefix:
- return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
- except NotThisMethod:
- pass
-
- return {"version": "0+unknown", "full-revisionid": None,
- "dirty": None,
- "error": "unable to compute version", "date": None}
-'''
-
-
-@register_vcs_handler("git", "get_keywords")
-def git_get_keywords(versionfile_abs: str) -> Dict[str, str]:
- """Extract version information from the given file."""
- # the code embedded in _version.py can just fetch the value of these
- # keywords. When used from setup.py, we don't want to import _version.py,
- # so we do it with a regexp instead. This function is not used from
- # _version.py.
- keywords: Dict[str, str] = {}
- try:
- with open(versionfile_abs, "r") as fobj:
- for line in fobj:
- if line.strip().startswith("git_refnames ="):
- mo = re.search(r'=\s*"(.*)"', line)
- if mo:
- keywords["refnames"] = mo.group(1)
- if line.strip().startswith("git_full ="):
- mo = re.search(r'=\s*"(.*)"', line)
- if mo:
- keywords["full"] = mo.group(1)
- if line.strip().startswith("git_date ="):
- mo = re.search(r'=\s*"(.*)"', line)
- if mo:
- keywords["date"] = mo.group(1)
- except OSError:
- pass
- return keywords
-
-
-@register_vcs_handler("git", "keywords")
-def git_versions_from_keywords(
- keywords: Dict[str, str],
- tag_prefix: str,
- verbose: bool,
-) -> Dict[str, Any]:
- """Get version information from git keywords."""
- if "refnames" not in keywords:
- raise NotThisMethod("Short version file found")
- date = keywords.get("date")
- if date is not None:
- # Use only the last line. Previous lines may contain GPG signature
- # information.
- date = date.splitlines()[-1]
-
- # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
- # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
- # -like" string, which we must then edit to make compliant), because
- # it's been around since git-1.5.3, and it's too difficult to
- # discover which version we're using, or to work around using an
- # older one.
- date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
- refnames = keywords["refnames"].strip()
- if refnames.startswith("$Format"):
- if verbose:
- print("keywords are unexpanded, not using")
- raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
- refs = {r.strip() for r in refnames.strip("()").split(",")}
- # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
- # just "foo-1.0". If we see a "tag: " prefix, prefer those.
- TAG = "tag: "
- tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)}
- if not tags:
- # Either we're using git < 1.8.3, or there really are no tags. We use
- # a heuristic: assume all version tags have a digit. The old git %d
- # expansion behaves like git log --decorate=short and strips out the
- # refs/heads/ and refs/tags/ prefixes that would let us distinguish
- # between branches and tags. By ignoring refnames without digits, we
- # filter out many common branch names like "release" and
- # "stabilization", as well as "HEAD" and "master".
- tags = {r for r in refs if re.search(r"\d", r)}
- if verbose:
- print("discarding '%s', no digits" % ",".join(refs - tags))
- if verbose:
- print("likely tags: %s" % ",".join(sorted(tags)))
- for ref in sorted(tags):
- # sorting will prefer e.g. "2.0" over "2.0rc1"
- if ref.startswith(tag_prefix):
- r = ref[len(tag_prefix) :]
- # Filter out refs that exactly match prefix or that don't start
- # with a number once the prefix is stripped (mostly a concern
- # when prefix is '')
- if not re.match(r"\d", r):
- continue
- if verbose:
- print("picking %s" % r)
- return {
- "version": r,
- "full-revisionid": keywords["full"].strip(),
- "dirty": False,
- "error": None,
- "date": date,
- }
- # no suitable tags, so version is "0+unknown", but full hex is still there
- if verbose:
- print("no suitable tags, using unknown + full revision id")
- return {
- "version": "0+unknown",
- "full-revisionid": keywords["full"].strip(),
- "dirty": False,
- "error": "no suitable tags",
- "date": None,
- }
-
-
-@register_vcs_handler("git", "pieces_from_vcs")
-def git_pieces_from_vcs(
- tag_prefix: str, root: str, verbose: bool, runner: Callable = run_command
-) -> Dict[str, Any]:
- """Get version from 'git describe' in the root of the source tree.
-
- This only gets called if the git-archive 'subst' keywords were *not*
- expanded, and _version.py hasn't already been rewritten with a short
- version string, meaning we're inside a checked out source tree.
- """
- GITS = ["git"]
- if sys.platform == "win32":
- GITS = ["git.cmd", "git.exe"]
-
- # GIT_DIR can interfere with correct operation of Versioneer.
- # It may be intended to be passed to the Versioneer-versioned project,
- # but that should not change where we get our version from.
- env = os.environ.copy()
- env.pop("GIT_DIR", None)
- runner = functools.partial(runner, env=env)
-
- _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose)
- if rc != 0:
- if verbose:
- print("Directory %s not under git control" % root)
- raise NotThisMethod("'git rev-parse --git-dir' returned error")
-
- # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
- # if there isn't one, this yields HEX[-dirty] (no NUM)
- describe_out, rc = runner(
- GITS,
- [
- "describe",
- "--tags",
- "--dirty",
- "--always",
- "--long",
- "--match",
- f"{tag_prefix}[[:digit:]]*",
- ],
- cwd=root,
- )
- # --long was added in git-1.5.5
- if describe_out is None:
- raise NotThisMethod("'git describe' failed")
- describe_out = describe_out.strip()
- full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root)
- if full_out is None:
- raise NotThisMethod("'git rev-parse' failed")
- full_out = full_out.strip()
-
- pieces: Dict[str, Any] = {}
- pieces["long"] = full_out
- pieces["short"] = full_out[:7] # maybe improved later
- pieces["error"] = None
-
- branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
- # --abbrev-ref was added in git-1.6.3
- if rc != 0 or branch_name is None:
- raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
- branch_name = branch_name.strip()
-
- if branch_name == "HEAD":
- # If we aren't exactly on a branch, pick a branch which represents
- # the current commit. If all else fails, we are on a branchless
- # commit.
- branches, rc = runner(GITS, ["branch", "--contains"], cwd=root)
- # --contains was added in git-1.5.4
- if rc != 0 or branches is None:
- raise NotThisMethod("'git branch --contains' returned error")
- branches = branches.split("\n")
-
- # Remove the first line if we're running detached
- if "(" in branches[0]:
- branches.pop(0)
-
- # Strip off the leading "* " from the list of branches.
- branches = [branch[2:] for branch in branches]
- if "master" in branches:
- branch_name = "master"
- elif not branches:
- branch_name = None
- else:
- # Pick the first branch that is returned. Good or bad.
- branch_name = branches[0]
-
- pieces["branch"] = branch_name
-
- # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
- # TAG might have hyphens.
- git_describe = describe_out
-
- # look for -dirty suffix
- dirty = git_describe.endswith("-dirty")
- pieces["dirty"] = dirty
- if dirty:
- git_describe = git_describe[: git_describe.rindex("-dirty")]
-
- # now we have TAG-NUM-gHEX or HEX
-
- if "-" in git_describe:
- # TAG-NUM-gHEX
- mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
- if not mo:
- # unparsable. Maybe git-describe is misbehaving?
- pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
- return pieces
-
- # tag
- full_tag = mo.group(1)
- if not full_tag.startswith(tag_prefix):
- if verbose:
- fmt = "tag '%s' doesn't start with prefix '%s'"
- print(fmt % (full_tag, tag_prefix))
- pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
- full_tag,
- tag_prefix,
- )
- return pieces
- pieces["closest-tag"] = full_tag[len(tag_prefix) :]
-
- # distance: number of commits since tag
- pieces["distance"] = int(mo.group(2))
-
- # commit: short hex revision ID
- pieces["short"] = mo.group(3)
-
- else:
- # HEX: no tags
- pieces["closest-tag"] = None
- out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root)
- pieces["distance"] = len(out.split()) # total number of commits
-
- # commit date: see ISO-8601 comment in git_versions_from_keywords()
- date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip()
- # Use only the last line. Previous lines may contain GPG signature
- # information.
- date = date.splitlines()[-1]
- pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
-
- return pieces
-
-
-def do_vcs_install(versionfile_source: str, ipy: Optional[str]) -> None:
- """Git-specific installation logic for Versioneer.
-
- For Git, this means creating/changing .gitattributes to mark _version.py
- for export-subst keyword substitution.
- """
- GITS = ["git"]
- if sys.platform == "win32":
- GITS = ["git.cmd", "git.exe"]
- files = [versionfile_source]
- if ipy:
- files.append(ipy)
- if "VERSIONEER_PEP518" not in globals():
- try:
- my_path = __file__
- if my_path.endswith((".pyc", ".pyo")):
- my_path = os.path.splitext(my_path)[0] + ".py"
- versioneer_file = os.path.relpath(my_path)
- except NameError:
- versioneer_file = "versioneer.py"
- files.append(versioneer_file)
- present = False
- try:
- with open(".gitattributes", "r") as fobj:
- for line in fobj:
- if line.strip().startswith(versionfile_source):
- if "export-subst" in line.strip().split()[1:]:
- present = True
- break
- except OSError:
- pass
- if not present:
- with open(".gitattributes", "a+") as fobj:
- fobj.write(f"{versionfile_source} export-subst\n")
- files.append(".gitattributes")
- run_command(GITS, ["add", "--"] + files)
-
-
-def versions_from_parentdir(
- parentdir_prefix: str,
- root: str,
- verbose: bool,
-) -> Dict[str, Any]:
- """Try to determine the version from the parent directory name.
-
- Source tarballs conventionally unpack into a directory that includes both
- the project name and a version string. We will also support searching up
- two directory levels for an appropriately named parent directory
- """
- rootdirs = []
-
- for _ in range(3):
- dirname = os.path.basename(root)
- if dirname.startswith(parentdir_prefix):
- return {
- "version": dirname[len(parentdir_prefix) :],
- "full-revisionid": None,
- "dirty": False,
- "error": None,
- "date": None,
- }
- rootdirs.append(root)
- root = os.path.dirname(root) # up a level
-
- if verbose:
- print(
- "Tried directories %s but none started with prefix %s"
- % (str(rootdirs), parentdir_prefix)
- )
- raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
-
-
-SHORT_VERSION_PY = """
-# This file was generated by 'versioneer.py' (0.29) from
-# revision-control system data, or from the parent directory name of an
-# unpacked source archive. Distribution tarballs contain a pre-generated copy
-# of this file.
-
-import json
-
-version_json = '''
-%s
-''' # END VERSION_JSON
-
-
-def get_versions():
- return json.loads(version_json)
-"""
-
-
-def versions_from_file(filename: str) -> Dict[str, Any]:
- """Try to determine the version from _version.py if present."""
- try:
- with open(filename) as f:
- contents = f.read()
- except OSError:
- raise NotThisMethod("unable to read _version.py")
- mo = re.search(
- r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S
- )
- if not mo:
- mo = re.search(
- r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S
- )
- if not mo:
- raise NotThisMethod("no version_json in _version.py")
- return json.loads(mo.group(1))
-
-
-def write_to_version_file(filename: str, versions: Dict[str, Any]) -> None:
- """Write the given version number to the given _version.py file."""
- contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": "))
- with open(filename, "w") as f:
- f.write(SHORT_VERSION_PY % contents)
-
- print("set %s to '%s'" % (filename, versions["version"]))
-
-
-def plus_or_dot(pieces: Dict[str, Any]) -> str:
- """Return a + if we don't already have one, else return a ."""
- if "+" in pieces.get("closest-tag", ""):
- return "."
- return "+"
-
-
-def render_pep440(pieces: Dict[str, Any]) -> str:
- """Build up version string, with post-release "local version identifier".
-
- Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
- get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
-
- Exceptions:
- 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += plus_or_dot(pieces)
- rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- else:
- # exception #1
- rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- return rendered
-
-
-def render_pep440_branch(pieces: Dict[str, Any]) -> str:
- """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
-
- The ".dev0" means not master branch. Note that .dev0 sorts backwards
- (a feature branch will appear "older" than the master branch).
-
- Exceptions:
- 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- if pieces["branch"] != "master":
- rendered += ".dev0"
- rendered += plus_or_dot(pieces)
- rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- else:
- # exception #1
- rendered = "0"
- if pieces["branch"] != "master":
- rendered += ".dev0"
- rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
- if pieces["dirty"]:
- rendered += ".dirty"
- return rendered
-
-
-def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]:
- """Split pep440 version string at the post-release segment.
-
- Returns the release segments before the post-release and the
- post-release version number (or -1 if no post-release segment is present).
- """
- vc = str.split(ver, ".post")
- return vc[0], int(vc[1] or 0) if len(vc) == 2 else None
-
-
-def render_pep440_pre(pieces: Dict[str, Any]) -> str:
- """TAG[.postN.devDISTANCE] -- No -dirty.
-
- Exceptions:
- 1: no tags. 0.post0.devDISTANCE
- """
- if pieces["closest-tag"]:
- if pieces["distance"]:
- # update the post release segment
- tag_version, post_version = pep440_split_post(pieces["closest-tag"])
- rendered = tag_version
- if post_version is not None:
- rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"])
- else:
- rendered += ".post0.dev%d" % (pieces["distance"])
- else:
- # no commits, use the tag as the version
- rendered = pieces["closest-tag"]
- else:
- # exception #1
- rendered = "0.post0.dev%d" % pieces["distance"]
- return rendered
-
-
-def render_pep440_post(pieces: Dict[str, Any]) -> str:
- """TAG[.postDISTANCE[.dev0]+gHEX] .
-
- The ".dev0" means dirty. Note that .dev0 sorts backwards
- (a dirty tree will appear "older" than the corresponding clean one),
- but you shouldn't be releasing software with -dirty anyways.
-
- Exceptions:
- 1: no tags. 0.postDISTANCE[.dev0]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += ".post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- rendered += plus_or_dot(pieces)
- rendered += "g%s" % pieces["short"]
- else:
- # exception #1
- rendered = "0.post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- rendered += "+g%s" % pieces["short"]
- return rendered
-
-
-def render_pep440_post_branch(pieces: Dict[str, Any]) -> str:
- """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] .
-
- The ".dev0" means not master branch.
-
- Exceptions:
- 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += ".post%d" % pieces["distance"]
- if pieces["branch"] != "master":
- rendered += ".dev0"
- rendered += plus_or_dot(pieces)
- rendered += "g%s" % pieces["short"]
- if pieces["dirty"]:
- rendered += ".dirty"
- else:
- # exception #1
- rendered = "0.post%d" % pieces["distance"]
- if pieces["branch"] != "master":
- rendered += ".dev0"
- rendered += "+g%s" % pieces["short"]
- if pieces["dirty"]:
- rendered += ".dirty"
- return rendered
-
-
-def render_pep440_old(pieces: Dict[str, Any]) -> str:
- """TAG[.postDISTANCE[.dev0]] .
-
- The ".dev0" means dirty.
-
- Exceptions:
- 1: no tags. 0.postDISTANCE[.dev0]
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"] or pieces["dirty"]:
- rendered += ".post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- else:
- # exception #1
- rendered = "0.post%d" % pieces["distance"]
- if pieces["dirty"]:
- rendered += ".dev0"
- return rendered
-
-
-def render_git_describe(pieces: Dict[str, Any]) -> str:
- """TAG[-DISTANCE-gHEX][-dirty].
-
- Like 'git describe --tags --dirty --always'.
-
- Exceptions:
- 1: no tags. HEX[-dirty] (note: no 'g' prefix)
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- if pieces["distance"]:
- rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
- else:
- # exception #1
- rendered = pieces["short"]
- if pieces["dirty"]:
- rendered += "-dirty"
- return rendered
-
-
-def render_git_describe_long(pieces: Dict[str, Any]) -> str:
- """TAG-DISTANCE-gHEX[-dirty].
-
- Like 'git describe --tags --dirty --always -long'.
- The distance/hash is unconditional.
-
- Exceptions:
- 1: no tags. HEX[-dirty] (note: no 'g' prefix)
- """
- if pieces["closest-tag"]:
- rendered = pieces["closest-tag"]
- rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
- else:
- # exception #1
- rendered = pieces["short"]
- if pieces["dirty"]:
- rendered += "-dirty"
- return rendered
-
-
-def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]:
- """Render the given version pieces into the requested style."""
- if pieces["error"]:
- return {
- "version": "unknown",
- "full-revisionid": pieces.get("long"),
- "dirty": None,
- "error": pieces["error"],
- "date": None,
- }
-
- if not style or style == "default":
- style = "pep440" # the default
-
- if style == "pep440":
- rendered = render_pep440(pieces)
- elif style == "pep440-branch":
- rendered = render_pep440_branch(pieces)
- elif style == "pep440-pre":
- rendered = render_pep440_pre(pieces)
- elif style == "pep440-post":
- rendered = render_pep440_post(pieces)
- elif style == "pep440-post-branch":
- rendered = render_pep440_post_branch(pieces)
- elif style == "pep440-old":
- rendered = render_pep440_old(pieces)
- elif style == "git-describe":
- rendered = render_git_describe(pieces)
- elif style == "git-describe-long":
- rendered = render_git_describe_long(pieces)
- else:
- raise ValueError("unknown style '%s'" % style)
-
- return {
- "version": rendered,
- "full-revisionid": pieces["long"],
- "dirty": pieces["dirty"],
- "error": None,
- "date": pieces.get("date"),
- }
-
-
-class VersioneerBadRootError(Exception):
- """The project root directory is unknown or missing key files."""
-
-
-def get_versions(verbose: bool = False) -> Dict[str, Any]:
- """Get the project version from whatever source is available.
-
- Returns dict with two keys: 'version' and 'full'.
- """
- if "versioneer" in sys.modules:
- # see the discussion in cmdclass.py:get_cmdclass()
- del sys.modules["versioneer"]
-
- root = get_root()
- cfg = get_config_from_root(root)
-
- assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg"
- handlers = HANDLERS.get(cfg.VCS)
- assert handlers, "unrecognized VCS '%s'" % cfg.VCS
- verbose = verbose or bool(cfg.verbose) # `bool()` used to avoid `None`
- assert (
- cfg.versionfile_source is not None
- ), "please set versioneer.versionfile_source"
- assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix"
-
- versionfile_abs = os.path.join(root, cfg.versionfile_source)
-
- # extract version from first of: _version.py, VCS command (e.g. 'git
- # describe'), parentdir. This is meant to work for developers using a
- # source checkout, for users of a tarball created by 'setup.py sdist',
- # and for users of a tarball/zipball created by 'git archive' or github's
- # download-from-tag feature or the equivalent in other VCSes.
-
- get_keywords_f = handlers.get("get_keywords")
- from_keywords_f = handlers.get("keywords")
- if get_keywords_f and from_keywords_f:
- try:
- keywords = get_keywords_f(versionfile_abs)
- ver = from_keywords_f(keywords, cfg.tag_prefix, verbose)
- if verbose:
- print("got version from expanded keyword %s" % ver)
- return ver
- except NotThisMethod:
- pass
-
- try:
- ver = versions_from_file(versionfile_abs)
- if verbose:
- print("got version from file %s %s" % (versionfile_abs, ver))
- return ver
- except NotThisMethod:
- pass
-
- from_vcs_f = handlers.get("pieces_from_vcs")
- if from_vcs_f:
- try:
- pieces = from_vcs_f(cfg.tag_prefix, root, verbose)
- ver = render(pieces, cfg.style)
- if verbose:
- print("got version from VCS %s" % ver)
- return ver
- except NotThisMethod:
- pass
-
- try:
- if cfg.parentdir_prefix:
- ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
- if verbose:
- print("got version from parentdir %s" % ver)
- return ver
- except NotThisMethod:
- pass
-
- if verbose:
- print("unable to compute version")
-
- return {
- "version": "0+unknown",
- "full-revisionid": None,
- "dirty": None,
- "error": "unable to compute version",
- "date": None,
- }
-
-
-def get_version() -> str:
- """Get the short version string for this project."""
- return get_versions()["version"]
-
-
-def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None):
- """Get the custom setuptools subclasses used by Versioneer.
-
- If the package uses a different cmdclass (e.g. one from numpy), it
- should be provide as an argument.
- """
- if "versioneer" in sys.modules:
- del sys.modules["versioneer"]
- # this fixes the "python setup.py develop" case (also 'install' and
- # 'easy_install .'), in which subdependencies of the main project are
- # built (using setup.py bdist_egg) in the same python process. Assume
- # a main project A and a dependency B, which use different versions
- # of Versioneer. A's setup.py imports A's Versioneer, leaving it in
- # sys.modules by the time B's setup.py is executed, causing B to run
- # with the wrong versioneer. Setuptools wraps the sub-dep builds in a
- # sandbox that restores sys.modules to it's pre-build state, so the
- # parent is protected against the child's "import versioneer". By
- # removing ourselves from sys.modules here, before the child build
- # happens, we protect the child from the parent's versioneer too.
- # Also see https://github.com/python-versioneer/python-versioneer/issues/52
-
- cmds = {} if cmdclass is None else cmdclass.copy()
-
- # we add "version" to setuptools
- from setuptools import Command
-
- class cmd_version(Command):
- description = "report generated version string"
- user_options: List[Tuple[str, str, str]] = []
- boolean_options: List[str] = []
-
- def initialize_options(self) -> None:
- pass
-
- def finalize_options(self) -> None:
- pass
-
- def run(self) -> None:
- vers = get_versions(verbose=True)
- print("Version: %s" % vers["version"])
- print(" full-revisionid: %s" % vers.get("full-revisionid"))
- print(" dirty: %s" % vers.get("dirty"))
- print(" date: %s" % vers.get("date"))
- if vers["error"]:
- print(" error: %s" % vers["error"])
-
- cmds["version"] = cmd_version
-
- # we override "build_py" in setuptools
- #
- # most invocation pathways end up running build_py:
- # distutils/build -> build_py
- # distutils/install -> distutils/build ->..
- # setuptools/bdist_wheel -> distutils/install ->..
- # setuptools/bdist_egg -> distutils/install_lib -> build_py
- # setuptools/install -> bdist_egg ->..
- # setuptools/develop -> ?
- # pip install:
- # copies source tree to a tempdir before running egg_info/etc
- # if .git isn't copied too, 'git describe' will fail
- # then does setup.py bdist_wheel, or sometimes setup.py install
- # setup.py egg_info -> ?
-
- # pip install -e . and setuptool/editable_wheel will invoke build_py
- # but the build_py command is not expected to copy any files.
-
- # we override different "build_py" commands for both environments
- if "build_py" in cmds:
- _build_py: Any = cmds["build_py"]
- else:
- from setuptools.command.build_py import build_py as _build_py
-
- class cmd_build_py(_build_py):
- def run(self) -> None:
- root = get_root()
- cfg = get_config_from_root(root)
- versions = get_versions()
- _build_py.run(self)
- if getattr(self, "editable_mode", False):
- # During editable installs `.py` and data files are
- # not copied to build_lib
- return
- # now locate _version.py in the new build/ directory and replace
- # it with an updated value
- if cfg.versionfile_build:
- target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build)
- print("UPDATING %s" % target_versionfile)
- write_to_version_file(target_versionfile, versions)
-
- cmds["build_py"] = cmd_build_py
-
- if "build_ext" in cmds:
- _build_ext: Any = cmds["build_ext"]
- else:
- from setuptools.command.build_ext import build_ext as _build_ext
-
- class cmd_build_ext(_build_ext):
- def run(self) -> None:
- root = get_root()
- cfg = get_config_from_root(root)
- versions = get_versions()
- _build_ext.run(self)
- if self.inplace:
- # build_ext --inplace will only build extensions in
- # build/lib<..> dir with no _version.py to write to.
- # As in place builds will already have a _version.py
- # in the module dir, we do not need to write one.
- return
- # now locate _version.py in the new build/ directory and replace
- # it with an updated value
- if not cfg.versionfile_build:
- return
- target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build)
- if not os.path.exists(target_versionfile):
- print(
- f"Warning: {target_versionfile} does not exist, skipping "
- "version update. This can happen if you are running build_ext "
- "without first running build_py."
- )
- return
- print("UPDATING %s" % target_versionfile)
- write_to_version_file(target_versionfile, versions)
-
- cmds["build_ext"] = cmd_build_ext
-
- if "cx_Freeze" in sys.modules: # cx_freeze enabled?
- from cx_Freeze.dist import build_exe as _build_exe # type: ignore
-
- # nczeczulin reports that py2exe won't like the pep440-style string
- # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g.
- # setup(console=[{
- # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION
- # "product_version": versioneer.get_version(),
- # ...
-
- class cmd_build_exe(_build_exe):
- def run(self) -> None:
- root = get_root()
- cfg = get_config_from_root(root)
- versions = get_versions()
- target_versionfile = cfg.versionfile_source
- print("UPDATING %s" % target_versionfile)
- write_to_version_file(target_versionfile, versions)
-
- _build_exe.run(self)
- os.unlink(target_versionfile)
- with open(cfg.versionfile_source, "w") as f:
- LONG = LONG_VERSION_PY[cfg.VCS]
- f.write(
- LONG
- % {
- "DOLLAR": "$",
- "STYLE": cfg.style,
- "TAG_PREFIX": cfg.tag_prefix,
- "PARENTDIR_PREFIX": cfg.parentdir_prefix,
- "VERSIONFILE_SOURCE": cfg.versionfile_source,
- }
- )
-
- cmds["build_exe"] = cmd_build_exe
- del cmds["build_py"]
-
- if "py2exe" in sys.modules: # py2exe enabled?
- try:
- from py2exe.setuptools_buildexe import py2exe as _py2exe # type: ignore
- except ImportError:
- from py2exe.distutils_buildexe import py2exe as _py2exe # type: ignore
-
- class cmd_py2exe(_py2exe):
- def run(self) -> None:
- root = get_root()
- cfg = get_config_from_root(root)
- versions = get_versions()
- target_versionfile = cfg.versionfile_source
- print("UPDATING %s" % target_versionfile)
- write_to_version_file(target_versionfile, versions)
-
- _py2exe.run(self)
- os.unlink(target_versionfile)
- with open(cfg.versionfile_source, "w") as f:
- LONG = LONG_VERSION_PY[cfg.VCS]
- f.write(
- LONG
- % {
- "DOLLAR": "$",
- "STYLE": cfg.style,
- "TAG_PREFIX": cfg.tag_prefix,
- "PARENTDIR_PREFIX": cfg.parentdir_prefix,
- "VERSIONFILE_SOURCE": cfg.versionfile_source,
- }
- )
-
- cmds["py2exe"] = cmd_py2exe
-
- # sdist farms its file list building out to egg_info
- if "egg_info" in cmds:
- _egg_info: Any = cmds["egg_info"]
- else:
- from setuptools.command.egg_info import egg_info as _egg_info
-
- class cmd_egg_info(_egg_info):
- def find_sources(self) -> None:
- # egg_info.find_sources builds the manifest list and writes it
- # in one shot
- super().find_sources()
-
- # Modify the filelist and normalize it
- root = get_root()
- cfg = get_config_from_root(root)
- self.filelist.append("versioneer.py")
- if cfg.versionfile_source:
- # There are rare cases where versionfile_source might not be
- # included by default, so we must be explicit
- self.filelist.append(cfg.versionfile_source)
- self.filelist.sort()
- self.filelist.remove_duplicates()
-
- # The write method is hidden in the manifest_maker instance that
- # generated the filelist and was thrown away
- # We will instead replicate their final normalization (to unicode,
- # and POSIX-style paths)
- from setuptools import unicode_utils
-
- normalized = [
- unicode_utils.filesys_decode(f).replace(os.sep, "/")
- for f in self.filelist.files
- ]
-
- manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
- with open(manifest_filename, "w") as fobj:
- fobj.write("\n".join(normalized))
-
- cmds["egg_info"] = cmd_egg_info
-
- # we override different "sdist" commands for both environments
- if "sdist" in cmds:
- _sdist: Any = cmds["sdist"]
- else:
- from setuptools.command.sdist import sdist as _sdist
-
- class cmd_sdist(_sdist):
- def run(self) -> None:
- versions = get_versions()
- self._versioneer_generated_versions = versions
- # unless we update this, the command will keep using the old
- # version
- self.distribution.metadata.version = versions["version"]
- return _sdist.run(self)
-
- def make_release_tree(self, base_dir: str, files: List[str]) -> None:
- root = get_root()
- cfg = get_config_from_root(root)
- _sdist.make_release_tree(self, base_dir, files)
- # now locate _version.py in the new base_dir directory
- # (remembering that it may be a hardlink) and replace it with an
- # updated value
- target_versionfile = os.path.join(base_dir, cfg.versionfile_source)
- print("UPDATING %s" % target_versionfile)
- write_to_version_file(
- target_versionfile, self._versioneer_generated_versions
- )
-
- cmds["sdist"] = cmd_sdist
-
- return cmds
-
-
-CONFIG_ERROR = """
-setup.cfg is missing the necessary Versioneer configuration. You need
-a section like:
-
- [versioneer]
- VCS = git
- style = pep440
- versionfile_source = src/myproject/_version.py
- versionfile_build = myproject/_version.py
- tag_prefix =
- parentdir_prefix = myproject-
-
-You will also need to edit your setup.py to use the results:
-
- import versioneer
- setup(version=versioneer.get_version(),
- cmdclass=versioneer.get_cmdclass(), ...)
-
-Please read the docstring in ./versioneer.py for configuration instructions,
-edit setup.cfg, and re-run the installer or 'python versioneer.py setup'.
-"""
-
-SAMPLE_CONFIG = """
-# See the docstring in versioneer.py for instructions. Note that you must
-# re-run 'versioneer.py setup' after changing this section, and commit the
-# resulting files.
-
-[versioneer]
-#VCS = git
-#style = pep440
-#versionfile_source =
-#versionfile_build =
-#tag_prefix =
-#parentdir_prefix =
-
-"""
-
-OLD_SNIPPET = """
-from ._version import get_versions
-__version__ = get_versions()['version']
-del get_versions
-"""
-
-INIT_PY_SNIPPET = """
-from . import {0}
-__version__ = {0}.get_versions()['version']
-"""
-
-
-def do_setup() -> int:
- """Do main VCS-independent setup function for installing Versioneer."""
- root = get_root()
- try:
- cfg = get_config_from_root(root)
- except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e:
- if isinstance(e, (OSError, configparser.NoSectionError)):
- print("Adding sample versioneer config to setup.cfg", file=sys.stderr)
- with open(os.path.join(root, "setup.cfg"), "a") as f:
- f.write(SAMPLE_CONFIG)
- print(CONFIG_ERROR, file=sys.stderr)
- return 1
-
- print(" creating %s" % cfg.versionfile_source)
- with open(cfg.versionfile_source, "w") as f:
- LONG = LONG_VERSION_PY[cfg.VCS]
- f.write(
- LONG
- % {
- "DOLLAR": "$",
- "STYLE": cfg.style,
- "TAG_PREFIX": cfg.tag_prefix,
- "PARENTDIR_PREFIX": cfg.parentdir_prefix,
- "VERSIONFILE_SOURCE": cfg.versionfile_source,
- }
- )
-
- ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py")
- maybe_ipy: Optional[str] = ipy
- if os.path.exists(ipy):
- try:
- with open(ipy, "r") as f:
- old = f.read()
- except OSError:
- old = ""
- module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0]
- snippet = INIT_PY_SNIPPET.format(module)
- if OLD_SNIPPET in old:
- print(" replacing boilerplate in %s" % ipy)
- with open(ipy, "w") as f:
- f.write(old.replace(OLD_SNIPPET, snippet))
- elif snippet not in old:
- print(" appending to %s" % ipy)
- with open(ipy, "a") as f:
- f.write(snippet)
- else:
- print(" %s unmodified" % ipy)
- else:
- print(" %s doesn't exist, ok" % ipy)
- maybe_ipy = None
-
- # Make VCS-specific changes. For git, this means creating/changing
- # .gitattributes to mark _version.py for export-subst keyword
- # substitution.
- do_vcs_install(cfg.versionfile_source, maybe_ipy)
- return 0
-
-
-def scan_setup_py() -> int:
- """Validate the contents of setup.py against Versioneer's expectations."""
- found = set()
- setters = False
- errors = 0
- with open("setup.py", "r") as f:
- for line in f.readlines():
- if "import versioneer" in line:
- found.add("import")
- if "versioneer.get_cmdclass()" in line:
- found.add("cmdclass")
- if "versioneer.get_version()" in line:
- found.add("get_version")
- if "versioneer.VCS" in line:
- setters = True
- if "versioneer.versionfile_source" in line:
- setters = True
- if len(found) != 3:
- print("")
- print("Your setup.py appears to be missing some important items")
- print("(but I might be wrong). Please make sure it has something")
- print("roughly like the following:")
- print("")
- print(" import versioneer")
- print(" setup( version=versioneer.get_version(),")
- print(" cmdclass=versioneer.get_cmdclass(), ...)")
- print("")
- errors += 1
- if setters:
- print("You should remove lines like 'versioneer.VCS = ' and")
- print("'versioneer.versionfile_source = ' . This configuration")
- print("now lives in setup.cfg, and should be removed from setup.py")
- print("")
- errors += 1
- return errors
-
-
-def setup_command() -> NoReturn:
- """Set up Versioneer and exit with appropriate error code."""
- errors = do_setup()
- errors += scan_setup_py()
- sys.exit(1 if errors else 0)
-
-
-if __name__ == "__main__":
- cmd = sys.argv[1]
- if cmd == "setup":
- setup_command()
diff --git a/recipes/conda/bld.bat b/recipes/conda/bld.bat
index 51e0c63..b4cd01b 100644
--- a/recipes/conda/bld.bat
+++ b/recipes/conda/bld.bat
@@ -9,7 +9,6 @@ cmake -G "Ninja" ^
-DCMAKE_BUILD_TYPE=Release ^
-DCMAKE_INSTALL_PREFIX="%LIBRARY_PREFIX%" ^
-DCMAKE_PREFIX_PATH="%LIBRARY_PREFIX%" ^
- -DDRF_DATA_PREFIX_PYTHON="%LIBRARY_PREFIX%" ^
-DPython_FIND_REGISTRY=NEVER ^
-DPython_ROOT_DIR="%PREFIX%" ^
..
diff --git a/recipes/conda/build.sh b/recipes/conda/build.sh
index 3dac1ef..2dcb7f5 100644
--- a/recipes/conda/build.sh
+++ b/recipes/conda/build.sh
@@ -7,7 +7,6 @@ cmake_config_args=(
-DCMAKE_BUILD_TYPE=Release
-DCMAKE_INSTALL_PREFIX=$PREFIX
-DCMAKE_INSTALL_LIBDIR=lib
- -DDRF_INSTALL_PREFIX_PYTHON=$PREFIX
-DPython_EXECUTABLE=$PYTHON
)
diff --git a/recipes/conda/meta.yaml b/recipes/conda/meta.yaml
index 6342e9d..3be51f8 100644
--- a/recipes/conda/meta.yaml
+++ b/recipes/conda/meta.yaml
@@ -24,27 +24,30 @@ requirements:
build:
- {{ compiler('c') }}
- {{ stdlib('c') }}
- - cmake >=3.15
+ - cmake >=3.20
- ninja
# cross-compilation dependencies
- python # [build_platform != target_platform]
- cross-python_{{ target_platform }} # [build_platform != target_platform]
+ - python-build # [build_platform != target_platform]
- numpy # [build_platform != target_platform]
+ - numpy >=2.0 # [build_platform != target_platform]
host:
- hdf5
- mako
- numpy
- - pkgconfig
+ - numpy >=2.0
- python
- - setuptools
+ - python-build
+ - scikit-build-core
+ - setuptools-scm
run:
- h5py
- packaging
- python
- python-dateutil
- - pytz
- six
- watchdog