-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathomi.py
More file actions
executable file
·571 lines (472 loc) · 19.1 KB
/
omi.py
File metadata and controls
executable file
·571 lines (472 loc) · 19.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
#!/usr/bin/env python3
"""
Omi - Version Control for Python
Optimized Micro Index - Git-like commands with SQLite storage
"""
import sys
import os
import re
import sqlite3
import subprocess
import hashlib
import getpass
from datetime import datetime
from pathlib import Path
from io import BytesIO
# Try to import urllib3 for internal HTTP
try:
import urllib3
URLLIB3_AVAILABLE = True
except ImportError:
URLLIB3_AVAILABLE = False
class Settings:
"""Load and manage settings from settings.txt"""
@staticmethod
def load():
"""Load settings from settings.txt file"""
settings = {}
if not os.path.exists("../settings.txt"):
print("Error: settings.txt not found")
sys.exit(1)
with open("../settings.txt", "r") as f:
for line in f:
match = re.match(r"^([^=]+)=(.*)$", line.strip())
if match:
key, value = match.groups()
settings[key] = value
# Set defaults
settings["API_ENABLED"] = settings.get("API_ENABLED", "1")
settings["API_RATE_LIMIT"] = settings.get("API_RATE_LIMIT", "60")
settings["API_RATE_LIMIT_WINDOW"] = settings.get("API_RATE_LIMIT_WINDOW", "60")
return settings
class OmiRepository:
"""Manage Omi repository operations"""
def __init__(self, settings):
self.settings = settings
self.db_name = self._read_dotomi() or "repo.omi"
def _read_dotomi(self):
"""Read database name from .omi file"""
if os.path.exists(".omi"):
with open(".omi", "r") as f:
match = re.search(r'OMI_DB="([^"]+)"', f.read())
if match:
return match.group(1)
return None
def _write_dotomi(self, db_name):
"""Write database name to .omi file"""
with open(".omi", "w") as f:
f.write(f'OMI_DB="{db_name}"\n')
def init(self, db_name="repo.omi"):
"""Initialize a new repository"""
print("Initializing omi repository...")
self.db_name = db_name
self._write_dotomi(db_name)
# Create database and tables
conn = sqlite3.connect(db_name)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS blobs (
hash TEXT PRIMARY KEY,
data BLOB,
size INTEGER
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT,
hash TEXT,
datetime TEXT,
commit_id INTEGER,
FOREIGN KEY(commit_id) REFERENCES commits(id)
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS commits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
message TEXT,
datetime TEXT,
user TEXT
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS staging (
filename TEXT PRIMARY KEY,
hash TEXT,
datetime TEXT
)
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_files_hash ON files(hash)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_files_commit ON files(commit_id)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_blobs_hash ON blobs(hash)")
conn.commit()
conn.close()
print(f"Repository initialized: {db_name}")
def clone(self, url):
"""Clone a repository from local or remote source"""
print(f"Cloning from {url}...")
if os.path.isfile(url):
# Local clone
import shutil
shutil.copy(url, "repo.omi")
self._write_dotomi("repo.omi")
self.db_name = "repo.omi"
print("Cloned to repo.omi")
else:
# Remote clone
repo_name = os.path.basename(url) or "repo.omi"
print(f"Downloading {repo_name} from {self.settings['REPOS']}...")
cmd = [
self.settings["CURL"],
"-f", "-o", repo_name,
f"{self.settings['REPOS']}/?download={repo_name}"
]
if subprocess.run(cmd, capture_output=True).returncode == 0:
self._write_dotomi(repo_name)
self.db_name = repo_name
print(f"Cloned to {repo_name}")
else:
print("Error: Failed to clone from remote")
sys.exit(1)
def add_files(self, pattern="--all"):
"""Stage files for commit"""
print("Adding files to staging...")
if pattern == "--all":
# Add all files in current directory
for filename in os.listdir("."):
if (os.path.isfile(filename) and
filename != self.db_name and
filename != ".omi"):
self._add_one_file(filename)
else:
self._add_one_file(pattern)
def _add_one_file(self, filename):
"""Add a single file to staging"""
if not os.path.isfile(filename):
print(f"Error: File not found: {filename}")
return False
# Calculate SHA256 hash
sha256_hash = hashlib.sha256()
with open(filename, "rb") as f:
sha256_hash.update(f.read())
hash_value = sha256_hash.hexdigest()
# Get current datetime
datetime_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Add to staging
conn = sqlite3.connect(self.db_name)
cursor = conn.cursor()
cursor.execute(
"INSERT OR REPLACE INTO staging (filename, hash, datetime) VALUES (?, ?, ?)",
(filename, hash_value, datetime_str)
)
conn.commit()
conn.close()
print(f"Staged: {filename} (hash: {hash_value})")
return True
def commit(self, message="No message"):
"""Create a commit from staged files"""
print("Committing changes...")
datetime_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
user = os.getenv("USER", "unknown")
conn = sqlite3.connect(self.db_name)
cursor = conn.cursor()
# Create commit record
cursor.execute(
"INSERT INTO commits (message, datetime, user) VALUES (?, ?, ?)",
(message, datetime_str, user)
)
commit_id = cursor.lastrowid
# Get staged files
cursor.execute("SELECT filename, hash, datetime FROM staging")
staged_files = cursor.fetchall()
# Process each staged file
for filename, hash_value, file_datetime in staged_files:
self._commit_one_file(cursor, filename, hash_value, file_datetime, commit_id)
# Clear staging
cursor.execute("DELETE FROM staging")
conn.commit()
conn.close()
print(f"Committed successfully (commit #{commit_id})")
def _commit_one_file(self, cursor, filename, hash_value, file_datetime, commit_id):
"""Add a single file to a commit"""
# Check if blob exists (deduplication)
cursor.execute("SELECT COUNT(*) FROM blobs WHERE hash=?", (hash_value,))
blob_count = cursor.fetchone()[0]
if blob_count == 0:
# Store new blob
with open(filename, "rb") as f:
data = f.read()
cursor.execute(
"INSERT INTO blobs (hash, data, size) VALUES (?, ?, ?)",
(hash_value, data, len(data))
)
print(f" Stored new blob: {hash_value}")
else:
print(f" Blob already exists (deduplicated): {hash_value}")
# Add file record
cursor.execute(
"INSERT INTO files (filename, hash, datetime, commit_id) VALUES (?, ?, ?, ?)",
(filename, hash_value, file_datetime, commit_id)
)
def _http_post_multipart(self, url, fields):
"""Upload files using multipart form data (urllib3 if available, else curl)"""
use_internal = self.settings.get("USE_INTERNAL_HTTP", "1") == "1"
if use_internal and URLLIB3_AVAILABLE:
try:
http = urllib3.PoolManager()
response = http.request(
'POST',
url,
fields=fields,
timeout=float(self.settings.get("HTTP_TIMEOUT", "30"))
)
return response.status, response.data
except Exception as e:
print(f"Warning: Internal HTTP failed, falling back to curl: {e}")
return self._http_post_multipart_curl(url, fields)
else:
return self._http_post_multipart_curl(url, fields)
def _http_post_multipart_curl(self, url, fields):
"""Upload files using curl executable"""
cmd = [self.settings["CURL"], "-f", "-X", "POST"]
for key, value in fields.items():
if isinstance(value, tuple) and len(value) == 2:
# File upload
cmd.extend(["-F", f"{key}=@{value[1]}"])
else:
# Regular form field
cmd.extend(["-F", f"{key}={value}"])
cmd.append(url)
result = subprocess.run(cmd, capture_output=True)
return result.returncode, result.stdout
def push(self):
"""Upload repository to remote server"""
print(f"Pushing {self.db_name} to remote...")
if not os.path.isfile(self.db_name):
print(f"Error: Database file {self.db_name} not found")
sys.exit(1)
if self.settings["API_ENABLED"] == "0":
print("Error: API is disabled")
sys.exit(1)
otp_code = ""
if self._has_2fa_enabled():
otp_code = getpass.getpass("Enter OTP code (6 digits): ")
# Build form fields
fields = {
'username': self.settings['USERNAME'],
'password': self.settings['PASSWORD'],
'repo_name': self.db_name,
'repo_file': ('file', self.db_name),
'action': 'Upload'
}
if otp_code:
fields['otp_code'] = otp_code
# Use internal or external HTTP based on settings
use_internal = self.settings.get("USE_INTERNAL_HTTP", "1") == "1"
if use_internal and URLLIB3_AVAILABLE:
try:
status, response = self._http_post_multipart(
f"{self.settings['REPOS']}/",
fields
)
if status == 200:
print(f"Successfully pushed to {self.settings['REPOS']}")
else:
print(f"Error: Server returned status {status}")
sys.exit(1)
except Exception as e:
print(f"Error: Failed to push: {e}")
sys.exit(1)
else:
# Fall back to curl
cmd = [
self.settings["CURL"],
"-f", "-X", "POST",
"-F", f"username={self.settings['USERNAME']}",
"-F", f"password={self.settings['PASSWORD']}",
"-F", f"repo_name={self.db_name}",
"-F", f"repo_file=@{self.db_name}",
"-F", "action=Upload"
]
if otp_code:
cmd.extend(["-F", f"otp_code={otp_code}"])
cmd.append(f"{self.settings['REPOS']}/")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
print(f"Successfully pushed to {self.settings['REPOS']}")
else:
print("Error: Failed to push to remote")
if result.stderr:
print(result.stderr)
sys.exit(1)
def pull(self):
"""Download repository from remote server"""
print(f"Pulling {self.db_name} from remote...")
if self.settings["API_ENABLED"] == "0":
print("Error: API is disabled")
sys.exit(1)
otp_code = ""
if self._has_2fa_enabled():
otp_code = getpass.getpass("Enter OTP code (6 digits): ")
use_internal = self.settings.get("USE_INTERNAL_HTTP", "1") == "1"
if use_internal and URLLIB3_AVAILABLE:
try:
http = urllib3.PoolManager()
fields = {
'username': self.settings['USERNAME'],
'password': self.settings['PASSWORD'],
'repo_name': self.db_name,
'action': 'pull'
}
if otp_code:
fields['otp_code'] = otp_code
response = http.request(
'POST',
f"{self.settings['REPOS']}/",
fields=fields,
timeout=float(self.settings.get("HTTP_TIMEOUT", "30"))
)
if response.status == 200:
with open(self.db_name, "wb") as f:
f.write(response.data)
print(f"Successfully pulled from {self.settings['REPOS']}")
else:
print(f"Error: Server returned status {response.status}")
sys.exit(1)
except Exception as e:
print(f"Error: Failed to pull: {e}")
sys.exit(1)
else:
# Fall back to curl
cmd = [
self.settings["CURL"],
"-f", "-X", "POST",
"-d", f"username={self.settings['USERNAME']}",
"-d", f"password={self.settings['PASSWORD']}",
"-d", f"repo_name={self.db_name}",
"-d", "action=pull"
]
if otp_code:
cmd.extend(["-d", f"otp_code={otp_code}"])
cmd.append(f"{self.settings['REPOS']}/")
result = subprocess.run(cmd, capture_output=True)
if result.returncode == 0:
# Write downloaded repository
with open(self.db_name, "wb") as f:
f.write(result.stdout)
print(f"Successfully pulled from {self.settings['REPOS']}")
else:
print("Error: Failed to pull from remote")
if result.stderr:
print(result.stderr.decode())
sys.exit(1)
def list_repos(self):
"""List available repositories on remote server"""
print(f"=== Available Repositories on {self.settings['REPOS']} ===")
cmd = [
self.settings["CURL"],
"-s",
f"{self.settings['REPOS']}/?format=json"
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
# Extract repo names from JSON
for match in re.finditer(r'"name":"([^"]*)"', result.stdout):
print(match.group(1))
else:
print("Error: Failed to retrieve repository list")
sys.exit(1)
def show_status(self):
"""Show repository status"""
print("=== Staged Files ===")
self._execute_query("SELECT filename, datetime FROM staging")
print("")
print("=== Recent Commits ===")
self._execute_query("SELECT id, message, datetime FROM commits ORDER BY id DESC LIMIT 5")
print("")
print("=== Statistics ===")
result = self._execute_query("SELECT COUNT(*) FROM blobs", fetch_one=True)
print(f"Total blobs (deduplicated): {result[0] if result else 0}")
result = self._execute_query("SELECT COUNT(*) FROM files", fetch_one=True)
print(f"Total file versions: {result[0] if result else 0}")
def log_commits(self, limit=10):
"""Show commit history"""
print("=== Commit History ===")
query = f"SELECT id, datetime, user, message FROM commits ORDER BY id DESC LIMIT {limit}"
self._execute_query(query)
def _execute_query(self, query, fetch_one=False):
"""Execute a query and print results"""
conn = sqlite3.connect(self.db_name)
cursor = conn.cursor()
cursor.execute(query)
if fetch_one:
return cursor.fetchone()
rows = cursor.fetchall()
for row in rows:
print("|".join(str(col) for col in row))
conn.close()
def _has_2fa_enabled(self):
"""Check if user has 2FA enabled"""
if not os.path.isfile("users.txt"):
return False
username = self.settings.get("USERNAME", "")
with open("users.txt", "r") as f:
for line in f:
parts = line.strip().split(":")
if len(parts) >= 3 and parts[0] == username and parts[2]:
return True
return False
def main():
"""Main entry point"""
settings = Settings.load()
repo = OmiRepository(settings)
if len(sys.argv) < 2:
print("Usage: omi <command> [args]")
print("Commands: init, clone, add, commit, push, pull, list, log, status")
sys.exit(1)
cmd = sys.argv[1]
args = sys.argv[2:]
try:
if cmd == "init":
db_name = args[0] if args else "repo.omi"
repo.init(db_name)
elif cmd == "clone":
if not args:
print("Usage: omi clone <url>")
sys.exit(1)
repo.clone(args[0])
elif cmd == "add":
pattern = args[0] if args else "--all"
repo.add_files(pattern)
elif cmd == "commit":
message = "No message"
# Parse -m "message"
for i, arg in enumerate(args):
if arg == "-m" and i + 1 < len(args):
message = args[i + 1]
break
repo.commit(message)
elif cmd == "push":
repo.push()
elif cmd == "pull":
repo.pull()
elif cmd == "list":
repo.list_repos()
elif cmd == "log":
limit = int(args[0]) if args else 10
repo.log_commits(limit)
elif cmd == "status":
repo.show_status()
else:
print(f"Unknown command: {cmd}")
print("Usage: omi <command> [args]")
print("Commands: init, clone, add, commit, push, pull, list, log, status")
sys.exit(1)
except KeyboardInterrupt:
print("\nInterrupted by user")
sys.exit(1)
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()