utils.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import os
  2. import subprocess
  3. def sudo_getsize(path):
  4. """Retourne la taille d'un fichier via sudo stat si non accessible directement."""
  5. try:
  6. return os.path.getsize(path)
  7. except OSError:
  8. result = subprocess.run(
  9. ["sudo", "stat", "--format=%s", path],
  10. capture_output=True, text=True,
  11. )
  12. if result.returncode == 0:
  13. try:
  14. return int(result.stdout.strip())
  15. except ValueError:
  16. pass
  17. return 0
  18. def sudo_getmtime(path):
  19. """Retourne le mtime d'un fichier via sudo stat si non accessible directement."""
  20. try:
  21. return os.path.getmtime(path)
  22. except OSError:
  23. result = subprocess.run(
  24. ["sudo", "stat", "--format=%Y", path],
  25. capture_output=True, text=True,
  26. )
  27. if result.returncode == 0:
  28. try:
  29. return float(result.stdout.strip())
  30. except ValueError:
  31. pass
  32. return 0.0
  33. def unique_archive_name(base_name, backup_dir):
  34. """Retourne un nom d'archive unique (ajoute _2, _3… si le nom du jour est déjà pris)."""
  35. name = base_name
  36. i = 2
  37. while sudo_exists(os.path.join(backup_dir, name + ".tar")):
  38. name = f"{base_name}_{i}"
  39. i += 1
  40. return name
  41. def sudo_exists(path):
  42. """Vérifie l'existence d'un fichier via sudo si non accessible directement."""
  43. if os.path.exists(path):
  44. return True
  45. result = subprocess.run(
  46. ["sudo", "stat", path],
  47. capture_output=True,
  48. )
  49. return result.returncode == 0
  50. def sudo_listdir(directory):
  51. """Liste les fichiers d'un répertoire via sudo find si non accessible directement."""
  52. try:
  53. return os.listdir(directory)
  54. except OSError:
  55. result = subprocess.run(
  56. ["sudo", "find", directory, "-maxdepth", "1", "-mindepth", "1",
  57. "-printf", "%f\n"],
  58. capture_output=True, text=True,
  59. )
  60. if result.returncode == 0:
  61. return [f for f in result.stdout.strip().split("\n") if f]
  62. return []