diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index b75d57e67..86e085ff5 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -8,11 +8,6 @@ FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} ARG NODE_VERSION="none" RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi -# [Optional] If your pip requirements rarely change, uncomment this section to add them to the image. -# COPY requirements.txt /tmp/pip-tmp/ -# RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \ -# && rm -rf /tmp/pip-tmp - # [Optional] Uncomment this section to install additional OS packages. RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ && apt-get -y install --no-install-recommends pandoc diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 08df8e873..8d7ed4977 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -37,7 +37,7 @@ // Use 'forwardPorts' to make a list of ports inside the container available locally. // "forwardPorts": [], // Use 'postCreateCommand' to run commands after the container is created. - // "postCreateCommand": "pip3 install --user -r requirements.txt", + "postCreateCommand": "pip3 install --user .[dev]", // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. "remoteUser": "vscode" } \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2373a3657..0f03a947a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,9 +16,9 @@ jobs: python-version: ["3.10"] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v3 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: "pip" @@ -30,6 +30,8 @@ jobs: pip install virtualenv pip install wheel pip install pex + pip install pip-tools + pip-compile -o requirements.txt - name: Repack confluent-kafka wheel run: | @@ -59,9 +61,9 @@ jobs: python-version: ["3.10", "3.11", "3.12"] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v3 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: "pip" @@ -69,7 +71,7 @@ jobs: - name: Install dependencies run: | pip install --upgrade pip wheel - pip install -r requirements_dev.txt + pip install .[dev] - name: Perform unit tests env: @@ -91,10 +93,10 @@ jobs: python-version: ["3.10"] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v3 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: "pip" @@ -103,8 +105,7 @@ jobs: run: | sudo apt-get update && sudo apt-get -y install pandoc pip install --upgrade pip wheel - pip install -r requirements_dev.txt - pip install -r doc/requirements.txt + pip install .[doc] - name: build docs run: | @@ -124,9 +125,9 @@ jobs: with: fetch-depth: 0 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v3 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: "pip" @@ -141,7 +142,7 @@ jobs: - name: Install dependencies run: | pip install --upgrade pip wheel - pip install -r requirements_dev.txt + pip install .[dev] - name: check black formating run: | diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 799239ba3..60cacdcc1 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -14,9 +14,9 @@ jobs: python-version: ["3.10"] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v3 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: "pip" @@ -28,6 +28,8 @@ jobs: pip install virtualenv pip install wheel pip install pex + pip install pip-tools + pip-compile -o requirements.txt - name: Repack confluent-kafka wheel run: | @@ -57,9 +59,9 @@ jobs: python-version: ["3.10", "3.11", "3.12"] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v3 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: "pip" @@ -67,7 +69,7 @@ jobs: - name: Install dependencies run: | pip install --upgrade pip wheel - pip install -r requirements_dev.txt + pip install .[dev] - name: Perform unit tests env: @@ -93,9 +95,9 @@ jobs: with: fetch-depth: 0 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Python - uses: actions/setup-python@v3 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: "pip" @@ -111,7 +113,7 @@ jobs: run: | sudo apt-get update && sudo apt-get -y install libhyperscan-dev librdkafka-dev pip install --upgrade pip wheel - pip install -r requirements_dev.txt + pip install .[dev] - name: check black formating run: | diff --git a/.github/workflows/publish-latest-dev-release-to-pypi.yml b/.github/workflows/publish-latest-dev-release-to-pypi.yml index 260a9f33f..6556dc33a 100644 --- a/.github/workflows/publish-latest-dev-release-to-pypi.yml +++ b/.github/workflows/publish-latest-dev-release-to-pypi.yml @@ -24,7 +24,7 @@ jobs: pip install --upgrade pip wheel - name: Build binary wheel and a source tarball - run: python setup.py sdist bdist_wheel + run: pip wheel --no-deps --wheel-dir ./dist . - uses: marvinpinto/action-automatic-releases@latest with: diff --git a/.github/workflows/publish-release-to-pypi.yml b/.github/workflows/publish-release-to-pypi.yml index 83b6ac326..869cbf409 100644 --- a/.github/workflows/publish-release-to-pypi.yml +++ b/.github/workflows/publish-release-to-pypi.yml @@ -21,7 +21,7 @@ jobs: python -m pip install --upgrade pip wheel - name: Build binary wheel and a source tarball - run: python setup.py sdist bdist_wheel + run: pip wheel --no-deps --wheel-dir ./dist . - name: Upload Artifact for next job uses: actions/upload-artifact@master diff --git a/.readthedocs.yaml b/.readthedocs.yaml index b9163f614..f5cd06cc5 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -29,5 +29,7 @@ sphinx: # Optionally declare the Python requirements required to build your docs python: install: - - requirements: requirements_dev.txt - - requirements: doc/requirements.txt + - method: pip + path: . + extra_requirements: + - doc diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a6f02bb4..e280b1c7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ ### Improvements +* refactor logprep build process and requirements management + ### Bugfix ## v10.0.3 diff --git a/Dockerfile b/Dockerfile index 46b6c22fe..7356b427d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,7 +13,7 @@ RUN python -m venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" RUN python -m pip install --upgrade pip wheel setuptools -RUN if [ "$LOGPREP_VERSION" = "dev" ]; then python setup.py sdist bdist_wheel && pip install ./dist/logprep-*.whl;\ +RUN if [ "$LOGPREP_VERSION" = "dev" ]; then pip install .;\ elif [ "$LOGPREP_VERSION" = "latest" ]; then pip install git+https://github.com/fkie-cad/Logprep.git@latest; \ else pip install "logprep==$LOGPREP_VERSION"; fi diff --git a/Makefile b/Makefile index 7286ff33a..09b60b1ea 100644 --- a/Makefile +++ b/Makefile @@ -1,17 +1,7 @@ -# Build requirements(_dev).txt with pinned package versions from requirements(_dev).in -build-requirements: - pip-compile requirements.in - pip-compile requirements_dev.in - -# Upgrade pinning in requirements(_dev).txt to newest available versions -upgrade-requirements: - pip-compile --upgrade requirements.in - pip-compile --upgrade requirements_dev.in - -# Uninstall all packaged that are not present in requirements.txt and install what is in requirements.txt +# Install all packages install-packages: - pip-sync + pip install -e .[dev] # Test all pytests test: - pytest ./tests --cov=logprep --cov-report=xml -vvv \ No newline at end of file + pytest ./tests --cov=logprep --cov-report=xml -vvv diff --git a/README.md b/README.md index f3119debd..6ae353be5 100644 --- a/README.md +++ b/README.md @@ -255,7 +255,7 @@ contribute to them. ``` git clone https://github.com/fkie-cad/Logprep.git cd Logprep -pip install -r requirements.txt +pip install . ``` **3. Option:** Installation via Github Release @@ -316,11 +316,7 @@ Where `$CONFIG` is the path or uri to a configuration file (see the documentatio ### Reload the Configuration -To change the configuration of Logprep it is not needed to restart Logprep entirely. -Instead, it can be issued to reload the configuration. -For this, the signal `SIGUSR1` must be send to the Logprep process. - -Additionally, a `config_refresh_interval` can be set to periodically and automatically refresh the given configuration. +A `config_refresh_interval` can be set to periodically and automatically refresh the given configuration. This can be useful in case of containerized environments (such as Kubernetes), when pod volumes often change on the fly. @@ -540,8 +536,8 @@ be built locally via: ``` sudo apt install pandoc +pip install -e .[doc] cd ./doc/ -pip install -r ./requirements.txt make html ``` diff --git a/create_pex.yml b/create_pex.yml index f614f7fcc..e1b2a7ae1 100644 --- a/create_pex.yml +++ b/create_pex.yml @@ -25,7 +25,7 @@ - name: Upgrade pip and wheel shell: "{{ python_interpreter_location }} -m pip install pip --upgrade && - {{ python_interpreter_location }} -m pip install wheel --upgrade" + {{ python_interpreter_location }} -m pip install wheel --upgrade && pip install pip-tools && pip-compile -o requirements.txt" - name: Repack confluent-kafka wheel shell: "cd {{ project_location }} && diff --git a/doc/README.md b/doc/README.md index dd8d62f92..d8a87b515 100644 --- a/doc/README.md +++ b/doc/README.md @@ -1,4 +1,4 @@ ## needed setup to generate documentation * install pandoc with `apt-get install pandoc` -* install requirements with `pip install -r requirements.txt` +* install requirements with `pip install .[doc]` in project root diff --git a/doc/requirements.txt b/doc/requirements.txt deleted file mode 100644 index 23c08efbf..000000000 --- a/doc/requirements.txt +++ /dev/null @@ -1,6 +0,0 @@ -sphinx -sphinx_rtd_theme -sphinxcontrib.datatemplates -sphinx-copybutton -nbsphinx -ipython diff --git a/doc/source/development/index.rst b/doc/source/development/index.rst index 887811aac..f26d17cf9 100644 --- a/doc/source/development/index.rst +++ b/doc/source/development/index.rst @@ -9,6 +9,5 @@ Development connector_how_to processor_how_to register_a_new_component - requirements testing coding_examples diff --git a/doc/source/development/requirements.rst b/doc/source/development/requirements.rst deleted file mode 100644 index 6daf36a05..000000000 --- a/doc/source/development/requirements.rst +++ /dev/null @@ -1,36 +0,0 @@ -Python Packages -=============== - -The used Python packages in requirements.txt and requirements_dev.txt should be always in a state that ensures a functioning installation of Logprep. -To achieve this, package versions are being pinned for a tested state. - -Pinning of Python Packages --------------------------- - -:code:`pip-tools` is used for the pinning process. -It should be installed in a virtual Python environment. - -The Python packages that are being used are defined in requirements.in and requirements_dev.in. -Only packages that must be necessarily pinned should be pinned within those files. -By using :code:`pip-compile` of :code:`pip-tools` the .in files can be used to generate the requirements.txt and the requirements_dev.txt. -All packages in those generated files will be pinned. - -Versions Upgrade of Python Packages ------------------------------------ - -Pinned package versions in requirements(_dev).txt can be updated via :code:`pip-compile --upgrade`. -After updating the packages :code:`pip-sync` should be executed. -It removes all unused packages from the current virtual Python environment and then installs the requirements. -pip-tools itself should be installed in the virtual environment and not globally. -The updated requirements can be committed if all tests were successful. - -Helper Scripts --------------- - -A Makefile simplifies this process. -:code:`make` must be present on the system. -It might have to be installed (i.e. via :code:`build-essential`). -requirements(_dev).txt can be build with :code:`make build-requirements`. -:code:`make upgrade-requirements` updates requirements(_dev).txt. -Executing :code:`make install-packages` runs pip-sync. -:code:`make test` creates a new virtual test environment, installs all requirements and runs all tests. diff --git a/doc/source/getting_started.rst b/doc/source/getting_started.rst index cd1629aea..aac0c474d 100644 --- a/doc/source/getting_started.rst +++ b/doc/source/getting_started.rst @@ -27,10 +27,10 @@ contribute to them. git clone https://github.com/fkie-cad/Logprep.git cd Logprep - pip install -r requirements.txt + pip install . To see if the installation was successful run -:code:`PYTHONPATH="." python3 logprep/run_logprep.py --version`. +:code:`logprep --version`. **3. Option:** Installation via Github Release @@ -49,7 +49,6 @@ This option can be used to build a container image from a specific commit .. code-block:: bash git clone https://github.com/fkie-cad/Logprep.git - cd Logprep docker build -t logprep . To see if the installation was successful run :code:`docker run logprep --version`. @@ -64,12 +63,6 @@ If you have installed it via PyPI or the Github Development release just run: logprep run $CONFIG -If you have installed Logprep via cloning the repository then you should run it via: - -.. code-block:: bash - - PYTHONPATH="." python3 logprep/run_logprep.py run $CONFIG - Where :code:`$CONFIG` is the path to a configuration file. For more information see the :ref:`configuration` section. diff --git a/logprep/abc/component.py b/logprep/abc/component.py index 884d7cfb7..36ea747b8 100644 --- a/logprep/abc/component.py +++ b/logprep/abc/component.py @@ -1,4 +1,5 @@ """ abstract module for components""" + from abc import ABC from functools import cached_property from logging import Logger diff --git a/logprep/abc/connector.py b/logprep/abc/connector.py index cc7617f2a..98101b35d 100644 --- a/logprep/abc/connector.py +++ b/logprep/abc/connector.py @@ -1,4 +1,5 @@ """ abstract module for connectors""" + from attrs import define, field from logprep.abc.component import Component diff --git a/logprep/abc/getter.py b/logprep/abc/getter.py index 5bb633454..64c84051d 100644 --- a/logprep/abc/getter.py +++ b/logprep/abc/getter.py @@ -1,4 +1,5 @@ """Module for getter interface""" + import json import os import re diff --git a/logprep/abc/processor.py b/logprep/abc/processor.py index b3e1a8a79..c1cddfa1f 100644 --- a/logprep/abc/processor.py +++ b/logprep/abc/processor.py @@ -1,4 +1,5 @@ """Abstract module for processors""" + from abc import abstractmethod from logging import DEBUG, Logger from pathlib import Path @@ -197,8 +198,7 @@ def _apply_rules_wrapper(self, event: dict, rule: "Rule"): pop_dotted_field_value(event, dotted_field) @abstractmethod - def _apply_rules(self, event, rule): - ... # pragma: no cover + def _apply_rules(self, event, rule): ... # pragma: no cover def test_rules(self) -> dict: """Perform custom rule tests. diff --git a/logprep/connector/console/output.py b/logprep/connector/console/output.py index 65acb27c6..fe824ae06 100644 --- a/logprep/connector/console/output.py +++ b/logprep/connector/console/output.py @@ -14,6 +14,7 @@ my_console_output: type: console_output """ + import sys from pprint import pprint diff --git a/logprep/connector/dummy/input.py b/logprep/connector/dummy/input.py index 76e945c25..292b351b2 100644 --- a/logprep/connector/dummy/input.py +++ b/logprep/connector/dummy/input.py @@ -18,6 +18,7 @@ type: dummy_input documents: [{"document":"one"}, "Exception", {"document":"two"}] """ + import copy from functools import cached_property from typing import List, Optional, Union diff --git a/logprep/connector/dummy/output.py b/logprep/connector/dummy/output.py index 4711c4a75..171a892fe 100644 --- a/logprep/connector/dummy/output.py +++ b/logprep/connector/dummy/output.py @@ -16,6 +16,7 @@ my_dummy_output: type: dummy_output """ + from logging import Logger from typing import TYPE_CHECKING, List diff --git a/logprep/connector/file/input.py b/logprep/connector/file/input.py index 99de5c83c..a1ad41232 100644 --- a/logprep/connector/file/input.py +++ b/logprep/connector/file/input.py @@ -19,6 +19,7 @@ interval: 1 watch_file: True """ + import queue import threading import zlib diff --git a/logprep/connector/http/input.py b/logprep/connector/http/input.py index 795b486d9..129f64739 100644 --- a/logprep/connector/http/input.py +++ b/logprep/connector/http/input.py @@ -21,6 +21,7 @@ /seccondendpoint: plaintext /thirdendpoint: jsonl """ + import contextlib import inspect import queue diff --git a/logprep/connector/json/input.py b/logprep/connector/json/input.py index adb6ae975..7269bd042 100644 --- a/logprep/connector/json/input.py +++ b/logprep/connector/json/input.py @@ -19,6 +19,7 @@ documents_path: path/to/a/document.json repeat_documents: true """ + import copy from functools import cached_property from typing import Optional diff --git a/logprep/connector/jsonl/input.py b/logprep/connector/jsonl/input.py index 4351548fe..426fd23dc 100644 --- a/logprep/connector/jsonl/input.py +++ b/logprep/connector/jsonl/input.py @@ -19,6 +19,7 @@ documents_path: path/to/a/document.jsonl repeat_documents: true """ + import copy from functools import cached_property diff --git a/logprep/connector/s3/output.py b/logprep/connector/s3/output.py index 2440baf4a..adb3b3edc 100644 --- a/logprep/connector/s3/output.py +++ b/logprep/connector/s3/output.py @@ -37,6 +37,7 @@ region_name: """ + import json import re from collections import defaultdict diff --git a/logprep/event_generator/http/controller.py b/logprep/event_generator/http/controller.py index 9d1974e72..6ad528e18 100644 --- a/logprep/event_generator/http/controller.py +++ b/logprep/event_generator/http/controller.py @@ -2,6 +2,7 @@ This generator will parse example events, manipulate their timestamps and send them to a defined output """ + import json import logging import time diff --git a/logprep/event_generator/http/input.py b/logprep/event_generator/http/input.py index cc6933508..a27552d98 100644 --- a/logprep/event_generator/http/input.py +++ b/logprep/event_generator/http/input.py @@ -1,4 +1,5 @@ """Input module that loads the jsonl files batch-wise""" + import itertools import logging import os diff --git a/logprep/event_generator/http/manipulator.py b/logprep/event_generator/http/manipulator.py index 425bfc66e..78b9c8734 100644 --- a/logprep/event_generator/http/manipulator.py +++ b/logprep/event_generator/http/manipulator.py @@ -2,6 +2,7 @@ Manipulator Module that takes a batch of input events, processes them and returns the updated versions. """ + import datetime import logging from datetime import datetime diff --git a/logprep/event_generator/http/output.py b/logprep/event_generator/http/output.py index 8edf3b1b4..b83f0630d 100644 --- a/logprep/event_generator/http/output.py +++ b/logprep/event_generator/http/output.py @@ -1,6 +1,7 @@ """ Output Module that takes a batch of events and sends them to a http endpoint with given credentials """ + import logging import time from functools import cached_property diff --git a/logprep/event_generator/http/reporter.py b/logprep/event_generator/http/reporter.py index 54bdeef9f..d5b696e48 100644 --- a/logprep/event_generator/http/reporter.py +++ b/logprep/event_generator/http/reporter.py @@ -1,4 +1,5 @@ """This module tracks statistics and creates a final report for the generator""" + import datetime import logging import os diff --git a/logprep/event_generator/kafka/configuration.py b/logprep/event_generator/kafka/configuration.py index 43e713f48..ed353f152 100644 --- a/logprep/event_generator/kafka/configuration.py +++ b/logprep/event_generator/kafka/configuration.py @@ -1,4 +1,5 @@ """ Contains configuration class with configuration validation """ + # pylint: disable=too-few-public-methods import sys from pathlib import Path diff --git a/logprep/event_generator/kafka/document_loader.py b/logprep/event_generator/kafka/document_loader.py index 05bbb9e0b..bd717ec89 100644 --- a/logprep/event_generator/kafka/document_loader.py +++ b/logprep/event_generator/kafka/document_loader.py @@ -1,4 +1,5 @@ """For loading documents from Kafka or from file and preparing them for sending""" + import json from datetime import datetime from logging import Logger diff --git a/logprep/event_generator/kafka/document_sender.py b/logprep/event_generator/kafka/document_sender.py index be35d9a25..d9c6272a9 100644 --- a/logprep/event_generator/kafka/document_sender.py +++ b/logprep/event_generator/kafka/document_sender.py @@ -1,4 +1,5 @@ """For repeatedly sending documents to Kafka""" + import itertools from logging import Logger from time import perf_counter diff --git a/logprep/event_generator/kafka/kafka_connector.py b/logprep/event_generator/kafka/kafka_connector.py index f2e2f93a8..ae125c514 100644 --- a/logprep/event_generator/kafka/kafka_connector.py +++ b/logprep/event_generator/kafka/kafka_connector.py @@ -1,4 +1,5 @@ """For retrieval and insertion of data from and into Kafka.""" + import json from typing import Optional diff --git a/logprep/event_generator/kafka/process_runner.py b/logprep/event_generator/kafka/process_runner.py index 0c7f1cc98..5db71f654 100644 --- a/logprep/event_generator/kafka/process_runner.py +++ b/logprep/event_generator/kafka/process_runner.py @@ -1,4 +1,5 @@ """Main module for the load-tester""" + import cProfile import pstats from logging import Logger diff --git a/logprep/event_generator/kafka/run_load_tester.py b/logprep/event_generator/kafka/run_load_tester.py index 64580f5be..98818f4d6 100644 --- a/logprep/event_generator/kafka/run_load_tester.py +++ b/logprep/event_generator/kafka/run_load_tester.py @@ -1,4 +1,5 @@ """Main module for the load-tester""" + from multiprocessing import Manager from pathlib import Path diff --git a/logprep/event_generator/kafka/util.py b/logprep/event_generator/kafka/util.py index 3497351f8..3b8ad9651 100644 --- a/logprep/event_generator/kafka/util.py +++ b/logprep/event_generator/kafka/util.py @@ -1,4 +1,5 @@ """Contains utility functions""" + from logging import Logger from pathlib import Path diff --git a/logprep/factory.py b/logprep/factory.py index 9ed6c5969..270233882 100644 --- a/logprep/factory.py +++ b/logprep/factory.py @@ -1,4 +1,5 @@ """This module contains a factory to create connectors and processors.""" + import copy import logging from typing import TYPE_CHECKING diff --git a/logprep/framework/pipeline.py b/logprep/framework/pipeline.py index f80b0d282..0d9090cc5 100644 --- a/logprep/framework/pipeline.py +++ b/logprep/framework/pipeline.py @@ -4,6 +4,7 @@ They can be multi-processed. """ + import copy import logging import logging.handlers diff --git a/logprep/framework/pipeline_manager.py b/logprep/framework/pipeline_manager.py index e4ffb9c67..4132288bc 100644 --- a/logprep/framework/pipeline_manager.py +++ b/logprep/framework/pipeline_manager.py @@ -1,4 +1,5 @@ """This module contains functionality to manage pipelines via multi-processing.""" + # pylint: disable=logging-fstring-interpolation import logging diff --git a/logprep/framework/rule_tree/rule_tagger.py b/logprep/framework/rule_tree/rule_tagger.py index c71ec959e..f71722b7a 100644 --- a/logprep/framework/rule_tree/rule_tagger.py +++ b/logprep/framework/rule_tree/rule_tagger.py @@ -1,4 +1,5 @@ """ This module implements functionality to add tags to filter expressions. """ + from typing import Union, List from logprep.filter.expression.filter_expression import ( diff --git a/logprep/processor/amides/features.py b/logprep/processor/amides/features.py index 47fbb4eca..a39d0fdcf 100644 --- a/logprep/processor/amides/features.py +++ b/logprep/processor/amides/features.py @@ -2,6 +2,7 @@ and token filtering callables to split (raw) documents into a list of token words. """ + import re from abc import ABC, abstractmethod diff --git a/logprep/processor/amides/normalize.py b/logprep/processor/amides/normalize.py index be7a3c378..793b564d4 100644 --- a/logprep/processor/amides/normalize.py +++ b/logprep/processor/amides/normalize.py @@ -1,4 +1,5 @@ """This module enables command line normalization of incoming command lines.""" + from typing import List from logprep.processor.amides.features import ( diff --git a/logprep/processor/amides/processor.py b/logprep/processor/amides/processor.py index d5f4fd480..671347f67 100644 --- a/logprep/processor/amides/processor.py +++ b/logprep/processor/amides/processor.py @@ -83,6 +83,7 @@ .. automodule:: logprep.processor.amides.rule """ + from functools import cached_property, lru_cache from multiprocessing import current_process from pathlib import Path diff --git a/logprep/processor/amides/rule.py b/logprep/processor/amides/rule.py index 804d88d80..486081bf6 100644 --- a/logprep/processor/amides/rule.py +++ b/logprep/processor/amides/rule.py @@ -26,6 +26,7 @@ :inherited-members: :no-undoc-members: """ + from attrs import define, field, validators from ruamel.yaml import YAML diff --git a/logprep/processor/calculator/processor.py b/logprep/processor/calculator/processor.py index 40f57d54e..6c34d6f58 100644 --- a/logprep/processor/calculator/processor.py +++ b/logprep/processor/calculator/processor.py @@ -24,6 +24,7 @@ .. automodule:: logprep.processor.calculator.rule """ + import re from functools import cached_property diff --git a/logprep/processor/calculator/rule.py b/logprep/processor/calculator/rule.py index bb27c5870..c81d0ef40 100644 --- a/logprep/processor/calculator/rule.py +++ b/logprep/processor/calculator/rule.py @@ -86,6 +86,7 @@ The calc expression is not whitespace sensitive. """ + import re from attrs import define, field, validators diff --git a/logprep/processor/concatenator/processor.py b/logprep/processor/concatenator/processor.py index ca0ed4f7a..3e91b0b05 100644 --- a/logprep/processor/concatenator/processor.py +++ b/logprep/processor/concatenator/processor.py @@ -26,6 +26,7 @@ .. automodule:: logprep.processor.concatenator.rule """ + from logprep.processor.concatenator.rule import ConcatenatorRule from logprep.processor.field_manager.processor import FieldManager from logprep.util.helper import get_dotted_field_value diff --git a/logprep/processor/datetime_extractor/rule.py b/logprep/processor/datetime_extractor/rule.py index f52ad6a34..d24002069 100644 --- a/logprep/processor/datetime_extractor/rule.py +++ b/logprep/processor/datetime_extractor/rule.py @@ -27,6 +27,7 @@ :inherited-members: :noindex: """ + from attr import define, field, validators from logprep.processor.field_manager.rule import FieldManagerRule diff --git a/logprep/processor/dissector/processor.py b/logprep/processor/dissector/processor.py index 9fcfb67c0..8d1444e5e 100644 --- a/logprep/processor/dissector/processor.py +++ b/logprep/processor/dissector/processor.py @@ -27,6 +27,7 @@ .. automodule:: logprep.processor.dissector.rule """ + from typing import Callable, List, Tuple from logprep.processor.dissector.rule import DissectorRule diff --git a/logprep/processor/dissector/rule.py b/logprep/processor/dissector/rule.py index 38dfda9f0..943a5e925 100644 --- a/logprep/processor/dissector/rule.py +++ b/logprep/processor/dissector/rule.py @@ -88,6 +88,7 @@ :template: testcase-renderer.tmpl """ + import re from typing import Callable, List, Tuple diff --git a/logprep/processor/domain_label_extractor/processor.py b/logprep/processor/domain_label_extractor/processor.py index db69ec1ef..6c52ff96a 100644 --- a/logprep/processor/domain_label_extractor/processor.py +++ b/logprep/processor/domain_label_extractor/processor.py @@ -33,6 +33,7 @@ .. automodule:: logprep.processor.domain_label_extractor.rule """ + import ipaddress import os import tempfile diff --git a/logprep/processor/domain_label_extractor/rule.py b/logprep/processor/domain_label_extractor/rule.py index b9f311284..4d3acf751 100644 --- a/logprep/processor/domain_label_extractor/rule.py +++ b/logprep/processor/domain_label_extractor/rule.py @@ -55,6 +55,7 @@ :inherited-members: :noindex: """ + from attr import define, field, validators from logprep.processor.field_manager.rule import FieldManagerRule diff --git a/logprep/processor/domain_resolver/processor.py b/logprep/processor/domain_resolver/processor.py index 7151f9484..485a3b994 100644 --- a/logprep/processor/domain_resolver/processor.py +++ b/logprep/processor/domain_resolver/processor.py @@ -32,6 +32,7 @@ .. automodule:: logprep.processor.domain_resolver.rule """ + import datetime import os import socket diff --git a/logprep/processor/domain_resolver/rule.py b/logprep/processor/domain_resolver/rule.py index 8daaf7ab9..909ed08a5 100644 --- a/logprep/processor/domain_resolver/rule.py +++ b/logprep/processor/domain_resolver/rule.py @@ -27,6 +27,7 @@ :inherited-members: :noindex: """ + from attrs import define, field, fields from logprep.processor.field_manager.rule import FieldManagerRule diff --git a/logprep/processor/field_manager/processor.py b/logprep/processor/field_manager/processor.py index 0bdcd441a..5fed2e52d 100644 --- a/logprep/processor/field_manager/processor.py +++ b/logprep/processor/field_manager/processor.py @@ -28,6 +28,7 @@ .. automodule:: logprep.processor.field_manager.rule """ + import itertools from typing import Any, List, Tuple diff --git a/logprep/processor/field_manager/rule.py b/logprep/processor/field_manager/rule.py index 9f68deee4..8cef9ec97 100644 --- a/logprep/processor/field_manager/rule.py +++ b/logprep/processor/field_manager/rule.py @@ -75,6 +75,7 @@ :template: testcase-renderer.tmpl """ + from attrs import define, field, validators from logprep.processor.base.rule import Rule diff --git a/logprep/processor/generic_adder/processor.py b/logprep/processor/generic_adder/processor.py index 2eff5abe1..a66034bd9 100644 --- a/logprep/processor/generic_adder/processor.py +++ b/logprep/processor/generic_adder/processor.py @@ -34,6 +34,7 @@ .. automodule:: logprep.processor.generic_adder.rule """ + import json import os import re diff --git a/logprep/processor/generic_resolver/processor.py b/logprep/processor/generic_resolver/processor.py index 02b872ff1..c1cd32dd0 100644 --- a/logprep/processor/generic_resolver/processor.py +++ b/logprep/processor/generic_resolver/processor.py @@ -24,6 +24,7 @@ .. automodule:: logprep.processor.generic_resolver.rule """ + import re from logging import Logger diff --git a/logprep/processor/generic_resolver/rule.py b/logprep/processor/generic_resolver/rule.py index 3110e3d0f..88ae3ee42 100644 --- a/logprep/processor/generic_resolver/rule.py +++ b/logprep/processor/generic_resolver/rule.py @@ -71,6 +71,7 @@ :inherited-members: :noindex: """ + from attrs import define, field, validators from logprep.processor.base.rule import Rule diff --git a/logprep/processor/geoip_enricher/processor.py b/logprep/processor/geoip_enricher/processor.py index e293fb550..b18639fae 100644 --- a/logprep/processor/geoip_enricher/processor.py +++ b/logprep/processor/geoip_enricher/processor.py @@ -25,6 +25,7 @@ .. automodule:: logprep.processor.geoip_enricher.rule """ + import os import tempfile from functools import cached_property diff --git a/logprep/processor/geoip_enricher/rule.py b/logprep/processor/geoip_enricher/rule.py index 475b8e75d..e94dcb3f7 100644 --- a/logprep/processor/geoip_enricher/rule.py +++ b/logprep/processor/geoip_enricher/rule.py @@ -25,6 +25,7 @@ :inherited-members: :noindex: """ + from attr import Factory from attrs import define, field, validators diff --git a/logprep/processor/grokker/processor.py b/logprep/processor/grokker/processor.py index 6e48a49ed..c910dedae 100644 --- a/logprep/processor/grokker/processor.py +++ b/logprep/processor/grokker/processor.py @@ -30,6 +30,7 @@ .. automodule:: logprep.processor.grokker.rule """ + import re from pathlib import Path from zipfile import ZipFile diff --git a/logprep/processor/hyperscan_resolver/rule.py b/logprep/processor/hyperscan_resolver/rule.py index 797cace7f..d38ab77f5 100644 --- a/logprep/processor/hyperscan_resolver/rule.py +++ b/logprep/processor/hyperscan_resolver/rule.py @@ -18,6 +18,7 @@ :inherited-members: :noindex: """ + import re from typing import Tuple diff --git a/logprep/processor/ip_informer/processor.py b/logprep/processor/ip_informer/processor.py index bd3eb347f..1c75bf702 100644 --- a/logprep/processor/ip_informer/processor.py +++ b/logprep/processor/ip_informer/processor.py @@ -24,6 +24,7 @@ .. automodule:: logprep.processor.ip_informer.rule """ + import ipaddress from functools import partial from itertools import chain diff --git a/logprep/processor/ip_informer/rule.py b/logprep/processor/ip_informer/rule.py index ff50dcb3f..ddd194eb6 100644 --- a/logprep/processor/ip_informer/rule.py +++ b/logprep/processor/ip_informer/rule.py @@ -57,6 +57,7 @@ :template: testcase-renderer.tmpl """ + from ipaddress import IPv4Address, IPv6Address from attrs import define, field, validators diff --git a/logprep/processor/labeler/rule.py b/logprep/processor/labeler/rule.py index 03ecfde0f..e3101ab49 100644 --- a/logprep/processor/labeler/rule.py +++ b/logprep/processor/labeler/rule.py @@ -26,6 +26,7 @@ :inherited-members: :noindex: """ + from attrs import define, field, validators from logprep.processor.base.rule import Rule diff --git a/logprep/processor/list_comparison/processor.py b/logprep/processor/list_comparison/processor.py index 53ea2cbea..4a23655fc 100644 --- a/logprep/processor/list_comparison/processor.py +++ b/logprep/processor/list_comparison/processor.py @@ -27,6 +27,7 @@ .. automodule:: logprep.processor.list_comparison.rule """ + from logging import Logger from attr import define, field, validators diff --git a/logprep/processor/list_comparison/rule.py b/logprep/processor/list_comparison/rule.py index 07df95f3e..2d920c877 100644 --- a/logprep/processor/list_comparison/rule.py +++ b/logprep/processor/list_comparison/rule.py @@ -40,6 +40,7 @@ :inherited-members: :noindex: """ + import os.path from string import Template from typing import List, Optional diff --git a/logprep/processor/normalizer/processor.py b/logprep/processor/normalizer/processor.py index 75a761a86..7ed5dc7a6 100644 --- a/logprep/processor/normalizer/processor.py +++ b/logprep/processor/normalizer/processor.py @@ -32,6 +32,7 @@ .. automodule:: logprep.processor.normalizer.rule """ + import calendar import html import json diff --git a/logprep/processor/pre_detector/processor.py b/logprep/processor/pre_detector/processor.py index 35fe80204..458598b69 100644 --- a/logprep/processor/pre_detector/processor.py +++ b/logprep/processor/pre_detector/processor.py @@ -29,6 +29,7 @@ .. automodule:: logprep.processor.pre_detector.rule """ + from functools import cached_property from uuid import uuid4 diff --git a/logprep/processor/pre_detector/rule.py b/logprep/processor/pre_detector/rule.py index ceeacfa47..6072df6ff 100644 --- a/logprep/processor/pre_detector/rule.py +++ b/logprep/processor/pre_detector/rule.py @@ -94,6 +94,7 @@ :inherited-members: :noindex: """ + from functools import cached_property from typing import Optional, Union diff --git a/logprep/processor/pseudonymizer/processor.py b/logprep/processor/pseudonymizer/processor.py index 93f778584..73ce37340 100644 --- a/logprep/processor/pseudonymizer/processor.py +++ b/logprep/processor/pseudonymizer/processor.py @@ -34,6 +34,7 @@ .. automodule:: logprep.processor.pseudonymizer.rule """ + import re from functools import cached_property, lru_cache from itertools import chain diff --git a/logprep/processor/requester/processor.py b/logprep/processor/requester/processor.py index 86a240e20..87320146c 100644 --- a/logprep/processor/requester/processor.py +++ b/logprep/processor/requester/processor.py @@ -25,6 +25,7 @@ .. automodule:: logprep.processor.requester.rule """ + import json import re diff --git a/logprep/processor/requester/rule.py b/logprep/processor/requester/rule.py index a2a68ad3b..c5b86fa3b 100644 --- a/logprep/processor/requester/rule.py +++ b/logprep/processor/requester/rule.py @@ -62,6 +62,7 @@ :inherited-members: :noindex: """ + import inspect import json import re diff --git a/logprep/processor/template_replacer/processor.py b/logprep/processor/template_replacer/processor.py index dcb9126ec..64f073619 100644 --- a/logprep/processor/template_replacer/processor.py +++ b/logprep/processor/template_replacer/processor.py @@ -33,6 +33,7 @@ .. automodule:: logprep.processor.template_replacer.rule """ + from logging import Logger from typing import Optional diff --git a/logprep/processor/timestamp_differ/processor.py b/logprep/processor/timestamp_differ/processor.py index c105fb39a..da92fcc97 100644 --- a/logprep/processor/timestamp_differ/processor.py +++ b/logprep/processor/timestamp_differ/processor.py @@ -24,6 +24,7 @@ .. automodule:: logprep.processor.timestamp_differ.rule """ + from datetime import datetime from functools import reduce from typing import Union diff --git a/logprep/processor/timestamp_differ/rule.py b/logprep/processor/timestamp_differ/rule.py index 738b0f77f..1ac50fd2d 100644 --- a/logprep/processor/timestamp_differ/rule.py +++ b/logprep/processor/timestamp_differ/rule.py @@ -43,6 +43,7 @@ .. datatemplate:import-module:: tests.unit.processor.timestamp_differ.test_timestamp_differ :template: testcase-renderer.tmpl """ + import re from attr import field diff --git a/logprep/processor/timestamper/rule.py b/logprep/processor/timestamper/rule.py index a58b62323..c2eca40d2 100644 --- a/logprep/processor/timestamper/rule.py +++ b/logprep/processor/timestamper/rule.py @@ -56,6 +56,7 @@ :template: testcase-renderer.tmpl """ + from zoneinfo import ZoneInfo from attrs import define, field, validators diff --git a/logprep/util/decorators.py b/logprep/util/decorators.py index 6637df509..56ef81262 100644 --- a/logprep/util/decorators.py +++ b/logprep/util/decorators.py @@ -1,4 +1,5 @@ """Decorators to use with logprep""" + import errno import os from functools import wraps diff --git a/logprep/util/defaults.py b/logprep/util/defaults.py index d0af78353..b2021de91 100644 --- a/logprep/util/defaults.py +++ b/logprep/util/defaults.py @@ -1,2 +1,3 @@ """Default values for logprep.""" + DEFAULT_CONFIG_LOCATION = "file:///etc/logprep/pipeline.yml" diff --git a/logprep/util/grok/grok.py b/logprep/util/grok/grok.py index 87ee283aa..75dd3fd1c 100644 --- a/logprep/util/grok/grok.py +++ b/logprep/util/grok/grok.py @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ + import re import string import sys diff --git a/logprep/util/grok_pattern_loader.py b/logprep/util/grok_pattern_loader.py index 32e45239a..6536edc52 100644 --- a/logprep/util/grok_pattern_loader.py +++ b/logprep/util/grok_pattern_loader.py @@ -97,9 +97,11 @@ def load_from_dir(pattern_dir_path: str) -> dict: @staticmethod def _update_pattern(grok_pattern_dict) -> dict: return { - grok: pattern.replace(non_supported_regex, supported_regex) - if non_supported_regex in pattern - else pattern + grok: ( + pattern.replace(non_supported_regex, supported_regex) + if non_supported_regex in pattern + else pattern + ) for grok, pattern in grok_pattern_dict.items() for non_supported_regex, supported_regex in PATTERN_CONVERSION } diff --git a/logprep/util/json_handling.py b/logprep/util/json_handling.py index 7b755df19..694b006b4 100644 --- a/logprep/util/json_handling.py +++ b/logprep/util/json_handling.py @@ -1,4 +1,5 @@ """ module for json handling helper methods""" + import json import os from typing import List diff --git a/logprep/util/validators.py b/logprep/util/validators.py index 586d6bdd3..1dd6f8185 100644 --- a/logprep/util/validators.py +++ b/logprep/util/validators.py @@ -1,4 +1,5 @@ """ validators to use with `attrs` fields""" + import os import typing from urllib.parse import urlparse diff --git a/pyproject.toml b/pyproject.toml index 88b236eff..691e83d28 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,3 +1,121 @@ +[build-system] +requires = ["setuptools>=68.0.0", "setuptools-scm", "wheel"] +build-backend = "setuptools.build_meta" + +[tool.setuptools] +packages = ["logprep"] + +[tool.setuptools.dynamic] +version = { attr = "logprep.__version__" } + +[project] +name = "logprep" +description = "Logprep allows to collect, process and forward log messages from various data sources." +requires-python = ">=3.10" +readme = "README.md" +dynamic = ["version"] +license = { file = "LICENSE" } +classifiers = [ + "Development Status :: 3 - Alpha", + + "Intended Audience :: Developers", + + "License :: LGPL-2.1", + + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", +] +keywords = [ + "elasticsearch", + "kafka", + "etl", + "sre", + "preprocessing", + "opensearch", + "soar", + "logdata", +] +dependencies = [ + "aiohttp>=3.9.2", # CVE-2024-23334 + "attrs", + "certifi>=2023.7.22", # CVE-2023-37920 + "ciso8601", # fastest iso8601 datetime parser. can be removed after dropping support for python < 3.11 + "colorama", + "confluent-kafka>2", + "elasticsearch>=7,<8", + "fastapi>=0.109.1", # CVE-2024-24762 + "geoip2", + "hyperscan>=0.7.0", + "jsonref", + "luqum", + "mysql-connector-python", + "numpy>=1.26.0", + "opensearch-py", + "prometheus_client", + "protobuf>=3.20.2", + "pycryptodome", + "pyparsing", + "pytz", # can be removed with normalizer code + "scikit-learn>=1.2.0", + "scipy>=1.9.2", + "joblib", + "pygrok", + "pyyaml", + "requests>=2.31.0", + "ruamel.yaml", + "schedule", + "tldextract", + "urlextract", + "urllib3>=1.26.17", # CVE-2023-43804 + "uvicorn", + "wheel", + "deepdiff", + "msgspec", + "boto3", + "pydantic", + "ndjson", + "arrow", + "click", + "pandas", + "tabulate", + +] + +[project.optional-dependencies] + +dev = [ + "black", + "httpx", + "isort", + "pylint", + "pytest", + "pytest-cov", + "responses", + "jinja2", +] + +doc = [ + "sphinx", + "sphinx_rtd_theme", + "sphinxcontrib.datatemplates", + "sphinx-copybutton", + "nbsphinx", + "ipython", +] + +[project.urls] +Homepage = "https://github.com/fkie-cad/Logprep" +Documentation = "https://logprep.readthedocs.io/en/latest/" +Repository = "https://github.com/fkie-cad/Logprep" +Issues = "https://github.com/fkie-cad/Logprep/issues" +Changelog = "https://github.com/fkie-cad/Logprep/blob/main/CHANGELOG.md" + +[project.scripts] +logprep = "logprep.run_logprep:cli" + [tool.black] line-length = 100 target-version = ['py310', 'py311', 'py312'] diff --git a/requirements.in b/requirements.in deleted file mode 100644 index 24e9871cf..000000000 --- a/requirements.in +++ /dev/null @@ -1,42 +0,0 @@ -aiohttp>=3.9.2 # CVE-2024-23334 -attrs -certifi>=2023.7.22 # CVE-2023-37920 -ciso8601 # fastest iso8601 datetime parser. can be removed after dropping support for python < 3.11 -colorama -confluent-kafka>2 -elasticsearch>=7,<8 -fastapi>=0.109.1 # CVE-2024-24762 -geoip2 -hyperscan>=0.4.0; sys_platform == 'linux' and platform_machine == 'x86_64' -jsonref -luqum -mysql-connector-python -numpy>=1.26.0 -opensearch-py -prometheus_client -protobuf>=3.20.2 -pycryptodome -pyparsing -pytz # can be removed with normalizer code -scikit-learn>=1.2.0 -scipy>=1.9.2 -joblib -pygrok -pyyaml -requests>=2.31.0 -ruamel.yaml -schedule -tldextract -urlextract -urllib3>=1.26.17 # CVE-2023-43804 -uvicorn -wheel -deepdiff -msgspec -boto3 -pydantic -ndjson -arrow -click -pandas -tabulate diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index efc00c535..000000000 --- a/requirements.txt +++ /dev/null @@ -1,210 +0,0 @@ -# -# This file is autogenerated by pip-compile with Python 3.11 -# by the following command: -# -# pip-compile requirements.in -# -aiohttp==3.9.3 - # via - # -r requirements.in - # geoip2 -aiosignal==1.3.1 - # via aiohttp -annotated-types==0.6.0 - # via pydantic -anyio==4.2.0 - # via starlette -arrow==1.3.0 - # via -r requirements.in -attrs==23.2.0 - # via - # -r requirements.in - # aiohttp -boto3==1.34.27 - # via -r requirements.in -botocore==1.34.27 - # via - # boto3 - # s3transfer -certifi==2023.11.17 - # via - # -r requirements.in - # elasticsearch - # opensearch-py - # requests -charset-normalizer==3.3.2 - # via requests -ciso8601==2.3.1 - # via -r requirements.in -click==8.1.7 - # via - # -r requirements.in - # uvicorn -colorama==0.4.6 - # via -r requirements.in -confluent-kafka==2.3.0 - # via -r requirements.in -deepdiff==6.7.1 - # via -r requirements.in -elasticsearch==7.17.9 - # via -r requirements.in -fastapi==0.109.1 - # via -r requirements.in -filelock==3.13.1 - # via - # tldextract - # urlextract -frozenlist==1.4.1 - # via - # aiohttp - # aiosignal -geoip2==4.8.0 - # via -r requirements.in -h11==0.14.0 - # via uvicorn -hyperscan==0.6.0 ; sys_platform == "linux" and platform_machine == "x86_64" - # via -r requirements.in -idna==3.6 - # via - # anyio - # requests - # tldextract - # urlextract - # yarl -jmespath==1.0.1 - # via - # boto3 - # botocore -joblib==1.3.2 - # via - # -r requirements.in - # scikit-learn -jsonref==1.1.0 - # via -r requirements.in -luqum==0.13.0 - # via -r requirements.in -maxminddb==2.5.2 - # via geoip2 -msgspec==0.18.6 - # via -r requirements.in -multidict==6.0.4 - # via - # aiohttp - # yarl -mysql-connector-python==8.3.0 - # via -r requirements.in -ndjson==0.3.1 - # via -r requirements.in -numpy==1.26.3 - # via - # -r requirements.in - # pandas - # scikit-learn - # scipy -opensearch-py==2.4.2 - # via -r requirements.in -ordered-set==4.1.0 - # via deepdiff -pandas==2.2.0 - # via -r requirements.in -platformdirs==4.1.0 - # via urlextract -ply==3.11 - # via luqum -prometheus-client==0.19.0 - # via -r requirements.in -protobuf==4.25.2 - # via -r requirements.in -pycryptodome==3.20.0 - # via -r requirements.in -pydantic==2.5.3 - # via - # -r requirements.in - # fastapi -pydantic-core==2.14.6 - # via pydantic -pygrok==1.0.0 - # via -r requirements.in -pyparsing==3.1.1 - # via -r requirements.in -python-dateutil==2.8.2 - # via - # arrow - # botocore - # opensearch-py - # pandas -pytz==2023.3.post1 - # via - # -r requirements.in - # pandas -pyyaml==6.0.1 - # via -r requirements.in -regex==2023.12.25 - # via pygrok -requests==2.31.0 - # via - # -r requirements.in - # geoip2 - # opensearch-py - # requests-file - # tldextract -requests-file==1.5.1 - # via tldextract -ruamel-yaml==0.18.5 - # via -r requirements.in -ruamel-yaml-clib==0.2.8 - # via ruamel-yaml -s3transfer==0.10.0 - # via boto3 -schedule==1.2.1 - # via -r requirements.in -scikit-learn==1.4.0 - # via -r requirements.in -scipy==1.12.0 - # via - # -r requirements.in - # scikit-learn -six==1.16.0 - # via - # opensearch-py - # python-dateutil - # requests-file -sniffio==1.3.0 - # via anyio -starlette==0.35.1 - # via fastapi -tabulate==0.9.0 - # via -r requirements.in -threadpoolctl==3.2.0 - # via scikit-learn -tldextract==5.1.1 - # via -r requirements.in -types-python-dateutil==2.8.19.20240106 - # via arrow -typing-extensions==4.9.0 - # via - # fastapi - # pydantic - # pydantic-core -tzdata==2023.4 - # via pandas -uritools==4.0.2 - # via urlextract -urlextract==1.8.0 - # via -r requirements.in -urllib3==1.26.18 - # via - # -r requirements.in - # botocore - # elasticsearch - # opensearch-py - # requests -uvicorn==0.27.0 - # via -r requirements.in -wheel==0.42.0 - # via -r requirements.in -yarl==1.9.4 - # via aiohttp - -# The following packages are considered to be unsafe in a requirements file: -# setuptools diff --git a/requirements_dev.in b/requirements_dev.in deleted file mode 100644 index 23faf2c5f..000000000 --- a/requirements_dev.in +++ /dev/null @@ -1,9 +0,0 @@ --r requirements.txt -black -httpx -isort -pylint -pytest -pytest-cov -responses -jinja2 diff --git a/requirements_dev.txt b/requirements_dev.txt deleted file mode 100644 index 0678c09a1..000000000 --- a/requirements_dev.txt +++ /dev/null @@ -1,320 +0,0 @@ -# -# This file is autogenerated by pip-compile with Python 3.11 -# by the following command: -# -# pip-compile requirements_dev.in -# -aiohttp==3.9.3 - # via - # -r requirements.txt - # geoip2 -aiosignal==1.3.1 - # via - # -r requirements.txt - # aiohttp -annotated-types==0.6.0 - # via - # -r requirements.txt - # pydantic -anyio==4.2.0 - # via - # -r requirements.txt - # httpx - # starlette -arrow==1.3.0 - # via -r requirements.txt -astroid==3.0.2 - # via pylint -attrs==23.2.0 - # via - # -r requirements.txt - # aiohttp -black==23.12.1 - # via -r requirements_dev.in -boto3==1.34.27 - # via -r requirements.txt -botocore==1.34.27 - # via - # -r requirements.txt - # boto3 - # s3transfer -certifi==2023.11.17 - # via - # -r requirements.txt - # elasticsearch - # httpcore - # httpx - # opensearch-py - # requests -charset-normalizer==3.3.2 - # via - # -r requirements.txt - # requests -ciso8601==2.3.1 - # via -r requirements.txt -click==8.1.7 - # via - # -r requirements.txt - # black - # uvicorn -colorama==0.4.6 - # via -r requirements.txt -confluent-kafka==2.3.0 - # via -r requirements.txt -coverage[toml]==7.4.0 - # via pytest-cov -deepdiff==6.7.1 - # via -r requirements.txt -dill==0.3.7 - # via pylint -elasticsearch==7.17.9 - # via -r requirements.txt -fastapi==0.109.1 - # via -r requirements.txt -filelock==3.13.1 - # via - # -r requirements.txt - # tldextract - # urlextract -frozenlist==1.4.1 - # via - # -r requirements.txt - # aiohttp - # aiosignal -geoip2==4.8.0 - # via -r requirements.txt -h11==0.14.0 - # via - # -r requirements.txt - # httpcore - # uvicorn -httpcore==1.0.2 - # via httpx -httpx==0.26.0 - # via -r requirements_dev.in -hyperscan==0.6.0 ; sys_platform == "linux" and platform_machine == "x86_64" - # via -r requirements.txt -idna==3.6 - # via - # -r requirements.txt - # anyio - # httpx - # requests - # tldextract - # urlextract - # yarl -iniconfig==2.0.0 - # via pytest -isort==5.13.2 - # via - # -r requirements_dev.in - # pylint -jinja2==3.1.3 - # via -r requirements_dev.in -jmespath==1.0.1 - # via - # -r requirements.txt - # boto3 - # botocore -joblib==1.3.2 - # via - # -r requirements.txt - # scikit-learn -jsonref==1.1.0 - # via -r requirements.txt -luqum==0.13.0 - # via -r requirements.txt -markupsafe==2.1.4 - # via jinja2 -maxminddb==2.5.2 - # via - # -r requirements.txt - # geoip2 -mccabe==0.7.0 - # via pylint -msgspec==0.18.6 - # via -r requirements.txt -multidict==6.0.4 - # via - # -r requirements.txt - # aiohttp - # yarl -mypy-extensions==1.0.0 - # via black -mysql-connector-python==8.3.0 - # via -r requirements.txt -ndjson==0.3.1 - # via -r requirements.txt -numpy==1.26.3 - # via - # -r requirements.txt - # pandas - # scikit-learn - # scipy -opensearch-py==2.4.2 - # via -r requirements.txt -ordered-set==4.1.0 - # via - # -r requirements.txt - # deepdiff -packaging==23.2 - # via - # black - # pytest -pandas==2.2.0 - # via -r requirements.txt -pathspec==0.12.1 - # via black -platformdirs==4.1.0 - # via - # -r requirements.txt - # black - # pylint - # urlextract -pluggy==1.4.0 - # via pytest -ply==3.11 - # via - # -r requirements.txt - # luqum -prometheus-client==0.19.0 - # via -r requirements.txt -protobuf==4.25.2 - # via -r requirements.txt -pycryptodome==3.20.0 - # via -r requirements.txt -pydantic==2.5.3 - # via - # -r requirements.txt - # fastapi -pydantic-core==2.14.6 - # via - # -r requirements.txt - # pydantic -pygrok==1.0.0 - # via -r requirements.txt -pylint==3.0.3 - # via -r requirements_dev.in -pyparsing==3.1.1 - # via -r requirements.txt -pytest==7.4.4 - # via - # -r requirements_dev.in - # pytest-cov -pytest-cov==4.1.0 - # via -r requirements_dev.in -python-dateutil==2.8.2 - # via - # -r requirements.txt - # arrow - # botocore - # opensearch-py - # pandas -pytz==2023.3.post1 - # via - # -r requirements.txt - # pandas -pyyaml==6.0.1 - # via - # -r requirements.txt - # responses -regex==2023.12.25 - # via - # -r requirements.txt - # pygrok -requests==2.31.0 - # via - # -r requirements.txt - # geoip2 - # opensearch-py - # requests-file - # responses - # tldextract -requests-file==1.5.1 - # via - # -r requirements.txt - # tldextract -responses==0.24.1 - # via -r requirements_dev.in -ruamel-yaml==0.18.5 - # via -r requirements.txt -ruamel-yaml-clib==0.2.8 - # via - # -r requirements.txt - # ruamel-yaml -s3transfer==0.10.0 - # via - # -r requirements.txt - # boto3 -schedule==1.2.1 - # via -r requirements.txt -scikit-learn==1.4.0 - # via -r requirements.txt -scipy==1.12.0 - # via - # -r requirements.txt - # scikit-learn -six==1.16.0 - # via - # -r requirements.txt - # opensearch-py - # python-dateutil - # requests-file -sniffio==1.3.0 - # via - # -r requirements.txt - # anyio - # httpx -starlette==0.35.1 - # via - # -r requirements.txt - # fastapi -tabulate==0.9.0 - # via -r requirements.txt -threadpoolctl==3.2.0 - # via - # -r requirements.txt - # scikit-learn -tldextract==5.1.1 - # via -r requirements.txt -tomlkit==0.12.3 - # via pylint -types-python-dateutil==2.8.19.20240106 - # via - # -r requirements.txt - # arrow -typing-extensions==4.9.0 - # via - # -r requirements.txt - # fastapi - # pydantic - # pydantic-core -tzdata==2023.4 - # via - # -r requirements.txt - # pandas -uritools==4.0.2 - # via - # -r requirements.txt - # urlextract -urlextract==1.8.0 - # via -r requirements.txt -urllib3==1.26.18 - # via - # -r requirements.txt - # botocore - # elasticsearch - # opensearch-py - # requests - # responses -uvicorn==0.27.0 - # via -r requirements.txt -wheel==0.42.0 - # via -r requirements.txt -yarl==1.9.4 - # via - # -r requirements.txt - # aiohttp - -# The following packages are considered to be unsafe in a requirements file: -# setuptools diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 9a1de0fb3..000000000 --- a/setup.cfg +++ /dev/null @@ -1,7 +0,0 @@ -[versioneer] -VCS = git -style = pep440 -versionfile_source = logprep/_version.py -versionfile_build = logprep/_version.py -tag_prefix = v -parentdir_prefix = logprep- \ No newline at end of file diff --git a/setup.py b/setup.py deleted file mode 100644 index 3a80767c0..000000000 --- a/setup.py +++ /dev/null @@ -1,45 +0,0 @@ -# pylint: disable=missing-module-docstring -from pathlib import Path - -from setuptools import find_packages, setup - -import versioneer - -with open("requirements.in", encoding="utf-8") as f: - requirements = f.read().splitlines() - -this_directory = Path(__file__).parent -long_description = (this_directory / "README.md").read_text() - -setup( - name="logprep", - version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), - description="Logprep allows to collect, process and forward log messages from various data " - "sources.", - long_description=long_description, - long_description_content_type="text/markdown", - url="https://github.com/fkie-cad/Logprep", - author="Logprep Team", - license="LGPL-2.1 license", - classifiers=[ - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - ], - project_urls={ - "Homepage": "https://github.com/fkie-cad/Logprep", - "Documentation": "https://logprep.readthedocs.io/en/latest/", - }, - packages=find_packages(), - include_package_data=True, - install_requires=["setuptools"] + requirements, - python_requires=">=3.10", - entry_points={ - "console_scripts": [ - "logprep = logprep.run_logprep:cli", - ] - }, -) diff --git a/tests/acceptance/util.py b/tests/acceptance/util.py index ba4615ffc..665c7d88c 100644 --- a/tests/acceptance/util.py +++ b/tests/acceptance/util.py @@ -202,8 +202,7 @@ def produce(self, target, value): with open(self.tmp_path, "a", encoding="utf-8") as tmp_file: tmp_file.write(f"{target} {value.decode()}\n") - def poll(self, _): - ... + def poll(self, _): ... def get_default_logprep_config(pipeline_config, with_hmac=True) -> Configuration: diff --git a/tests/unit/event_generator/kafka/test_document_sender.py b/tests/unit/event_generator/kafka/test_document_sender.py index 7fbe7a805..e0724d9c3 100644 --- a/tests/unit/event_generator/kafka/test_document_sender.py +++ b/tests/unit/event_generator/kafka/test_document_sender.py @@ -21,11 +21,9 @@ def __init__(self): def produce(self, _, value): self.produced.append(json.loads(value)) - def poll(self, timeout): - ... + def poll(self, timeout): ... - def flush(self, timeout): - ... + def flush(self, timeout): ... class TestDocumentSender: diff --git a/versioneer.py b/versioneer.py deleted file mode 100644 index 27d91c655..000000000 --- a/versioneer.py +++ /dev/null @@ -1,2172 +0,0 @@ -# pylint:disable-all -# Version: 0.22 - -"""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 -* Compatible with: Python 3.6, 3.7, 3.8, 3.9, 3.10 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 distutils/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 - -* `pip install versioneer` to somewhere in your $PATH -* add a `[versioneer]` section to your setup.cfg (see [Install](INSTALL.md)) -* run `versioneer install` 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`, if necessary, to include any new configuration settings - indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. -* re-run `versioneer install` 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 Creative Commons "Public Domain -Dedication" license (CC0-1.0), as described in -https://creativecommons.org/publicdomain/zero/1.0/ . - -[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 functools -import json -import os -import re -import subprocess -import sys -from typing import Callable, Dict - -from logprep.abc.exceptions import LogprepException - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - -def get_root(): - """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") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) 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") - versioneer_py = os.path.join(root, "versioneer.py") - if not (os.path.exists(setup_py) 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: - 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): - """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 . - setup_cfg = os.path.join(root, "setup.cfg") - parser = configparser.ConfigParser() - with open(setup_cfg, "r") as cfg_file: - parser.read_file(cfg_file) - VCS = parser.get("versioneer", "VCS") # mandatory - - # Dict-like interface for non-mandatory entries - section = parser["versioneer"] - - cfg = VersioneerConfig() - cfg.VCS = VCS - cfg.style = section.get("style", "") - cfg.versionfile_source = section.get("versionfile_source") - cfg.versionfile_build = section.get("versionfile_build") - cfg.tag_prefix = section.get("tag_prefix") - if cfg.tag_prefix in ("''", '""'): - cfg.tag_prefix = "" - cfg.parentdir_prefix = section.get("parentdir_prefix") - cfg.verbose = section.get("verbose") - return cfg - - -class NotThisMethod(LogprepException): - """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, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - - def decorate(f): - """Store f in HANDLERS[vcs][method].""" - HANDLERS.setdefault(vcs, {})[method] = f - return f - - return decorate - - -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs = {} - 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: - e = sys.exc_info()[1] - 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.22 (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 Callable, Dict -import functools - - -def get_keywords(): - """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.""" - - -def get_config(): - """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(LogprepException): - """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, method): # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f): - """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, args, cwd=None, verbose=False, hide_stderr=False, - env=None): - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs = {} - 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: - e = sys.exc_info()[1] - 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, root, verbose): - """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): - """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 = {} - 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, tag_prefix, verbose): - """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, root, verbose, runner=run_command): - """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=True) - if rc != 0: - if verbose: - print("Directory %%s not under git control" %% root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - MATCH_ARGS = ["--match", "%%s*" %% tag_prefix] if tag_prefix else [] - - # 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_ARGS], - 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 = {} - 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 - count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) - pieces["distance"] = int(count_out) # 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): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """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): - """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): - """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): - """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): - """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): - """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): - """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): - """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): - """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, style): - """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(): - """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): - """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 = {} - 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, tag_prefix, verbose): - """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, root, verbose, runner=run_command): - """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=True) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - MATCH_ARGS = ["--match", "%s*" % tag_prefix] if tag_prefix else [] - - # 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_ARGS], 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 = {} - 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 - count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) - pieces["distance"] = int(count_out) # 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(manifest_in, versionfile_source, ipy): - """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 = [manifest_in, versionfile_source] - if ipy: - files.append(ipy) - try: - my_path = __file__ - if my_path.endswith(".pyc") or my_path.endswith(".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, root, verbose): - """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.22) 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): - """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, versions): - """Write the given version number to the given _version.py file.""" - os.unlink(filename) - 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): - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces): - """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): - """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): - """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): - """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): - """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): - """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): - """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): - """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): - """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, style): - """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(LogprepException): - """The project root directory is unknown or missing key files.""" - - -def get_versions(verbose=False): - """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 cfg.verbose - 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(): - """Get the short version string for this project.""" - return get_versions()["version"] - - -def get_cmdclass(cmdclass=None): - """Get the custom setuptools/distutils 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() - - from setuptools import Command - - class cmd_version(Command): - description = "report generated version string" - user_options = [] - boolean_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - 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 both distutils and 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 -> ? - - # we override different "build_py" commands for both environments - if "build_py" in cmds: - _build_py = cmds["build_py"] - elif "setuptools" in sys.modules: - from setuptools.command.build_py import build_py as _build_py - else: - from distutils.command.build_py import build_py as _build_py - - class cmd_build_py(_build_py): - def run(self): - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_py.run(self) - # 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 = cmds["build_ext"] - elif "setuptools" in sys.modules: - from setuptools.command.build_ext import build_ext as _build_ext - else: - from distutils.command.build_ext import build_ext as _build_ext - - class cmd_build_ext(_build_ext): - def run(self): - 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 - 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_ext"] = cmd_build_ext - - if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe - - # 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): - 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? - from py2exe.distutils_buildexe import py2exe as _py2exe - - class cmd_py2exe(_py2exe): - def run(self): - 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 - - # we override different "sdist" commands for both environments - if "sdist" in cmds: - _sdist = cmds["sdist"] - elif "setuptools" in sys.modules: - from setuptools.command.sdist import sdist as _sdist - else: - from distutils.command.sdist import sdist as _sdist - - class cmd_sdist(_sdist): - def run(self): - 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, files): - 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(): - """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") - 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) - ipy = None - - # Make sure both the top-level "versioneer.py" and versionfile_source - # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so - # they'll be copied into source distributions. Pip won't be able to - # install the package without this. - manifest_in = os.path.join(root, "MANIFEST.in") - simple_includes = set() - try: - with open(manifest_in, "r") as f: - for line in f: - if line.startswith("include "): - for include in line.split()[1:]: - simple_includes.add(include) - except OSError: - pass - # That doesn't cover everything MANIFEST.in can do - # (http://docs.python.org/2/distutils/sourcedist.html#commands), so - # it might give some false negatives. Appending redundant 'include' - # lines is safe, though. - if "versioneer.py" not in simple_includes: - print(" appending 'versioneer.py' to MANIFEST.in") - with open(manifest_in, "a") as f: - f.write("include versioneer.py\n") - else: - print(" 'versioneer.py' already in MANIFEST.in") - if cfg.versionfile_source not in simple_includes: - print(" appending versionfile_source ('%s') to MANIFEST.in" % cfg.versionfile_source) - with open(manifest_in, "a") as f: - f.write("include %s\n" % cfg.versionfile_source) - else: - print(" versionfile_source already in MANIFEST.in") - - # Make VCS-specific changes. For git, this means creating/changing - # .gitattributes to mark _version.py for export-subst keyword - # substitution. - do_vcs_install(manifest_in, cfg.versionfile_source, ipy) - return 0 - - -def scan_setup_py(): - """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 - - -if __name__ == "__main__": - cmd = sys.argv[1] - if cmd == "setup": - errors = do_setup() - errors += scan_setup_py() - if errors: - sys.exit(1)