-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupgit_app.py
More file actions
executable file
·437 lines (368 loc) · 19 KB
/
Copy pathupgit_app.py
File metadata and controls
executable file
·437 lines (368 loc) · 19 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
===============================================================================
UpGit — Master Terminal User Interface
Professioneller GitHub-Uploader & Repository-Manager
===============================================================================
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional
from textual import work
from textual.app import App, ComposeResult
from textual.containers import Container, Horizontal, Vertical
from textual.widgets import Button, DataTable, Footer, Header, Input, Label, Static
from core.auth import clear_token, detect_system_gh_token, get_saved_token, load_auth_config, save_token
from core.github_api import check_repo_exists, create_remote_repo, verify_token
from core.git_manager import configure_git_user, init_repository, is_git_installed, push_to_github, stage_and_commit
from core.scanner import scan_workspace
from core.i18n import t, toggle_language, get_language
from ui.screens.auth_screen import AuthScreen
from ui.screens.log_modal import LogModal
from ui.screens.upload_modal import UploadModal
from ui.theme import UPGIT_TCSS
class UpGitApp(App):
"""Hauptanwendung für UpGit TUI."""
TITLE = "UPGIT — GITHUB REPOSITORY UPLOADER"
SUB_TITLE = "Single-Login TUI Architecture │ CachyOS / Arch Edition"
CSS = UPGIT_TCSS
BINDINGS = [
("u", "upload_selected", "Hochladen / Upload"),
("r", "refresh_scan", "Aktualisieren / Refresh"),
("s", "sync_profile", "Sync Profil"),
("t", "open_auth", "Token / Login"),
("l", "toggle_lang", "🌐 DE/EN"),
("q", "quit", "Beenden / Quit"),
]
def __init__(self, initial_dir: Optional[Path] = None) -> None:
super().__init__()
# Standardmäßig übergeordnetes Verzeichnis scannen (wo alle Tools liegen)
self.current_dir = (initial_dir or Path(__file__).resolve().parent.parent).resolve()
self.token: Optional[str] = None
self.user_profile: Optional[Dict[str, Any]] = None
self.projects: List[Dict[str, Any]] = []
self.selected_project: Optional[Dict[str, Any]] = None
def compose(self) -> ComposeResult:
yield Header(show_clock=True)
# 1. Benutzerprofil-Leiste
with Horizontal(id="profile-bar"):
yield Static(t("status_checking"), id="profile-info")
with Horizontal(id="profile-actions"):
yield Button(t("btn_sync"), id="btn-sync-profile")
yield Button(t("btn_token"), id="btn-open-auth")
yield Button(t("btn_lang_toggle"), id="btn-lang-toggle", variant="warning")
yield Button(t("btn_logout"), id="btn-logout", classes="danger")
# 2. Verzeichnispfad-Leiste
with Horizontal(id="path-bar"):
yield Label(t("path_label"), id="lbl-path", classes="field-label")
yield Input(value=str(self.current_dir), id="path-input")
yield Button(t("btn_scan"), id="btn-scan-path", variant="primary")
yield Button(t("btn_up"), id="btn-path-up")
# 3. Hauptbereich (Tabelle & Detailansicht)
with Container(id="main-container"):
with Container(id="table-container"):
yield DataTable(id="projects-table", cursor_type="row")
with Container(id="sidebar"):
yield Static(t("details_title"), id="details-title")
yield Static(t("details_empty"), id="details-content")
with Vertical(id="action-buttons"):
yield Button(t("btn_upload"), id="btn-upload-action", classes="primary")
yield Footer()
def action_toggle_lang(self) -> None:
new_lang = toggle_language()
self.notify(f"Sprache / Language: {new_lang.upper()}", timeout=2.0)
self.query_one("#btn-lang-toggle", Button).label = t("btn_lang_toggle")
self.query_one("#btn-sync-profile", Button).label = t("btn_sync")
self.query_one("#btn-open-auth", Button).label = t("btn_token")
self.query_one("#btn-logout", Button).label = t("btn_logout")
self.query_one("#lbl-path", Label).update(t("path_label"))
self.query_one("#btn-scan-path", Button).label = t("btn_scan")
self.query_one("#btn-path-up", Button).label = t("btn_up")
self.query_one("#details-title", Static).update(t("details_title"))
self.query_one("#btn-upload-action", Button).label = t("btn_upload")
self.init_table_columns()
self.refresh_projects_table()
def init_table_columns(self) -> None:
table = self.query_one("#projects-table", DataTable)
table.clear(columns=True)
table.add_column(t("col_name"), key="name")
table.add_column(t("col_status"), key="status")
table.add_column(t("col_readme"), key="readme")
table.add_column(t("col_license"), key="license")
table.add_column(t("col_gitignore"), key="gitignore")
table.add_column(t("col_git"), key="git")
table.add_column(t("col_branch"), key="branch")
def on_mount(self) -> None:
"""Initialisiert die Tabelle und Authentifizierung beim Start."""
self.init_table_columns()
# Git-Prüfung
if not is_git_installed():
self.notify("Warnung: 'git' wurde nicht im Systempfad gefunden!", severity="error")
# Autonome Authentifizierung
self.init_authentication()
# Verzeichnis initial scannen
self.refresh_projects_table()
def init_authentication(self) -> None:
"""Prüft gespeicherte Tokens oder importiert sie automatisch."""
token = get_saved_token()
if not token:
# Versuch, aus systemweitem gh CLI zu laden
token = detect_system_gh_token()
if token:
self.notify("Token aus GitHub CLI (gh) erkannt und verknüpft.", severity="information")
if token:
self.token = token
self.run_profile_sync()
else:
self.update_profile_bar_logged_out()
@work(exclusive=True)
async def run_profile_sync(self) -> None:
"""Synchronisiert das Benutzerprofil im Hintergrund mit der GitHub API."""
if not self.token:
self.update_profile_bar_logged_out()
return
info_widget = self.query_one("#profile-info", Static)
info_widget.update("[yellow]Synchronisiere mit GitHub API...[/yellow]")
ok, profile, msg = verify_token(self.token)
if ok and profile:
self.user_profile = profile
save_token(self.token, profile)
self.update_profile_bar_logged_in(profile)
else:
info_widget.update(f"[red]Authentifizierungsfehler: {msg}[/red]")
self.user_profile = None
def update_profile_bar_logged_in(self, profile: Dict[str, Any]) -> None:
"""Aktualisiert die Profilanzeige für angemeldete Benutzer."""
login = profile.get("login", "Unbekannt")
name = profile.get("name") or login
pub = profile.get("public_repos", 0)
priv = profile.get("total_private_repos", 0)
rate = profile.get("rate_limit_remaining", "?")
text = (
f"[bold green]● Verbunden:[/bold green] [bold white]@{login}[/bold white] ({name}) │ "
f"[cyan]Repos:[/cyan] {pub} öffentlich / {priv} privat │ "
f"[dim]API-Kontingent: {rate}[/dim]"
)
self.query_one("#profile-info", Static).update(text)
def update_profile_bar_logged_out(self) -> None:
"""Aktualisiert die Profilanzeige für nicht angemeldete Benutzer."""
text = "[bold red]○ Nicht angemeldet[/bold red] │ [dim]Klicke auf [bold cyan]'🔑 Token'[/bold cyan] zum Anmelden[/dim]"
self.query_one("#profile-info", Static).update(text)
def refresh_projects_table(self) -> None:
"""Liest das Verzeichnis neu ein und füllt die DataTable."""
table = self.query_one("#projects-table", DataTable)
table.clear()
self.projects = scan_workspace(self.current_dir)
self.query_one("#path-input", Input).value = str(self.current_dir)
if not self.projects:
self.query_one("#details-content", Static).update(
f"[yellow]Keine Projekt-Unterordner in '{self.current_dir}' gefunden.[/yellow]"
)
return
for p in self.projects:
# Status-Formatierung
tag = p["status_tag"]
if tag in ("Bereit", "Neu (Git bereit)"):
status_markup = f"[bold green]{tag}[/bold green]"
elif tag == "Remote aktiv":
status_markup = f"[bold cyan]{tag}[/bold cyan]"
else:
status_markup = f"[yellow]{tag}[/yellow]"
readme_str = "[green]✔ Ja[/green]" if p["has_readme"] else "[red]✖ Nein[/red]"
license_str = "[green]✔ Ja[/green]" if p["has_license"] else "[yellow]✖ Nein[/yellow]"
gitignore_str = "[green]✔ Ja[/green]" if p["has_gitignore"] else "[yellow]✖ Nein[/yellow]"
git_str = "[green]✔ Git[/green]" if p["has_git"] else "[dim]✖ Kein Git[/dim]"
table.add_row(
p["name"],
status_markup,
readme_str,
license_str,
gitignore_str,
git_str,
p["branch"] or "-",
key=p["name"],
)
# Erstes Projekt fokussieren
if self.projects:
self.select_project(self.projects[0])
def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
"""Wird ausgelöst, wenn eine Zeile ausgewählt/geklickt wird."""
row_key = event.row_key.value
for p in self.projects:
if p["name"] == row_key:
self.select_project(p)
break
def on_data_table_row_highlighted(self, event: DataTable.RowHighlighted) -> None:
"""Aktualisiert die Sidebar bei Navigation mit Cursortasten."""
if event.row_key:
row_key = event.row_key.value
for p in self.projects:
if p["name"] == row_key:
self.select_project(p)
break
def select_project(self, project: Dict[str, Any]) -> None:
"""Zeigt detaillierte Metadaten des gewählten Projekts in der Sidebar an."""
self.selected_project = project
details = self.query_one("#details-content", Static)
desc = project.get("description") or "[dim italic]Keine Beschreibung in README gefunden.[/dim italic]"
remote_info = project.get("remote_url") or "[dim]Keine Remote-URL konfiguriert[/dim]"
txt = (
f"[bold cyan]{project['name']}[/bold cyan]\n"
f"[dim]{project['path']}[/dim]\n\n"
f"[bold white]Beschreibung:[/bold white]\n{desc}\n\n"
f"[bold white]Prüfliste für GitHub:[/bold white]\n"
f" • README: {('[green]Vorhanden[/green]' if project['has_readme'] else '[red]Fehlt[/red]')}\n"
f" • Lizenz (LICENSE): {('[green]Vorhanden[/green]' if project['has_license'] else '[yellow]Fehlt (Empfohlen)[/yellow]')}\n"
f" • .gitignore: {('[green]Vorhanden[/green]' if project['has_gitignore'] else '[yellow]Fehlt (Empfohlen)[/yellow]')}\n"
f" • Lokales Git-Repo: {('[green]Initialisiert[/green]' if project['has_git'] else '[cyan]Wird automatisch initialisiert[/cyan]')}\n"
f" • Branch: [cyan]{project['branch']}[/cyan]\n"
f" • Ungesicherte Änderungen: [yellow]{project['uncommitted']}[/yellow]\n"
f" • Lokale Commits: [cyan]{project['commits']}[/cyan]\n\n"
f"[bold white]Remote Origin:[/bold white]\n{remote_info}\n"
)
details.update(txt)
def on_button_pressed(self, event: Button.Pressed) -> None:
"""Zentraler Button-Handler."""
btn_id = event.button.id
if btn_id == "btn-sync-profile":
self.action_sync_profile()
elif btn_id == "btn-open-auth":
self.action_open_auth()
elif btn_id == "btn-logout":
clear_token()
self.token = None
self.user_profile = None
self.update_profile_bar_logged_out()
self.notify("Erfolgreich abgemeldet.", severity="information")
elif btn_id == "btn-scan-path":
self.handle_path_change()
elif btn_id == "btn-path-up":
parent = self.current_dir.parent
if parent != self.current_dir:
self.current_dir = parent
self.refresh_projects_table()
elif btn_id == "btn-upload-action":
self.action_upload_selected()
def handle_path_change(self) -> None:
"""Übernimmt den Pfad aus dem Eingabefeld."""
input_path = self.query_one("#path-input", Input).value.strip()
p = Path(input_path).expanduser().resolve()
if p.is_dir():
self.current_dir = p
self.refresh_projects_table()
else:
self.notify(f"Verzeichnis existiert nicht: {p}", severity="error")
def action_upload_selected(self) -> None:
"""Startet den Upload-Dialog für das gewählte Projekt."""
if not self.selected_project:
self.notify("Bitte wähle zuerst ein Projekt aus der Liste aus.", severity="warning")
return
if not self.token or not self.user_profile:
self.notify("Bitte melde dich zuerst mit deinem GitHub Token an.", severity="warning")
self.action_open_auth(next_action_upload=True)
return
owner = self.user_profile.get("login", "")
self.push_screen(UploadModal(self.selected_project, owner), self.on_upload_modal_closed)
def on_upload_modal_closed(self, result: Optional[Dict[str, Any]]) -> None:
"""Wird aufgerufen, wenn der Benutzer die Upload-Parameter bestätigt hat."""
if not result:
return
def _open_log_screen() -> None:
log_screen = LogModal(title=f"Upload: {result['repo_name']}")
self.push_screen(log_screen)
self.execute_upload_workflow(result, log_screen)
self.call_later(_open_log_screen)
@work(thread=True)
def execute_upload_workflow(self, config: Dict[str, Any], log_modal: LogModal) -> None:
"""Führt alle Git- und GitHub-Schritte strukturiert im Hintergrund aus."""
project = config["project"]
project_path: Path = project["path"]
repo_name: str = config["repo_name"]
description: str = config["description"]
is_private: bool = config["private"]
branch: str = config["branch"]
commit_msg: str = config["commit_message"]
token: str = self.token or ""
owner: str = self.user_profile.get("login", "") if self.user_profile else ""
def log(msg: str) -> None:
self.call_from_thread(log_modal.log_line, msg)
log(f"[bold cyan]▶ Starte Upload-Prozess für '{repo_name}'[/bold cyan]")
log(f" • Lokaler Pfad: {project_path}")
log(f" • Ziel-Account: @{owner}")
log(f" • Sichtbarkeit: {'Privat (Private)' if is_private else 'Öffentlich (Public)'}")
log(f" • Branch: {branch}\n")
# 1. GitHub Remote-Repo prüfen oder erstellen
log("[cyan][1/5] Prüfe GitHub Remote-Repository...[/cyan]")
exists = check_repo_exists(token, owner, repo_name)
if exists:
log(f"[yellow] • Repository 'https://github.com/{owner}/{repo_name}' existiert bereits auf GitHub.[/yellow]")
else:
log(" • Erstelle neues Repository via GitHub REST API...")
ok, repo_data, api_msg = create_remote_repo(token, repo_name, description, is_private)
if not ok:
log(f"[bold red]✖ {api_msg}[/bold red]")
self.call_from_thread(log_modal.finish_log, False, api_msg)
return
log(f"[green] • {api_msg}[/green]")
# 2. Lokales Git-Repository initialisieren
log("\n[cyan][2/5] Prüfe lokales Git-Repository...[/cyan]")
if not project_path.joinpath(".git").is_dir():
log(" • Initialisiere lokales Git-Repo...")
ok, init_msg = init_repository(project_path, default_branch=branch)
if not ok:
log(f"[bold red]✖ {init_msg}[/bold red]")
self.call_from_thread(log_modal.finish_log, False, init_msg)
return
log(f"[green] • {init_msg}[/green]")
else:
log(f"[green] • Lokales Git-Repository bereits aktiv (Branch: {branch}).[/green]")
# 3. Git-Benutzer konfigurieren
log("\n[cyan][3/5] Prüfe Git User-Konfiguration...[/cyan]")
configure_git_user(project_path, username=owner)
log(f"[green] • Git-Committer auf '{owner}' konfiguriert.[/green]")
# 4. Dateien stagen & committen
log("\n[cyan][4/5] Stage & Commit (git add / commit)...[/cyan]")
ok, commit_res = stage_and_commit(project_path, message=commit_msg)
if not ok:
log(f"[bold red]✖ {commit_res}[/bold red]")
self.call_from_thread(log_modal.finish_log, False, commit_res)
return
log(f"[green] • {commit_res}[/green]")
# 5. Push zu GitHub
log(f"\n[cyan][5/5] Übertrage Daten nach GitHub (git push origin {branch})...[/cyan]")
ok, push_res = push_to_github(project_path, token, owner, repo_name, branch=branch)
if not ok:
log(f"[bold red]✖ {push_res}[/bold red]")
self.call_from_thread(log_modal.finish_log, False, push_res)
return
target_url = f"https://github.com/{owner}/{repo_name}"
log(f"[bold green]✔ {push_res}[/bold green]")
log(f"\n[bold white]🌐 Online erreichbar unter:[/bold white] [underline cyan]{target_url}[/underline cyan]")
self.call_from_thread(log_modal.finish_log, True, f"Repository erfolgreich veröffentlicht: {target_url}")
self.call_from_thread(self.refresh_projects_table)
def action_refresh_scan(self) -> None:
"""Aktualisiert die Projektliste."""
self.refresh_projects_table()
self.notify("Projektliste aktualisiert.", severity="information")
def action_sync_profile(self) -> None:
"""Erzwingt Profil-Synchronisation."""
self.run_profile_sync()
self.notify("Profil-Synchronisation angestoßen...", severity="information")
def action_open_auth(self, next_action_upload: bool = False) -> None:
"""Öffnet das Authentifizierungs-Modal."""
def handle_auth_result(success: bool) -> None:
if success:
self.token = get_saved_token()
self.run_profile_sync()
self.notify("Erfolgreich mit GitHub verbunden!", severity="information")
if next_action_upload:
self.action_upload_selected()
self.push_screen(AuthScreen(current_token=self.token or ""), handle_auth_result)
def main() -> None:
app = UpGitApp()
app.run()
if __name__ == "__main__":
main()