-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.py
More file actions
65 lines (47 loc) · 1.92 KB
/
git.py
File metadata and controls
65 lines (47 loc) · 1.92 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
"""Git operations for detached-HEAD deploy strategy."""
from flow_deploy import log, process
def is_dirty() -> bool:
"""Return True if the working tree has uncommitted changes."""
result = process.run(["git", "status", "--porcelain"])
return bool(result.stdout.strip())
def fetch() -> process.Result:
"""Fetch from origin."""
return process.run(["git", "fetch", "origin"])
def current_sha() -> str:
"""Return the current HEAD SHA."""
result = process.run(["git", "rev-parse", "HEAD"])
return result.stdout.strip()
def checkout_detached(sha: str) -> process.Result:
"""Checkout a specific SHA in detached HEAD mode."""
return process.run(["git", "checkout", "--detach", sha])
def preflight_and_checkout(tag: str) -> tuple[int, str | None]:
"""Run git pre-flight checks and checkout the deploy SHA.
Returns (exit_code, previous_sha).
- (0, previous_sha) on success — repo is now at `tag` in detached HEAD.
- (1, None) on error — git operation failed or working tree is dirty.
"""
# 1. Dirty check
if is_dirty():
log.error("working tree is dirty — deploy aborted")
return 1, None
# 2. Fetch
result = fetch()
if result.returncode != 0:
log.error(f"git fetch failed: {result.stderr.strip()}")
return 1, None
# 3. Record previous SHA
previous_sha = current_sha()
# 4. Checkout new SHA (detached HEAD)
result = checkout_detached(tag)
if result.returncode != 0:
log.error(f"git checkout failed: {result.stderr.strip()}")
return 1, None
return 0, previous_sha
def restore(previous_sha: str) -> bool:
"""Restore repo to a previous SHA after a failed deploy."""
log.step(f"restoring repo to {previous_sha[:7]}...")
result = checkout_detached(previous_sha)
if result.returncode != 0:
log.error(f"git restore failed: {result.stderr.strip()}")
return False
return True