Repository navigation
230 lines (214 loc) · 10.2 KB
/
Copy pathfix_lang_code.yml
File metadata and controls
230 lines (214 loc) · 10.2 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
name: Fix Bare Lang Code PR
on:
issues:
types: [opened]
jobs:
create-pr:
if: contains(github.event.issue.labels.*.name, 'fix-lang-code') || startsWith(github.event.issue.title, '[fix-lang-code]')
runs-on: ubuntu-latest
steps:
- name: Parse issue body
id: parse
uses: actions/github-script@v9
with:
script: |
const body = context.payload.issue.body || '';
const meta = {};
// Parse <!-- FIX_LANG_CODE_META ... --> block
const match = body.match(/<!--\s*FIX_LANG_CODE_META\s+([\s\S]*?)-->/);
if (!match) {
core.setFailed('No FIX_LANG_CODE_META block found in issue body');
return;
}
for (const line of match[1].trim().split('\n')) {
const [key, ...rest] = line.split(':');
if (key && rest.length) meta[key.trim()] = rest.join(':').trim();
}
// Parse renames array: "rename_0: locale/eu -> locale/eu-ES"
const renames = [];
for (const [k, v] of Object.entries(meta)) {
if (k.startsWith('rename_')) {
const parts = v.split('->').map(s => s.trim());
if (parts.length === 2) renames.push({ from: parts[0], to: parts[1] });
}
}
if (!meta.org || !meta.repo) {
core.setFailed('Missing org or repo in FIX_LANG_CODE_META');
return;
}
if (!renames.length) {
core.setFailed('No rename_ entries found in FIX_LANG_CODE_META');
return;
}
// Issue bodies are written by anyone, and these values choose a
// repository and the directories to move. Check them first.
const NAME = /^[A-Za-z0-9._-]+$/;
const SEG = /^[A-Za-z0-9._-]+$/;
const fail = (m) => { core.setFailed(m); return false; };
if (!NAME.test(meta.org)) return fail(`Invalid org: ${meta.org}`);
if (!NAME.test(meta.repo)) return fail(`Invalid repo: ${meta.repo}`);
if (meta.branch && !/^[A-Za-z0-9._\/-]+$/.test(meta.branch)) {
return fail(`Invalid branch: ${meta.branch}`);
}
for (const r of renames) {
for (const side of [r.from, r.to]) {
const parts = side.split('/');
if (parts.some((x) => !SEG.test(x))) return fail(`Unsafe path: ${side}`);
const rootIdx = parts.findIndex((x) => x === 'locale' || x === 'res');
if (rootIdx === -1 || rootIdx > 1 || parts.length !== rootIdx + 2) {
return fail(`Rename must name a language directory under locale/ or res/: ${side}`);
}
}
}
core.setOutput('org', meta.org);
core.setOutput('repo', meta.repo);
core.setOutput('branch', meta.branch || 'dev');
core.setOutput('renames_json', JSON.stringify(renames));
core.setOutput('author', context.payload.issue.user.login);
- name: Generate GitHub App token
id: app-token
uses: actions/create-github-app-token@v3
with:
app-id: ${{ vars.LOCALIZE_APP_ID }}
private-key: ${{ secrets.LOCALIZE_APP_PRIVATE_KEY }}
owner: ${{ steps.parse.outputs.org }}
repositories: ${{ steps.parse.outputs.repo }}
- name: Resolve base branch
id: base
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
ORG: ${{ steps.parse.outputs.org }}
REPO: ${{ steps.parse.outputs.repo }}
WANTED: ${{ steps.parse.outputs.branch }}
run: |
# The submitted branch is a hint. Repos differ (dev / main / master),
# so verify it exists and fall back to the repo's default branch.
if [ -n "$WANTED" ] && gh api "repos/$ORG/$REPO/branches/$WANTED" --silent 2>/dev/null; then
RESOLVED="$WANTED"
else
RESOLVED="$(gh api "repos/$ORG/$REPO" --jq .default_branch)"
echo "::warning::branch '$WANTED' not found on $ORG/$REPO; using default '$RESOLVED'"
fi
echo "branch=$RESOLVED" >> "$GITHUB_OUTPUT"
- name: Checkout target repo
uses: actions/checkout@v7
with:
repository: ${{ steps.parse.outputs.org }}/${{ steps.parse.outputs.repo }}
ref: ${{ steps.base.outputs.branch }}
token: ${{ steps.app-token.outputs.token }}
- name: Rename locale directories
id: rename
env:
RENAMES_JSON: ${{ steps.parse.outputs.renames_json }}
AUTHOR: ${{ steps.parse.outputs.author }}
run: |
BRANCH_NAME="fix/lang-code-$(date +%s)"
git checkout -b "$BRANCH_NAME"
git config user.name "ovos-localize[bot]"
git config user.email "ovos-localize[bot]@users.noreply.github.com"
echo "$RENAMES_JSON" | python3 -c "
import json, sys, os, shutil
renames = json.load(sys.stdin)
for r in renames:
src, dst = r['from'], r['to']
if not os.path.isdir(src):
print(f'SKIP: {src} not found', file=sys.stderr)
continue
# Walk the whole tree. Comparing only the top level would skip an
# entire subdirectory whenever both sides have one by the same
# name, leaving those translations behind in the old directory.
for root, _dirs, files in os.walk(src):
rel = os.path.relpath(root, src)
target = dst if rel == '.' else os.path.join(dst, rel)
os.makedirs(target, exist_ok=True)
for name in files:
s = os.path.join(root, name)
d = os.path.join(target, name)
if os.path.exists(d):
print(f'KEEP existing {d} (skipped {s})')
else:
shutil.move(s, d)
print(f'Moved {s} -> {d}')
# Prune directories that are now empty, deepest first.
for root, _dirs, _files in sorted(os.walk(src), reverse=True):
if not os.listdir(root):
os.rmdir(root)
print(f'Removed empty dir {root}')
if os.path.isdir(src):
left = [os.path.join(dp, f) for dp, _, fs in os.walk(src) for f in fs]
print(f'::warning::{src} still holds {len(left)} file(s) that also exist under {dst}: ' + ', '.join(left))
"
git add -A
git diff --cached --quiet && echo "no_changes=true" >> "$GITHUB_OUTPUT" && exit 0
git commit -m "fix: rename bare lang code locale directories" \
-m "Automated rename submitted by @${AUTHOR} via OVOS Localize."
git push origin "$BRANCH_NAME"
echo "branch_name=$BRANCH_NAME" >> "$GITHUB_OUTPUT"
echo "no_changes=false" >> "$GITHUB_OUTPUT"
- name: Create Pull Request
if: steps.rename.outputs.no_changes != 'true'
id: pr
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
# Environment variables, not template expansion: these come from an
# issue anyone can write.
ORG: ${{ steps.parse.outputs.org }}
REPO: ${{ steps.parse.outputs.repo }}
BASE: ${{ steps.base.outputs.branch }}
HEAD_BRANCH: ${{ steps.rename.outputs.branch_name }}
RENAMES_JSON: ${{ steps.parse.outputs.renames_json }}
AUTHOR: ${{ steps.parse.outputs.author }}
ISSUE_URL: ${{ github.server_url }}/${{ github.repository }}/issues/${{ github.event.issue.number }}
run: |
PR_URL=$(gh pr create \
--repo "$ORG/$REPO" \
--base "$BASE" \
--head "$HEAD_BRANCH" \
--title "fix: rename bare lang code locale directories" \
--body "## Fix: Bare lang code locale directories
Locale directory names without a region subtag are ambiguous. This PR renames them to their canonical BCP-47 form.
| Old path | New path |
|----------|----------|
$(echo "$RENAMES_JSON" | python3 -c "
import json,sys
for r in json.load(sys.stdin): print(f'| \`{r[\"from\"]}\` | \`{r[\"to\"]}\` |')
")
- **Submitted by**: @$AUTHOR
- **Triggered by**: $ISSUE_URL
Submitted via [OVOS Localize](https://openvoiceos.github.io/ovos-localize/).")
echo "pr_url=$PR_URL" >> "$GITHUB_OUTPUT"
- name: Close issue with result
uses: actions/github-script@v9
with:
script: |
const noChanges = '${{ steps.rename.outputs.no_changes }}' === 'true';
const prUrl = '${{ steps.pr.outputs.pr_url }}';
const body = noChanges
? '⚠️ **No changes made** — the locale directories may have already been renamed, or the paths could not be found in the repository.'
: `✅ **Fix PR created!**\n\n${prUrl}\n\nThe skill maintainer will review and merge it.`;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body
});
await github.rest.issues.update({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
state: 'closed',
state_reason: noChanges ? 'not_planned' : 'completed'
});
- name: Report failure on the issue
if: failure()
uses: actions/github-script@v9
with:
script: |
const run = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `⚠️ **This rename request could not be turned into a pull request.**\n\n` +
`A maintainer has been alerted and will re-run it.\n\nDetails: ${run}`
});