Compare commits

..

No commits in common. "master" and "main" have entirely different histories.
master ... main

15 changed files with 390 additions and 77 deletions

21
README.md Normal file
View file

@ -0,0 +1,21 @@
# Python template
A template for python project using [cookicutter](https://github.com/cookiecutter/cookiecutter).
## Cookicutter config
A good config to have for cookicutter at `~/.cookiecutterrc`:
```
abbreviations:
pp: https://git.pains-perdus.fr/templates/{}.git
default_context:
full_name: "Jane Doe"
email: "jane.doe@example.com"
git_user: "jdoe"
gitea_url: "https://git.pains-perdus.fr"
```
To create the project on gitea, cookie cutter needs the `giteapy` module and a gitea token. The token can be retrieved with the `secretstorage` by looking up the secret `"Title": "Gitea Token"`, or by prompting the user.

44
TODO.md
View file

@ -1,5 +1,45 @@
# TODO:
- tests
- add AGPL
- publish to gitea repo: [container](https://docs.gitea.io/en-us/usage/packages/container/) [badge](https://docs.gitea.io/en-us/usage/packages/generic/)
- use bool value for `generate_gitea_project` when the feature is available
### Package
```
curl -i --upload-file README.md --user "histausse:`secret-tool lookup Title 'Gitea Token'`" https://git.pains-perdus.fr/api/packages/histausse/generic/test_flake_poetry2nix/latest/README.md
curl https://git.pains-perdus.fr/api/packages/histausse/generic/test_flake_poetry2nix/latest/README.md
curl -i -X DELETE --user "histausse:`secret-tool lookup Title 'Gitea Token'`" https://git.pains-perdus.fr/api/packages/histausse/generic/test_flake_poetry2nix/latest/pyproject.toml
```
```
podman login -u histausse -p `secret-tool lookup Title 'Gitea Token'` git.pains-perdus.fr
podman push test_flake_poetry2nix:latest git.pains-perdus.fr/histausse/test_flake_poetry2nix:latest
```
Put secret in CI:
```
connection.request(
"POST",
f"/api/repos/{repo}/secrets",
json.dumps(
{
"name": "test_token",
"value": "loren ispum",
"image": ["test"],
"event": ["push", "tag"],
}
),
{
"Authorization": f"Bearer {API_KEY}",
"content-type": "application/json",
},
)
```
Gen badge:
```
https://github.com/smarie/python-genbadge/issues
```

View file

@ -1,15 +1,18 @@
{
"project_name": "",
"project_short_description": "",
"full_name": "Jean-Marie 'Histausse' Mineau",
"email": "histausse@protonmail.com",
"git_user": "histausse",
"full_name": "",
"email": "",
"git_user": "",
"project_slug": "{{ cookiecutter.project_name.lower().replace(' ', '_').replace('-', '_') }}",
"gitea_url": "https://git.mineau.eu",
"gitea_url": "https://git.pains-perdus.fr",
"project_url": "{{ cookiecutter.gitea_url }}/{{ cookiecutter.git_user }}/{{ cookiecutter.project_slug }}",
"generate_gitea_project": [ true, false ],
"configure_ci": [ true, false ],
"woodpecker_gitea_user": "ci",
"woodpecker_server": "https://ci.pains-perdus.fr",
"git_origin": "{{ cookiecutter.gitea_url.replace('https://', 'gitea@').replace('http://', 'gitea') }}:{{ cookiecutter.git_user }}/{{ cookiecutter.project_slug }}.git",
"version": "0.1.0",
"open_source_license": ["GNU General Public License v3", "MIT license", "BSD license", "ISC license", "Apache Software License 2.0", "Not open source"],
"open_source_license": ["AGPL-3.0-only", "GPL-3.0-only", "MIT", "BSD-3-Clause", "ISC", "Apache-2.0", "Proprietary"],
"python_min_version": "3.10"
}

View file

@ -1,49 +1,188 @@
import subprocess
import http.client
import json
import os
from base64 import b64encode
REMOVE_PATHS = [
{% if cookiecutter.open_source_license == "Proprietary" %} "LICENSE", {% endif %}
{% if cookiecutter.configure_ci == "False" %} ".woodpecker.yml", {% endif %}
]
for path in REMOVE_PATHS:
if path and os.path.exists(path):
if os.path.isdir(path):
os.rmdir(path)
else:
os.unlink(path)
subprocess.call(["poetry", "lock"])
subprocess.call(["git", "init"])
subprocess.call(["git", "checkout", "-b", "main"])
subprocess.call(["git", "add", "*"])
subprocess.call(["git", "commit", "-m", "Initial commit"])
subprocess.call(["git", "config", "user.name", "{{ cookiecutter.git_user }}"])
subprocess.call(["git", "config", "user.email", "{{ cookiecutter.email }}"])
subprocess.call(["git", "commit", "-m", "Initial commit"])
subprocess.call(["python", "-m", "venv", "venv"])
# subprocess.call(["python", "-m", "venv", "venv"])
if {{cookiecutter.generate_gitea_project}}:
try:
import giteapy
except ModuleNotFoundError:
print("giteapy is not availabled, repository not created")
exit()
def get_secret(secret_name: str):
try:
import secretstorage
connection = secretstorage.dbus_init()
collection = secretstorage.get_default_collection(connection)
collection.unlock()
secret = collection.search_items({"Title": "Gitea Token"}).__next__()
secret = collection.search_items({"Title": secret_name}).__next__()
secret.unlock()
API_KEY = secret.get_secret().decode("utf-8")
return secret.get_secret().decode("utf-8")
except (ModuleNotFoundError, StopIteration):
try:
import getpass
import getpass
my_input = getpass.getpass
except ModuleNotFoundError:
my_input = input
API_KEY = my_input(
"Secret service or secret {'Title': 'Gitea Token'} not available,"
return getpass.getpass(
f"Secret service or secret {'Title': 'secret_name'} not available,"
"please enter you gitea api token:"
)
def get_new_gitea_token(
connection: http.client.HTTPSConnection, new_token_name: str, user: str, token: str
) -> str:
auth = b64encode(f"{user}:{token}".encode("utf-8")).decode("ascii")
connection.request(
"POST",
f"/api/v1/users/{user}/tokens",
json.dumps(
{
"name": new_token_name,
}
),
{
"Authorization": f"Basic {auth}",
"content-type": "application/json",
},
)
response = connection.getresponse()
status = response.status
if status != 201:
print(
f"\033[38;2;255;0;0mInvalid response from gitea while creating a new token: {status} ({response.reason})\033[0m"
)
print(response.read())
exit(1)
data = json.load(response)
return data["sha1"]
def push_woodpecker_secret(
connection: http.client.HTTPSConnection,
repo: str,
secret_name: str,
secret: str,
woodpecker_token: str,
images: list[str] | None = None
):
if images is None: images = []
connection.request(
"POST",
f"/api/repos/{repo}/secrets",
json.dumps(
{
"name": secret_name,
"value": secret,
"image": images,
"event": ["push", "tag"],
}
),
{
"Authorization": f"Bearer {woodpecker_token}",
"content-type": "application/json",
},
)
response = connection.getresponse()
status = response.status
if status != 200:
print(
f"\033[38;2;255;0;0mInvalid response from woodpecker when sending a new secret: {status} ({response.reason})\033[0m"
)
print(response.read())
exit(1)
response.read()
if {{cookiecutter.generate_gitea_project}}:
try:
import giteapy
except ModuleNotFoundError:
print("module `giteapy` is not availabled, repository not created")
exit()
GITEA_API_KEY = get_secret("Gitea Token")
configuration = giteapy.Configuration()
configuration.api_key["access_token"] = API_KEY
configuration.api_key["access_token"] = GITEA_API_KEY
client = giteapy.ApiClient(configuration)
client.configuration.host = "{{ cookiecutter.gitea_url }}/api/v1"
api_instance = giteapy.AdminApi(client)
username = "{{ cookiecutter.git_user }}"
api_instance = giteapy.UserApi(client)
repo = giteapy.CreateRepoOption(
name="{{ cookiecutter.project_slug }}", private=True
)
api_instance.admin_create_repo(username, repo)
api_instance.create_current_user_repo(body=repo)
if {{cookiecutter.generate_gitea_project}} and {{cookiecutter.configure_ci}}:
api_instance = giteapy.RepositoryApi(client)
options = giteapy.AddCollaboratorOption("read")
api_instance.repo_add_collaborator(
"{{ cookiecutter.git_user }}",
"{{ cookiecutter.project_slug }}",
"{{ cookiecutter.woodpecker_gitea_user }}",
body=options,
)
connection_gitea = http.client.HTTPSConnection("git.pains-perdus.fr")
GITEA_API_KEY = get_new_gitea_token(connection_gitea, "CI {{ cookiecutter.git_user }}/{{ cookiecutter.project_slug }}", "{{ cookiecutter.git_user }}", GITEA_API_KEY)
WOODPECKER_API_KEY = get_secret("Woodpecker Token")
WOODPECKER_SERVER = "{{ cookiecutter.woodpecker_server }}".removeprefix("https://")
origin = "{{ cookiecutter.git_origin }}"
repo = "/".join(origin.removesuffix(".git").split(":")[-1].split("/")[-2:])
connection = http.client.HTTPSConnection(WOODPECKER_SERVER)
connection.request(
"GET",
"/api/user/repos?all=true&flush=true",
headers={"Authorization": f"Bearer {WOODPECKER_API_KEY}"},
)
response = connection.getresponse()
status = response.status
response.read()
if status != 200:
print(
f"\033[38;2;255;0;0mInvalid response from woodpecker while loading repos: {status} ({response.reason})\033[0m"
)
exit(1)
connection.request(
"POST",
f"/api/repos/{repo}",
headers={
"Authorization": f"Bearer {WOODPECKER_API_KEY}",
"referer": f"https://{WOODPECKER_SERVER}/repo/add",
},
)
response = connection.getresponse()
status = response.status
if status != 200:
print(
f"\033[38;2;255;0;0mInvalid response from woodpecker while linking repo: {status} ({response.reason})\033[0m"
)
print(response.read())
exit(1)
response.read()
push_woodpecker_secret(
connection,
repo,
"gitea_token",
GITEA_API_KEY,
WOODPECKER_API_KEY
)
if {{cookiecutter.generate_gitea_project}}:
subprocess.call(["git", "remote", "add", "origin", "{{ cookiecutter.git_origin }}"])
subprocess.call(["git", "push", "-u", "origin", "master"])
subprocess.call(["git", "push", "-u", "origin", "main"])

View file

@ -26,6 +26,7 @@ wheels/
*.egg
# virtualenv
.venv/
venv/
# mypy

View file

@ -1 +0,0 @@
{{ cookiecutter.python_min_version }}

View file

@ -0,0 +1,39 @@
pipeline:
test:
group: test
image: python:${PYTHON_VERSION}
pull: true
environment:
- POETRY_VIRTUALENVS_IN_PROJECT=true
commands:
- pip install poetry
- poetry install
- poetry run pytest
nix:
group: test
image: nixos/nix:latest
pull: true
commands:
- nix build --experimental-features 'nix-command flakes'
- nix build -o image_link --experimental-features 'nix-command flakes' .#docker
- cp image_link image
when:
matrix:
PYTHON_VERSION: {{ cookiecutter.python_min_version}} # Still not sure about how to make flake for different python version
push_image:
image: quay.io/podman/stable:latest
pull: true
commands:
- podman login -u {{ cookiecutter.git_user }} -p $GITEA_TOKEN {{ cookiecutter.gitea_url.removeprefix('https://') }}
- podman load < image
- podman push {{ cookiecutter.project_slug }}:latest {{ cookiecutter.gitea_url.removeprefix('https://') }}/{{ cookiecutter.git_user }}/{{ cookiecutter.project_slug }}:latest
secrets: [ gitea_token ]
when:
matrix:
PYTHON_VERSION: {{ cookiecutter.python_min_version}} # Still not sure about how to make flake for different python version
matrix:
PYTHON_VERSION:
- {{ cookiecutter.python_min_version}}

View file

@ -1,4 +1,4 @@
{% if cookiecutter.open_source_license == 'MIT license' -%}
{% if cookiecutter.open_source_license == 'MIT' -%}
MIT License
Copyright (c) {% now 'local', '%Y' %}, {{ cookiecutter.full_name }}
@ -20,7 +20,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
{% elif cookiecutter.open_source_license == 'BSD license' %}
{% elif cookiecutter.open_source_license == 'BSD-3-Clause' %}
BSD License
@ -51,7 +51,7 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
{% elif cookiecutter.open_source_license == 'ISC license' -%}
{% elif cookiecutter.open_source_license == 'ISC' -%}
ISC License
Copyright (c) {% now 'local', '%Y' %}, {{ cookiecutter.full_name }}
@ -59,7 +59,7 @@ Copyright (c) {% now 'local', '%Y' %}, {{ cookiecutter.full_name }}
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
{% elif cookiecutter.open_source_license == 'Apache Software License 2.0' -%}
{% elif cookiecutter.open_source_license == 'Apache-2.0' -%}
Apache Software License 2.0
Copyright (c) {% now 'local', '%Y' %}, {{ cookiecutter.full_name }}
@ -75,7 +75,7 @@ distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
{% elif cookiecutter.open_source_license == 'GNU General Public License v3' -%}
{% elif cookiecutter.open_source_license == 'GPL-3.0-only' -%}
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
@ -84,8 +84,7 @@ GNU GENERAL PUBLIC LICENSE
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
the Free Software Foundation, version 3.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@ -94,18 +93,22 @@ GNU GENERAL PUBLIC LICENSE
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
{% elif cookiecutter.open_source_license == 'AGPL-3.0-only' %}
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Also add information on how to contact you by electronic and paper mail.
{{ cookiecutter.project_short_description }}
Copyright (C) {% now 'local', '%Y' %} {{ cookiecutter.full_name }}
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, version 3.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
{% endif %}

View file

@ -1,16 +1,50 @@
{% set is_open_source = cookiecutter.open_source_license != 'Not open source' -%}
{% set is_open_source = cookiecutter.open_source_license != 'Proprietary' -%}
{% set repo = "/".join(cookiecutter.git_origin.removesuffix(".git").split(":")[-1].split("/")[-2:]) %}
# {{ cookiecutter.project_name }}
{% if cookiecutter.configure_ci == "True" %}[![CI status badge]({{ cookiecutter.woodpecker_server }}/api/badges/{{ repo }}/status.svg)](https://ci.pains-perdus.fr/{{ repo }}){% endif %}
{{ cookiecutter.project_short_description }}
## Install
### With pip
This project can be installed using pip:
```
pip install git+{{ cookiecutter.project_url }}.git
```
### With Nix
There is a `flake.nix`, so you can clone the repo and use `nix shell` if you want.
### Docker/Podman
{% if cookiecutter.configure_ci == "True" %}
You can run this projet with docker or podman:
```
podman run --rm -it {{ cookiecutter.gitea_url.removeprefix('https://') }}/{{ cookiecutter.git_user }}/{{ cookiecutter.project_slug }}:latest {{ cookiecutter.project_slug }}
```
{% else %}
You can build a container image using nix. To build the image, in the repo, run:
```
nix build -o {{ cookiecutter.project_slug }}.img .#docker
```
You can then load the image with:
```
podman load < {{ cookiecutter.project_slug }}.img
```
{% endif %}
Notice the image is build with nix and is very minimalist.
{% if is_open_source %}
## License
@ -18,13 +52,14 @@ This project if a free software released under the {{ cookiecutter.open_source_l
## Dev
If you want to tinker with this project, you can clone it and install it in editable mode:
This project is managed by [poetry](https://python-poetry.org/).
To open a shell in a venv of the project:
```
git clone {{ cookiecutter.project_url }}.git
cd {{ cookiecutter.project_slug }}
python -m venv venv && source venv/bin/activate
pip install -e .[dev]
poetry shell
poetry install
```
### Test
@ -32,8 +67,9 @@ pip install -e .[dev]
Tests are run using `pytest`:
```
pytest
poetry run pytest
```
{% endif %}
## Author

View file

@ -0,0 +1,36 @@
{
description = "{{ cookiecutter.project_short_description }}";
inputs.flake-utils.url = "github:numtide/flake-utils";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
inputs.poetry2nix = {
url = "github:nix-community/poetry2nix";
inputs.nixpkgs.follows = "nixpkgs";
};
outputs = { self, nixpkgs, flake-utils, poetry2nix }:
flake-utils.lib.eachDefaultSystem (system:
let
inherit (poetry2nix.legacyPackages.${system}) mkPoetryApplication;
pkgs = nixpkgs.legacyPackages.${system};
in
{
packages = {
{{ cookiecutter.project_slug }} = mkPoetryApplication { projectDir = self; };
docker = pkgs.dockerTools.buildImage {
name = "{{ cookiecutter.project_slug }}";
tag = "latest";
copyToRoot = pkgs.buildEnv {
name = "{{ cookiecutter.project_slug }}_root_img";
paths = [ self.packages.${system}.{{ cookiecutter.project_slug }} ];
pathsToLink = [ "/bin" ];
};
};
default = self.packages.${system}.{{ cookiecutter.project_slug }};
};
devShells.default = pkgs.mkShell {
packages = [ poetry2nix.packages.${system}.poetry ];
};
});
}

View file

@ -1,33 +1,29 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
[tool.poetry]
name = "{{ cookiecutter.project_slug }}"
version = "{{ cookiecutter.version }}"
authors = [
{ name="{{ cookiecutter.full_name }}", email="{{ cookiecutter.email }}" },
]
description = "{{ cookiecutter.project_short_description }}"
authors = ["{{ cookiecutter.full_name }} <{{ cookiecutter.email }}>"]
readme = "README.md"
homepage = "{{ cookiecutter.project_url }}"
repository = "{{ cookiecutter.project_url }}"
license = "{{ cookiecutter.open_source_license }}"
requires-python = ">={{ cookiecutter.python_min_version }}"
dependencies = []
[project.optional-dependencies]
test = [
"pytest >=7.2.2",
]
dev = ["{{ cookiecutter.project_slug }}[test]"]
[project.urls]
"Homepage" = "{{ cookiecutter.project_url }}"
[tool.poetry.urls]
"Bug Tracker" = "{{ cookiecutter.project_url }}/issues"
[project.scripts]
[tool.poetry.dependencies]
python = "^3.10"
[tool.poetry.scripts]
{{ cookiecutter.project_slug }} = "{{ cookiecutter.project_slug }}.cli:main"
[tool.poetry.group.dev.dependencies]
pytest = "*"
pytest-cov = "*"
[tool.pytest.ini_options]
addopts = [
"--import-mode=importlib",
]
addopts = "--cov"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

View file

@ -1,9 +1,9 @@
import argparse
def main():
""" Console entrypoint for {{cookiecutter.project_slug}}."""
parser = argparse.ArgumentParser()
parser.add_argument('_', nargs='*')
args = parser.parse_args()
print("Hello word!")