Skip to content
Closed
Show file tree
Hide file tree
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
32 changes: 32 additions & 0 deletions .github/scripts/mobile-ios-preview-record.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const { readFileSync } = require("node:fs");

function readClient(value, now = Date.now()) {
try {
const record = JSON.parse(value);
return typeof record?.link === "string" && Date.parse(record.expiresAt) > now
? record.link
: "";
} catch {
return "";
}
}

function createRecord(link, profile) {
const expiration = /<key>ExpirationDate<\/key>\s*<date>([^<]+)<\/date>/.exec(profile)?.[1];
if (!expiration || !Number.isFinite(Date.parse(expiration))) {
throw new Error("The provisioning profile has no valid ExpirationDate.");
}
return JSON.stringify({ link, expiresAt: new Date(expiration).toISOString() });
}

if (require.main === module) {
if (process.argv[2] === "read") {
process.stdout.write(readClient(readFileSync(0, "utf8")));
} else if (process.argv[2] === "create") {
process.stdout.write(createRecord(process.argv[3], readFileSync(process.argv[4], "utf8")));
} else {
throw new Error("Expected read or create.");
}
}

module.exports = { createRecord, readClient };
17 changes: 17 additions & 0 deletions .github/scripts/mobile-ios-preview-record.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const assert = require("node:assert/strict");
const test = require("node:test");
const { createRecord, readClient } = require("./mobile-ios-preview-record.cjs");

test("only clients with an unexpired provisioning profile are reused", () => {
const link = "https://expo.dev/accounts/pingdotgg/projects/t3-code/builds/client";
const profile =
"<plist><dict><key>ExpirationDate</key><date>2027-01-01T00:00:00Z</date></dict></plist>";
const record = createRecord(link, profile);
assert.equal(readClient(record, Date.parse("2026-12-31T00:00:00Z")), link);
assert.equal(readClient(record, Date.parse("2027-01-01T00:00:00Z")), "");
assert.equal(readClient(record, Date.parse("2027-01-02T00:00:00Z")), "");
for (const invalid of [link, "{}", "null", JSON.stringify({ link, expiresAt: "invalid" })]) {
assert.equal(readClient(invalid, 0), "");
}
assert.throws(() => createRecord(link, "<plist></plist>"), /ExpirationDate/);
});
123 changes: 77 additions & 46 deletions .github/scripts/mobile-preview-comment.cjs
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
// The Android half of the mobile preview comment. The android job writes the fingerprint and
// the update; the android-build job adds the client's install link a few minutes later. Each
// run merges what it knows into the state kept in the comment's first line.
const MARKER = "mobile-preview-android";
const PROJECT_ID = "d763fcb8-d37c-41ea-a773-b54a0ab4a454";
const APP_SCHEME = "t3-code";

function readState(body) {
const match = new RegExp(`^<!-- ${MARKER} (\\{.*\\}) -->`).exec(body ?? "");
const match = /^<!-- mobile-preview(?:-(android|ios))? (\{.*\}) -->/.exec(body ?? "");
if (!match) return null;
try {
const state = JSON.parse(match[1]);
const parsed = JSON.parse(match[2]);
const state = match[1] ? { [match[1]]: parsed } : parsed;
const text = (value) => (typeof value === "string" ? value : "");
return {
fingerprint: text(state.fingerprint),
client: text(state.client),
group: text(state.group),
};
return Object.fromEntries(
["android", "ios"]
.filter((platform) => state?.[platform])
.map((platform) => [
platform,
{
fingerprint: text(state[platform].fingerprint),
client: text(state[platform].client),
group: text(state[platform].group),
},
]),
);
} catch {
return null;
}
Expand All @@ -27,6 +31,7 @@ function readState(body) {
* the comment now shows.
*/
function mergeState(previous, next) {
if (!next.client && !next.group) return previous;
const buildOnly = Boolean(next.client) && !next.group;
if (
buildOnly &&
Expand All @@ -46,22 +51,23 @@ function mergeState(previous, next) {
}

function render(state, runUrl) {
const qr = `https://qr.expo.dev/eas-update?appScheme=${APP_SCHEME}&projectId=${PROJECT_ID}&groupId=${state.group}`;
const platforms = ["android", "ios"];
const cells = (value) => platforms.map((platform) => value(state[platform]));
const rows = [
`<!-- ${MARKER} ${JSON.stringify(state)} -->`,
"🤖 Android preview",
`<!-- mobile-preview ${JSON.stringify(state)} -->`,
"🚀 Mobile preview",
"",
"&nbsp; | 🤖 Android",
"--- | ---",
`Fingerprint | ${state.fingerprint || "n/a"}`,
`Dev client | ${state.client ? `[Install](${state.client})` : `Building on Blacksmith ([run](${runUrl})); this comment gets the install link when it finishes`}`,
"&nbsp; | 🤖 Android | 🍎 iOS",
"--- | --- | ---",
`Fingerprint | ${cells((entry) => entry?.fingerprint || "n/a").join(" | ")}`,
`Dev client | ${cells((entry) => (entry?.client ? `[Install](${entry.client})` : entry?.fingerprint ? `Client unavailable ([build run](${runUrl}))` : "n/a")).join(" | ")}`,
`Update Details | ${cells((entry) => (entry?.group ? `[Update Permalink](https://expo.dev/projects/${PROJECT_ID}/updates/${entry.group})` : "n/a")).join(" | ")}`,
`Update QR | ${cells((entry) => {
if (!entry?.group) return "n/a";
const qr = `https://qr.expo.dev/eas-update?appScheme=${APP_SCHEME}&projectId=${PROJECT_ID}&groupId=${entry.group}`;
return `<a href="${qr}"><img src="${qr}" width="250px" height="250px" /></a>`;
}).join(" | ")}`,
];
if (state.group) {
rows.push(
`Update Details | [Update Permalink](https://expo.dev/projects/${PROJECT_ID}/updates/${state.group})`,
`Update QR | <a href="${qr}"><img src="${qr}" width="250px" height="250px" /></a>`,
);
}
return rows.join("\n");
}

Expand All @@ -80,39 +86,64 @@ async function github(path, init = {}) {
`GitHub ${init.method ?? "GET"} ${path}: ${response.status} ${await response.text()}`,
);
}
return response.json();
return response.status === 204 ? null : response.json();
}

async function main() {
const repository = process.env.GITHUB_REPOSITORY;
const pr = process.env.PR;
if (!repository || !pr || !process.env.GH_TOKEN) {
async function main({ env = process.env, request = github } = {}) {
const repository = env.GITHUB_REPOSITORY;
const pr = env.PR;
if (!repository || !pr || !env.GH_TOKEN) {
throw new Error("GITHUB_REPOSITORY, PR and GH_TOKEN are required.");
}
const runUrl = `${process.env.GITHUB_SERVER_URL}/${repository}/actions/runs/${process.env.GITHUB_RUN_ID}`;
let existing = null;
for (let page = 1; existing === null; page++) {
const comments = await github(
if (!env.ANDROID_FINGERPRINT && !env.IOS_FINGERPRINT) return;
if (env.PR_HEAD_SHA) {
const pull = await request(`/repos/${repository}/pulls/${pr}`);
if (pull.head.sha !== env.PR_HEAD_SHA) return;
}
const runUrl = `${env.GITHUB_SERVER_URL}/${repository}/actions/runs/${env.GITHUB_RUN_ID}`;
const previews = [];
for (let page = 1; ; page++) {
const comments = await request(
`/repos/${repository}/issues/${pr}/comments?per_page=100&page=${page}`,
);
// Only this workflow's own comment: anyone can post the marker, and nobody else's is editable.
existing =
comments.find(
previews.push(
...comments.filter(
(comment) =>
comment.user?.login === "github-actions[bot]" && readState(comment.body) !== null,
) ?? null;
comment.user?.login === "github-actions[bot]" &&
(readState(comment.body) !== null ||
comment.body?.startsWith(
`<!-- continuous-deploy-fingerprint-projectId:${PROJECT_ID} -->`,
)),
),
);
if (comments.length < 100) break;
}
const state = mergeState(readState(existing?.body), {
fingerprint: process.env.FINGERPRINT ?? "",
client: process.env.CLIENT ?? "",
group: process.env.GROUP ?? "",
});
const existing =
previews.find((comment) => comment.body.startsWith("<!-- mobile-preview ")) ?? previews[0];
const state = Object.assign(
{},
...previews.map((comment) => readState(comment.body)),
readState(existing?.body),
);
for (const platform of ["android", "ios"]) {
const prefix = platform.toUpperCase();
const next = {
fingerprint: env[`${prefix}_FINGERPRINT`] ?? "",
client: env[`${prefix}_CLIENT`] ?? "",
group: env[`${prefix}_GROUP`] ?? "",
};
if (next.fingerprint) state[platform] = mergeState(state[platform], next);
}
const body = JSON.stringify({ body: render(state, runUrl) });
if (existing) {
await github(`/repos/${repository}/issues/comments/${existing.id}`, { method: "PATCH", body });
await request(`/repos/${repository}/issues/comments/${existing.id}`, { method: "PATCH", body });
} else {
await github(`/repos/${repository}/issues/${pr}/comments`, { method: "POST", body });
await request(`/repos/${repository}/issues/${pr}/comments`, { method: "POST", body });
}
for (const comment of previews) {
if (comment.id !== existing.id) {
await request(`/repos/${repository}/issues/comments/${comment.id}`, { method: "DELETE" });
}
}
}

Expand All @@ -123,4 +154,4 @@ if (require.main === module) {
});
}

module.exports = { mergeState, readState, render };
module.exports = { main, mergeState, readState, render };
117 changes: 100 additions & 17 deletions .github/scripts/mobile-preview-comment.test.cjs
Original file line number Diff line number Diff line change
@@ -1,35 +1,42 @@
const assert = require("node:assert/strict");
const test = require("node:test");

const { mergeState, readState, render } = require("./mobile-preview-comment.cjs");
const { main, mergeState, readState, render } = require("./mobile-preview-comment.cjs");

const fingerprint = "c31608b37a8a2dca35ccee39cfd2ec7305042629";
const run = "https://github.com/pingdotgg/t3code/actions/runs/1";

test("the comment round-trips its state", () => {
const state = { fingerprint, client: "", group: "8e413a0a" };
const state = {
android: { fingerprint, client: "", group: "8e413a0a" },
ios: { fingerprint: "ios-fingerprint", client: "https://expo.dev/ios", group: "ios-group" },
};
const body = render(state, run);
assert.deepEqual(readState(body), state);
assert.match(
body,
/Building on Blacksmith \(\[run\]\(https:\/\/github\.com\/pingdotgg\/t3code\/actions\/runs\/1\)\)/,
);
assert.match(
body,
/qr\.expo\.dev\/eas-update\?appScheme=t3-code&projectId=[0-9a-f-]+&groupId=8e413a0a/,
);
assert.match(body, /Client unavailable/);
assert.match(body, /groupId=8e413a0a/);
assert.match(body, /groupId=ios-group/);
assert.match(body, /\[Install\]\(https:\/\/expo.dev\/ios\)/);
assert.equal(readState("🚀 Expo continuous deployment is ready!"), null);
});

test("the build job adds the install link without losing the update", () => {
const first = mergeState(null, { fingerprint, client: "", group: "8e413a0a" });
const built = mergeState(first, { fingerprint, client: "https://expo.dev/a/b", group: "" });
assert.deepEqual(built, { fingerprint, client: "https://expo.dev/a/b", group: "8e413a0a" });
assert.match(render(built, run), /Dev client \| \[Install\]\(https:\/\/expo\.dev\/a\/b\)/);
assert.match(
render({ android: built }, run),
/Dev client \| \[Install\]\(https:\/\/expo\.dev\/a\/b\)/,
);
});

test("a new fingerprint drops the old client; the same one keeps it", () => {
test("only a successful publication changes the fingerprint and client", () => {
const built = { fingerprint, client: "https://expo.dev/a/b", group: "old" };
assert.equal(mergeState(null, { fingerprint, client: "", group: "" }), null);
assert.deepEqual(
mergeState(built, { fingerprint: "f".repeat(40), client: "", group: "" }),
built,
);
assert.deepEqual(mergeState(built, { fingerprint, client: "", group: "new" }), {
fingerprint,
client: "https://expo.dev/a/b",
Expand All @@ -53,10 +60,86 @@ test("a build that finishes after the PR moved to another fingerprint changes no
test("state from the comment is always three strings", () => {
assert.deepEqual(
readState('<!-- mobile-preview-android {"fingerprint":5,"client":null} -->\nx'),
{
fingerprint: "",
client: "",
group: "",
},
{ android: { fingerprint: "", client: "", group: "" } },
);
});

test("publishing consolidates platform comments and preserves unrelated comments", async () => {
const android = { fingerprint, client: "https://expo.dev/android", group: "android-group" };
const ios = {
fingerprint: "ios-fingerprint",
client: "https://expo.dev/ios",
group: "ios-group",
};
const comments = new Map([
[
1,
{
id: 1,
user: { login: "github-actions[bot]" },
body: `<!-- mobile-preview-android ${JSON.stringify(android)} -->`,
},
],
[
2,
{
id: 2,
user: { login: "github-actions[bot]" },
body: `<!-- mobile-preview-ios ${JSON.stringify(ios)} -->`,
},
],
[
4,
{
id: 4,
user: { login: "github-actions[bot]" },
body: "<!-- continuous-deploy-fingerprint-projectId:d763fcb8-d37c-41ea-a773-b54a0ab4a454 -->\nOld Expo preview",
},
],
[
3,
{
id: 3,
user: { login: "contributor" },
body: `<!-- mobile-preview-ios ${JSON.stringify(ios)} -->`,
},
],
]);
await main({
env: {
GITHUB_REPOSITORY: "pingdotgg/t3code",
PR: "1",
GH_TOKEN: "test",
ANDROID_FINGERPRINT: fingerprint,
ANDROID_GROUP: "new-group",
},
request: async (path, init = {}) => {
if (!init.method) return [...comments.values()];
const id = Number(path.split("/").at(-1));
if (init.method === "DELETE") comments.delete(id);
else if (init.method === "PATCH") comments.get(id).body = JSON.parse(init.body).body;
else assert.fail("an existing preview should be reused");
},
});
assert.equal(comments.size, 2);
assert.deepEqual(readState(comments.get(1).body), {
android: { ...android, group: "new-group" },
ios,
});
assert.equal(comments.has(2), false);
assert.equal(comments.has(4), false);
assert.equal(comments.get(3).user.login, "contributor");
await main({
env: {
GITHUB_REPOSITORY: "pingdotgg/t3code",
PR: "1",
GH_TOKEN: "test",
ANDROID_FINGERPRINT: fingerprint,
PR_HEAD_SHA: "old-head",
},
request: async (path) => {
assert.equal(path, "/repos/pingdotgg/t3code/pulls/1");
return { head: { sha: "new-head" } };
},
});
});
Loading