Big-Link-Man/scripts/update_project_entities.py

68 lines
2.2 KiB
Python

"""
Update entities for a project
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
import click
from src.database.session import db_manager
from src.database.repositories import ProjectRepository
@click.command()
@click.argument('project_id', type=int)
@click.option('--entities', '-e', multiple=True, help='Entity to add (can be used multiple times)')
@click.option('--file', '-f', type=click.Path(exists=True), help='File with entities (one per line)')
@click.option('--replace', is_flag=True, help='Replace existing entities instead of appending')
def main(project_id: int, entities: tuple, file: str, replace: bool):
"""Update entities for PROJECT_ID"""
db_manager.initialize()
session = db_manager.get_session()
try:
repo = ProjectRepository(session)
project = repo.get_by_id(project_id)
if not project:
click.echo(f"Error: Project {project_id} not found", err=True)
return
# Collect entities from arguments or file
new_entities = list(entities)
if file:
with open(file, 'r', encoding='utf-8') as f:
file_entities = [line.strip() for line in f if line.strip()]
new_entities.extend(file_entities)
if not new_entities:
click.echo("No entities provided. Use --entities or --file", err=True)
return
# Update project entities
if replace:
project.entities = new_entities
click.echo(f"Replaced entities for project {project_id}")
else:
existing = project.entities or []
project.entities = existing + new_entities
click.echo(f"Added {len(new_entities)} entities to project {project_id}")
session.commit()
click.echo(f"\nTotal entities: {len(project.entities)}")
click.echo("Entities:")
for entity in project.entities:
click.echo(f" - {entity}")
except Exception as e:
session.rollback()
click.echo(f"Error: {e}", err=True)
raise
finally:
session.close()
if __name__ == "__main__":
main()