Skip to content

Commit

Permalink
feat(cli): enhance CLI with subcommands for database management and a…
Browse files Browse the repository at this point in the history
…dd schema retrieval functionality

- Introduced subcommands for creating databases and retrieving existing database schemas.
- Updated argument parsing to support new commands and improved error handling.
- Added a new script to retrieve and format the schema of a Notion database.
- Updated .gitignore to exclude notion_automation.log from version control.
  • Loading branch information
atxtechbro committed Dec 22, 2024
1 parent 5abaeb3 commit 7afec84
Show file tree
Hide file tree
Showing 4 changed files with 111 additions and 14 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ venv/

plugins

*.log
notion_automation.log

22 changes: 22 additions & 0 deletions notion_automation.log
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,25 @@
2024-09-13 14:04:17,978 - notion_automation - ERROR - Failed to create task: {"object":"error","status":400,"code":"validation_error","message":"body failed validation. Fix one:\nbody.properties.Type.select.id should be defined, instead was `undefined`.\nbody.properties.Type.select.name should be a string, instead was `null`.","request_id":"def6977e-d052-43fb-b402-804df036cd60"}
2024-09-13 19:01:28,060 - notion_automation - INFO - Database 'Test DB' created with ID: fake_database_id
2024-09-13 19:01:28,062 - notion_automation - ERROR - Failed to create database: {"error": "Unauthorized"}
2024-09-13 20:46:34,099 - notion_automation - ERROR - Error processing schema or tasks: Property 'Task' is not defined in the schema.
2024-09-13 20:47:06,412 - notion_automation - INFO - Database 'Siphon CLI Utility Tests' created with ID: 1016bf94-c111-81ef-94d1-ed392899725c
2024-09-13 20:48:09,407 - notion_automation - ERROR - Error processing schema or tasks: Property 'Task' is not defined in the schema.
2024-09-13 20:51:18,810 - notion_automation - INFO - Database 'Siphon CLI Utility Tests' created with ID: 1016bf94-c111-815a-9ade-e18d9347f1a9
2024-09-13 20:51:19,496 - notion_automation - INFO - Task created in database '1016bf94-c111-815a-9ade-e18d9347f1a9'.
2024-09-13 20:51:19,907 - notion_automation - INFO - Task created in database '1016bf94-c111-815a-9ade-e18d9347f1a9'.
2024-09-13 20:51:20,223 - notion_automation - INFO - Task created in database '1016bf94-c111-815a-9ade-e18d9347f1a9'.
2024-09-13 20:51:20,623 - notion_automation - INFO - Task created in database '1016bf94-c111-815a-9ade-e18d9347f1a9'.
2024-09-13 20:51:23,658 - notion_automation - INFO - Task created in database '1016bf94-c111-815a-9ade-e18d9347f1a9'.
2024-09-13 20:51:24,010 - notion_automation - INFO - Task created in database '1016bf94-c111-815a-9ade-e18d9347f1a9'.
2024-09-13 20:51:24,614 - notion_automation - INFO - Task created in database '1016bf94-c111-815a-9ade-e18d9347f1a9'.
2024-09-13 20:51:25,027 - notion_automation - INFO - Task created in database '1016bf94-c111-815a-9ade-e18d9347f1a9'.
2024-09-13 20:51:25,641 - notion_automation - INFO - Task created in database '1016bf94-c111-815a-9ade-e18d9347f1a9'.
2024-09-13 20:51:27,074 - notion_automation - INFO - Task created in database '1016bf94-c111-815a-9ade-e18d9347f1a9'.
2024-10-19 10:44:55,941 - notion_automation - INFO - Database 'Worship Night Guests' created with ID: 1246bf94-c111-81dd-8566-f0ea928e3f90
2024-10-19 10:44:56,288 - notion_automation - INFO - Task created in database '1246bf94-c111-81dd-8566-f0ea928e3f90'.
2024-10-19 10:44:56,724 - notion_automation - INFO - Task created in database '1246bf94-c111-81dd-8566-f0ea928e3f90'.
2024-10-19 10:44:57,338 - notion_automation - INFO - Task created in database '1246bf94-c111-81dd-8566-f0ea928e3f90'.
2024-10-19 10:46:08,577 - notion_automation - INFO - Database 'Worship Night Guests' created with ID: 1246bf94-c111-81fa-a5e0-f2832ce24354
2024-10-19 10:46:09,202 - notion_automation - INFO - Task created in database '1246bf94-c111-81fa-a5e0-f2832ce24354'.
2024-10-19 10:46:09,771 - notion_automation - INFO - Task created in database '1246bf94-c111-81fa-a5e0-f2832ce24354'.
2024-10-19 10:46:10,208 - notion_automation - INFO - Task created in database '1246bf94-c111-81fa-a5e0-f2832ce24354'.
43 changes: 30 additions & 13 deletions notion_automation/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@

from dotenv import load_dotenv

from notion_automation.notion_client.api import NotionClient
from notion_automation.notion_client.logger import logger
from notion_automation.notion_client.models import EntryConfig, EntryProperty, PropertyConfig, PropertyOption, SchemaConfig
from notion_client.api import NotionClient
from notion_client.logger import logger
from notion_client.models import PropertyConfig, PropertyOption, SchemaConfig, TaskConfig, TaskProperty
from scripts.get_database import get_database_schema

# Load environment variables from .env
load_dotenv()
Expand Down Expand Up @@ -177,16 +178,32 @@ def parse_natural_language_properties(property_descriptions):
return properties

if __name__ == "__main__":
# Set up argument parser
parser = argparse.ArgumentParser(
description="Create a Notion database and add entries."
description="Manage Notion databases"
)
parser.add_argument("--schema", required=True, help="Path to the JSON schema file.")
parser.add_argument("--entries", required=False, help="Path to the JSON entries file.")
parser.add_argument("--page-id", required=False, help="Target Notion Page ID to create the database in.")

# Parse the arguments

# Create subparsers for different commands
subparsers = parser.add_subparsers(dest='command', help='Available commands')

# Create database command
create_parser = subparsers.add_parser('create', help='Create a new database')
create_parser.add_argument("--schema", required=True, help="Path to the JSON schema file.")
create_parser.add_argument("--tasks", required=False, help="Path to the JSON tasks file.")

# Get database schema command
get_parser = subparsers.add_parser('get-schema', help='Get schema of existing database')
get_parser.add_argument("--id", required=True, help="ID of the database to retrieve")
get_parser.add_argument("--output", help="Optional file path to save the schema")

args = parser.parse_args()

# Call the create_database function with the provided arguments
create_database(args.schema, args.entries, args.page_id)

if args.command == 'create':
create_database(args.schema, args.tasks)
elif args.command == 'get-schema':
schema = get_database_schema(args.id)
if args.output:
with open(args.output, 'w') as f:
json.dump(schema, f, indent=2)
print(f"Schema saved to {args.output}")
else:
print(json.dumps(schema, indent=2))
58 changes: 58 additions & 0 deletions notion_automation/get_database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import sys
import json
from notion_client import Client
import os
from dotenv import load_dotenv

def get_database_schema(database_id):
"""Retrieve and format the schema of a Notion database."""
load_dotenv()
notion = Client(auth=os.getenv("NOTION_TOKEN"))

try:
database = notion.databases.retrieve(database_id=database_id)

# Extract and format the properties schema
schema = {
"title": database["title"][0]["plain_text"] if database.get("title") else "",
"properties": {}
}

for prop_name, prop_data in database["properties"].items():
prop_type = prop_data["type"]
prop_info = {
"type": prop_type,
"name": prop_name
}

# Add additional info for specific property types
if prop_type == "select":
prop_info["options"] = [
option["name"] for option in prop_data["select"]["options"]
]
elif prop_type == "multi_select":
prop_info["options"] = [
option["name"] for option in prop_data["multi_select"]["options"]
]

schema["properties"][prop_name] = prop_info

return schema

except Exception as e:
print(f"Error retrieving database: {str(e)}", file=sys.stderr)
sys.exit(1)

def main():
if len(sys.argv) != 2:
print("Usage: python get_database.py <database_id>", file=sys.stderr)
sys.exit(1)

database_id = sys.argv[1]
schema = get_database_schema(database_id)

# Pretty print the schema
print(json.dumps(schema, indent=2))

if __name__ == "__main__":
main()

0 comments on commit 7afec84

Please sign in to comment.