Compare commits

..
Author SHA1 Message Date
Will Schurman c34d865741 Add continuous-deploy-fingerprint action 2024-04-15 14:55:23 -07:00
14 changed files with 4242 additions and 749 deletions

No files matched your search

+1 -1
View File
@@ -3,4 +3,4 @@
* text=auto
# These files are text and should be normalized (Convert crlf => lf)
build/** text eol=lf linguist-generated=true
build/** text eol=lf
+346 -262
View File
@@ -41830,6 +41830,267 @@ try {
} catch (er) {}
/***/ }),
/***/ 3793:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.continuousDeployFingerprintAction = exports.collectContinuousDeployFingerprintInput = exports.MESSAGE_ID = void 0;
const core_1 = __nccwpck_require__(2186);
const exec_1 = __nccwpck_require__(1514);
const io_1 = __nccwpck_require__(7436);
const comment_1 = __nccwpck_require__(7810);
const expo_1 = __nccwpck_require__(2489);
const github_1 = __nccwpck_require__(978);
const project_1 = __nccwpck_require__(7191);
const utils_1 = __nccwpck_require__(1314);
const worker_1 = __nccwpck_require__(8912);
exports.MESSAGE_ID = 'continuous-deploy-fingerprint-projectId:{projectId}';
function collectContinuousDeployFingerprintInput() {
return {
profile: (0, core_1.getInput)('profile'),
branch: (0, core_1.getInput)('branch'),
githubToken: (0, core_1.getInput)('github-token'),
workingDirectory: (0, core_1.getInput)('working-directory'),
commentId: (0, core_1.getInput)('comment-id') || exports.MESSAGE_ID,
};
}
exports.collectContinuousDeployFingerprintInput = collectContinuousDeployFingerprintInput;
(0, worker_1.executeAction)(continuousDeployFingerprintAction);
async function continuousDeployFingerprintAction(input = collectContinuousDeployFingerprintInput()) {
const config = await (0, project_1.loadProjectConfig)(input.workingDirectory);
if (!config.extra?.eas?.projectId) {
return (0, core_1.setFailed)(`Missing 'extra.eas.projectId' in app.json or app.config.js.`);
}
const androidFingerprintHash = await getFingerprintHashForPlatformAsync({
cwd: input.workingDirectory,
platform: 'android',
});
const iosFingerprintHash = await getFingerprintHashForPlatformAsync({ cwd: input.workingDirectory, platform: 'ios' });
(0, core_1.info)(`Android fingerprint: ${androidFingerprintHash}`);
(0, core_1.info)(`iOS fingerprint: ${iosFingerprintHash}`);
let androidBuildInfo = await getBuildInfoWithFingerprintAsync({
cwd: input.workingDirectory,
platform: 'android',
profile: input.profile,
fingerprintHash: androidFingerprintHash,
});
if (androidBuildInfo) {
(0, core_1.info)(`Existing Android build found for fingerprint: ${androidBuildInfo.id}`);
}
else {
(0, core_1.info)(`No existing Android build found for fingerprint, starting a new build...`);
androidBuildInfo = await createEASBuildAsync({
cwd: input.workingDirectory,
platform: 'android',
profile: input.profile,
});
}
let iosBuildInfo = await getBuildInfoWithFingerprintAsync({
cwd: input.workingDirectory,
platform: 'ios',
profile: input.profile,
fingerprintHash: iosFingerprintHash,
});
if (iosBuildInfo) {
(0, core_1.info)(`Existing iOS build found for fingerprint: ${iosBuildInfo.id}`);
}
else {
(0, core_1.info)(`No existing iOS build found for fingerprint, starting a new build...`);
iosBuildInfo = await createEASBuildAsync({ cwd: input.workingDirectory, platform: 'ios', profile: input.profile });
}
const builds = [androidBuildInfo, iosBuildInfo];
(0, core_1.info)(`Publishing EAS Update`);
const updates = await publishEASUpdatesAsync({
cwd: input.workingDirectory,
branch: input.branch,
});
if (!(0, github_1.hasPullContext)()) {
(0, core_1.info)(`Skipped comment: action was not run from a pull request`);
}
else {
const updatesVariables = (0, comment_1.getTemplateVariablesForUpdates)(config, updates, input);
const messageId = (0, utils_1.template)(input.commentId, updatesVariables);
const messageBody = createSummaryForUpdatesAndBuilds(updates, builds, updatesVariables);
await (0, github_1.createIssueComment)({
...(0, github_1.pullContext)(),
token: input.githubToken,
id: messageId,
body: messageBody,
});
}
(0, core_1.setOutput)('android-fingerprint', androidFingerprintHash);
(0, core_1.setOutput)('ios-fingerprint', iosFingerprintHash);
(0, core_1.setOutput)('android-build-id', androidBuildInfo.id);
(0, core_1.setOutput)('ios-build-id', iosBuildInfo.id);
(0, core_1.setOutput)('update-output', updates);
}
exports.continuousDeployFingerprintAction = continuousDeployFingerprintAction;
async function getFingerprintHashForPlatformAsync({ cwd, platform, }) {
try {
const { stdout } = await (0, exec_1.getExecOutput)('npx', ['expo-updates', 'fingerprint:generate', '--platform', platform], {
cwd,
});
const { hash } = JSON.parse(stdout);
if (!hash || typeof hash !== 'string') {
throw new Error(`Invalid fingerprint output: ${stdout}`);
}
return hash;
}
catch (error) {
throw new Error(`Could not get fingerprint for project`, { cause: error });
}
}
async function getBuildInfoWithFingerprintAsync({ cwd, platform, profile, fingerprintHash, }) {
let stdout;
try {
const execOutput = await (0, exec_1.getExecOutput)(await (0, io_1.which)('eas', true), [
'build:list',
'--platform',
platform,
'--status',
'finished',
'--profile',
profile,
'--runtimeVersion',
fingerprintHash,
'--limit',
'1',
'--json',
'--non-interactive',
], {
cwd,
silent: true,
});
stdout = execOutput.stdout;
}
catch (error) {
throw new Error(`Could not list project builds`, { cause: error });
}
const builds = JSON.parse(stdout);
if (!builds || !Array.isArray(builds)) {
throw new Error(`Could not get EAS builds for project`);
}
if (!builds[0]) {
return null;
}
return builds[0];
}
async function createEASBuildAsync({ cwd, profile, platform, }) {
let stdout;
try {
const execOutput = await (0, exec_1.getExecOutput)(await (0, io_1.which)('eas', true), [
'build',
'--profile',
profile,
'--platform',
platform,
'--non-interactive',
'--json',
'--no-wait',
'--build-logger-level',
'debug',
], {
cwd,
});
stdout = execOutput.stdout;
}
catch (error) {
throw new Error(`Could not run command eas build`, { cause: error });
}
return JSON.parse(stdout);
}
async function publishEASUpdatesAsync({ cwd, branch }) {
let stdout = '';
try {
({ stdout } = await (0, exec_1.getExecOutput)(await (0, io_1.which)('eas', true), ['update', '--auto', '--branch', branch, '--non-interactive'], {
cwd,
}));
}
catch (error) {
throw new Error(`Could not create a new EAS Update`, { cause: error });
}
return JSON.parse(stdout);
}
function createSummaryForUpdatesAndBuilds(updates, builds, updatesVariables) {
return [
createSummaryForBuilds(builds),
'',
createMultipleQrSummaryForUpdates(updates, updatesVariables),
`> Learn more about [𝝠 Expo Github Action](https://github.com/expo/expo-github-action/tree/main/continuous-deploy-fingerprint)`,
].join('\n');
}
async function createSummaryForBuilds(builds) {
const tableRows = [];
for (const build of builds) {
let name;
if (build.platform === 'ANDROID') {
name = `${expo_1.appPlatformEmojis.ANDROID} Android build`;
}
else if (build.platform === 'IOS') {
name = `${expo_1.appPlatformEmojis.IOS} iOS build`;
}
else {
name = 'Unknown build';
}
const buildPageURL = (0, expo_1.getBuildLogsUrl)(build);
const details = (0, comment_1.createDetails)({
summary: 'Details',
details: [
`Distribution: \`${build.distribution}\``,
`Build profile: \`${build.buildProfile}\``,
`Runtime version: \`${build.runtimeVersion}\``,
`App version: \`${build.appVersion}\``,
].join('<br>'),
delim: '',
});
tableRows.push(`| ${name} | [View build page](${buildPageURL}) | ${details} |`);
}
return ['| Name | Build | Details |', '| :-- | :-- | :-- |', ...tableRows].join('\n');
}
function createMultipleQrSummaryForUpdates(updates, vars) {
const createTableHeader = (segments) => segments.filter(Boolean).join(' <br /> ');
const androidHeader = createTableHeader([
'Android',
vars.androidId && vars.androidRuntimeVersion ? `_(${vars.androidRuntimeVersion})_` : '',
vars.androidId && vars.androidLink ? `**[More info](${vars.androidLink})**` : '',
]);
const androidQr = vars.androidId && vars.androidQR
? `<a href="${vars.androidQR}"><img src="${vars.androidQR}" width="250px" height="250px" /></a>`
: null;
const iosHeader = createTableHeader([
'iOS',
vars.iosId && vars.iosRuntimeVersion ? `_(${vars.iosRuntimeVersion})_` : '',
vars.iosId && vars.iosLink ? `**[More info](${vars.iosLink})**` : '',
]);
const iosQr = vars.iosId && vars.iosQR
? `<a href="${vars.iosQR}"><img src="${vars.iosQR}" width="250px" height="250px" /></a>`
: null;
return `${createSummaryHeaderForUpdates(updates, vars)}
${androidHeader} | ${iosHeader}
--- | ---
${androidQr || '_not created_'} | ${iosQr || '_not created_'}`;
}
function createSummaryHeaderForUpdates(updates, vars) {
const platformName = `Platform${updates.length === 1 ? '' : 's'}`;
const platformValue = updates
.map(update => update.platform)
.sort((a, b) => a.localeCompare(b))
.map(platform => `**${platform}**`)
.join(', ');
const appSchemes = vars.projectScheme ? `- Scheme → **${JSON.parse(vars.projectSchemes).join('**, **')}**` : '';
return `🚀 Expo preview is ready!
- Project → **${vars.projectSlug}**
- ${platformName} → ${platformValue}
${appSchemes}`.trim();
}
/***/ }),
/***/ 7810:
@@ -41838,9 +42099,63 @@ try {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createDetails = exports.getSchemesInOrderFromConfig = exports.getQrTarget = void 0;
exports.createDetails = exports.getSchemesInOrderFromConfig = exports.getQrTarget = exports.prefixKeys = exports.getTemplateVariablesForUpdates = void 0;
const core_1 = __nccwpck_require__(2186);
const eas_1 = __nccwpck_require__(3251);
const expo_1 = __nccwpck_require__(2489);
/**
* Generate useful variables for the message body, and as step outputs from a set of updates.
*/
function getTemplateVariablesForUpdates(config, updates, options) {
const projectId = config.extra?.eas?.projectId;
const android = updates.find(update => update.platform === 'android');
const ios = updates.find(update => update.platform === 'ios');
const appSchemes = getSchemesInOrderFromConfig(config) || [];
const appSlug = config.slug;
const qrTarget = getQrTarget(options);
return {
// EAS / Expo specific
projectId,
projectName: config.name,
projectSlug: appSlug,
projectScheme: appSchemes[0] || '', // This is the longest scheme from one or more custom app schemes
projectSchemes: JSON.stringify(appSchemes), // These are all custom app schemes, in order from longest to shortest as JSON
// Shared update properties
// Note, only use these properties when the update groups are identical
groupId: updates[0].group,
runtimeVersion: updates[0].runtimeVersion,
qr: (0, eas_1.getUpdateGroupQr)({ projectId, updateGroupId: updates[0].group, appSlug, qrTarget }),
link: (0, eas_1.getUpdateGroupWebsite)({ projectId, updateGroupId: updates[0].group }),
// These are safe to access regardless of the update groups
branchName: updates[0].branch,
message: updates[0].message,
createdAt: updates[0].createdAt,
gitCommitHash: updates[0].gitCommitHash,
// Android update
androidId: android?.id || '',
androidGroupId: android?.group || '',
androidBranchName: android?.branch || '',
androidManifestPermalink: android?.manifestPermalink || '',
androidMessage: android?.message || '',
androidRuntimeVersion: android?.runtimeVersion || '',
androidQR: android ? (0, eas_1.getUpdateGroupQr)({ projectId, updateGroupId: android.group, appSlug, qrTarget }) : '',
androidLink: android ? (0, eas_1.getUpdateGroupWebsite)({ projectId, updateGroupId: android.group }) : '',
// iOS update
iosId: ios?.id || '',
iosGroupId: ios?.group || '',
iosBranchName: ios?.branch || '',
iosManifestPermalink: ios?.manifestPermalink || '',
iosMessage: ios?.message || '',
iosRuntimeVersion: ios?.runtimeVersion || '',
iosQR: ios ? (0, eas_1.getUpdateGroupQr)({ projectId, updateGroupId: ios.group, appSlug, qrTarget }) : '',
iosLink: ios ? (0, eas_1.getUpdateGroupWebsite)({ projectId, updateGroupId: ios.group }) : '',
};
}
exports.getTemplateVariablesForUpdates = getTemplateVariablesForUpdates;
function prefixKeys(input, prefix) {
return Object.fromEntries(Object.entries(input).map(([k, v]) => [prefix + k, v]));
}
exports.prefixKeys = prefixKeys;
function getQrTarget(input) {
if (!input.qrTarget) {
const appType = (0, expo_1.projectAppType)(input.workingDirectory);
@@ -42411,6 +42726,29 @@ async function loadProjectConfig(cwd) {
exports.loadProjectConfig = loadProjectConfig;
/***/ }),
/***/ 1314:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.template = void 0;
/**
* Replace all template variables in a string.
* This uses the notation of `{varname}`, which can be defined as object.
*/
function template(template, replacements) {
let result = template;
for (const name in replacements) {
result = result.replaceAll(`{${name}}`, replacements[name]);
}
return result;
}
exports.template = template;
/***/ }),
/***/ 8912:
@@ -44507,266 +44845,12 @@ module.exports = JSON.parse('[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"]
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";
var exports = __webpack_exports__;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.continuousDeployFingerprintAction = exports.collectContinuousDeployFingerprintInput = void 0;
const core_1 = __nccwpck_require__(2186);
const exec_1 = __nccwpck_require__(1514);
const io_1 = __nccwpck_require__(7436);
const comment_1 = __nccwpck_require__(7810);
const eas_1 = __nccwpck_require__(3251);
const expo_1 = __nccwpck_require__(2489);
const github_1 = __nccwpck_require__(978);
const project_1 = __nccwpck_require__(7191);
const worker_1 = __nccwpck_require__(8912);
function collectContinuousDeployFingerprintInput() {
return {
profile: (0, core_1.getInput)('profile'),
branch: (0, core_1.getInput)('branch'),
githubToken: (0, core_1.getInput)('github-token'),
workingDirectory: (0, core_1.getInput)('working-directory'),
};
}
exports.collectContinuousDeployFingerprintInput = collectContinuousDeployFingerprintInput;
(0, worker_1.executeAction)(continuousDeployFingerprintAction);
async function continuousDeployFingerprintAction(input = collectContinuousDeployFingerprintInput()) {
const isInPullRequest = (0, github_1.hasPullContext)();
const config = await (0, project_1.loadProjectConfig)(input.workingDirectory);
const projectId = config.extra?.eas?.projectId;
if (!projectId) {
return (0, core_1.setFailed)(`Missing 'extra.eas.projectId' in app.json or app.config.js.`);
}
const androidFingerprintHash = await getFingerprintHashForPlatformAsync({
cwd: input.workingDirectory,
platform: 'android',
});
const iosFingerprintHash = await getFingerprintHashForPlatformAsync({ cwd: input.workingDirectory, platform: 'ios' });
(0, core_1.info)(`Android fingerprint: ${androidFingerprintHash}`);
(0, core_1.info)(`iOS fingerprint: ${iosFingerprintHash}`);
(0, core_1.info)('Looking for builds with matching runtime version (fingerprint)...');
let androidBuildInfo = await getBuildInfoWithFingerprintAsync({
cwd: input.workingDirectory,
platform: 'android',
profile: input.profile,
fingerprintHash: androidFingerprintHash,
excludeExpiredBuilds: isInPullRequest,
});
if (androidBuildInfo) {
(0, core_1.info)(`Existing Android build found with matching fingerprint: ${androidBuildInfo.id}`);
}
else {
(0, core_1.info)(`No existing Android build found for fingerprint, starting a new build...`);
androidBuildInfo = await createEASBuildAsync({
cwd: input.workingDirectory,
platform: 'android',
profile: input.profile,
});
}
let iosBuildInfo = await getBuildInfoWithFingerprintAsync({
cwd: input.workingDirectory,
platform: 'ios',
profile: input.profile,
fingerprintHash: iosFingerprintHash,
excludeExpiredBuilds: isInPullRequest,
});
if (iosBuildInfo) {
(0, core_1.info)(`Existing iOS build found with matching fingerprint: ${iosBuildInfo.id}`);
}
else {
(0, core_1.info)(`No existing iOS build found for fingerprint, starting a new build...`);
iosBuildInfo = await createEASBuildAsync({ cwd: input.workingDirectory, platform: 'ios', profile: input.profile });
}
const builds = [androidBuildInfo, iosBuildInfo];
(0, core_1.info)(`Publishing EAS Update...`);
const updates = await publishEASUpdatesAsync({
cwd: input.workingDirectory,
branch: input.branch,
});
if (!isInPullRequest) {
(0, core_1.info)(`Skipped comment: action was not run from a pull request`);
}
else {
const messageId = `continuous-deploy-fingerprint-projectId:${projectId}`;
const messageBody = createSummaryForUpdatesAndBuilds({ config, projectId, updates, builds, options: input });
await (0, github_1.createIssueComment)({
...(0, github_1.pullContext)(),
token: input.githubToken,
id: messageId,
body: messageBody,
});
}
(0, core_1.setOutput)('android-fingerprint', androidFingerprintHash);
(0, core_1.setOutput)('ios-fingerprint', iosFingerprintHash);
(0, core_1.setOutput)('android-build-id', androidBuildInfo.id);
(0, core_1.setOutput)('ios-build-id', iosBuildInfo.id);
(0, core_1.setOutput)('update-output', updates);
}
exports.continuousDeployFingerprintAction = continuousDeployFingerprintAction;
async function getFingerprintHashForPlatformAsync({ cwd, platform, }) {
try {
const extraArgs = (0, core_1.isDebug)() ? ['--debug'] : [];
const { stdout } = await (0, exec_1.getExecOutput)('npx', ['expo-updates', 'fingerprint:generate', '--platform', platform, ...extraArgs], {
cwd,
silent: !(0, core_1.isDebug)(),
});
const { hash } = JSON.parse(stdout);
if (!hash || typeof hash !== 'string') {
throw new Error(`Invalid fingerprint output: ${stdout}`);
}
return hash;
}
catch (error) {
throw new Error(`Could not get fingerprint for project: ${String(error)}`);
}
}
async function getBuildInfoWithFingerprintAsync({ cwd, platform, profile, fingerprintHash, excludeExpiredBuilds, }) {
let stdout;
try {
const execOutput = await (0, exec_1.getExecOutput)(await (0, io_1.which)('eas', true), [
'build:list',
'--platform',
platform,
'--status',
'finished',
'--buildProfile',
profile,
'--runtimeVersion',
fingerprintHash,
'--limit',
'1',
'--json',
'--non-interactive',
], {
cwd,
silent: !(0, core_1.isDebug)(),
});
stdout = execOutput.stdout;
}
catch (error) {
throw new Error(`Could not list project builds: ${String(error)}`);
}
const builds = JSON.parse(stdout);
if (!builds || !Array.isArray(builds)) {
throw new Error(`Could not get EAS builds for project`);
}
if (!builds[0]) {
return null;
}
const build = builds[0];
if (excludeExpiredBuilds) {
// if the build is expired or will expire within the next day,
// return null to trigger a new build
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
if (tomorrow > new Date(build.expirationDate)) {
return null;
}
}
return build;
}
async function createEASBuildAsync({ cwd, profile, platform, }) {
let stdout;
try {
const extraArgs = (0, core_1.isDebug)() ? ['--build-logger-level', 'debug'] : [];
const execOutput = await (0, exec_1.getExecOutput)(await (0, io_1.which)('eas', true), ['build', '--profile', profile, '--platform', platform, '--non-interactive', '--json', '--no-wait', ...extraArgs], {
cwd,
silent: !(0, core_1.isDebug)(),
});
stdout = execOutput.stdout;
}
catch (error) {
throw new Error(`Could not run command eas build: ${String(error)}`);
}
return JSON.parse(stdout)[0];
}
async function publishEASUpdatesAsync({ cwd, branch }) {
let stdout;
try {
const execOutput = await (0, exec_1.getExecOutput)(await (0, io_1.which)('eas', true), ['update', '--auto', '--branch', branch, '--non-interactive', '--json'], {
cwd,
silent: !(0, core_1.isDebug)(),
});
stdout = execOutput.stdout;
}
catch (error) {
throw new Error(`Could not create a new EAS Update: ${String(error)}`);
}
return JSON.parse(stdout);
}
function createSummaryForUpdatesAndBuilds({ config, projectId, updates, builds, options, }) {
const appSlug = config.slug;
const qrTarget = (0, comment_1.getQrTarget)(options);
const appSchemes = (0, comment_1.getSchemesInOrderFromConfig)(config) || [];
const androidBuild = builds.find(build => build.platform === expo_1.AppPlatform.Android);
const iosBuild = builds.find(build => build.platform === expo_1.AppPlatform.Ios);
const androidUpdate = updates.find(update => update.platform === 'android');
const iosUpdate = updates.find(update => update.platform === 'ios');
const getBuildLink = (build) => build ? `[Build Permalink](${(0, expo_1.getBuildLogsUrl)(build)})` : 'n/a';
const getUpdateLink = (update) => update ? `[Update Permalink](${(0, eas_1.getUpdateGroupWebsite)({ projectId, updateGroupId: update.group })})` : 'n/a';
const getUpdateQRURL = (update) => update ? (0, eas_1.getUpdateGroupQr)({ projectId, updateGroupId: update.group, appSlug, qrTarget }) : null;
const getBuildDetails = (build) => build
? getBuildLink(build) +
'<br />' +
(0, comment_1.createDetails)({
summary: 'Details',
details: [
`Distribution: \`${build.distribution}\``,
`Build profile: \`${build.buildProfile}\``,
`Runtime version: \`${build.runtimeVersion}\``,
`App version: \`${build.appVersion}\``,
`Git commit: \`${build.gitCommitHash}\``,
].join('<br />'),
delim: '',
})
: 'n/a';
const getUpdateDetails = (update) => update
? getUpdateLink(update) +
'<br />' +
(0, comment_1.createDetails)({
summary: 'Details',
details: [
`Branch: \`${update.branch}\``,
`Runtime version: \`${update.runtimeVersion}\``,
`Git commit: \`${update.gitCommitHash}\``,
].join('<br />'),
delim: '',
})
: 'n/a';
const androidQRURL = getUpdateQRURL(androidUpdate);
const iosQRURL = getUpdateQRURL(iosUpdate);
const androidQr = androidQRURL
? `<a href="${androidQRURL}"><img src="${androidQRURL}" width="250px" height="250px" /></a>`
: null;
const iosQr = iosQRURL ? `<a href="${iosQRURL}"><img src="${iosQRURL}" width="250px" height="250px" /></a>` : null;
const platformName = `Platform${updates.length === 1 ? '' : 's'}`;
const platformValue = updates
.map(update => update.platform)
.sort((a, b) => a.localeCompare(b))
.map(platform => `**${platform}**`)
.join(', ');
const schemesMessage = appSchemes[0] ? `- Scheme → **${appSchemes.join('**, **')}**` : '';
return `🚀 Expo continuous deployment is ready!
- Project → **${appSlug}**
- ${platformName} → ${platformValue}
${schemesMessage}
&nbsp; | ${expo_1.appPlatformEmojis[expo_1.AppPlatform.Android]} Android | ${expo_1.appPlatformEmojis[expo_1.AppPlatform.Ios]} iOS
--- | --- | ---
Fingerprint | ${androidBuild?.runtimeVersion ?? 'n/a'} | ${iosBuild?.runtimeVersion ?? 'n/a'}
Build Details | ${getBuildDetails(androidBuild)} | ${getBuildDetails(iosBuild)}
Update Details | ${getUpdateDetails(androidUpdate)} | ${getUpdateDetails(iosUpdate)}
Update QR | ${androidQr ?? 'n/a'} | ${iosQr ?? 'n/a'}
`;
}
})();
module.exports = __webpack_exports__;
/******/
/******/ // startup
/******/ // Load entry module and return exports
/******/ // This entry module is referenced by other modules so it can't be inlined
/******/ var __webpack_exports__ = __nccwpck_require__(3793);
/******/ module.exports = __webpack_exports__;
/******/
/******/ })()
;
File diff suppressed because it is too large. Load diff
+38
View File
@@ -1191,6 +1191,25 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
lru-cache
ISC
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
mime-db
MIT
(The MIT License)
@@ -1596,3 +1615,22 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
yallist
ISC
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+86 -81
View File
@@ -41838,7 +41838,7 @@ try {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createSummary = exports.getVariables = exports.previewAction = exports.previewInput = exports.MESSAGE_ID = void 0;
exports.createSummaryForUpdates = exports.previewAction = exports.previewInput = exports.MESSAGE_ID = void 0;
const core_1 = __nccwpck_require__(2186);
const comment_1 = __nccwpck_require__(7810);
const eas_1 = __nccwpck_require__(3251);
@@ -41881,9 +41881,9 @@ async function previewAction(input = previewInput()) {
if (!config.extra?.eas?.projectId) {
return (0, core_1.setFailed)(`Missing 'extra.eas.projectId' in app.json or app.config.js.`);
}
const variables = getVariables(config, updates, input);
const variables = (0, comment_1.getTemplateVariablesForUpdates)(config, updates, input);
const messageId = (0, utils_1.template)(input.commentId, variables);
const messageBody = createSummary(updates, variables);
const messageBody = createSummaryForUpdates(updates, variables);
if (!input.shouldComment) {
(0, core_1.info)(`Skipped comment: 'comment' is disabled`);
}
@@ -41927,15 +41927,90 @@ function sanitizeCommand(input) {
return command;
}
/**
* Generate useful variables for the message body, and as step outputs.
* Generate the message body for a single update.
* Note, this is not configurable, but you can use the variables used to construct your own.
*/
function getVariables(config, updates, options) {
function createSummaryForUpdates(updates, vars) {
// If all updates are in the same group, we can unify QR codes
if (updates.every(update => update.group === updates[0].group)) {
return createSingleQrSummaryForUpdates(updates, vars);
}
return createMultipleQrSummaryForUpdates(updates, vars);
}
exports.createSummaryForUpdates = createSummaryForUpdates;
function createSummaryHeaderForUpdates(updates, vars) {
const platformName = `Platform${updates.length === 1 ? '' : 's'}`;
const platformValue = updates
.map(update => update.platform)
.sort((a, b) => a.localeCompare(b))
.map(platform => `**${platform}**`)
.join(', ');
const appSchemes = vars.projectScheme ? `- Scheme → **${JSON.parse(vars.projectSchemes).join('**, **')}**` : '';
return `🚀 Expo preview is ready!
- Project → **${vars.projectSlug}**
- ${platformName} → ${platformValue}
${appSchemes}`.trim();
}
function createSingleQrSummaryForUpdates(updates, vars) {
return `${createSummaryHeaderForUpdates(updates, vars)}
- Runtime Version → **${vars.runtimeVersion}**
- **[More info](${vars.link})**
<a href="${vars.qr}"><img src="${vars.qr}" width="250px" height="250px" /></a>
> Learn more about [𝝠 Expo Github Action](https://github.com/expo/expo-github-action/tree/main/preview#example-workflows)`;
}
function createMultipleQrSummaryForUpdates(updates, vars) {
const createTableHeader = (segments) => segments.filter(Boolean).join(' <br /> ');
const androidHeader = createTableHeader([
'Android',
vars.androidId && vars.androidRuntimeVersion ? `_(${vars.androidRuntimeVersion})_` : '',
vars.androidId && vars.androidLink ? `**[More info](${vars.androidLink})**` : '',
]);
const androidQr = vars.androidId && vars.androidQR
? `<a href="${vars.androidQR}"><img src="${vars.androidQR}" width="250px" height="250px" /></a>`
: null;
const iosHeader = createTableHeader([
'iOS',
vars.iosId && vars.iosRuntimeVersion ? `_(${vars.iosRuntimeVersion})_` : '',
vars.iosId && vars.iosLink ? `**[More info](${vars.iosLink})**` : '',
]);
const iosQr = vars.iosId && vars.iosQR
? `<a href="${vars.iosQR}"><img src="${vars.iosQR}" width="250px" height="250px" /></a>`
: null;
return `${createSummaryHeaderForUpdates(updates, vars)}
${androidHeader} | ${iosHeader}
--- | ---
${androidQr || '_not created_'} | ${iosQr || '_not created_'}
> Learn more about [𝝠 Expo Github Action](https://github.com/expo/expo-github-action/tree/main/preview#example-workflows)`;
}
/***/ }),
/***/ 7810:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createDetails = exports.getSchemesInOrderFromConfig = exports.getQrTarget = exports.prefixKeys = exports.getTemplateVariablesForUpdates = void 0;
const core_1 = __nccwpck_require__(2186);
const eas_1 = __nccwpck_require__(3251);
const expo_1 = __nccwpck_require__(2489);
/**
* Generate useful variables for the message body, and as step outputs from a set of updates.
*/
function getTemplateVariablesForUpdates(config, updates, options) {
const projectId = config.extra?.eas?.projectId;
const android = updates.find(update => update.platform === 'android');
const ios = updates.find(update => update.platform === 'ios');
const appSchemes = (0, comment_1.getSchemesInOrderFromConfig)(config) || [];
const appSchemes = getSchemesInOrderFromConfig(config) || [];
const appSlug = config.slug;
const qrTarget = (0, comment_1.getQrTarget)(options);
const qrTarget = getQrTarget(options);
return {
// EAS / Expo specific
projectId,
@@ -41974,81 +42049,11 @@ function getVariables(config, updates, options) {
iosLink: ios ? (0, eas_1.getUpdateGroupWebsite)({ projectId, updateGroupId: ios.group }) : '',
};
}
exports.getVariables = getVariables;
/**
* Generate the message body for a single update.
* Note, this is not configurable, but you can use the variables used to construct your own.
*/
function createSummary(updates, vars) {
// If all updates are in the same group, we can unify QR codes
if (updates.every(update => update.group === updates[0].group)) {
return createSingleQrSummary(updates, vars);
}
return createMultipleQrSummary(updates, vars);
exports.getTemplateVariablesForUpdates = getTemplateVariablesForUpdates;
function prefixKeys(input, prefix) {
return Object.fromEntries(Object.entries(input).map(([k, v]) => [prefix + k, v]));
}
exports.createSummary = createSummary;
function createSummaryHeader(updates, vars) {
const platformName = `Platform${updates.length === 1 ? '' : 's'}`;
const platformValue = updates
.map(update => update.platform)
.sort((a, b) => a.localeCompare(b))
.map(platform => `**${platform}**`)
.join(', ');
const appSchemes = vars.projectScheme ? `- Scheme → **${JSON.parse(vars.projectSchemes).join('**, **')}**` : '';
return `🚀 Expo preview is ready!
- Project → **${vars.projectSlug}**
- ${platformName} → ${platformValue}
${appSchemes}`.trim();
}
function createSingleQrSummary(updates, vars) {
return `${createSummaryHeader(updates, vars)}
- Runtime Version → **${vars.runtimeVersion}**
- **[More info](${vars.link})**
<a href="${vars.qr}"><img src="${vars.qr}" width="250px" height="250px" /></a>
> Learn more about [𝝠 Expo Github Action](https://github.com/expo/expo-github-action/tree/main/preview#example-workflows)`;
}
function createMultipleQrSummary(updates, vars) {
const createTableHeader = (segments) => segments.filter(Boolean).join(' <br /> ');
const androidHeader = createTableHeader([
'Android',
vars.androidId && vars.androidRuntimeVersion ? `_(${vars.androidRuntimeVersion})_` : '',
vars.androidId && vars.androidLink ? `**[More info](${vars.androidLink})**` : '',
]);
const androidQr = vars.androidId && vars.androidQR
? `<a href="${vars.androidQR}"><img src="${vars.androidQR}" width="250px" height="250px" /></a>`
: null;
const iosHeader = createTableHeader([
'iOS',
vars.iosId && vars.iosRuntimeVersion ? `_(${vars.iosRuntimeVersion})_` : '',
vars.iosId && vars.iosLink ? `**[More info](${vars.iosLink})**` : '',
]);
const iosQr = vars.iosId && vars.iosQR
? `<a href="${vars.iosQR}"><img src="${vars.iosQR}" width="250px" height="250px" /></a>`
: null;
return `${createSummaryHeader(updates, vars)}
${androidHeader} | ${iosHeader}
--- | ---
${androidQr || '_not created_'} | ${iosQr || '_not created_'}
> Learn more about [𝝠 Expo Github Action](https://github.com/expo/expo-github-action/tree/main/preview#example-workflows)`;
}
/***/ }),
/***/ 7810:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.createDetails = exports.getSchemesInOrderFromConfig = exports.getQrTarget = void 0;
const core_1 = __nccwpck_require__(2186);
const expo_1 = __nccwpck_require__(2489);
exports.prefixKeys = prefixKeys;
function getQrTarget(input) {
if (!input.qrTarget) {
const appType = (0, expo_1.projectAppType)(input.workingDirectory);
+38 -80
View File
@@ -33,7 +33,7 @@
<br />
> **Warning**
> This sub action is still in development and might change without notice. It is not yet ready for use.
> This sub action is experimental and might change without notice. Use it at your own risk.
## Overview
@@ -44,6 +44,41 @@
4. Publish an update on EAS update.
5. If run on a PR, post a comment indicating what was done.
## Usage
To use this action, add the following code to your workflow:
```yaml
on:
push:
# REQUIRED: push main (default) branch is necessary for this action to update its fingerprint database
branches: [main]
pull_request:
types: [opened, synchronize]
jobs:
<JOB_NAME>:
runs-on: <RUNNER>
# REQUIRED: limit concurrency when running on main or within a PR
concurrency: continuous-deploy-fingerprint-${{ github.event_name != 'pull_request' && 'main' || github.run_id }}
permissions:
# REQUIRED: Allow comments of PRs
pull-requests: write # Allow comments on PRs
steps:
- name: 🏗 Setup EAS
uses: expo/expo-github-action@v8
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
- name: Continuously Deploy
id: continuous-deploy
uses: expo/expo-github-action/continuous-deploy-fingerprint@main
with:
profile: ${{ github.event_name != 'pull_request' && 'production' || 'development }}
```
### Configuration options
This action is customizable through variables defined in the [`action.yml`](action.yml).
@@ -51,8 +86,8 @@ Here is a summary of all the input options you can use.
| variable | default | description |
| ---------------------------------- | ---------------- | ----------------------------------------------------------------------- |
| **profile** | (required) | The EAS Build profile to use |
| **branch** | (required) | The EAS Update branch on which to publish |
| **profile** | (required) | The EAS Build profile to use, must have EAS Update channel specified in eas.json |
| **branch** | (channel name from profile) | The EAS Update branch on which to publish |
| **working-directory** | - | The relative directory of your Expo app |
| **github-token** | `github.token` | GitHub token to use when commenting on PR ([read more](#github-tokens)) |
@@ -78,85 +113,8 @@ When using the GitHub API, you always need to be authenticated.
This action tries to auto-authenticate using the [Automatic token authentication][link-gha-token] from GitHub.
You can overwrite the token by adding the `GITHUB_TOKEN` environment variable or add the **github-token** input.
## Example workflows
Before diving into the workflow examples, you should know the basics of GitHub Actions.
You can read more about this in the [GitHub Actions documentation][link-actions].
### Continuously deploy after tests on main branch and pull requests
This workflow continuously deploys:
- main branch -> production EAS Build profile and EAS Update branch
- PR branches -> development EAS Build profile and EAS Update branch
This means that every commit landed to main will go out to users on production. If a new build is created, it will need to be manually submitted to the app stores.
Pull requests also do a build if necessary and display a QR code to scan to preview the latest commit on the PR.
```yml
on:
push:
branches:
- main
pull_request:
types: [opened, synchronize]
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: 🏗 Setup repo
uses: actions/checkout@v4
- name: 🏗 Setup Node
uses: actions/setup-node@v3
with:
node-version: 18.x
cache: yarn
- name: 📦 Install dependencies
run: yarn install
- name: 🧪 Run tests
run: yarn test
continuously-deploy:
needs: test
runs-on: ubuntu-latest
concurrency: continuous-deploy-fingerprint-${{ github.event_name != 'pull_request' && 'main' || github.run_id }}
permissions:
contents: read # Allow checkout
pull-requests: write # Allow comments on PRs
steps:
- name: 🏗 Setup repo
uses: actions/checkout@v4
- name: 🏗 Setup Node
uses: actions/setup-node@v3
with:
node-version: 18.x
- name: 📦 Install dependencies
run: yarn install
- name: 🏗 Setup EAS
uses: expo/expo-github-action@main
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
- name: Continuously Deploy
uses: expo/expo-github-action/continuous-deploy-fingerprint@main
with:
profile: ${{ github.event_name != 'pull_request' && 'production' || 'development' }}
branch: ${{ github.event_name != 'pull_request' && 'production' || 'development' }}
```
<div align="center">
<br />
with :heart:&nbsp;<strong>Expo</strong>
<br />
</div>
[link-actions]: https://help.github.com/en/categories/automating-your-workflow-with-github-actions
[link-gha-token]: https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token
+1 -1
View File
@@ -14,7 +14,7 @@ inputs:
required: true
branch:
description: The EAS Update branch on which to publish.
required: true
required: false
github-token:
description: GitHub token to use when commenting on PR
required: false
+133 -146
View File
@@ -1,32 +1,32 @@
import { getInput, info, isDebug, setFailed, setOutput } from '@actions/core';
import { getInput, info, setFailed, setOutput } from '@actions/core';
import { getExecOutput } from '@actions/exec';
import { which } from '@actions/io';
import { ExpoConfig } from '@expo/config';
import { createDetails, getQrTarget, getSchemesInOrderFromConfig } from '../comment';
import { EasUpdate, getUpdateGroupQr, getUpdateGroupWebsite } from '../eas';
import { AppPlatform, BuildInfo, appPlatformEmojis, getBuildLogsUrl } from '../expo';
import { createDetails, getTemplateVariablesForUpdates } from '../comment';
import { EasUpdate } from '../eas';
import { BuildInfo, appPlatformEmojis, getBuildLogsUrl } from '../expo';
import { createIssueComment, hasPullContext, pullContext } from '../github';
import { loadProjectConfig } from '../project';
import { template } from '../utils';
import { executeAction } from '../worker';
export const MESSAGE_ID = 'continuous-deploy-fingerprint-projectId:{projectId}';
export function collectContinuousDeployFingerprintInput() {
return {
profile: getInput('profile'),
branch: getInput('branch'),
githubToken: getInput('github-token'),
workingDirectory: getInput('working-directory'),
commentId: getInput('comment-id') || MESSAGE_ID,
};
}
executeAction(continuousDeployFingerprintAction);
export async function continuousDeployFingerprintAction(input = collectContinuousDeployFingerprintInput()) {
const isInPullRequest = hasPullContext();
const config = await loadProjectConfig(input.workingDirectory);
const projectId = config.extra?.eas?.projectId;
if (!projectId) {
if (!config.extra?.eas?.projectId) {
return setFailed(`Missing 'extra.eas.projectId' in app.json or app.config.js.`);
}
@@ -39,17 +39,14 @@ export async function continuousDeployFingerprintAction(input = collectContinuou
info(`Android fingerprint: ${androidFingerprintHash}`);
info(`iOS fingerprint: ${iosFingerprintHash}`);
info('Looking for builds with matching runtime version (fingerprint)...');
let androidBuildInfo = await getBuildInfoWithFingerprintAsync({
cwd: input.workingDirectory,
platform: 'android',
profile: input.profile,
fingerprintHash: androidFingerprintHash,
excludeExpiredBuilds: isInPullRequest,
});
if (androidBuildInfo) {
info(`Existing Android build found with matching fingerprint: ${androidBuildInfo.id}`);
info(`Existing Android build found for fingerprint: ${androidBuildInfo.id}`);
} else {
info(`No existing Android build found for fingerprint, starting a new build...`);
androidBuildInfo = await createEASBuildAsync({
@@ -64,10 +61,9 @@ export async function continuousDeployFingerprintAction(input = collectContinuou
platform: 'ios',
profile: input.profile,
fingerprintHash: iosFingerprintHash,
excludeExpiredBuilds: isInPullRequest,
});
if (iosBuildInfo) {
info(`Existing iOS build found with matching fingerprint: ${iosBuildInfo.id}`);
info(`Existing iOS build found for fingerprint: ${iosBuildInfo.id}`);
} else {
info(`No existing iOS build found for fingerprint, starting a new build...`);
iosBuildInfo = await createEASBuildAsync({ cwd: input.workingDirectory, platform: 'ios', profile: input.profile });
@@ -75,18 +71,19 @@ export async function continuousDeployFingerprintAction(input = collectContinuou
const builds = [androidBuildInfo, iosBuildInfo];
info(`Publishing EAS Update...`);
info(`Publishing EAS Update`);
const updates = await publishEASUpdatesAsync({
cwd: input.workingDirectory,
branch: input.branch,
});
if (!isInPullRequest) {
if (!hasPullContext()) {
info(`Skipped comment: action was not run from a pull request`);
} else {
const messageId = `continuous-deploy-fingerprint-projectId:${projectId}`;
const messageBody = createSummaryForUpdatesAndBuilds({ config, projectId, updates, builds, options: input });
const updatesVariables = getTemplateVariablesForUpdates(config, updates, input);
const messageId = template(input.commentId, updatesVariables);
const messageBody = createSummaryForUpdatesAndBuilds(updates, builds, updatesVariables);
await createIssueComment({
...pullContext(),
@@ -111,22 +108,16 @@ async function getFingerprintHashForPlatformAsync({
platform: 'ios' | 'android';
}): Promise<string> {
try {
const extraArgs = isDebug() ? ['--debug'] : [];
const { stdout } = await getExecOutput(
'npx',
['expo-updates', 'fingerprint:generate', '--platform', platform, ...extraArgs],
{
cwd,
silent: !isDebug(),
}
);
const { stdout } = await getExecOutput('npx', ['expo-updates', 'fingerprint:generate', '--platform', platform], {
cwd,
});
const { hash } = JSON.parse(stdout);
if (!hash || typeof hash !== 'string') {
throw new Error(`Invalid fingerprint output: ${stdout}`);
}
return hash;
} catch (error: unknown) {
throw new Error(`Could not get fingerprint for project: ${String(error)}`);
throw new Error(`Could not get fingerprint for project`, { cause: error });
}
}
@@ -135,15 +126,13 @@ async function getBuildInfoWithFingerprintAsync({
platform,
profile,
fingerprintHash,
excludeExpiredBuilds,
}: {
cwd: string;
platform: 'ios' | 'android';
profile: string;
fingerprintHash: string;
excludeExpiredBuilds: boolean;
}): Promise<BuildInfo | null> {
let stdout: string;
let stdout;
try {
const execOutput = await getExecOutput(
await which('eas', true),
@@ -153,7 +142,7 @@ async function getBuildInfoWithFingerprintAsync({
platform,
'--status',
'finished',
'--buildProfile',
'--profile',
profile,
'--runtimeVersion',
fingerprintHash,
@@ -164,12 +153,12 @@ async function getBuildInfoWithFingerprintAsync({
],
{
cwd,
silent: !isDebug(),
silent: true,
}
);
stdout = execOutput.stdout;
} catch (error: unknown) {
throw new Error(`Could not list project builds: ${String(error)}`);
throw new Error(`Could not list project builds`, { cause: error });
}
const builds = JSON.parse(stdout);
@@ -181,19 +170,7 @@ async function getBuildInfoWithFingerprintAsync({
return null;
}
const build = builds[0] as BuildInfo;
if (excludeExpiredBuilds) {
// if the build is expired or will expire within the next day,
// return null to trigger a new build
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
if (tomorrow > new Date(build.expirationDate)) {
return null;
}
}
return build;
return builds[0];
}
async function createEASBuildAsync({
@@ -205,113 +182,131 @@ async function createEASBuildAsync({
profile: string;
platform: 'ios' | 'android';
}): Promise<BuildInfo> {
let stdout: string;
let stdout;
try {
const extraArgs = isDebug() ? ['--build-logger-level', 'debug'] : [];
const execOutput = await getExecOutput(
await which('eas', true),
['build', '--profile', profile, '--platform', platform, '--non-interactive', '--json', '--no-wait', ...extraArgs],
[
'build',
'--profile',
profile,
'--platform',
platform,
'--non-interactive',
'--json',
'--no-wait',
'--build-logger-level',
'debug',
],
{
cwd,
silent: !isDebug(),
}
);
stdout = execOutput.stdout;
} catch (error: unknown) {
throw new Error(`Could not run command eas build: ${String(error)}`);
}
return JSON.parse(stdout)[0];
}
async function publishEASUpdatesAsync({ cwd, branch }: { cwd: string; branch: string }): Promise<EasUpdate[]> {
let stdout: string;
try {
const execOutput = await getExecOutput(
await which('eas', true),
['update', '--auto', '--branch', branch, '--non-interactive', '--json'],
{
cwd,
silent: !isDebug(),
}
);
stdout = execOutput.stdout;
} catch (error: unknown) {
throw new Error(`Could not create a new EAS Update: ${String(error)}`);
throw new Error(`Could not run command eas build`, { cause: error });
}
return JSON.parse(stdout);
}
function createSummaryForUpdatesAndBuilds({
config,
projectId,
updates,
builds,
options,
}: {
config: ExpoConfig;
projectId: string;
updates: EasUpdate[];
builds: BuildInfo[];
options: { qrTarget?: 'expo-go' | 'dev-build' | 'dev-client'; workingDirectory: string };
}) {
const appSlug = config.slug;
const qrTarget = getQrTarget(options);
const appSchemes = getSchemesInOrderFromConfig(config) || [];
async function publishEASUpdatesAsync({ cwd, branch }: { cwd: string; branch: string }): Promise<EasUpdate[]> {
let stdout = '';
const androidBuild = builds.find(build => build.platform === AppPlatform.Android);
const iosBuild = builds.find(build => build.platform === AppPlatform.Ios);
try {
({ stdout } = await getExecOutput(
await which('eas', true),
['update', '--auto', '--branch', branch, '--non-interactive'],
{
cwd,
}
));
} catch (error: unknown) {
throw new Error(`Could not create a new EAS Update`, { cause: error });
}
const androidUpdate = updates.find(update => update.platform === 'android');
const iosUpdate = updates.find(update => update.platform === 'ios');
return JSON.parse(stdout);
}
const getBuildLink = (build: BuildInfo | undefined) =>
build ? `[Build Permalink](${getBuildLogsUrl(build)})` : 'n/a';
const getUpdateLink = (update: EasUpdate | undefined) =>
update ? `[Update Permalink](${getUpdateGroupWebsite({ projectId, updateGroupId: update.group })})` : 'n/a';
const getUpdateQRURL = (update: EasUpdate | undefined) =>
update ? getUpdateGroupQr({ projectId, updateGroupId: update.group, appSlug, qrTarget }) : null;
const getBuildDetails = (build: BuildInfo | undefined) =>
build
? getBuildLink(build) +
'<br />' +
createDetails({
summary: 'Details',
details: [
`Distribution: \`${build.distribution}\``,
`Build profile: \`${build.buildProfile}\``,
`Runtime version: \`${build.runtimeVersion}\``,
`App version: \`${build.appVersion}\``,
`Git commit: \`${build.gitCommitHash}\``,
].join('<br />'),
delim: '',
})
: 'n/a';
const getUpdateDetails = (update: EasUpdate | undefined) =>
update
? getUpdateLink(update) +
'<br />' +
createDetails({
summary: 'Details',
details: [
`Branch: \`${update.branch}\``,
`Runtime version: \`${update.runtimeVersion}\``,
`Git commit: \`${update.gitCommitHash}\``,
].join('<br />'),
delim: '',
})
: 'n/a';
function createSummaryForUpdatesAndBuilds(
updates: EasUpdate[],
builds: BuildInfo[],
updatesVariables: ReturnType<typeof getTemplateVariablesForUpdates>
) {
return [
createSummaryForBuilds(builds),
'',
createMultipleQrSummaryForUpdates(updates, updatesVariables),
`> Learn more about [𝝠 Expo Github Action](https://github.com/expo/expo-github-action/tree/main/continuous-deploy-fingerprint)`,
].join('\n');
}
const androidQRURL = getUpdateQRURL(androidUpdate);
const iosQRURL = getUpdateQRURL(iosUpdate);
async function createSummaryForBuilds(builds: BuildInfo[]) {
const tableRows: string[] = [];
for (const build of builds) {
let name;
if (build.platform === 'ANDROID') {
name = `${appPlatformEmojis.ANDROID} Android build`;
} else if (build.platform === 'IOS') {
name = `${appPlatformEmojis.IOS} iOS build`;
} else {
name = 'Unknown build';
}
const androidQr = androidQRURL
? `<a href="${androidQRURL}"><img src="${androidQRURL}" width="250px" height="250px" /></a>`
: null;
const buildPageURL = getBuildLogsUrl(build);
const details = createDetails({
summary: 'Details',
details: [
`Distribution: \`${build.distribution}\``,
`Build profile: \`${build.buildProfile}\``,
`Runtime version: \`${build.runtimeVersion}\``,
`App version: \`${build.appVersion}\``,
].join('<br>'),
delim: '',
});
const iosQr = iosQRURL ? `<a href="${iosQRURL}"><img src="${iosQRURL}" width="250px" height="250px" /></a>` : null;
tableRows.push(`| ${name} | [View build page](${buildPageURL}) | ${details} |`);
}
return ['| Name | Build | Details |', '| :-- | :-- | :-- |', ...tableRows].join('\n');
}
function createMultipleQrSummaryForUpdates(
updates: EasUpdate[],
vars: ReturnType<typeof getTemplateVariablesForUpdates>
) {
const createTableHeader = (segments: string[]) => segments.filter(Boolean).join(' <br /> ');
const androidHeader = createTableHeader([
'Android',
vars.androidId && vars.androidRuntimeVersion ? `_(${vars.androidRuntimeVersion})_` : '',
vars.androidId && vars.androidLink ? `**[More info](${vars.androidLink})**` : '',
]);
const androidQr =
vars.androidId && vars.androidQR
? `<a href="${vars.androidQR}"><img src="${vars.androidQR}" width="250px" height="250px" /></a>`
: null;
const iosHeader = createTableHeader([
'iOS',
vars.iosId && vars.iosRuntimeVersion ? `_(${vars.iosRuntimeVersion})_` : '',
vars.iosId && vars.iosLink ? `**[More info](${vars.iosLink})**` : '',
]);
const iosQr =
vars.iosId && vars.iosQR
? `<a href="${vars.iosQR}"><img src="${vars.iosQR}" width="250px" height="250px" /></a>`
: null;
return `${createSummaryHeaderForUpdates(updates, vars)}
${androidHeader} | ${iosHeader}
--- | ---
${androidQr || '_not created_'} | ${iosQr || '_not created_'}`;
}
function createSummaryHeaderForUpdates(updates: EasUpdate[], vars: ReturnType<typeof getTemplateVariablesForUpdates>) {
const platformName = `Platform${updates.length === 1 ? '' : 's'}`;
const platformValue = updates
.map(update => update.platform)
@@ -319,19 +314,11 @@ function createSummaryForUpdatesAndBuilds({
.map(platform => `**${platform}**`)
.join(', ');
const schemesMessage = appSchemes[0] ? `- Scheme → **${appSchemes.join('**, **')}**` : '';
const appSchemes = vars.projectScheme ? `- Scheme → **${JSON.parse(vars.projectSchemes).join('**, **')}**` : '';
return `🚀 Expo continuous deployment is ready!
return `🚀 Expo preview is ready!
- Project → **${appSlug}**
- Project → **${vars.projectSlug}**
- ${platformName} → ${platformValue}
${schemesMessage}
&nbsp; | ${appPlatformEmojis[AppPlatform.Android]} Android | ${appPlatformEmojis[AppPlatform.Ios]} iOS
--- | --- | ---
Fingerprint | ${androidBuild?.runtimeVersion ?? 'n/a'} | ${iosBuild?.runtimeVersion ?? 'n/a'}
Build Details | ${getBuildDetails(androidBuild)} | ${getBuildDetails(iosBuild)}
Update Details | ${getUpdateDetails(androidUpdate)} | ${getUpdateDetails(iosUpdate)}
Update QR | ${androidQr ?? 'n/a'} | ${iosQr ?? 'n/a'}
`;
${appSchemes}`.trim();
}
+32 -28
View File
@@ -76,7 +76,7 @@ export async function previewAction(input = collectPreviewBuildActionInput()) {
manyBuilds: [{ fingerprint: currentFingerprint }],
});
await maybeCancelPreviousBuildsAsync(config, input);
const variables = getVariables(config, []);
const variables = getTemplateVariablesForBuilds(config, []);
const messageId = template(input.commentId, variables);
const latestEasEntity = await dbManager.getLatestEasEntityFromFingerprintAsync(currentFingerprint.hash);
const latestEasBuildInfo = latestEasEntity?.easBuildId
@@ -111,13 +111,35 @@ export async function previewAction(input = collectPreviewBuildActionInput()) {
fingerprint: currentFingerprint,
})),
});
const variables = getVariables(config, builds);
const variables = getTemplateVariablesForBuilds(config, builds);
const messageId = template(input.commentId, variables);
const messageBody = createMessageBodyInBuilding(builds, diff, input);
await maybeCreateCommentAsync(input, messageId, messageBody);
setOutputs(variables, messageId, messageBody);
}
/**
* Generate useful variables for the message body, and as step outputs from a set of builds.
*/
export function getTemplateVariablesForBuilds(config: ExpoConfig, builds: BuildInfo[]) {
const projectId: string = config.extra?.eas?.projectId;
const android = builds.find(build => build.platform === 'ANDROID');
const ios = builds.find(build => build.platform === 'IOS');
const gitCommitHash = android?.gitCommitHash || ios?.gitCommitHash || '';
return {
projectId,
gitCommitHash,
androidBuildId: android?.id || '',
androidLink: android != null ? getBuildLogsUrl(android) : '',
androidAppVersion: android?.appVersion || '',
iosBuildId: ios?.id || '',
iosLink: ios != null ? getBuildLogsUrl(ios) : '',
iosAppVersion: ios?.appVersion || '',
};
}
/**
* Validate and sanitize the command that creates the update.
* It also ensures that the command starts with `eas ...` to make sure we can run it.
@@ -137,7 +159,7 @@ async function maybeCancelPreviousBuildsAsync(
config: ExpoConfig,
input: ReturnType<typeof collectPreviewBuildActionInput>
) {
const variables = getVariables(config, []);
const variables = getTemplateVariablesForBuilds(config, []);
const messageId = template(input.commentId, variables);
const comment = await fetchIssueComment({
...pullContext(),
@@ -175,7 +197,11 @@ async function maybeCreateCommentAsync(
}
}
function setOutputs(variables: ReturnType<typeof getVariables>, messageId: string, messageBody: string) {
function setOutputs(
variables: ReturnType<typeof getTemplateVariablesForBuilds>,
messageId: string,
messageBody: string
) {
for (const [name, value] of Object.entries(variables)) {
setOutput(name, value);
}
@@ -183,28 +209,6 @@ function setOutputs(variables: ReturnType<typeof getVariables>, messageId: strin
setOutput('comment', messageBody);
}
/**
* Generate useful variables for the message body, and as step outputs.
*/
export function getVariables(config: ExpoConfig, builds: BuildInfo[]) {
const projectId: string = config.extra?.eas?.projectId;
const android = builds.find(build => build.platform === 'ANDROID');
const ios = builds.find(build => build.platform === 'IOS');
const gitCommitHash = android?.gitCommitHash || ios?.gitCommitHash || '';
return {
projectId,
gitCommitHash,
androidBuildId: android?.id || '',
androidLink: android != null ? getBuildLogsUrl(android) : '',
androidAppVersion: android?.appVersion || '',
iosBuildId: ios?.id || '',
iosLink: ios != null ? getBuildLogsUrl(ios) : '',
iosAppVersion: ios?.appVersion || '',
};
}
function createMessageBodyInBuilding(
builds: BuildInfo[],
fingerprintDiff: FingerprintSource[],
@@ -372,7 +376,7 @@ async function handleNonPullRequest(config: ExpoConfig, input: ReturnType<typeof
gitCommitHash: input.currentGitCommitHash,
manyBuilds,
});
const variables = getVariables(config, []);
const variables = getTemplateVariablesForBuilds(config, []);
setOutputs(variables, '', '');
}
@@ -381,7 +385,7 @@ async function queryEasBuildIdsFromPrAsync(
config: ExpoConfig,
input: ReturnType<typeof collectPreviewBuildActionInput>
): Promise<string[]> {
const variables = getVariables(config, []);
const variables = getTemplateVariablesForBuilds(config, []);
const messageId = template(input.commentId, variables);
const comment = await fetchIssueComment({
...context.repo,
+18 -64
View File
@@ -1,8 +1,7 @@
import { getBooleanInput, getInput, setOutput, group, setFailed, info } from '@actions/core';
import { ExpoConfig } from '@expo/config';
import { getQrTarget, getSchemesInOrderFromConfig } from '../comment';
import { assertEasVersion, createUpdate, EasUpdate, getUpdateGroupQr, getUpdateGroupWebsite } from '../eas';
import { getTemplateVariablesForUpdates } from '../comment';
import { EasUpdate, assertEasVersion, createUpdate } from '../eas';
import { createIssueComment, hasPullContext, pullContext } from '../github';
import { loadProjectConfig } from '../project';
import { template } from '../utils';
@@ -50,9 +49,9 @@ export async function previewAction(input = previewInput()) {
return setFailed(`Missing 'extra.eas.projectId' in app.json or app.config.js.`);
}
const variables = getVariables(config, updates, input);
const variables = getTemplateVariablesForUpdates(config, updates, input);
const messageId = template(input.commentId, variables);
const messageBody = createSummary(updates, variables);
const messageBody = createSummaryForUpdates(updates, variables);
if (!input.shouldComment) {
info(`Skipped comment: 'comment' is disabled`);
@@ -100,71 +99,20 @@ function sanitizeCommand(input: string): string {
return command;
}
/**
* Generate useful variables for the message body, and as step outputs.
*/
export function getVariables(config: ExpoConfig, updates: EasUpdate[], options: ReturnType<typeof previewInput>) {
const projectId: string = config.extra?.eas?.projectId;
const android = updates.find(update => update.platform === 'android');
const ios = updates.find(update => update.platform === 'ios');
const appSchemes = getSchemesInOrderFromConfig(config) || [];
const appSlug = config.slug;
const qrTarget = getQrTarget(options);
return {
// EAS / Expo specific
projectId,
projectName: config.name,
projectSlug: appSlug,
projectScheme: appSchemes[0] || '', // This is the longest scheme from one or more custom app schemes
projectSchemes: JSON.stringify(appSchemes), // These are all custom app schemes, in order from longest to shortest as JSON
// Shared update properties
// Note, only use these properties when the update groups are identical
groupId: updates[0].group,
runtimeVersion: updates[0].runtimeVersion,
qr: getUpdateGroupQr({ projectId, updateGroupId: updates[0].group, appSlug, qrTarget }),
link: getUpdateGroupWebsite({ projectId, updateGroupId: updates[0].group }),
// These are safe to access regardless of the update groups
branchName: updates[0].branch,
message: updates[0].message,
createdAt: updates[0].createdAt,
gitCommitHash: updates[0].gitCommitHash,
// Android update
androidId: android?.id || '',
androidGroupId: android?.group || '',
androidBranchName: android?.branch || '',
androidManifestPermalink: android?.manifestPermalink || '',
androidMessage: android?.message || '',
androidRuntimeVersion: android?.runtimeVersion || '',
androidQR: android ? getUpdateGroupQr({ projectId, updateGroupId: android.group, appSlug, qrTarget }) : '',
androidLink: android ? getUpdateGroupWebsite({ projectId, updateGroupId: android.group }) : '',
// iOS update
iosId: ios?.id || '',
iosGroupId: ios?.group || '',
iosBranchName: ios?.branch || '',
iosManifestPermalink: ios?.manifestPermalink || '',
iosMessage: ios?.message || '',
iosRuntimeVersion: ios?.runtimeVersion || '',
iosQR: ios ? getUpdateGroupQr({ projectId, updateGroupId: ios.group, appSlug, qrTarget }) : '',
iosLink: ios ? getUpdateGroupWebsite({ projectId, updateGroupId: ios.group }) : '',
};
}
/**
* Generate the message body for a single update.
* Note, this is not configurable, but you can use the variables used to construct your own.
*/
export function createSummary(updates: EasUpdate[], vars: ReturnType<typeof getVariables>) {
export function createSummaryForUpdates(updates: EasUpdate[], vars: ReturnType<typeof getTemplateVariablesForUpdates>) {
// If all updates are in the same group, we can unify QR codes
if (updates.every(update => update.group === updates[0].group)) {
return createSingleQrSummary(updates, vars);
return createSingleQrSummaryForUpdates(updates, vars);
}
return createMultipleQrSummary(updates, vars);
return createMultipleQrSummaryForUpdates(updates, vars);
}
function createSummaryHeader(updates: EasUpdate[], vars: ReturnType<typeof getVariables>) {
function createSummaryHeaderForUpdates(updates: EasUpdate[], vars: ReturnType<typeof getTemplateVariablesForUpdates>) {
const platformName = `Platform${updates.length === 1 ? '' : 's'}`;
const platformValue = updates
.map(update => update.platform)
@@ -181,8 +129,11 @@ function createSummaryHeader(updates: EasUpdate[], vars: ReturnType<typeof getVa
${appSchemes}`.trim();
}
function createSingleQrSummary(updates: EasUpdate[], vars: ReturnType<typeof getVariables>) {
return `${createSummaryHeader(updates, vars)}
function createSingleQrSummaryForUpdates(
updates: EasUpdate[],
vars: ReturnType<typeof getTemplateVariablesForUpdates>
) {
return `${createSummaryHeaderForUpdates(updates, vars)}
- Runtime Version → **${vars.runtimeVersion}**
- **[More info](${vars.link})**
@@ -191,7 +142,10 @@ function createSingleQrSummary(updates: EasUpdate[], vars: ReturnType<typeof get
> Learn more about [𝝠 Expo Github Action](https://github.com/expo/expo-github-action/tree/main/preview#example-workflows)`;
}
function createMultipleQrSummary(updates: EasUpdate[], vars: ReturnType<typeof getVariables>) {
function createMultipleQrSummaryForUpdates(
updates: EasUpdate[],
vars: ReturnType<typeof getTemplateVariablesForUpdates>
) {
const createTableHeader = (segments: string[]) => segments.filter(Boolean).join(' <br /> ');
const androidHeader = createTableHeader([
@@ -216,7 +170,7 @@ function createMultipleQrSummary(updates: EasUpdate[], vars: ReturnType<typeof g
? `<a href="${vars.iosQR}"><img src="${vars.iosQR}" width="250px" height="250px" /></a>`
: null;
return `${createSummaryHeader(updates, vars)}
return `${createSummaryHeaderForUpdates(updates, vars)}
${androidHeader} | ${iosHeader}
--- | ---
+73
View File
@@ -1,8 +1,81 @@
import { debug } from '@actions/core';
import { ExpoConfig } from '@expo/config';
import { EasUpdate, getUpdateGroupQr, getUpdateGroupWebsite } from './eas';
import { projectAppType } from './expo';
/**
* Generate useful variables for the message body, and as step outputs from a set of updates.
*/
export function getTemplateVariablesForUpdates(
config: ExpoConfig,
updates: EasUpdate[],
options: { qrTarget?: 'expo-go' | 'dev-build' | 'dev-client'; workingDirectory: string }
) {
const projectId: string = config.extra?.eas?.projectId;
const android = updates.find(update => update.platform === 'android');
const ios = updates.find(update => update.platform === 'ios');
const appSchemes = getSchemesInOrderFromConfig(config) || [];
const appSlug = config.slug;
const qrTarget = getQrTarget(options);
return {
// EAS / Expo specific
projectId,
projectName: config.name,
projectSlug: appSlug,
projectScheme: appSchemes[0] || '', // This is the longest scheme from one or more custom app schemes
projectSchemes: JSON.stringify(appSchemes), // These are all custom app schemes, in order from longest to shortest as JSON
// Shared update properties
// Note, only use these properties when the update groups are identical
groupId: updates[0].group,
runtimeVersion: updates[0].runtimeVersion,
qr: getUpdateGroupQr({ projectId, updateGroupId: updates[0].group, appSlug, qrTarget }),
link: getUpdateGroupWebsite({ projectId, updateGroupId: updates[0].group }),
// These are safe to access regardless of the update groups
branchName: updates[0].branch,
message: updates[0].message,
createdAt: updates[0].createdAt,
gitCommitHash: updates[0].gitCommitHash,
// Android update
androidId: android?.id || '',
androidGroupId: android?.group || '',
androidBranchName: android?.branch || '',
androidManifestPermalink: android?.manifestPermalink || '',
androidMessage: android?.message || '',
androidRuntimeVersion: android?.runtimeVersion || '',
androidQR: android ? getUpdateGroupQr({ projectId, updateGroupId: android.group, appSlug, qrTarget }) : '',
androidLink: android ? getUpdateGroupWebsite({ projectId, updateGroupId: android.group }) : '',
// iOS update
iosId: ios?.id || '',
iosGroupId: ios?.group || '',
iosBranchName: ios?.branch || '',
iosManifestPermalink: ios?.manifestPermalink || '',
iosMessage: ios?.message || '',
iosRuntimeVersion: ios?.runtimeVersion || '',
iosQR: ios ? getUpdateGroupQr({ projectId, updateGroupId: ios.group, appSlug, qrTarget }) : '',
iosLink: ios ? getUpdateGroupWebsite({ projectId, updateGroupId: ios.group }) : '',
};
}
type Prefix = 'updates' | 'builds';
type MappedProperties<TObj, TPrefix extends Prefix> = {
[Property in keyof TObj as `${TPrefix}.${string & Property}`]: TObj[Property];
};
export function prefixKeys<T extends object, TPrefix extends Prefix>(
input: T,
prefix: TPrefix
): MappedProperties<T, TPrefix> {
return Object.fromEntries(Object.entries(input).map(([k, v]) => [prefix + k, v])) as MappedProperties<T, TPrefix>;
}
export function getQrTarget(input: { qrTarget?: 'expo-go' | 'dev-build' | 'dev-client'; workingDirectory: string }) {
if (!input.qrTarget) {
const appType = projectAppType(input.workingDirectory);
-1
View File
@@ -42,7 +42,6 @@ export type BuildInfo = {
sdkVersion: string;
appVersion: string;
gitCommitHash: string;
expirationDate: string;
};
export const appPlatformDisplayNames: Record<AppPlatform, string> = {
+55 -1
View File
@@ -1,7 +1,14 @@
import { ExpoConfig } from '@expo/config';
import { createSummary, getVariables, previewInput } from '../../src/actions/preview';
import {
createSummary,
getQrTarget,
getSchemesInOrderFromConfig,
getVariables,
previewInput,
} from '../../src/actions/preview';
import { EasUpdate } from '../../src/eas';
import { projectAppType } from '../../src/expo';
jest.mock('../../src/expo');
@@ -43,6 +50,53 @@ const fakeUpdatesSingle: EasUpdate[] = [
const fakeUpdatesMultiple = fakeUpdatesSingle.map(update => ({ ...update, group: `fake-group-${update.id}` }));
describe(getQrTarget, () => {
it('returns `dev-build` for `qr-target: dev-build`', () => {
expect(getQrTarget({ ...fakeOptions, qrTarget: 'dev-build' })).toBe('dev-build');
});
it('returns `dev-build` for `qr-target: dev-client`', () => {
expect(getQrTarget({ ...fakeOptions, qrTarget: 'dev-client' })).toBe('dev-build');
});
it('returns `expo-go` for `qr-target: expo-go`', () => {
expect(getQrTarget({ ...fakeOptions, qrTarget: 'expo-go' })).toBe('expo-go');
});
it('throws for unknown `qr-target`', () => {
expect(() => getQrTarget({ ...fakeOptions, qrTarget: 'unknown' } as any)).toThrow(
`Invalid QR code target: "unknown", expected "expo-go" or "dev-build"`
);
});
it('returns infered `dev-build` when input is omitted', () => {
jest.mocked(projectAppType).mockReturnValue('dev-build');
expect(getQrTarget({ ...fakeOptions, qrTarget: undefined })).toBe('dev-build');
});
it('returns infered `expo-go` when input is omitted', () => {
jest.mocked(projectAppType).mockReturnValue('expo-go');
expect(getQrTarget({ ...fakeOptions, qrTarget: undefined })).toBe('expo-go');
});
});
describe(getSchemesInOrderFromConfig, () => {
it('returns empty array when not defined', () => {
expect(getSchemesInOrderFromConfig({} as ExpoConfig)).toEqual([]);
});
it('returns scheme as array when defined as string', () => {
expect(getSchemesInOrderFromConfig({ scheme: 'ega' } as ExpoConfig)).toEqual(['ega']);
});
it('returns schemes in order when defined as array', () => {
expect(getSchemesInOrderFromConfig({ scheme: ['ega', 'expogithubaction'] } as ExpoConfig)).toEqual([
'expogithubaction',
'ega',
]);
});
});
describe(createSummary, () => {
describe('single update group', () => {
it('returns expected message for both platforms', () => {
-57
View File
@@ -1,57 +0,0 @@
import { ExpoConfig } from '@expo/config';
import { getQrTarget, getSchemesInOrderFromConfig } from '../src/comment';
import { projectAppType } from '../src/expo';
jest.mock('../src/expo');
const fakeOptions = {
workingDirectory: '',
};
describe(getQrTarget, () => {
it('returns `dev-build` for `qr-target: dev-build`', () => {
expect(getQrTarget({ ...fakeOptions, qrTarget: 'dev-build' })).toBe('dev-build');
});
it('returns `dev-build` for `qr-target: dev-client`', () => {
expect(getQrTarget({ ...fakeOptions, qrTarget: 'dev-client' })).toBe('dev-build');
});
it('returns `expo-go` for `qr-target: expo-go`', () => {
expect(getQrTarget({ ...fakeOptions, qrTarget: 'expo-go' })).toBe('expo-go');
});
it('throws for unknown `qr-target`', () => {
expect(() => getQrTarget({ ...fakeOptions, qrTarget: 'unknown' } as any)).toThrow(
`Invalid QR code target: "unknown", expected "expo-go" or "dev-build"`
);
});
it('returns infered `dev-build` when input is omitted', () => {
jest.mocked(projectAppType).mockReturnValue('dev-build');
expect(getQrTarget({ ...fakeOptions, qrTarget: undefined })).toBe('dev-build');
});
it('returns infered `expo-go` when input is omitted', () => {
jest.mocked(projectAppType).mockReturnValue('expo-go');
expect(getQrTarget({ ...fakeOptions, qrTarget: undefined })).toBe('expo-go');
});
});
describe(getSchemesInOrderFromConfig, () => {
it('returns empty array when not defined', () => {
expect(getSchemesInOrderFromConfig({} as ExpoConfig)).toEqual([]);
});
it('returns scheme as array when defined as string', () => {
expect(getSchemesInOrderFromConfig({ scheme: 'ega' } as ExpoConfig)).toEqual(['ega']);
});
it('returns schemes in order when defined as array', () => {
expect(getSchemesInOrderFromConfig({ scheme: ['ega', 'expogithubaction'] } as ExpoConfig)).toEqual([
'expogithubaction',
'ega',
]);
});
});