From 345e64ea2bf447e64674e98e7e32aaa7906e22da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Maty=C3=A1=C5=A1ek?= Date: Sat, 12 Mar 2022 11:15:45 +0100 Subject: [PATCH] Improve direnv and poetry interop - Adds global `.direnvrc` which defines `layout poetry` that initialized poetry environment in a directory with `pyproject.toml` - Adds utility script `poetry-here` that creates local `.envrc` and sets up direnv - Makes appropriate symlinks of these files into `$HOME` --- .direnvrc | 25 +++++++++++++++++++++++++ .local/bin/poetry-here | 10 ++++++++++ Makefile | 2 ++ 3 files changed, 37 insertions(+) create mode 100644 .direnvrc create mode 100755 .local/bin/poetry-here diff --git a/.direnvrc b/.direnvrc new file mode 100644 index 0000000..f0b4c6f --- /dev/null +++ b/.direnvrc @@ -0,0 +1,25 @@ +# Define `layout poetry` for local `.envrc` +# - https://github.com/direnv/direnv/wiki/Python#poetry +# - https://medium.com/analytics-vidhya/best-practice-for-using-poetry-608ab6feaaf +layout_poetry() { + + if [[ ! -f pyproject.toml ]]; then + log_status 'No pyproject.toml found. Will initialize poetry in no-interactive mode' + + # Initialize poetry in no-interactive mode + poetry init -n -q + fi + + # Create venv if it doesn't exist + poetry run true + + # Setup VIRTUAL_ENV and add it to PATH + export VIRTUAL_ENV=$(poetry env info --path) + export POETRY_ACTIVE=1 + PATH_add "$VIRTUAL_ENV/bin" + + # Make symlink to `.venv` for easy IDE environment setup + if [ ! -L .venv ]; then + ln -ns $VIRTUAL_ENV .venv + fi +} diff --git a/.local/bin/poetry-here b/.local/bin/poetry-here new file mode 100755 index 0000000..85fd4b3 --- /dev/null +++ b/.local/bin/poetry-here @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + +# Allows to run `poetry-here` anywhere one wants to have poetry setup. +# - Works even if new project with poetry has not yet been set up +# - https://medium.com/analytics-vidhya/best-practice-for-using-poetry-608ab6feaaf + +echo "layout poetry" > .envrc + +direnv allow . +direnv exec . true diff --git a/Makefile b/Makefile index 110960d..c4d64ad 100644 --- a/Makefile +++ b/Makefile @@ -189,6 +189,7 @@ links: $(ALACRITTY_CONFIG_DIR) $(BYOBU_CONFIG_DIR) ~/.config/nvim/vim-plug ~/.co $(CFG_DIR)/.xsession \ $(CFG_DIR)/.gitconfig \ $(CFG_DIR)/.pam_environment \ + $(CFG_DIR)/.direnvrc \ $(CFG_DIR)/.zsh* \ $(CFG_DIR)/.p10k.zsh @{ \ @@ -200,6 +201,7 @@ links: $(ALACRITTY_CONFIG_DIR) $(BYOBU_CONFIG_DIR) ~/.config/nvim/vim-plug ~/.co $(CFG_DIR)/.local/bin/alacritty_toggle.sh \ $(CFG_DIR)/.local/bin/increase_swap.sh \ $(CFG_DIR)/.local/bin/init_ubuntu.sh \ + $(CFG_DIR)/.local/bin/poetry-here \ $(CFG_DIR)/.local/bin/upgrade_kernel.sh @[ "$$(grep 'user_readenv=1' /etc/pam.d/login)" ] || \ echo "Finish pam env setup by manually updating '/etc/pam.d/login' - see https://askubuntu.com/a/636544"