The command-line tool for creating and managing DBBasic apps: thin scripts over git, cp and sed.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-cli-new.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-cli-new.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-cli-new.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Prepare for PyPI publication 57213b9 1 year, 1 month ago History
cli.py · 7.2 KB · 241 lines
1#!/usr/bin/env python3
2"""
3dbbasic CLI - Unix-style tool wrapper
4
5Following the Unix philosophy:
61. Optional - Can use dbbasic without it
72. Simple - ~100 lines of code
83. Thin wrapper - Just automates Unix commands
94. Extensible - Modules can add commands
105. No magic - Everything is visible
11"""
12
13import sys
14import os
15import shutil
16import subprocess
17from pathlib import Path
18
19
20# Template locations
21TEMPLATES_REPO = "https://github.com/askrobots/dbbasic-examples"
22TEMPLATES_DIR = Path.home() / ".dbbasic" / "templates"
23
24
25def ensure_templates():
26 """Clone templates repo if not present"""
27 if not TEMPLATES_DIR.exists():
28 print("Downloading templates...")
29 subprocess.run([
30 'git', 'clone', TEMPLATES_REPO, str(TEMPLATES_DIR)
31 ])
32 print(f"Templates downloaded to {TEMPLATES_DIR}")
33
34
35def cmd_new(args):
36 """Create new app from template"""
37 if len(args) < 2:
38 print("Usage: dbbasic new <type> <name>")
39 print("\nAvailable templates:")
40 print(" blog - WordPress-like blog")
41 print(" microblog - Twitter-like social app")
42 print(" api - REST API")
43 print(" shop - E-commerce")
44 print(" intranet - Basecamp-like project manager")
45 print("\nRun 'dbbasic list' to see all templates")
46 return
47
48 template_type = args[0]
49 app_name = args[1]
50
51 ensure_templates()
52
53 template_path = TEMPLATES_DIR / template_type
54 if not template_path.exists():
55 print(f"Template '{template_type}' not found")
56 print("Run: dbbasic list")
57 return
58
59 # Copy template
60 print(f"Creating {app_name} from {template_type} template...")
61 try:
62 shutil.copytree(template_path, app_name)
63 except FileExistsError:
64 print(f"Error: Directory '{app_name}' already exists")
65 return
66
67 # Remove .git
68 git_dir = Path(app_name) / ".git"
69 if git_dir.exists():
70 shutil.rmtree(git_dir)
71
72 print(f"\n✓ Created {app_name}!")
73 print(f" cd {app_name}")
74 print(f" pip install -r requirements.txt")
75 print(f" python app.py")
76
77
78def cmd_list(args):
79 """List available templates"""
80 ensure_templates()
81
82 print("Available templates:\n")
83
84 # Define templates and descriptions (fallback if repo not available)
85 default_templates = {
86 "blog": "WordPress-like blog (~200 lines)",
87 "microblog": "Twitter-like social app (~300 lines)",
88 "api": "REST API (~150 lines)",
89 "shop": "E-commerce (~400 lines)",
90 "intranet": "Basecamp-like project manager (~500 lines)",
91 }
92
93 found_templates = False
94 if TEMPLATES_DIR.exists():
95 for template in sorted(TEMPLATES_DIR.iterdir()):
96 if template.is_dir() and not template.name.startswith('.'):
97 found_templates = True
98 readme = template / "README.md"
99 description = default_templates.get(template.name, "No description")
100 if readme.exists():
101 # Extract first line from README
102 first_line = readme.read_text().split('\n')[0].strip('# ')
103 if first_line:
104 description = first_line
105
106 print(f" {template.name:15} - {description}")
107
108 if not found_templates:
109 # Show default list
110 for name, desc in default_templates.items():
111 print(f" {name:15} - {desc}")
112
113 print("\nUsage: dbbasic new <type> <name>")
114
115
116def cmd_run(args):
117 """Run the app (optional, just 'python app.py' works too)"""
118 if Path('app.py').exists():
119 print("Starting app...")
120 subprocess.run(['python', 'app.py'] + args)
121 else:
122 print("No app.py found in current directory")
123
124
125def cmd_test(args):
126 """Run tests"""
127 if Path('tests').exists():
128 print("Running tests...")
129 subprocess.run(['pytest'] + args)
130 else:
131 print("No tests directory found")
132
133
134def discover_commands():
135 """
136 Discover commands from installed modules
137
138 Modules can provide CLI commands by including a cli.py with COMMANDS dict:
139
140 # dbbasic_queue/cli.py
141 def worker_command(args):
142 '''Run the queue worker'''
143 from .worker import process_jobs
144 print("Starting queue worker...")
145 while True:
146 process_jobs()
147
148 COMMANDS = {
149 'queue:worker': worker_command,
150 'queue:stats': stats_command,
151 }
152 """
153 import importlib
154 import pkg_resources
155
156 commands = {}
157
158 # Find all installed packages starting with dbbasic-
159 # Use pkg_resources to find installed distributions
160 try:
161 for dist in pkg_resources.working_set:
162 project_name = dist.project_name
163 if project_name.startswith('dbbasic-'):
164 # Convert package name to module name (dbbasic-queue -> dbbasic_queue)
165 module_name = project_name.replace('-', '_')
166 try:
167 # Try to import module.cli
168 module = importlib.import_module(f'{module_name}.cli')
169 if hasattr(module, 'COMMANDS'):
170 commands.update(module.COMMANDS)
171 except (ImportError, AttributeError):
172 pass # Module doesn't have CLI commands
173 except Exception:
174 # Fallback: try common module names
175 for module_name in ['dbbasic_queue', 'dbbasic_logs', 'dbbasic_accounts', 'dbbasic_web']:
176 try:
177 module = importlib.import_module(f'{module_name}.cli')
178 if hasattr(module, 'COMMANDS'):
179 commands.update(module.COMMANDS)
180 except (ImportError, AttributeError):
181 pass
182
183 return commands
184
185
186def print_help():
187 """Print help message"""
188 print("Usage: dbbasic <command> [args]")
189 print("\nCore commands:")
190 print(" new <type> <name> - Create new app from template")
191 print(" list - List available templates")
192 print(" run - Run the app")
193 print(" test - Run tests")
194
195 # Discover module commands
196 commands = discover_commands()
197 if commands:
198 print("\nModule commands:")
199 for name in sorted(commands.keys()):
200 cmd = commands[name]
201 doc = cmd.__doc__ or "No description"
202 # Get first line of docstring
203 doc_first_line = doc.strip().split('\n')[0]
204 print(f" {name:20} - {doc_first_line}")
205
206 print("\nRun 'dbbasic <command> --help' for command-specific help")
207
208
209def main():
210 """Main entry point"""
211 if len(sys.argv) < 2:
212 print_help()
213 return
214
215 command = sys.argv[1]
216 args = sys.argv[2:]
217
218 # Core commands
219 if command in ['help', '--help', '-h']:
220 print_help()
221 elif command == 'new':
222 cmd_new(args)
223 elif command == 'list':
224 cmd_list(args)
225 elif command == 'run':
226 cmd_run(args)
227 elif command == 'test':
228 cmd_test(args)
229 else:
230 # Try module commands
231 commands = discover_commands()
232 if command in commands:
233 commands[command](args)
234 else:
235 print(f"Unknown command: {command}")
236 print("Run 'dbbasic help' to see available commands")
237 sys.exit(1)
238
239
240if __name__ == '__main__':
241 main()