|
| 1 | +#!/usr/bin/env python |
| 2 | +# coding=utf-8 |
| 3 | +# PYTHON_ARGCOMPLETE_OK |
| 4 | + |
| 5 | +import sys |
| 6 | +from argparse import ArgumentParser |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +# Allow this script to be used from the parent directory |
| 10 | +sys.path.append(".") |
| 11 | + |
| 12 | +from app import db |
| 13 | +from app.models import Project, File |
| 14 | + |
| 15 | + |
| 16 | +def main(): |
| 17 | + # Parse arguments |
| 18 | + argument_parser = ArgumentParser(description="Add files to a project.") |
| 19 | + argument_parser.add_argument( |
| 20 | + "--project", type=str, required=True, |
| 21 | + help="The name of the project." |
| 22 | + ) |
| 23 | + argument_parser.add_argument( |
| 24 | + 'files', type=str, metavar="FILE", nargs='+', |
| 25 | + help="A file to be added to the project." |
| 26 | + ) |
| 27 | + arguments = argument_parser.parse_args() |
| 28 | + |
| 29 | + # Verify that the project exists |
| 30 | + project_query = Project.query.filter(Project.name == arguments.project) |
| 31 | + if project_query.count() != 1: |
| 32 | + print(f"Project '{arguments.project}' doesn't exist.", file=sys.stderr) |
| 33 | + exit(1) |
| 34 | + |
| 35 | + # Retrieve project id |
| 36 | + project_id = project_query.first().id |
| 37 | + |
| 38 | + for arg_filename in arguments.files: |
| 39 | + file_path: Path = Path(arg_filename) |
| 40 | + filename = file_path.absolute().as_posix() |
| 41 | + |
| 42 | + # Verify that the file exists |
| 43 | + if not file_path.exists(): |
| 44 | + print(f"File '{file_path}' doesn't exist.", file=sys.stderr) |
| 45 | + exit(2) |
| 46 | + |
| 47 | + # Verify that the file isn't already added to the project |
| 48 | + file_contents = file_path.read_text() |
| 49 | + |
| 50 | + # Add the file to the db |
| 51 | + file = File( |
| 52 | + filename=filename, |
| 53 | + content=file_contents, |
| 54 | + project_id=project_id |
| 55 | + ) |
| 56 | + |
| 57 | + if File.query.filter(File.project_id == project_id).filter(File.filename == filename).count() > 0: |
| 58 | + print(f"Skipping file '{file_path.name}' since it is already added to project '{arguments.project}'.") |
| 59 | + continue |
| 60 | + |
| 61 | + db.session.add(file) |
| 62 | + db.session.commit() |
| 63 | + |
| 64 | + print(f"File '{file_path.name}' added successfully.") |
| 65 | + exit(0) |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + main() |
0 commit comments