Skip to content

Instantly share code, notes, and snippets.

@AFirooz
Last active April 29, 2025 05:12
Show Gist options
  • Save AFirooz/d38d501737a96ff522cea54701d46682 to your computer and use it in GitHub Desktop.
Save AFirooz/d38d501737a96ff522cea54701d46682 to your computer and use it in GitHub Desktop.
Poetry Scripts
#! /usr/bin/env python3
# =================================================================================
# Name : list-groups.py
# Author : Ali Firooz
# Version : 0.0.2
# Copyright : Copyright © 2025 Ali Firooz. All Rights Reserved.
# Description : Adding the function of listing available groups in poetry.
# Can be used by running `$ poetry run groups` or
# `$ poetry run groups "<pyproject.toml path>"`.
# Inspired by https://dev.to/bowmanjd/build-command-line-tools-with-python-poetry-4mnc
# =================================================================================
# TODO:
# 1. make this a plugin
# 2. Fix the utils import so we can delete the join()
import sys
import toml
from os import path
# from utils import join
def join(*args, lvl_max: int = 5) -> str:
"""
Special join function that accepts the inputs of the original join function and normalize the output path.
In addition, the function will verify that the path created exists. If this is not true,
the function will go up one folder and check again (until the limit is reached).
:param args: The arguments for the original join function.
:param lvl_max: The maximum number of folders that the function is allowed to go up and check.
:return: A path that exists.
:raises: Raise ValueError if the maximum folder is reached but couldn't find the correct folder.
"""
mypath = path.normpath(path.join(*args))
lvl = 0
while not path.exists(mypath):
lvl += 1
if lvl > (lvl_max + 1):
raise ValueError(f"Could not find {args[-1]}."
f"{args}"
f"Try increasing the lvl_max variable if you need to go up more."
f"The current path is: {path}")
mypath = path.normpath(path.join(args[0], *(['..'] * lvl), *args[1:]))
return mypath
def list_groups(pyporjectpath: path = None) -> str:
"""
List all available groups in poetry pyproject.toml
:param pyporjectpath: path to poetry pyproject.toml
:return: string containing group names
"""
if pyporjectpath is None:
pyporjectpath = join('.', 'pyproject.toml')
if not path.exists(pyporjectpath):
return "Could not find pyproject.toml, please pass it's path in the command line"
with open(pyporjectpath, 'r') as file:
file = toml.load(file)
postfix = ("\n\nUseful commands:\n"
"1. poetry add <package names> --group <group name>\n"
"2. poetry install --with <group name> --sync\n")
grp = list(file['tool']['poetry']['group'].keys())
nums = list(range(1, len(grp) + 1))
groups = '\n'.join([f"{nums[i]}. {grp[i]}" for i in range(len(grp))]) + postfix
return groups
# def cli(args=None):
# """Process command line arguments."""
# if not args:
# args = sys.argv[1:]
# pyporjectpath = path.normpath(args[0])
# else:
# pyporjectpath = join('.', 'pyproject.toml')
#
# print(list_groups(pyporjectpath))
if __name__ == '__main__':
# print(list_groups())
pass
#! /usr/bin/env python3
# =================================================================================
# Name : sync-pip.py
# Author : Ali Firooz
# Version : 0.0.1
# Copyright : Copyright © 2025 Ali Firooz. All Rights Reserved.
# Description : If you have installed packages using pip, running this script will add them to poetry
# =================================================================================
# TODO:
# 1. Check if there is groups, if so, ask where to add the new dependencies
# 2. Only add new dependencies if they are not already in the poetry.lock file
import subprocess
def main():
# Get the list of poetry installed packages
poetry_list = subprocess.run(['poetry', 'show'], capture_output=True, text=True).stdout.strip().split("\n")
poetry_list = [name.split(" ")[0] for name in poetry_list]
# Get the list of pip installed packages with their versions
pip_list = subprocess.run(["pip", "freeze"], capture_output=True, text=True).stdout.strip().split("\n")
strip_pip_name = [package.split("==")[0] for package in pip_list]
precommand = "poetry add"
command = ""
# Find the packages that are not installed by poetry
# Generate and execute 'poetry add' commands for all new packages
for i, package in enumerate(strip_pip_name):
if package not in poetry_list:
package_name, package_version = pip_list[i].split("==")
command = f"{command} {package_name}@{package_version}"
command = f"{precommand}{command}"
print(f"\n{command}\n")
if input("Do you want to execute this command? (y/n): ") == "y":
subprocess.run(command, shell=True)
if __name__ == "__main__":
pass
# main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment