mirror of
https://github.com/Alex38Lyon/Synthese-PSM_LARRA.git
synced 2026-11-29 19:58:36 +00:00
pyDatatoMergin
This commit is contained in:
1 parent
93c884fba4
commit
8096831b70
10 files changed
+800
-1
No files matched your search
@@ -0,0 +1,19 @@
|
||||
"""#####################################################################################################################################
|
||||
# #
|
||||
# Variables globales de pyDatatoMergin.py #
|
||||
# #
|
||||
#####################################################################################################################################"""
|
||||
|
||||
Version = "2026 10 12"
|
||||
|
||||
Inputs_folder = "D:/08_GitHub/Synthese-PSM_LARRA/Outputs/SHP/QGis_GPKG_Files"
|
||||
Output_log = "./pyDatatoMergin.log"
|
||||
Temp_folder = "Temp_mergin"
|
||||
Debug_log = False
|
||||
Dest_project = "mergin/ARR" # mergin/Synthese_Folly-Puaire-Criou" # "mergin/LAKORA" # "mergin/ARR"
|
||||
Dest_folder = "Tests"
|
||||
Mergin_url = "https://mergin.arsip.fr"
|
||||
|
||||
Github_repo = "Alex38Lyon/Synthese-PSM_LARRA"
|
||||
Github_branch = "main"
|
||||
Github_path = "Outputs/SHP/QGis_GPKG_Files/areas2dMasked.gpkg" # sous-dossier du dépôt contenant les .gpkg
|
||||
@@ -0,0 +1,184 @@
|
||||
"""
|
||||
#############################################################################################
|
||||
Librairies générales pour pyDatatoMergin.py
|
||||
#############################################################################################
|
||||
"""
|
||||
|
||||
import logging, sys, re, hashlib # noqa: I001
|
||||
|
||||
logger = logging.getLogger("Logger")
|
||||
|
||||
#################################################################################################
|
||||
# Couleurs ANSI par niveau de log
|
||||
#################################################################################################
|
||||
COLOR_CODES = {
|
||||
logging.DEBUG: "\033[94m", # Bleu
|
||||
logging.INFO: "\033[92m", # Vert
|
||||
logging.WARNING: "\033[95m", # MAGENTA
|
||||
logging.ERROR: "\033[91m", # Rouge
|
||||
logging.CRITICAL: "\033[1;91m", # Rouge vif
|
||||
}
|
||||
|
||||
RESET = "\033[0m"
|
||||
|
||||
|
||||
#################################################################################################
|
||||
# Coloration des messages d'aide d'arg #
|
||||
#################################################################################################
|
||||
def colored_help(parser):
|
||||
"""
|
||||
Affiche l'aide colorée pour les arguments de la ligne de commande.
|
||||
|
||||
Args:
|
||||
parser (argparse.ArgumentParser): Le parseur d'arguments.
|
||||
Returns:
|
||||
None
|
||||
|
||||
"""
|
||||
# Captures the help output
|
||||
help_text = parser.format_help()
|
||||
|
||||
# Coloration des différentes parties
|
||||
colored_help_text = (
|
||||
help_text.replace("usage:", f"{Colors.ERROR}Usage:{Colors.ENDC}")
|
||||
.replace("options:", f"{Colors.GREEN}options:{Colors.ENDC}")
|
||||
.replace(", --help", f"{Colors.BLUE}, --help:{Colors.ENDC}")
|
||||
.replace("elp:", f"{Colors.BLUE}elp{Colors.ENDC}")
|
||||
.replace("show this help message and exit", f"Voir ce message et terminer")
|
||||
)
|
||||
|
||||
# Surligner les arguments
|
||||
for action in parser._actions:
|
||||
if action.option_strings:
|
||||
# Colorer les options (--xyz)
|
||||
for opt in action.option_strings:
|
||||
colored_help_text = (
|
||||
colored_help_text.replace(opt, f"{Colors.BLUE}{opt}{Colors.ENDC}")
|
||||
.replace("--help", f"{Colors.BLUE}--help:{Colors.ENDC}")
|
||||
.replace("python", f"{Colors.BLUE}python{Colors.ENDC}")
|
||||
)
|
||||
|
||||
# Imprimer le texte coloré
|
||||
print(colored_help_text)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
#################################################################################################
|
||||
# Codes de couleur ANSI
|
||||
#################################################################################################
|
||||
class Colors:
|
||||
BLACK = "\033[90m"
|
||||
RED = "\033[91m"
|
||||
GREEN = "\033[92m"
|
||||
YELLOW = "\033[93m"
|
||||
BLUE = "\033[94m"
|
||||
MAGENTA = "\033[95m"
|
||||
CYAN = "\033[96m"
|
||||
WHITE = "\033[97m"
|
||||
TITRE = "\033[30m\033[42m"
|
||||
TITRE_2 = "\033[37m\033[42m"
|
||||
|
||||
ERROR = "\033[91m"
|
||||
WARNING = "\033[95m"
|
||||
HEADER = "\033[96m"
|
||||
DEBUG = "\033[94m" # Bleu
|
||||
INFO = "\033[92m" # Vert
|
||||
CRITICAL = "\033[1;91m" # Rouge vif
|
||||
|
||||
ENDC = "\033[0m"
|
||||
BOLD = "\033[1m"
|
||||
UNDERLINE = "\033[4m"
|
||||
|
||||
|
||||
#################################################################################################
|
||||
# Formatter pour la console avec couleurs
|
||||
#################################################################################################
|
||||
class ConsoleFormatter(logging.Formatter):
|
||||
def format(self, record):
|
||||
color = COLOR_CODES.get(record.levelno, "")
|
||||
message = super().format(record)
|
||||
return f"{color}{message}{RESET}"
|
||||
|
||||
|
||||
#################################################################################################
|
||||
# Supprime les codes ANSI (pour l'écriture dans les fichiers)
|
||||
#################################################################################################
|
||||
def strip_ansi_codes(text):
|
||||
ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
|
||||
return ansi_escape.sub("", text)
|
||||
|
||||
|
||||
#################################################################################################
|
||||
# Formatter pour le fichier avec "!!!" sur les erreurs
|
||||
#################################################################################################
|
||||
class FileFormatter(logging.Formatter):
|
||||
def format(self, record):
|
||||
clean_msg = strip_ansi_codes(record.getMessage())
|
||||
prefix = "!!! " if record.levelno >= logging.ERROR else ""
|
||||
record_copy = logging.LogRecord(
|
||||
name=record.name,
|
||||
level=record.levelno,
|
||||
pathname=record.pathname,
|
||||
lineno=record.lineno,
|
||||
msg=f"{prefix}{clean_msg}",
|
||||
args=(),
|
||||
exc_info=record.exc_info,
|
||||
func=record.funcName,
|
||||
sinfo=record.stack_info,
|
||||
)
|
||||
return super().format(record_copy)
|
||||
|
||||
|
||||
#################################################################################################
|
||||
# Fonction de configuration du logger
|
||||
#################################################################################################
|
||||
def setup_logger(logfile="app.log", debug_log=False):
|
||||
logger = logging.getLogger("Logger")
|
||||
logger.setLevel(logging.DEBUG)
|
||||
logger.handlers.clear()
|
||||
|
||||
min_level = logging.DEBUG if debug_log else logging.INFO
|
||||
|
||||
# Console stderr handler — affichage à l'écran avec couleurs
|
||||
stderr_handler = logging.StreamHandler(sys.stderr)
|
||||
stderr_handler.setLevel(min_level)
|
||||
stderr_formatter = ConsoleFormatter("%(levelname)s: %(message)s") # <-- Ta classe personnalisée
|
||||
stderr_handler.setFormatter(stderr_formatter)
|
||||
logger.addHandler(stderr_handler)
|
||||
|
||||
# File handler — fichier de log
|
||||
file_handler = logging.FileHandler(logfile, encoding="utf-8")
|
||||
file_handler.setLevel(min_level)
|
||||
file_formatter = FileFormatter("%(asctime)s - %(levelname)s - %(message)s") # <-- Ta classe personnalisée
|
||||
file_handler.setFormatter(file_formatter)
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
return logger
|
||||
|
||||
|
||||
#################################################################################################
|
||||
def release_log_file(logger):
|
||||
handlers = logger.handlers[:]
|
||||
for handler in handlers:
|
||||
if isinstance(handler, logging.FileHandler):
|
||||
handler.close()
|
||||
logger.removeHandler(handler)
|
||||
|
||||
|
||||
################################################################################################
|
||||
def get_sha256(file_path):
|
||||
"""Calcule le hash SHA-256 d'un fichier.
|
||||
|
||||
Args:
|
||||
file_path (str): Le chemin vers le fichier.
|
||||
|
||||
Returns:
|
||||
str: Le hash SHA-256 du fichier.
|
||||
"""
|
||||
|
||||
sha256 = hashlib.sha256()
|
||||
with open(file_path, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(4096), b""):
|
||||
sha256.update(chunk)
|
||||
|
||||
return sha256.hexdigest()
|
||||
@@ -0,0 +1,13 @@
|
||||
pyDatatoMergin.py
|
||||
=================
|
||||
|
||||
** Création de l’environnement virtuel **
|
||||
py -3.13 -m venv "D:\08_GitHub\.venv"
|
||||
|
||||
** Activer l’environnement virtuel (Powershell) **
|
||||
. "D:\08_GitHub\.venv\Scripts\Activate.ps1"
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"folders": [
|
||||
{
|
||||
"path": "."
|
||||
}
|
||||
],
|
||||
"settings": {
|
||||
"python-envs.defaultEnvManager": "ms-python.python:system"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
2026-10-14 15:29:53,697 - INFO - ═══════════════════════════════════════════════════════════════════════════════════════════════
|
||||
2026-10-14 15:29:53,698 - INFO - INFORMATIONS DU PROJET MERGIN MAPS
|
||||
2026-10-14 15:29:53,698 - INFO - ═══════════════════════════════════════════════════════════════════════════════════════════════
|
||||
2026-10-14 15:29:53,868 - INFO - Projet : ARR
|
||||
2026-10-14 15:29:53,869 - INFO - Identifiant : 1707d35a-d99f-47a9-a714-519d7d9c147e
|
||||
2026-10-14 15:29:53,870 - INFO - Version : v17
|
||||
2026-10-14 15:29:53,870 - INFO - Créé le : 2026-08-19T09:31:30Z
|
||||
2026-10-14 15:29:53,870 - INFO - Mis à jour : 2026-10-14T08:39:10Z
|
||||
2026-10-14 15:29:53,870 - INFO - Taille totale : 128415971 Octets
|
||||
2026-10-14 15:29:53,871 - INFO - Public : True
|
||||
2026-10-14 15:29:53,871 - INFO - Nbre de fichiers : 14
|
||||
2026-10-14 15:29:53,871 - INFO - Taille totale : 122.47 Mo
|
||||
2026-10-14 15:29:53,872 - INFO - ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
2026-10-14 15:29:53,872 - INFO - 20260819_115533.jpeg 2.632 Mo
|
||||
2026-10-14 15:29:53,872 - INFO - ARR.gpkg 93.309 Mo
|
||||
2026-10-14 15:29:53,872 - INFO - ARR.qgs 0.713 Mo
|
||||
2026-10-14 15:29:53,873 - INFO - ARR_attachments.zip 0.002 Mo
|
||||
2026-10-14 15:29:53,873 - INFO - Inventaire Cavités.gpkg 0.660 Mo
|
||||
2026-10-14 15:29:53,873 - INFO - JPEG_20260819_113638_3152669861975410066.jpg 3.024 Mo
|
||||
2026-10-14 15:29:53,873 - INFO - JPEG_20260819_113919_5886287470656202827.jpg 3.034 Mo
|
||||
2026-10-14 15:29:53,874 - INFO - JPEG_20260819_121951_8365685850227103103.jpg 2.974 Mo
|
||||
2026-10-14 15:29:53,874 - INFO - JPEG_20260819_122929_1446792337025110147.jpg 3.007 Mo
|
||||
2026-10-14 15:29:53,874 - INFO - JPEG_20260819_123117_33265926990508961.jpg 2.516 Mo
|
||||
2026-10-14 15:29:53,875 - INFO - JPEG_20260819_124915_3186813976814177670.jpg 2.899 Mo
|
||||
2026-10-14 15:29:53,875 - INFO - JPEG_20260819_125124_7007318829424129864.jpg 3.165 Mo
|
||||
2026-10-14 15:29:53,875 - INFO - Tests/areas2dMasked.gpkg 4.531 Mo
|
||||
2026-10-14 15:29:53,875 - INFO - karstpro_etude.json 0.001 Mo
|
||||
2026-10-14 15:29:53,875 - INFO - ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
2026-10-14 15:29:53,876 - INFO - ═══════════════════════════════════════════════════════════════════════════════════════════════
|
||||
2026-10-14 15:29:53,876 - INFO - Envoi des données GitHub vers Mergin Maps
|
||||
2026-10-14 15:29:53,876 - INFO - ═══════════════════════════════════════════════════════════════════════════════════════════════
|
||||
2026-10-14 15:29:53,878 - INFO - [1/5] Téléchargement desfichiers depuis le GitHub : Alex38Lyon/Synthese-PSM_LARRA@main:Outputs/SHP/QGis_GPKG_Files/areas2dMasked.gpkg
|
||||
2026-10-14 15:29:55,701 - INFO - [2/5] Synchronisation du projet local existant : C:\Users\alexa\Desktop\pyDatatoMergin\Temp_mergin\Projet
|
||||
2026-10-14 15:29:56,655 - INFO - [3/5] Copie des fichiers C:\Users\alexa\Desktop\pyDatatoMergin\Temp_mergin\Github\areas2dMasked.gpkg
|
||||
2026-10-14 15:29:56,663 - INFO - + Tests\areas2dMasked.gpkg
|
||||
2026-10-14 15:29:56,664 - INFO - [4/5] Push vers Mergin Maps...
|
||||
2026-10-14 15:29:57,050 - WARNING - Aucune modification à envoyer.
|
||||
2026-10-14 15:29:57,050 - INFO - [5/5] Push terminé. Nettoyage...
|
||||
2026-10-14 15:29:57,053 - INFO - Envoi terminé avec succès.
|
||||
2026-10-14 15:29:57,053 - INFO - ═══════════════════════════════════════════════════════════════════════════════════════════════
|
||||
2026-10-14 15:29:57,053 - INFO - INFORMATIONS DU PROJET MERGIN MAPS
|
||||
2026-10-14 15:29:57,053 - INFO - ═══════════════════════════════════════════════════════════════════════════════════════════════
|
||||
2026-10-14 15:29:57,225 - INFO - Projet : ARR
|
||||
2026-10-14 15:29:57,225 - INFO - Identifiant : 1707d35a-d99f-47a9-a714-519d7d9c147e
|
||||
2026-10-14 15:29:57,225 - INFO - Version : v17
|
||||
2026-10-14 15:29:57,225 - INFO - Créé le : 2026-08-19T09:31:30Z
|
||||
2026-10-14 15:29:57,226 - INFO - Mis à jour : 2026-10-14T08:39:10Z
|
||||
2026-10-14 15:29:57,226 - INFO - Taille totale : 128415971 Octets
|
||||
2026-10-14 15:29:57,226 - INFO - Public : True
|
||||
2026-10-14 15:29:57,226 - INFO - Nbre de fichiers : 14
|
||||
2026-10-14 15:29:57,227 - INFO - Taille totale : 122.47 Mo
|
||||
2026-10-14 15:29:57,227 - INFO - ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
2026-10-14 15:29:57,227 - INFO - 20260819_115533.jpeg 2.632 Mo
|
||||
2026-10-14 15:29:57,227 - INFO - ARR.gpkg 93.309 Mo
|
||||
2026-10-14 15:29:57,228 - INFO - ARR.qgs 0.713 Mo
|
||||
2026-10-14 15:29:57,228 - INFO - ARR_attachments.zip 0.002 Mo
|
||||
2026-10-14 15:29:57,228 - INFO - Inventaire Cavités.gpkg 0.660 Mo
|
||||
2026-10-14 15:29:57,228 - INFO - JPEG_20260819_113638_3152669861975410066.jpg 3.024 Mo
|
||||
2026-10-14 15:29:57,228 - INFO - JPEG_20260819_113919_5886287470656202827.jpg 3.034 Mo
|
||||
2026-10-14 15:29:57,228 - INFO - JPEG_20260819_121951_8365685850227103103.jpg 2.974 Mo
|
||||
2026-10-14 15:29:57,228 - INFO - JPEG_20260819_122929_1446792337025110147.jpg 3.007 Mo
|
||||
2026-10-14 15:29:57,229 - INFO - JPEG_20260819_123117_33265926990508961.jpg 2.516 Mo
|
||||
2026-10-14 15:29:57,229 - INFO - JPEG_20260819_124915_3186813976814177670.jpg 2.899 Mo
|
||||
2026-10-14 15:29:57,229 - INFO - JPEG_20260819_125124_7007318829424129864.jpg 3.165 Mo
|
||||
2026-10-14 15:29:57,229 - INFO - Tests/areas2dMasked.gpkg 4.531 Mo
|
||||
2026-10-14 15:29:57,230 - INFO - karstpro_etude.json 0.001 Mo
|
||||
2026-10-14 15:29:57,230 - INFO - ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
@@ -0,0 +1,481 @@
|
||||
#!/usr/bin/env python3
|
||||
"""#####################################################################################################################################
|
||||
# #
|
||||
# #
|
||||
#####################################################################################################################################"""
|
||||
|
||||
import argparse, shutil, os, sys, subprocess, time, logging # noqa: I001
|
||||
import requests
|
||||
from urllib.parse import quote
|
||||
from pathlib import Path
|
||||
from dotenv import load_dotenv
|
||||
from alive_progress import alive_bar
|
||||
|
||||
from mergin import MerginClient
|
||||
from mergin.client_pull import download_project_async, download_project_is_running, download_project_finalize
|
||||
from mergin.client_push import push_project_async, push_project_is_running, push_project_finalize
|
||||
|
||||
from Lib.Librairies import setup_logger, Colors
|
||||
from Lib import GlobalData
|
||||
|
||||
GITHUB_API = "https://api.github.com"
|
||||
|
||||
|
||||
############################################################################################################################################
|
||||
def suivre_transfert(job, verifier, titre: str) -> None:
|
||||
"""Affiche la progression et le débit d'un transfert Mergin Maps."""
|
||||
|
||||
taille_totale = job.total_size
|
||||
|
||||
if taille_totale <= 0:
|
||||
while verifier(job):
|
||||
time.sleep(0.2)
|
||||
return
|
||||
|
||||
precedent = 0
|
||||
|
||||
with alive_bar(taille_totale, title=f"{Colors.YELLOW}{titre}{Colors.ENDC}", stats=True, dual_line=True, scale="SI", unit="o") as barre:
|
||||
while verifier(job):
|
||||
actuel = job.transferred_size
|
||||
delta = actuel - precedent
|
||||
|
||||
if delta > 0:
|
||||
barre(delta)
|
||||
precedent = actuel
|
||||
|
||||
time.sleep(0.2)
|
||||
|
||||
# Comptabilise les derniers octets transférés.
|
||||
actuel = job.transferred_size
|
||||
delta = actuel - precedent
|
||||
|
||||
if delta > 0:
|
||||
barre(delta)
|
||||
|
||||
|
||||
############################################################################################################################################
|
||||
def telecharger_avec_progression(client: MerginClient, projet: str, dossier: Path) -> None:
|
||||
"""Télécharge un projet Mergin Maps avec suivi de progression."""
|
||||
|
||||
job = download_project_async(client, projet, str(dossier))
|
||||
suivre_transfert(job, download_project_is_running, "Téléchargement")
|
||||
download_project_finalize(job)
|
||||
|
||||
|
||||
############################################################################################################################################
|
||||
def envoyer_avec_progression(client: MerginClient, dossier: Path) -> None:
|
||||
"""Envoie les modifications vers Mergin Maps avec suivi."""
|
||||
|
||||
job = push_project_async(client, str(dossier))
|
||||
if job is None:
|
||||
logger.warning("Aucune modification à envoyer.")
|
||||
return
|
||||
suivre_transfert(job, push_project_is_running, "Envoi vers Mergin")
|
||||
push_project_finalize(job)
|
||||
|
||||
|
||||
############################################################################################################################################
|
||||
def supprimer_dossier_temporaire(dossier: Path, tentatives: int = 5) -> bool:
|
||||
"""Supprime un dossier temporaire en réessayant si un fichier est verrouillé."""
|
||||
|
||||
for tentative in range(tentatives):
|
||||
try:
|
||||
shutil.rmtree(dossier)
|
||||
logger.info(f"Dossier temporaire supprimé : {Colors.ENDC}{dossier}")
|
||||
return True
|
||||
|
||||
except PermissionError as erreur:
|
||||
if tentative == tentatives - 1:
|
||||
logger.warning(f"Suppression impossible, dossier conservé : {Colors.ENDC}{dossier}{Colors.WARNING},{Colors.ENDC}{erreur}")
|
||||
return False
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
############################################################################################################################################
|
||||
def fermer_journaux_mergin() -> None:
|
||||
"""Ferme les gestionnaires de fichiers de journalisation Mergin."""
|
||||
|
||||
loggers = [logging.getLogger()]
|
||||
|
||||
loggers.extend(logging.Logger.manager.loggerDict.values())
|
||||
|
||||
for logger in loggers:
|
||||
if not isinstance(logger, logging.Logger):
|
||||
continue
|
||||
|
||||
for handler in logger.handlers[:]:
|
||||
if isinstance(handler, logging.FileHandler):
|
||||
handler.flush()
|
||||
handler.close()
|
||||
logger.removeHandler(handler)
|
||||
|
||||
|
||||
############################################################################################################################################
|
||||
def _entetes_github(token: str | None, brut: bool = False) -> dict:
|
||||
accept = "application/vnd.github.raw+json" if brut else "application/vnd.github+json"
|
||||
entetes = {"Accept": accept, "X-GitHub-Api-Version": "2022-11-28"}
|
||||
if token:
|
||||
entetes["Authorization"] = f"Bearer {token}"
|
||||
return entetes
|
||||
|
||||
|
||||
############################################################################################################################################
|
||||
def lister_fichiers_github(session: requests.Session, depot: str, branche: str, chemin: str, token: str | None) -> list[dict]:
|
||||
"""Liste récursivement les fichiers d'un dossier GitHub (ou le fichier lui-même)."""
|
||||
|
||||
url = f"{GITHUB_API}/repos/{depot}/contents/{quote(chemin)}"
|
||||
reponse = session.get(url, params={"ref": branche}, headers=_entetes_github(token), timeout=60)
|
||||
|
||||
if reponse.status_code == 404:
|
||||
raise FileNotFoundError(f"Chemin introuvable (ou jeton manquant) : {depot}@{branche}:{chemin}")
|
||||
reponse.raise_for_status()
|
||||
contenu = reponse.json()
|
||||
|
||||
if isinstance(contenu, dict): # le chemin désigne un fichier
|
||||
return [contenu]
|
||||
|
||||
fichiers = []
|
||||
for entree in contenu:
|
||||
if entree["type"] == "file":
|
||||
fichiers.append(entree)
|
||||
elif entree["type"] == "dir":
|
||||
fichiers.extend(lister_fichiers_github(session, depot, branche, entree["path"], token))
|
||||
return fichiers
|
||||
|
||||
|
||||
############################################################################################################################################
|
||||
def telecharger_depuis_github(depot: str, branche: str, chemin: str, dossier_cible: Path, token: str | None = None) -> Path:
|
||||
"""Télécharge uniquement un fichier ou un dossier d'un dépôt GitHub.
|
||||
|
||||
chemin : chemin dans le dépôt, ex. 'data/gpkg' ou 'data/couche.gpkg' ('' = tout le dépôt)
|
||||
Retourne le fichier ou le dossier local téléchargé.
|
||||
"""
|
||||
|
||||
chemin = chemin.strip("/")
|
||||
|
||||
if dossier_cible.exists():
|
||||
shutil.rmtree(dossier_cible)
|
||||
dossier_cible.mkdir(parents=True)
|
||||
|
||||
with requests.Session() as session:
|
||||
fichiers = lister_fichiers_github(session, depot, branche, chemin, token)
|
||||
if not fichiers:
|
||||
raise ValueError(f"Aucun fichier trouvé dans : {chemin or '/'}")
|
||||
|
||||
# Un seul fichier demandé : on le garde à plat ; sinon on conserve l'arborescence relative au dossier demandé.
|
||||
est_fichier = len(fichiers) == 1 and fichiers[0]["path"] == chemin
|
||||
base = chemin.rpartition("/")[0] if est_fichier else chemin
|
||||
total = sum(f.get("size", 0) for f in fichiers) or None
|
||||
|
||||
with alive_bar(total, title=f"{Colors.YELLOW}Téléchargement GitHub{Colors.ENDC}", stats=True, scale="SI", unit="o") as barre:
|
||||
for fichier in fichiers:
|
||||
relatif = fichier["path"][len(base) :].lstrip("/") if base else fichier["path"]
|
||||
local = dossier_cible / relatif
|
||||
local.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
url = f"{GITHUB_API}/repos/{depot}/contents/{quote(fichier['path'])}"
|
||||
with session.get(url, params={"ref": branche}, headers=_entetes_github(token, brut=True), stream=True, timeout=120) as r:
|
||||
r.raise_for_status()
|
||||
with open(local, "wb") as f:
|
||||
for morceau in r.iter_content(chunk_size=1024 * 256):
|
||||
f.write(morceau)
|
||||
barre(len(morceau))
|
||||
|
||||
return dossier_cible / Path(chemin).name if est_fichier else dossier_cible
|
||||
|
||||
|
||||
############################################################################################################################################
|
||||
def envoyer_mergin(
|
||||
projet: str,
|
||||
client: MerginClient,
|
||||
depot: str,
|
||||
chemin: str,
|
||||
branche: str = "main",
|
||||
token: str | None = None,
|
||||
destination: str = "",
|
||||
dossier_temporaire: Path = Path(__file__).parent / GlobalData.Temp_folder,
|
||||
):
|
||||
"""#####################################################################################################################################
|
||||
Télécharge un fichier ou un dossier depuis GitHub puis l'envoie vers Mergin Maps.
|
||||
|
||||
Le dossier temporaire est conservé en cas d'erreur.
|
||||
La copie GitHub est supprimée après un succès complet.
|
||||
#####################################################################################################################################"""
|
||||
|
||||
logger.info("═" * 95)
|
||||
logger.info(f"{Colors.YELLOW}Envoi des données GitHub vers Mergin Maps")
|
||||
logger.info("═" * 95)
|
||||
|
||||
dossier_temporaire = Path(dossier_temporaire).resolve()
|
||||
destination = Path(destination)
|
||||
|
||||
if destination.is_absolute() or ".." in destination.parts:
|
||||
raise ValueError("La destination doit être un chemin relatif.")
|
||||
|
||||
if ".mergin" in destination.parts:
|
||||
raise ValueError("Le dossier .mergin est réservé à Mergin Maps.")
|
||||
|
||||
dossier_temporaire.mkdir(parents=True, exist_ok=True)
|
||||
dossier_github = dossier_temporaire / "Github"
|
||||
dossier_projet = dossier_temporaire / "Projet"
|
||||
|
||||
try:
|
||||
# 1. Téléchargement du fichier ou dossier nécessaire depuis GitHub.
|
||||
logger.info(f"[1/5]{Colors.YELLOW} Téléchargement desfichiers depuis le GitHub : {Colors.ENDC}{depot}@{branche}:{chemin}")
|
||||
source = telecharger_depuis_github(depot, branche, chemin, dossier_github, token)
|
||||
|
||||
# 2. Projet Mergin local.
|
||||
if not (dossier_projet / ".mergin").is_dir():
|
||||
logger.info(f"[2/5]{Colors.YELLOW} Téléchargement initial du projet : {Colors.ENDC}{dossier_projet}")
|
||||
telecharger_avec_progression(client, projet, dossier_projet)
|
||||
|
||||
else:
|
||||
logger.info(f"[2/5] {Colors.YELLOW}Synchronisation du projet local existant : {Colors.ENDC}{dossier_projet}")
|
||||
client.sync_project(str(dossier_projet))
|
||||
|
||||
# 3. Copie des fichiers GitHub dans le projet Mergin.
|
||||
logger.info(f"[3/5]{Colors.YELLOW} Copie des fichiers {Colors.ENDC}{source}")
|
||||
cible = dossier_projet / destination
|
||||
cible.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if source.is_file():
|
||||
fichiers = [(source, cible / source.name)]
|
||||
|
||||
elif source.is_dir():
|
||||
fichiers = [
|
||||
(f, cible / f.relative_to(source))
|
||||
for f in source.rglob("*")
|
||||
if f.is_file() and ".mergin" not in f.relative_to(source).parts and "__pycache__" not in f.relative_to(source).parts
|
||||
]
|
||||
|
||||
else:
|
||||
raise ValueError(f"Source non prise en charge : {Colors.ENDC}{source}")
|
||||
|
||||
if not fichiers:
|
||||
raise ValueError("Aucun fichier à envoyer.")
|
||||
|
||||
for origine, destination_fichier in fichiers:
|
||||
destination_fichier.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(origine, destination_fichier)
|
||||
logger.info(f" + {Colors.ENDC}{destination_fichier.relative_to(dossier_projet)}")
|
||||
|
||||
# 4. Push vers le serveur.
|
||||
logger.info(f"[4/5]{Colors.YELLOW} Push vers Mergin Maps...")
|
||||
envoyer_avec_progression(client, dossier_projet)
|
||||
|
||||
# 5. Nettoyage de la copie GitHub uniquement après succès.
|
||||
logger.info(f"[5/5]{Colors.YELLOW} Push terminé. Nettoyage...")
|
||||
shutil.rmtree(dossier_github, ignore_errors=True)
|
||||
|
||||
logger.info("Envoi terminé avec succès.")
|
||||
|
||||
except Exception:
|
||||
logger.error("ERREUR : le dossier temporaire est conservé pour diagnostic :")
|
||||
logger.error(f"{Colors.ENDC}{dossier_temporaire}")
|
||||
raise
|
||||
|
||||
|
||||
############################################################################################################################################
|
||||
def envoyer_dossier_old_fichierslocaux(
|
||||
source: Path, projet: str, client: MerginClient, destination: str = "", dossier_temporaire: Path = Path(__file__).parent / GlobalData.Temp_folder
|
||||
):
|
||||
"""#####################################################################################################################################
|
||||
Envoie un fichier ou un dossier vers Mergin Maps.
|
||||
|
||||
Le dossier temporaire est supprimé au début du traitement.
|
||||
Il est conservé en cas d'erreur et supprimé après un succès complet. #
|
||||
# #
|
||||
#####################################################################################################################################"""
|
||||
|
||||
logger.info("═" * 95)
|
||||
logger.info(f"{Colors.YELLOW}Envoie des donnée vers Mergin Maps")
|
||||
logger.info("═" * 95)
|
||||
|
||||
source = Path(source).resolve()
|
||||
dossier_temporaire = Path(dossier_temporaire).resolve()
|
||||
destination = Path(destination)
|
||||
|
||||
if not source.exists():
|
||||
raise FileNotFoundError(f"Source introuvable : {Colors.ENDC}{source}")
|
||||
|
||||
if destination.is_absolute() or ".." in destination.parts:
|
||||
raise ValueError("La destination doit être un chemin relatif.")
|
||||
|
||||
if ".mergin" in destination.parts:
|
||||
raise ValueError("Le dossier .mergin est réservé à Mergin Maps.")
|
||||
|
||||
if dossier_temporaire == source or source in dossier_temporaire.parents:
|
||||
raise ValueError("Le dossier temporaire ne doit pas se trouver dans la source.")
|
||||
|
||||
dossier_temporaire.mkdir(parents=True, exist_ok=True)
|
||||
dossier_temporaire = dossier_temporaire / "Projet"
|
||||
|
||||
try:
|
||||
if not (dossier_temporaire / ".mergin").is_dir():
|
||||
logger.info(f"[1/4]{Colors.YELLOW} Téléchargement initial du projet : {Colors.ENDC}{dossier_temporaire}")
|
||||
telecharger_avec_progression(client, projet, dossier_temporaire)
|
||||
|
||||
else:
|
||||
logger.info(f"[1/4] {Colors.YELLOW}Synchronisation du projet local existant : {Colors.ENDC}{dossier_temporaire}")
|
||||
client.sync_project(str(dossier_temporaire))
|
||||
|
||||
# 2. Copier le fichier ou les fichiers source.
|
||||
logger.info(f"[2/4]{Colors.YELLOW} Copie des fichiers {Colors.ENDC}{source}")
|
||||
cible = dossier_temporaire / destination
|
||||
cible.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if source.is_file():
|
||||
fichiers = [(source, cible / source.name)]
|
||||
|
||||
elif source.is_dir():
|
||||
fichiers = [
|
||||
(f, cible / f.relative_to(source))
|
||||
for f in source.rglob("*")
|
||||
if f.is_file() and ".mergin" not in f.relative_to(source).parts and "__pycache__" not in f.relative_to(source).parts
|
||||
]
|
||||
|
||||
else:
|
||||
raise ValueError(f"Source non prise en charge : {Colors.ENDC}{source}")
|
||||
|
||||
if not fichiers:
|
||||
raise ValueError("Aucun fichier à envoyer.")
|
||||
|
||||
for origine, destination_fichier in fichiers:
|
||||
destination_fichier.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(origine, destination_fichier)
|
||||
logger.info(f" + {Colors.ENDC}{destination_fichier.relative_to(dossier_temporaire)}")
|
||||
|
||||
# 3. Synchroniser avec le serveur.
|
||||
logger.info(f"[3/4]{Colors.YELLOW} Push vers Mergin Maps...")
|
||||
# client.sync_project(str(dossier_temporaire))
|
||||
envoyer_avec_progression(client, dossier_temporaire)
|
||||
|
||||
# 4. Nettoyer uniquement après le succès.
|
||||
logger.info(f"[4/4]{Colors.YELLOW} Push terminé. Nettoyage...")
|
||||
# fermer_journaux_mergin()
|
||||
# supprimer_dossier_temporaire(dossier_temporaire)
|
||||
|
||||
logger.info("Envoi terminé avec succès.")
|
||||
|
||||
except Exception:
|
||||
logger.error("ERREUR : le dossier temporaire est conservé pour diagnostic :")
|
||||
logger.error(f"{Colors.ENDC}{dossier_temporaire}")
|
||||
raise
|
||||
|
||||
|
||||
############################################################################################################################################
|
||||
def information_depot_mergin(projet, client):
|
||||
"""#####################################################################################################################################
|
||||
# Affiche les informations d'un projet Mergin Maps.
|
||||
projet : nom complet du projet, sous la forme 'espace/nom_projet',
|
||||
ou chemin du dossier local du projet.
|
||||
client : instance de MerginClient. #
|
||||
# #
|
||||
#####################################################################################################################################"""
|
||||
|
||||
logger.info("═" * 95)
|
||||
logger.info(f"{Colors.YELLOW}INFORMATIONS DU PROJET MERGIN MAPS")
|
||||
logger.info("═" * 95)
|
||||
|
||||
# Récupération des informations distantes
|
||||
try:
|
||||
info = client.project_info(str(projet))
|
||||
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error(f"Erreur lors de la récupération du projet : {Colors.ENDC}{e}")
|
||||
return
|
||||
|
||||
logger.info(f"Projet : {Colors.ENDC}{info.get('name', projet)}")
|
||||
logger.info(f"Identifiant : {Colors.ENDC}{info.get('id', 'Non renseigné')}")
|
||||
logger.info(f"Version : {Colors.ENDC}{info.get('version', 'Non renseignée')}")
|
||||
logger.info(f"Créé le : {Colors.ENDC}{info.get('created', 'Non renseigné')}")
|
||||
logger.info(f"Mis à jour : {Colors.ENDC}{info.get('updated', 'Non renseigné')}")
|
||||
logger.info(f"Taille totale : {Colors.ENDC}{info.get('disk_usage', 'Non renseignée')}{Colors.INFO} Octets")
|
||||
logger.info(f"Public : {Colors.ENDC}{info.get('public', 'Non renseigné')}")
|
||||
|
||||
# Liste des fichiers distants
|
||||
fichiers = info.get("files", [])
|
||||
|
||||
logger.info(f"Nbre de fichiers : {Colors.ENDC}{len(fichiers)}")
|
||||
|
||||
tailleTotale = 0.0
|
||||
if fichiers:
|
||||
for fichier in fichiers:
|
||||
taille = fichier.get("size", 0)
|
||||
tailleTotale += taille
|
||||
logger.info(f"Taille totale : {Colors.ENDC}{tailleTotale / (1024 * 1024):.2f}{Colors.INFO} Mo")
|
||||
logger.info("━" * 95)
|
||||
|
||||
for fichier in sorted(fichiers, key=lambda f: f.get("path", "")):
|
||||
chemin = fichier.get("path", "?")
|
||||
taille = fichier.get("size", 0)
|
||||
taille_mo = taille / (1024 * 1024)
|
||||
|
||||
logger.info(f"{Colors.ENDC}{chemin:<83} {Colors.CYAN}{taille_mo:>8.3f}{Colors.INFO} Mo")
|
||||
else:
|
||||
logger.warning("Aucun fichier répertorié dans les informations reçues.")
|
||||
|
||||
logger.info("━" * 95)
|
||||
|
||||
|
||||
############################################################################################################################################
|
||||
# Main fonction #
|
||||
# #
|
||||
############################################################################################################################################
|
||||
if __name__ == "__main__":
|
||||
if os.name == "nt": # Windows
|
||||
subprocess.run("cls", shell=True, check=True)
|
||||
else: # Linux / macOS
|
||||
subprocess.run(["clear"], check=True)
|
||||
|
||||
parser = argparse.ArgumentParser(description="Envoi de fichiers vers Mergin Maps")
|
||||
# parser.add_argument("--source", required=True, help="Dossier contenant les fichiers à envoyer")
|
||||
# parser.add_argument("--projet-local", required=True, help="Dossier local du projet Mergin Maps")
|
||||
args = parser.parse_args()
|
||||
|
||||
logger = setup_logger(GlobalData.Output_log, GlobalData.Debug_log)
|
||||
|
||||
titre = [
|
||||
f"{Colors.TITRE}╔{'═' * 99}",
|
||||
"║" + ("Synchronisation des fichiers gpkg vers Mergin Maps").center(99),
|
||||
"║" + (f"Par : {Colors.TITRE_2}alexandre.pont@yahoo.fr{Colors.TITRE}").center(119),
|
||||
"║" + (f"Version : {Colors.TITRE_2}{GlobalData.Version}{Colors.TITRE}").center(119),
|
||||
"║" + (f"Serveur MerginMaps : {Colors.TITRE_2}{GlobalData.Mergin_url}{Colors.TITRE}").center(119),
|
||||
"║" + (f"Projet MerginMaps : {Colors.TITRE_2}{GlobalData.Dest_project}{Colors.TITRE}").center(119),
|
||||
"║" + (f"Dossier source : {Colors.TITRE_2}{GlobalData.Inputs_folder}{Colors.TITRE}").center(119),
|
||||
"║" + (f"Fichier log : {Colors.TITRE_2}{GlobalData.Output_log}{Colors.TITRE}").center(119),
|
||||
"║ ",
|
||||
f"╚{'═' * 99}",
|
||||
]
|
||||
|
||||
for i in range(10):
|
||||
fin = "╗" if i == 0 else "╝" if i == 9 else "║"
|
||||
print(f"{Colors.TITRE}" + titre[i].ljust(100) + f"{fin}{Colors.ENDC}")
|
||||
|
||||
fichier_env = Path(__file__).resolve().parent / ".env"
|
||||
load_dotenv(fichier_env)
|
||||
|
||||
login = os.getenv("MERGIN_USERNAME")
|
||||
password = os.getenv("MERGIN_PASSWORD")
|
||||
|
||||
if not login or not password:
|
||||
sys.exit("Définir MERGIN_USERNAME et MERGIN_PASSWORD.")
|
||||
|
||||
client = MerginClient(url=GlobalData.Mergin_url, login=login, password=password)
|
||||
|
||||
information_depot_mergin(GlobalData.Dest_project, client)
|
||||
|
||||
envoyer_mergin(
|
||||
GlobalData.Dest_project,
|
||||
client,
|
||||
depot=GlobalData.Github_repo,
|
||||
chemin=GlobalData.Github_path, # ex. "data/gpkg" ou "data/couche.gpkg"
|
||||
branche=GlobalData.Github_branch,
|
||||
# token=os.environ.get("GITHUB_TOKEN"),
|
||||
destination=GlobalData.Dest_folder,
|
||||
)
|
||||
|
||||
# envoyer_dossier(GlobalData.Inputs_folder, GlobalData.Dest_project, client, destination=GlobalData.Dest_folder)
|
||||
|
||||
information_depot_mergin(GlobalData.Dest_project, client)
|
||||
@@ -0,0 +1,6 @@
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 160
|
||||
|
||||
[tool.ruff.format]
|
||||
skip-magic-trailing-comma = true
|
||||
Reference in new issue
Block a user