Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 37 additions & 27 deletions script.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,25 @@
REPO_OWNER = "NammaLakes"
REPO_NAME = "node"
BRANCH = "main"
LOCAL_REPO_PATH = "Add Local Path"
BACKUP_PATH = "Add a path for backup"
LOCAL_REPO_PATH = r"local_repo_path"
BACKUP_PATH = "" # add if this is a private repo

# GitHub API URL for commits
GITHUB_API_URL = (
f"https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}/commits?sha={BRANCH}"
)


# Optional: GitHub Personal Access Token (if using a private repo)
GITHUB_TOKEN = "your-github-token"
# Optional: GitHub Personal Access Token
GITHUB_TOKEN = "" # keep empty if public repo


def get_latest_commit():
"""Fetch the latest commit SHA from GitHub API."""
headers = {}
if GITHUB_TOKEN:
headers["Authorization"] = f"token {GITHUB_TOKEN}"

try:
response = requests.get(GITHUB_API_URL, headers=headers)
response = requests.get(GITHUB_API_URL, headers=headers, timeout=10)
response.raise_for_status()
commits = response.json()
return commits[0]["sha"] if commits else None
Expand All @@ -36,23 +34,40 @@ def get_latest_commit():
return None


def get_latest_commit():
"""Fetch the latest commit SHA from GitHub API for a public repo."""
def get_local_commit():
try:
response = requests.get(GITHUB_API_URL, timeout=10) # No auth needed
response.raise_for_status()
commits = response.json()
return commits[0]["sha"] if commits else None
except requests.exceptions.RequestException as e:
print(f"Error checking for updates: {e}")
result = subprocess.run(
["git", "rev-parse", "HEAD"],
cwd=LOCAL_REPO_PATH,
capture_output=True,
text=True,
)
if result.returncode == 0:
return result.stdout.strip()
else:
print(f"Error getting local commit: {result.stderr}")
return None
except FileNotFoundError as e:
print(
f"File not found error: {e}. Ensure the 'git' executable and the repository path exist."
)
return None
except PermissionError as e:
print(
f"Permission error: {e}. Check your access rights to the repository path."
)
return None
except subprocess.SubprocessError as e:
print(
f"Subprocess error: {e}. An issue occurred while running the 'git' command."
)
return None


def create_backup():
"""Create a backup of the current repository."""
try:
if os.path.exists(BACKUP_PATH):
shutil.rmtree(BACKUP_PATH) # Remove old backup
shutil.rmtree(BACKUP_PATH)
shutil.copytree(LOCAL_REPO_PATH, BACKUP_PATH)
print("Backup created successfully.")
return True
Expand All @@ -62,22 +77,20 @@ def create_backup():


def restore_backup():
"""Restore the backup if update fails."""
try:
if os.path.exists(BACKUP_PATH):
if os.path.exists(LOCAL_REPO_PATH):
shutil.rmtree(LOCAL_REPO_PATH) # Delete failed update
shutil.rmtree(LOCAL_REPO_PATH)
shutil.copytree(BACKUP_PATH, LOCAL_REPO_PATH)
print("Rollback successful: Restored backup.")
print("Rollback successful.")
else:
print("No backup found to restore.")
except Exception as e:
print(f"Error restoring backup: {e}")


def update_repository():
"""Pull the latest changes from GitHub after backing up."""
if create_backup(): # Only proceed if backup is successful
if create_backup():
try:
print("Pulling latest changes from GitHub...")
result = subprocess.run(
Expand All @@ -86,14 +99,12 @@ def update_repository():
capture_output=True,
text=True,
)

if result.returncode == 0:
print("Repository updated successfully.")
shutil.rmtree(BACKUP_PATH) # Delete backup after a successful update
shutil.rmtree(BACKUP_PATH)
else:
print(f"Update failed: {result.stderr}. Restoring backup...")
restore_backup()

except Exception as e:
print(f"Update process failed: {e}. Rolling back...")
restore_backup()
Expand All @@ -102,10 +113,9 @@ def update_repository():


def main():
"""Check for updates and apply them safely."""
print("Checking for updates...")
latest_commit = get_latest_commit()
local_commit = get_latest_commit()
local_commit = get_local_commit()

if latest_commit and local_commit:
if latest_commit != local_commit:
Expand Down