Skip to content

Commit d4f7fee

Browse files
committed
📝 Update tools/stringtableDeploy.py
1 parent 341d7c5 commit d4f7fee

1 file changed

Lines changed: 120 additions & 66 deletions

File tree

tools/stringtableDeploy.py

Lines changed: 120 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,95 +1,149 @@
11
#!/usr/bin/env python3
22

3+
"""
4+
stringtableDeploy.py
5+
Updated deploy script that:
6+
- reads repo from GITHUB_REPOSITORY
7+
- reads GH token from GH_TOKEN
8+
- optionally uses TRANSLATION_ISSUE env var (issue number)
9+
- searches for an issue titled "Translations" if TRANSLATION_ISSUE is not provided
10+
- generates the markdown report by calling tools/stringtablediag.py --markdown
11+
- updates the issue body only when different (adds a timestamp footer)
12+
- logs sizes and actions for easier debugging
13+
"""
14+
315
import os
416
import sys
517
import traceback
618
import subprocess as sp
7-
import difflib
8-
from github import Github
9-
10-
# Path to stringtablediag.py
11-
STRINGTABLEDIAG_PATH = os.path.join("tools", "stringtablediag.py")
12-
if not os.path.isfile(STRINGTABLEDIAG_PATH):
13-
print(f"❌ Error: {STRINGTABLEDIAG_PATH} not found.")
14-
print(" Hint: Ensure that the repository contains 'tools/stringtablediag.py' and that you ran 'actions/checkout'.")
15-
sys.exit(1)
16-
17-
def generate_markdown():
18-
"""Runs stringtablediag.py and returns enhanced markdown output."""
19-
result = sp.run(
20-
["python3", STRINGTABLEDIAG_PATH, "--markdown"],
21-
stdout=sp.PIPE,
22-
stderr=sp.PIPE,
23-
text=True,
24-
check=True
25-
)
26-
return result.stdout
27-
28-
def update_translations(repo, issue_number):
29-
new_body = generate_markdown()
30-
31-
issue = repo.get_issue(issue_number)
32-
old_body = issue.body or ""
33-
34-
if old_body.strip() == new_body.strip():
35-
print("ℹ️ Translation issue is already up to date. No changes made.")
36-
return
37-
38-
# Show diff
39-
diff = difflib.unified_diff(
40-
old_body.splitlines(),
41-
new_body.splitlines(),
42-
fromfile="current_issue",
43-
tofile="new_issue",
44-
lineterm=""
45-
)
46-
print("📝 Changes detected in translation issue:")
47-
print("\n".join(diff))
48-
49-
# Update issue
50-
issue.edit(body=new_body)
51-
print("✅ Translation issue updated.")
19+
from datetime import datetime
5220

53-
def main():
54-
# Get GitHub token
21+
# PyGithub modern auth
22+
from github import Github, Auth
23+
24+
TRANSLATIONBODY = """**[Translation Guide](https://ace3.acemod.org/wiki/development/how-to-translate-ace3.html)**
25+
{}
26+
"""
27+
28+
def get_repo():
29+
"""Authenticate and return the GitHub repository object."""
5530
try:
5631
token = os.environ["GH_TOKEN"]
5732
except KeyError:
58-
print("❌ Error: GH_TOKEN environment variable not set.")
33+
print("❌ Missing environment variable: GH_TOKEN")
5934
sys.exit(1)
6035

61-
# Get translation issue number
62-
try:
63-
translation_issue = int(os.environ["TRANSLATION_ISSUE"])
64-
except KeyError:
65-
print("❌ Error: TRANSLATION_ISSUE environment variable not set.")
36+
repo_path = os.environ.get("GITHUB_REPOSITORY")
37+
if not repo_path:
38+
print("❌ Missing environment variable: GITHUB_REPOSITORY (expected 'owner/repo')")
6639
sys.exit(1)
67-
except ValueError:
68-
print(f"❌ Error: TRANSLATION_ISSUE must be an integer, got '{os.environ['TRANSLATION_ISSUE']}'.")
40+
41+
try:
42+
github = Github(auth=Auth.Token(token))
43+
repo = github.get_repo(repo_path)
44+
print(f"✅ Connected to repository: {repo_path}")
45+
return repo
46+
except Exception:
47+
print("❌ Could not connect to GitHub repository.")
48+
print(traceback.format_exc())
6949
sys.exit(1)
7050

71-
# Get repo info
72-
github_repo = os.getenv("GITHUB_REPOSITORY")
73-
if not github_repo:
74-
print("❌ Error: GITHUB_REPOSITORY environment variable not set.")
51+
52+
def find_translation_issue(repo):
53+
"""
54+
Determine which issue to update.
55+
1) If TRANSLATION_ISSUE env var exists and is a number, use it.
56+
2) Otherwise search open issues for one titled 'Translations' (case-insensitive).
57+
3) If none found, exit gracefully (soft success).
58+
"""
59+
env_val = os.environ.get("TRANSLATION_ISSUE", "").strip()
60+
if env_val:
61+
try:
62+
issue_number = int(env_val)
63+
issue = repo.get_issue(issue_number)
64+
print(f"✅ Using translation issue #{issue_number} (from TRANSLATION_ISSUE env).")
65+
print(f" {issue.html_url}")
66+
return issue
67+
except Exception:
68+
print(f"⚠️ TRANSLATION_ISSUE provided but invalid or not found: '{env_val}'")
69+
# fall through to search
70+
71+
print("ℹ️ No valid TRANSLATION_ISSUE env var found. Searching for an open issue titled 'Translations'...")
72+
try:
73+
issues = repo.get_issues(state="open")
74+
for issue in issues:
75+
if issue.title and issue.title.strip().lower() == "translations":
76+
print(f"✅ Found translation issue #{issue.number} by title.")
77+
print(f" {issue.html_url}")
78+
return issue
79+
except Exception:
80+
print("⚠️ Error while searching for issues (continuing to soft-exit if none found).")
81+
print(traceback.format_exc())
82+
83+
print("⚠️ No 'Translations' issue found. Exiting gracefully (no failure).")
84+
sys.exit(0)
85+
86+
87+
def generate_translation_report():
88+
"""Run the diagnostic tool and return its markdown output."""
89+
diag_script = os.path.join(os.path.dirname(os.path.realpath(__file__)), "stringtablediag.py")
90+
if not os.path.isfile(diag_script):
91+
print("❌ Diagnostic script not found at tools/stringtablediag.py")
7592
sys.exit(1)
76-
user, repo_name = github_repo.split("/")
7793

78-
# Connect to GitHub
7994
try:
80-
repo = Github(token).get_repo(f"{user}/{repo_name}")
95+
# Use text=True to get str directly (py3.7+)
96+
diag_output = sp.check_output(["python3", diag_script, "--markdown"], text=True, stderr=sp.STDOUT)
97+
return diag_output
98+
except sp.CalledProcessError as e:
99+
print("❌ stringtablediag.py failed:")
100+
# print command output for debugging
101+
print(e.output)
102+
sys.exit(1)
81103
except Exception:
82-
print("❌ Could not obtain repo object from GitHub.")
104+
print("❌ Unexpected error running stringtablediag.py.")
83105
print(traceback.format_exc())
84106
sys.exit(1)
85107

86-
print(f"\n📝 Updating translation issue #{translation_issue} ...")
108+
109+
def update_issue(issue, body):
110+
"""Update the translation issue with the latest report, with logging & timestamp."""
87111
try:
88-
update_translations(repo, translation_issue)
112+
timestamp = datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")
113+
new_body = TRANSLATIONBODY.format(body) + f"\n\n_Last updated automatically: {timestamp}_"
114+
115+
current_body = issue.body or ""
116+
117+
# Log sizes
118+
print(f"ℹ️ Current issue body length: {len(current_body)} characters")
119+
print(f"ℹ️ New issue body length: {len(new_body)} characters")
120+
121+
# If identical, skip
122+
if new_body.strip() == current_body.strip():
123+
print("ℹ️ Issue body is already up to date — no changes made.")
124+
return
125+
126+
print(f"📝 Updating issue #{issue.number} …")
127+
issue.edit(body=new_body)
128+
print(f"✅ Successfully updated issue #{issue.number}")
129+
89130
except Exception:
90-
print("❌ Failed to update translation issue.")
131+
print("❌ Failed to update issue.")
91132
print(traceback.format_exc())
92133
sys.exit(1)
93134

135+
136+
def main():
137+
repo = get_repo()
138+
issue = find_translation_issue(repo)
139+
# If find_translation_issue returns, we have an issue object.
140+
141+
print("\n🧾 Generating translation report...")
142+
diag_body = generate_translation_report()
143+
144+
print("\n✏️ Updating translation issue...")
145+
update_issue(issue, diag_body)
146+
147+
94148
if __name__ == "__main__":
95149
main()

0 commit comments

Comments
 (0)