Vision / setup_xet.py
kishankrish19's picture
Deploy MoM application
bcfb8cf
Raw History Blame Contribute Delete
7.8 kB
import os
import shutil
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent
XET_NAME = "git-xet.exe"
BIN_DIR = Path.home() / "bin"
XET_TARGET = BIN_DIR / XET_NAME
ATTRIBUTES = ROOT / ".gitattributes"
def run(command, check=True):
print(f"\n> {command}")
result = subprocess.run(
command,
cwd=ROOT,
shell=True,
text=True,
capture_output=True
)
if result.stdout:
print(result.stdout.strip())
if result.stderr:
print(result.stderr.strip())
if check and result.returncode != 0:
print(f"\n❌ Command failed with exit code {result.returncode}")
sys.exit(result.returncode)
return result
def find_xet():
"""
Look for git-xet.exe in common user locations.
"""
candidates = [
XET_TARGET,
Path.home() / "Downloads" / XET_NAME,
Path.home() / "Desktop" / XET_NAME,
ROOT / XET_NAME,
ROOT.parent / XET_NAME,
]
# Search one level deeper in Downloads
downloads = Path.home() / "Downloads"
if downloads.exists():
for path in downloads.rglob(XET_NAME):
candidates.append(path)
# Search one level deeper on Desktop
desktop = Path.home() / "Desktop"
if desktop.exists():
for path in desktop.rglob(XET_NAME):
candidates.append(path)
for path in candidates:
if path.exists() and path.is_file():
return path
return None
def add_to_user_path(directory):
directory = str(directory)
current_path = os.environ.get("PATH", "")
if directory.lower() not in [
p.strip().lower()
for p in current_path.split(";")
if p.strip()
]:
os.environ["PATH"] = directory + ";" + current_path
user_path = os.environ.get("PATH", "")
# Read actual persistent User PATH
try:
import winreg
with winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r"Environment",
0,
winreg.KEY_READ
) as key:
try:
persistent_path, _ = winreg.QueryValueEx(key, "Path")
except FileNotFoundError:
persistent_path = ""
entries = [
p.strip()
for p in persistent_path.split(";")
if p.strip()
]
if directory.lower() not in [p.lower() for p in entries]:
entries.append(directory)
new_path = ";".join(entries)
with winreg.OpenKey(
winreg.HKEY_CURRENT_USER,
r"Environment",
0,
winreg.KEY_SET_VALUE
) as key:
winreg.SetValueEx(
key,
"Path",
0,
winreg.REG_EXPAND_SZ,
new_path
)
print(f"βœ“ Added to User PATH: {directory}")
else:
print(f"βœ“ Already in User PATH: {directory}")
except Exception as e:
print(f"⚠ Could not update persistent User PATH: {e}")
print("=" * 65)
print("MoM Project - Git Xet Setup")
print("=" * 65)
# ---------------------------------------------------------
# 1. Check whether git-xet already works
# ---------------------------------------------------------
print("\n[1/7] Checking Git Xet...")
result = run("git xet --version", check=False)
if result.returncode == 0:
print("βœ“ Git Xet is already available.")
else:
print("Git Xet is not currently available through PATH.")
# -----------------------------------------------------
# 2. Find git-xet.exe
# -----------------------------------------------------
print("\n[2/7] Searching for git-xet.exe...")
xet_path = find_xet()
if not xet_path:
print("""
❌ Could not find git-xet.exe.
Please download/extract the Windows Git Xet CLI and make sure
git-xet.exe exists somewhere such as:
C:\\Users\\Sowmya\\Downloads\\git-xet.exe
Then run this script again.
""")
sys.exit(1)
print(f"βœ“ Found: {xet_path}")
# -----------------------------------------------------
# 3. Copy to permanent user bin folder
# -----------------------------------------------------
print("\n[3/7] Installing Git Xet for your user...")
BIN_DIR.mkdir(parents=True, exist_ok=True)
if xet_path.resolve() != XET_TARGET.resolve():
shutil.copy2(xet_path, XET_TARGET)
print(f"βœ“ Copied to: {XET_TARGET}")
else:
print(f"βœ“ Already installed at: {XET_TARGET}")
# Add to PATH
add_to_user_path(BIN_DIR)
# Make available immediately to this Python process
os.environ["PATH"] = str(BIN_DIR) + ";" + os.environ.get("PATH", "")
# -----------------------------------------------------
# 4. Verify
# -----------------------------------------------------
print("\n[4/7] Verifying Git Xet...")
result = run("git xet --version", check=False)
if result.returncode != 0:
print("""
❌ Git Xet was installed but this Python process cannot see it.
Close PowerShell, open a NEW PowerShell window and run:
git xet --version
Then run this script again.
""")
sys.exit(1)
# ---------------------------------------------------------
# 5. Install Xet Git integration
# ---------------------------------------------------------
print("\n[5/7] Installing Xet Git integration...")
run("git xet install")
# ---------------------------------------------------------
# 6. Configure Excel files
# ---------------------------------------------------------
print("\n[6/7] Configuring Excel files for Xet...")
ATTRIBUTES.write_text(
"sources/*.xlsx filter=xet diff=xet merge=xet -text\n",
encoding="utf-8"
)
print("βœ“ .gitattributes configured:")
print()
print(ATTRIBUTES.read_text(encoding="utf-8").strip())
# Check sources
sources = ROOT / "sources"
if not sources.exists():
print("\n❌ sources/ folder does not exist.")
sys.exit(1)
xlsx_files = list(sources.glob("*.xlsx"))
if not xlsx_files:
print("\n❌ No .xlsx files found inside sources/.")
sys.exit(1)
print("\nExcel files found:")
for file in xlsx_files:
size_mb = file.stat().st_size / (1024 * 1024)
print(f" βœ“ {file.name} ({size_mb:.2f} MB)")
# ---------------------------------------------------------
# 7. Check .gitignore and Git status
# ---------------------------------------------------------
print("\n[7/7] Checking .gitignore...")
gitignore = ROOT / ".gitignore"
if gitignore.exists():
content = gitignore.read_text(
encoding="utf-8",
errors="ignore"
)
lines = content.splitlines()
cleaned = []
removed = False
for line in lines:
stripped = line.strip()
if stripped in ("*.xlsx", "**/*.xlsx"):
removed = True
continue
cleaned.append(line)
if removed:
gitignore.write_text(
"\n".join(cleaned) + "\n",
encoding="utf-8"
)
print("βœ“ Removed blanket Excel ignore rule.")
else:
print("βœ“ No blanket Excel ignore rule found.")
else:
print("βœ“ No .gitignore file found.")
print("\nGit status:")
run("git status --short")
print("\n" + "=" * 65)
print("βœ… XET SETUP COMPLETE")
print("=" * 65)
print("""
Your project is now configured for Xet.
IMPORTANT:
βœ“ No application code was changed.
βœ“ Excel files under sources/ are configured for Xet.
βœ“ git-xet.exe is stored outside the project.
βœ“ Nothing was committed.
βœ“ Nothing was pushed.
βœ“ No force push was performed.
DO NOT run git push yet.
Next we will safely synchronize your local repository
with the Hugging Face Space before making the deployment commit.
""")