11 Commits

Author SHA1 Message Date
Jack Boswell (boswelja)
78c9e796b1 Update dependencies + prepare for release 2022-10-24 08:17:46 +00:00
Jack Boswell
980a5c4201 Write edit expiry time to debug console (#152) 2022-10-24 21:11:26 +13:00
Jack Boswell
81a2f1ad1c Print track names when invalid track provided (#151)
* Print track names when invalid track provided

* Remove redundant safe call
2022-10-24 21:06:38 +13:00
Jack Boswell
b84eace68d Set up full input testing (#150)
* Extract main loop to something testable

* Revert "Extract main loop to something testable"

This reverts commit 35a78459698fe267933c554283212c2d06ed4bf0.

* Extract code that interacts with Google Play
We can now test our input flow as a whole

* Create some basic tests for `completed` status publishing

* Fix applying inputs
We don't want to be keeping values between runs

* Drop some redundant tests

* Create basic tests for draft rollout

* Run build

* Fix userFraction bug

* Improve readability of initialising inputs

* Fix runUpload mocking

* Migrate to github-action-ts-run-api
2022-10-24 14:18:11 +13:00
Jack Boswell (boswelja)
4d510d380a Attempt at fixing status validation
Our validation tests are A-OK, but inputs are not :(
2022-09-26 15:37:05 +13:00
Jack Boswell
99b7a1e1d4 Fix issues parsing Int and Float (#145)
Undefined was transformed into NaN, which is not undefined and thus failed validation
2022-09-24 16:51:04 +12:00
Jack Boswell
7cd1379b4f refactor: Centralized input validation (#142)
* Initial implementaion of service account json, user fraction and status validation

* Move validation to input-validation
Also created some more validators

* Rearrange whatsnew tests to clear out test folder

* Return error messages for input validation

* Create tests for some validation code

* Separate user fraction and status validation

* Write more tests and fix some bugs

* Refactor to use promises

* Fix release file loading from glob
2022-09-21 17:15:54 +12:00
Jack Boswell
b028ed83b3 Set up ESLint (#138)
* Add eslint and config

* Refactor edits.ts to comply with eslint

* Refactor whatsnew.ts to comply with eslint

* Fix final ESLint issues

* Run build
2022-09-12 20:37:51 +12:00
Jack Boswell
5427bcbe2b Ignore userFraction if status is draft (#140) 2022-09-12 20:23:41 +12:00
Thomas Aunvik
6a74f079de Add Debug Symbol File/Folder Upload (#130)
* Add Debug Symbol File/Folder Upload

Uploads Deobfuscation File type 'nativeCode'.

Inputs allowed in 'debugSymbols', a .zip file, or a folder that contains the symbols.

* Space Formatting

* Zip Directory Function higher level, and formatting
2022-09-12 00:21:02 +12:00
Jack Boswell
c16321c553 feature: Infer status from provided parameters (#122)
* Mark status as deprecated

* Make userFraction required & provide a default
We'll use this to infer `inProgress` or `completed`

* Infer status from userFraction

* Fix workflow

* Update README

* Run build

* Add support for drafts again

* Pass in isDraft

* Warn about setting draft and userFraction simultaneously

* Expose isDraft

* Do a build

* Allow passing status in again
This will be required for draft/halted
It is optional though, if it's not specified, we have updated logic for inferring it

* Update userFraction description

* Revert "Fix workflow"

This reverts commit ad98b3d449f0f36c9d4f0a3d0b2eb49a4c3e1aa9.

* Remove deprecated tag from status

* Move status back

* Allow 0 userFraction

* Run build
2022-09-11 20:53:18 +12:00
20 changed files with 4326 additions and 1371 deletions

15
.eslintrc.cjs Normal file
View File

@@ -0,0 +1,15 @@
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
parserOptions: {
tsconfigRootDir: __dirname,
project: ['./tsconfig.json'],
},
plugins: ['@typescript-eslint'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
],
ignorePatterns: ["lib/*.js", "jest.config.js", "__tests__/**"]
};

View File

@@ -12,10 +12,11 @@ This action will help you upload an Android `.apk` or `.aab` (Android App Bundle
| track | The track in which you want to assign the uploaded app. Defaults to `production` | One of `production`, `beta`, `alpha`, `internalsharing`, `internal`, or a custom track name (case sensitive) | true |
| releaseName | The release name. Not required to be unique. Default is configured by Google Play Console | A user-friendly update name, e.g. `v1.0.0` | false |
| inAppUpdatePriority | In-app update priority of the release. All newly added APKs in the release will be considered at this priority. Defaults to `0` | `[0-5]`, where `5` is the highest priority | false |
| userFraction | Percentage of users who should get the staged version of the app. Defaults to `1.0` | `(0.0-1.0)` | false |
| status | Release status. This can be set to `draft` to complete the release at some other time. Defaults to `completed` if targeting 100% rollout, else `inProgress` | One of `completed`, `inProgress`, `halted`, `draft` | false |
| userFraction | Percentage of users who should get the staged version of the app. Defaults to `1.0` | `[0.0-1.0]` | true |
| status | Release status. Defaults to `completed` if targeting 100% rollout, `halted` for 0%, and `inProgress` for anything in between | One of `completed`, `inProgress`, `halted`, `draft` | false |
| whatsNewDirectory | The directory of localized "whats new" files to upload as the release notes. The files contained in the `whatsNewDirectory` MUST use the pattern `whatsnew-<LOCALE>` where `LOCALE` is using the [`BCP 47`](https://tools.ietf.org/html/bcp47) format | A path to a valid `whatsNewDirectory` | false |
| mappingFile | The mapping.txt file used to de-obfuscate your stack traces from crash reports | A path to a valid `mapping.txt` file | false |
| debugSymbols | The native-debug-symbols.zip file or folder that contains your debug symbols | A path to a valid `native-debug-symbols.zip file` file or a folder | false |
| changesNotSentForReview | Indicates that the changes in this edit will not be reviewed until they are explicitly sent for review from the Google Play Console. Defaults to `false` | `true` or `false` | `false` |
| serviceAccountJson | The service account json private key file to authorize the upload request. Can be used instead of `serviceAccountJsonPlainText` to specify a file rather than provide a secret | A path to a valid `service-account.json` file | true (or serviceAccountJsonPlainText) |
| existingEditId | The ID of an existing edit that has not been completed. If this is supplied, the action will append information to that rather than creating an edit | A valid, unpublished Edit ID | false |
@@ -44,6 +45,7 @@ with:
userFraction: 0.33
whatsNewDirectory: distribution/whatsnew
mappingFile: app/build/outputs/mapping/release/mapping.txt
debugSymbols: app/intermediates/merged_native_libs/release/out/lib
```
The `whatsNewDirectory` in this example supplies changelogs for English, German and Japanese

View File

@@ -0,0 +1,74 @@
import { validateInAppUpdatePriority, validateReleaseFiles, validateStatus, validateUserFraction } from "../src/input-validation"
test("invalid in-app update priority fails validation", async () => {
const testValues = [-1, 6, -1000, 1000]
for (const value of testValues) {
await expect(validateInAppUpdatePriority(value)).rejects.toThrowError()
}
})
test("valid in-app update priority passes validation", async () => {
const testValues = [0, 1, 2, 3, 4, 5, undefined]
for (const value of testValues) {
await validateInAppUpdatePriority(value)
}
})
test("invalid releaseFiles glob fails validation", async () => {
const testValues = ['./__tests__/releasefiles/*.null', `./__tests__/releasefiles/nonexistent-release.aab`]
await expect(validateReleaseFiles(testValues)).rejects.toThrowError()
})
test("valid releaseFiles glob passes validation", async () => {
const testValues = ['./__tests__/releasefiles/*.aab', `./__tests__/releasefiles/release.aab`]
await validateReleaseFiles(testValues)
})
test("fractionless status without fraction passes validation", async () => {
const testValues = ['completed', 'draft']
for (const value of testValues) {
await validateStatus(value, false)
}
})
test("fractionless status with fraction fails validation", async () => {
const testValues = ['completed', 'draft']
for (const value of testValues) {
await expect(validateStatus(value, true)).rejects.toThrowError()
}
})
test("fractioned status without fraction fails validation", async () => {
const testValues = ['inProgress', 'halted']
for (const value of testValues) {
await expect(validateStatus(value, false)).rejects.toThrowError()
}
})
test("fractioned status with fraction passes validation", async () => {
const testValues = ['inProgress', 'halted']
for (const value of testValues) {
await validateStatus(value, true)
}
})
test("invalid status fails validation", async () => {
const testValues = ['statusGoBrrr', undefined]
for (const value of testValues) {
await expect(validateStatus(value, true)).rejects.toThrowError()
}
})
test("invalid user fraction fails validation", async () => {
const testValues = [0, 1, -1, 2, NaN]
for (const value of testValues) {
await expect(validateUserFraction(value)).rejects.toThrowError()
}
})
test("valid user fraction passes validation", async () => {
const testValues = [0.1, 0.9, 0.5, undefined]
for (const value of testValues) {
await validateUserFraction(value)
}
})

98
__tests__/main.test.ts Normal file
View File

@@ -0,0 +1,98 @@
import {RunOptions, RunTarget} from 'github-action-ts-run-api';
const target = RunTarget.mainJs('action.yml');
async function expectRunInitiatesUpload(options: RunOptions) {
const result = await target.run(options)
expect(result.commands.errors.length).toBe(1)
expect(result.commands.errors).toContainEqual("The incoming JSON object does not contain a client_email field")
}
test("correct inputs for complete rollout", async () => {
// Run with the bare minimum
const minimumOptions = RunOptions.create()
.setInputs({
serviceAccountJsonPlainText: "{}",
packageName: "com.package.name",
releaseFiles: "./__tests__/releasefiles/*.aab",
track: "production",
status: "completed",
})
await expectRunInitiatesUpload(minimumOptions)
// Test with optional extras
const extraOptions = RunOptions.create()
.setInputs({
serviceAccountJsonPlainText: "{}",
packageName: "com.package.name",
releaseFiles: "./__tests__/releasefiles/*.aab",
releaseName: "Release name",
track: "production",
inAppUpdatePriority: "3",
status: "completed",
whatsNewDir: "./__tests__/whatsnew",
changesNotSentForReview: "true",
existingEditId: "123"
})
await expectRunInitiatesUpload(extraOptions)
})
test("correct inputs for inProgress rollout", async () => {
// Run with the bare minimum
const minimumOptions = RunOptions.create()
.setInputs({
serviceAccountJsonPlainText: "{}",
packageName: "com.package.name",
releaseFiles: "./__tests__/releasefiles/*.aab",
track: "production",
userFraction: "0.99",
status: "inProgress",
})
await expectRunInitiatesUpload(minimumOptions)
// Test with optional extras
const extraOptions = RunOptions.create()
.setInputs({
serviceAccountJsonPlainText: "{}",
packageName: "com.package.name",
releaseFiles: "./__tests__/releasefiles/*.aab",
releaseName: "Release name",
track: "production",
inAppUpdatePriority: "3",
userFraction: "0.5",
status: "inProgress",
whatsNewDir: "./__tests__/whatsnew",
changesNotSentForReview: "true",
existingEditId: "123"
})
await expectRunInitiatesUpload(extraOptions)
})
test("correct inputs for draft rollout", async () => {
// Run with the bare minimum
const minimumOptions = RunOptions.create()
.setInputs({
serviceAccountJsonPlainText: "{}",
packageName: "com.package.name",
releaseFiles: "./__tests__/releasefiles/*.aab",
track: "production",
status: "draft",
})
await expectRunInitiatesUpload(minimumOptions)
// Test with optional extras
const extraOptions = RunOptions.create()
.setInputs({
serviceAccountJsonPlainText: "{}",
packageName: "com.package.name",
releaseFiles: "./__tests__/releasefiles/*.aab",
releaseName: "Release name",
track: "production",
inAppUpdatePriority: "3",
status: "draft",
whatsNewDir: "./__tests__/whatsnew",
changesNotSentForReview: "true",
existingEditId: "123"
})
await expectRunInitiatesUpload(extraOptions)
})

View File

View File

@@ -1,12 +1,7 @@
import * as process from 'process'
import * as cp from 'child_process'
import * as path from 'path'
import {readLocalizedReleaseNotes} from "../src/whatsnew";
import {androidpublisher_v3} from "@googleapis/androidpublisher";
import LocalizedText = androidpublisher_v3.Schema$LocalizedText;
test("read localized whatsnew files", async () => {
let texts = await readLocalizedReleaseNotes("./__tests__");
let texts = await readLocalizedReleaseNotes("./__tests__/whatsnew");
expect(texts).toHaveLength(6);
expect(texts).toContainEqual({
language: "en-US",
@@ -32,4 +27,4 @@ test("read localized whatsnew files", async () => {
language: "et",
text: "test_changelog_file_estonian"
});
});
});

View File

@@ -43,9 +43,12 @@ inputs:
mappingFile:
description: "The mapping.txt file used to de-obfuscate your stack traces from crash reports"
required: false
debugSymbols:
description: "The native-debug-symbols.zip file or folder that contains your debug symbols"
required: false
changesNotSentForReview:
description: "Indicates that the changes in this edit will not be reviewed until they are explicitly sent for review from the Google Play Console"
default: false
default: 'false'
required: false
existingEditId:
description: "The ID of an existing edit that has not been completed. If this is supplied, the action will append information to that rather than creating an edit"

File diff suppressed because one or more lines are too long

4924
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "upload-google-play",
"version": "1.0.17",
"version": "1.0.19",
"private": true,
"description": "Upload an Android release (.apk or .aab) to Google Play Console",
"main": "lib/index.js",
@@ -20,16 +20,21 @@
"author": "r0adkll",
"license": "MIT",
"dependencies": {
"@actions/core": "^1.9.1",
"@actions/core": "^1.10.0",
"@googleapis/androidpublisher": "^3.0.0",
"fast-glob": "^3.2.12"
"fast-glob": "^3.2.12",
"jszip": "^3.10.1"
},
"devDependencies": {
"@types/jest": "^29.0.0",
"@types/node": "^18.7.16",
"@types/jest": "^29.2.0",
"@types/node": "^18.11.4",
"@typescript-eslint/eslint-plugin": "^5.40.1",
"@typescript-eslint/parser": "^5.40.1",
"@vercel/ncc": "^0.34.0",
"jest": "^29.0.3",
"ts-jest": "^29.0.0",
"typescript": "^4.8.3"
"eslint": "^8.26.0",
"github-action-ts-run-api": "^2.2.2",
"jest": "^29.2.1",
"ts-jest": "^29.0.3",
"typescript": "^4.8.4"
}
}

View File

@@ -1,6 +1,9 @@
import * as core from '@actions/core';
import * as fs from "fs";
import { readFileSync } from "fs";
import { readFileSync, lstatSync } from "fs";
import JSZip from 'jszip';
import path = require('path');
import { Readable } from 'stream';
import * as google from '@googleapis/androidpublisher';
import { androidpublisher_v3 } from "@googleapis/androidpublisher";
@@ -24,75 +27,91 @@ export interface EditOptions {
userFraction?: number;
whatsNewDir?: string;
mappingFile?: string;
debugSymbols?: string;
name?: string;
status?: string;
status: string;
changesNotSentForReview?: boolean;
existingEditId?: string;
}
export async function uploadToPlayStore(options: EditOptions, releaseFiles: string[]): Promise<string | undefined> {
export async function runUpload(
packageName: string,
track: string,
inAppUpdatePriority: number | undefined,
userFraction: number | undefined,
whatsNewDir: string | undefined,
mappingFile: string | undefined,
debugSymbols: string | undefined,
name: string | undefined,
changesNotSentForReview: boolean,
existingEditId: string | undefined,
status: string,
validatedReleaseFiles: string[]
) {
const auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/androidpublisher']
});
const authClient = await auth.getClient();
const result = await uploadToPlayStore({
auth: authClient,
applicationId: packageName,
track: track,
inAppUpdatePriority: inAppUpdatePriority || 0,
userFraction: userFraction,
whatsNewDir: whatsNewDir,
mappingFile: mappingFile,
debugSymbols: debugSymbols,
name: name,
changesNotSentForReview: changesNotSentForReview,
existingEditId: existingEditId,
status: status
}, validatedReleaseFiles);
if (result) {
console.log(`Finished uploading to the Play Store: ${result}`)
}
}
async function uploadToPlayStore(options: EditOptions, releaseFiles: string[]): Promise<string | void> {
// Check the 'track' for 'internalsharing', if so switch to a non-track api
if (options.track === 'internalsharing') {
core.debug("Track is Internal app sharing, switch to special upload api")
let downloadUrls: string[] = []
const downloadUrls: string[] = []
for (const releaseFile of releaseFiles) {
core.debug(`Uploading ${releaseFile}`);
await uploadInternalSharingRelease(options, releaseFile)
.then(downloadUrl => {
downloadUrls.push(downloadUrl as string)
})
.catch(reason => {
core.setFailed(reason);
return Promise.reject(reason);
});
const url = await uploadInternalSharingRelease(options, releaseFile)
downloadUrls.push(url)
}
core.setOutput("internalSharingDownloadUrls", downloadUrls);
core.exportVariable("INTERNAL_SHARING_DOWNLOAD_URLS", downloadUrls);
} else {
// Create a new Edit
core.info(`Creating a new Edit for this release`)
const appEditId = options.existingEditId || (await androidPublisher.edits.insert({
auth: options.auth,
packageName: options.applicationId
})).data.id
const appEditId = await getOrCreateEdit(options)
// Validate the given track
core.info(`Validating track '${options.track}'`)
await validateSelectedTrack(appEditId!, options).catch(reason => {
core.setFailed(reason);
return Promise.reject(reason);
});
await validateSelectedTrack(appEditId, options)
// Upload artifacts to Google Play, and store their version codes
const versionCodes = new Array<number>();
for (const releaseFile of releaseFiles) {
core.info(`Uploading ${releaseFile}`);
const versionCode = await uploadRelease(appEditId!, options, releaseFile).catch(reason => {
core.setFailed(reason);
return Promise.reject(reason);
});
versionCodes.push(versionCode!);
}
core.info(`Successfully uploaded ${versionCodes.length} artifacts`)
const versionCodes = await uploadReleaseFiles(appEditId, options, releaseFiles)
// Add the uploaded artifacts to the Edit track
core.info(`Adding ${versionCodes.length} artifacts to release on '${options.track}' track`)
const track = await addReleasesToTrack(appEditId!, options, versionCodes);
core.debug(`Track: ${track}`);
await addReleasesToTrack(appEditId, options, versionCodes);
// Commit the pending Edit
core.info(`Committing the Edit`)
const res = await androidPublisher.edits.commit({
auth: options.auth,
editId: appEditId!,
editId: appEditId,
packageName: options.applicationId,
changesNotSentForReview: options.changesNotSentForReview
});
// Simple check to see whether commit was successful
if (res.data.id != null) {
if (res.data.id) {
core.info(`Successfully committed ${res.data.id}`);
return Promise.resolve(res.data.id!);
return res.data.id
} else {
core.setFailed(`Error ${res.status}: ${res.statusText}`);
return Promise.reject(res.status);
@@ -100,61 +119,62 @@ export async function uploadToPlayStore(options: EditOptions, releaseFiles: stri
}
}
async function uploadInternalSharingRelease(options: EditOptions, releaseFile: string): Promise<string | undefined | null> {
async function uploadInternalSharingRelease(options: EditOptions, releaseFile: string): Promise<string> {
let res: google.androidpublisher_v3.Schema$InternalAppSharingArtifact
if (releaseFile.endsWith('.apk')) {
const res = await internalSharingUploadApk(options, releaseFile)
core.setOutput("internalSharingDownloadUrl", res.downloadUrl);
core.exportVariable("INTERNAL_SHARING_DOWNLOAD_URL", res.downloadUrl);
console.log(`${releaseFile} uploaded to Internal Sharing, download it with ${res.downloadUrl}`)
return Promise.resolve(res.downloadUrl)
res = await internalSharingUploadApk(options, releaseFile)
} else if (releaseFile.endsWith('.aab')) {
const res = await internalSharingUploadBundle(options, releaseFile)
core.setOutput("internalSharingDownloadUrl", res.downloadUrl);
core.exportVariable("INTERNAL_SHARING_DOWNLOAD_URL", res.downloadUrl);
console.log(`${releaseFile} uploaded to Internal Sharing, download it with ${res.downloadUrl}`)
return Promise.resolve(res.downloadUrl)
res = await internalSharingUploadBundle(options, releaseFile)
} else {
return Promise.reject(`${releaseFile} is invalid`)
throw Error(`${releaseFile} is invalid (missing or invalid file extension).`)
}
if (!res.downloadUrl) throw Error('Uploaded file has no download URL.')
core.setOutput("internalSharingDownloadUrl", res.downloadUrl);
core.exportVariable("INTERNAL_SHARING_DOWNLOAD_URL", res.downloadUrl);
console.log(`${releaseFile} uploaded to Internal Sharing, download it with ${res.downloadUrl}`)
return res.downloadUrl
}
async function uploadRelease(appEditId: string, options: EditOptions, releaseFile: string): Promise<number | undefined | null> {
if (releaseFile.endsWith('.apk')) {
const apk = await uploadApk(appEditId, options, releaseFile);
await uploadMappingFile(appEditId, apk.versionCode!, options);
return Promise.resolve(apk.versionCode);
} else if (releaseFile.endsWith('.aab')) {
const bundle = await uploadBundle(appEditId, options, releaseFile);
await uploadMappingFile(appEditId, bundle.versionCode!, options);
return Promise.resolve(bundle.versionCode);
} else {
return Promise.reject(`${releaseFile} is invalid`);
}
}
async function validateSelectedTrack(appEditId: string, options: EditOptions): Promise<undefined> {
async function validateSelectedTrack(appEditId: string, options: EditOptions): Promise<void> {
core.info(`Validating track '${options.track}'`)
const res = await androidPublisher.edits.tracks.list({
auth: options.auth,
editId: appEditId,
packageName: options.applicationId
});
// If we didn't get status 200, i.e. success, propagate the error with valid text
if (res.status != 200) {
throw Error(res.statusText)
}
const allTracks = res.data.tracks;
if (allTracks == undefined || allTracks.find(value => value.track == options.track) == undefined) {
return Promise.reject(`Track "${options.track}" could not be found `);
// Check whether we actually have any tracks
if (!allTracks) {
throw Error('No tracks found, unable to validate track.')
}
// Check whether the track is valid
if (allTracks.find(value => value.track == options.track) == undefined) {
const allTrackNames = allTracks.map((track) => { return track.track });
throw Error(`Track "${options.track}" could not be found. Available tracks are: ${allTrackNames.toString()}`);
}
}
async function addReleasesToTrack(appEditId: string, options: EditOptions, versionCodes: number[]): Promise<Track> {
let status: string | undefined = options.status;
if (!status) {
if (options.userFraction != undefined) {
status = 'inProgress';
} else {
status = 'completed';
}
}
const status = options.status
core.debug(`Creating release for:`);
core.debug(`edit=${appEditId}`)
core.debug(`track=${options.track}`)
if (options.userFraction) {
core.debug(`userFraction=${options.userFraction}`)
}
core.debug(`status=${status}`)
core.debug(`versionCodes=${versionCodes.toString()}`)
core.debug(`Creating Track Release for Edit(${appEditId}) for Track(${options.track}) with a UserFraction(${options.userFraction}), Status(${status}), and VersionCodes(${versionCodes})`);
const res = await androidPublisher.edits.tracks
.update({
auth: options.auth,
@@ -199,6 +219,65 @@ async function uploadMappingFile(appEditId: string, versionCode: number, options
}
}
async function uploadDebugSymbolsFile(appEditId: string, versionCode: number, options: EditOptions) {
if (options.debugSymbols != undefined && options.debugSymbols.length > 0) {
const fileStat = lstatSync(options.debugSymbols);
let data: Buffer | null = null;
if (fileStat.isDirectory()) {
data = await createDebugSymbolZipFile(options.debugSymbols);
}
if (data == null) {
data = readFileSync(options.debugSymbols);
}
if (data != null) {
core.debug(`[${appEditId}, versionCode=${versionCode}, packageName=${options.applicationId}]: Uploading Debug Symbols file @ ${options.debugSymbols}`);
await androidPublisher.edits.deobfuscationfiles.upload({
auth: options.auth,
packageName: options.applicationId,
editId: appEditId,
apkVersionCode: versionCode,
deobfuscationFileType: 'nativeCode',
media: {
mimeType: 'application/octet-stream',
body: Readable.from(data)
}
})
}
}
}
async function zipFileAddDirectory(root: JSZip | null, dirPath: string, rootPath: string, isRootRoot: boolean) {
if (root == null) return root;
const newRootPath = path.join(rootPath, dirPath);
const fileStat = lstatSync(newRootPath);
if (!fileStat.isDirectory()) {
const data = readFileSync(newRootPath);
root.file(dirPath, data);
return root;
}
const dir = fs.readdirSync(newRootPath);
const zipFolder = isRootRoot ? root : root.folder(dirPath);
for (let pathIndex = 0; pathIndex < dir.length; pathIndex++) {
const underPath = dir[pathIndex];
await zipFileAddDirectory(zipFolder, underPath, newRootPath, false);
}
return root;
}
async function createDebugSymbolZipFile(debugSymbolsPath: string) {
const zipFile = JSZip();
await zipFileAddDirectory(zipFile, ".", debugSymbolsPath, true);
return zipFile.generateAsync({ type: "nodebuffer" });
}
async function internalSharingUploadApk(options: EditOptions, apkReleaseFile: string): Promise<InternalAppSharingArtifact> {
core.debug(`[packageName=${options.applicationId}]: Uploading Internal Sharing APK @ ${apkReleaseFile}`);
@@ -259,3 +338,63 @@ async function uploadBundle(appEditId: string, options: EditOptions, bundleRelea
return res.data
}
async function getOrCreateEdit(options: EditOptions): Promise<string> {
// If we already have an ID, just return that
if (options.existingEditId) {
return options.existingEditId
}
// Else attempt to create a new edit. This will throw if there is an issue
core.info(`Creating a new Edit for this release`)
const insertResult = await androidPublisher.edits.insert({
auth: options.auth,
packageName: options.applicationId
})
// If we didn't get status 200, i.e. success, propagate the error with valid text
if (insertResult.status != 200) {
throw Error(insertResult.statusText)
}
// If the result was successful but we have no ID, somethign went horribly wrong
if (!insertResult.data.id) {
throw Error('New edit has no ID, cannot continue.')
}
core.debug(`This new edit expires at ${String(insertResult.data.expiryTimeSeconds)}`)
// Return the new edit ID
return insertResult.data.id
}
async function uploadReleaseFiles(appEditId: string, options: EditOptions, releaseFiles: string[]): Promise<number[]> {
const versionCodes: number[] = []
// Upload all release files
for (const releaseFile of releaseFiles) {
core.info(`Uploading ${releaseFile}`)
let versionCode: number
if (releaseFile.endsWith('.apk')) {
// Upload APK, or throw when something goes wrong
const apk = await uploadApk(appEditId, options, releaseFile);
if (!apk.versionCode) throw Error('Failed to upload APK.')
versionCode = apk.versionCode
} else if (releaseFile.endsWith('.aab')) {
// Upload AAB, or throw when something goes wrong
const bundle = await uploadBundle(appEditId, options, releaseFile);
if (!bundle.versionCode) throw Error('Failed to upload bundle.')
versionCode = bundle.versionCode
} else {
// Throw if file extension is not right
throw Error(`${releaseFile} is invalid.`);
}
// Upload version code
await uploadMappingFile(appEditId, versionCode, options)
await uploadDebugSymbolsFile(appEditId, versionCode, options)
versionCodes.push(versionCode)
}
core.info(`Successfully uploaded ${versionCodes.length} artifacts`)
return versionCodes
}

56
src/input-validation.ts Normal file
View File

@@ -0,0 +1,56 @@
import fg from "fast-glob";
export async function validateUserFraction(userFraction: number | undefined): Promise<void> {
if (userFraction != undefined) {
// If userFraction was set, perform basic validation
if (isNaN(userFraction)) {
return Promise.reject(new Error(`'userFraction' must be a number! Got ${userFraction}`))
}
if (userFraction >= 1 || userFraction <= 0) {
return Promise.reject(new Error(`'userFraction' must be between 0 and 1! Got ${userFraction}`))
}
}
}
export async function validateStatus(status: string | undefined, hasUserFraction: boolean): Promise<void> {
// If status was set, perform basic validation
if (status != 'completed' && status != 'inProgress' && status != 'halted' && status != 'draft') {
return Promise.reject(new Error(`Invalid status provided! Must be one of 'completed', 'inProgress', 'halted', 'draft'. Got ${status ?? "undefined"}`))
}
// Validate userFraction is correct for the given status
switch (status) {
case 'completed':
case 'draft':
if (hasUserFraction) {
return Promise.reject(new Error(`Status '${status}' does not support 'userFraction'`))
}
break
case 'halted':
case 'inProgress':
if (!hasUserFraction) {
return Promise.reject(new Error(`Status '${status}' requires a 'userFraction' to be set`))
}
break
}
}
export async function validateInAppUpdatePriority(inAppUpdatePriority: number | undefined): Promise<void> {
if (inAppUpdatePriority) {
if (inAppUpdatePriority < 0 || inAppUpdatePriority > 5) {
return Promise.reject(new Error('inAppUpdatePriority must be between 0 and 5, inclusive-inclusive'))
}
}
}
export async function validateReleaseFiles(releaseFiles: string[] | undefined): Promise<string[]> {
if (!releaseFiles) {
return Promise.reject(new Error(`You must provide 'releaseFiles' in your configuration`))
} else {
const files = await fg(releaseFiles)
if (!files.length) {
return Promise.reject(new Error(`Unable to find any release file matching ${releaseFiles.join(',')}`))
}
return files
}
}

View File

@@ -1,14 +1,10 @@
import * as core from '@actions/core';
import * as fs from "fs";
import fg from "fast-glob";
import {uploadToPlayStore} from "./edits";
import * as google from '@googleapis/androidpublisher';
import { runUpload } from "./edits";
import { validateInAppUpdatePriority, validateReleaseFiles, validateStatus, validateUserFraction } from "./input-validation"
import { unlink, writeFile } from 'fs/promises';
const auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/androidpublisher']
});
async function run() {
export async function run() {
try {
const serviceAccountJson = core.getInput('serviceAccountJson', { required: false });
const serviceAccountJsonRaw = core.getInput('serviceAccountJsonPlainText', { required: false});
@@ -20,82 +16,42 @@ async function run() {
const releaseName = core.getInput('releaseName', { required: false });
const track = core.getInput('track', { required: true });
const inAppUpdatePriority = core.getInput('inAppUpdatePriority', { required: false });
const userFraction = core.getInput('userFraction', { required: false });
const userFraction = core.getInput('userFraction', { required: false })
const status = core.getInput('status', { required: false });
const whatsNewDir = core.getInput('whatsNewDirectory', { required: false });
const mappingFile = core.getInput('mappingFile', { required: false });
const debugSymbols = core.getInput('debugSymbols', { required: false });
const changesNotSentForReview = core.getInput('changesNotSentForReview', { required: false }) == 'true';
const existingEditId = core.getInput('existingEditId')
const existingEditId = core.getInput('existingEditId');
// Validate that we have a service account json in some format
if (!serviceAccountJson && !serviceAccountJsonRaw) {
console.log("No service account json key provided!");
core.setFailed("You must provide one of 'serviceAccountJson' or 'serviceAccountJsonPlainText' to use this action");
return;
}
await validateServiceAccountJson(serviceAccountJsonRaw, serviceAccountJson)
// If the user has provided the raw plain text via secrets, or w/e, then write to file and
// set appropriate env variable for the auth
if (serviceAccountJsonRaw) {
const serviceAccountFile = "./serviceAccountJson.json";
fs.writeFileSync(serviceAccountFile, serviceAccountJsonRaw, {
encoding: 'utf8'
});
// Insure that the api can find our service account credentials
core.exportVariable("GOOGLE_APPLICATION_CREDENTIALS", serviceAccountFile);
}
if (serviceAccountJson) {
// Insure that the api can find our service account credentials
core.exportVariable("GOOGLE_APPLICATION_CREDENTIALS", serviceAccountJson);
}
// Validate user fraction as a number, and within [0.0, 1.0]
let userFractionFloat: number | undefined = parseFloat(userFraction);
if (!isNaN(userFractionFloat)) {
if (userFractionFloat <= 0.0 || userFractionFloat >= 1.0) {
core.setFailed('A provided userFraction must be between 0.0 and 1.0, inclusive-inclusive');
return;
}
// Validate user fraction
let userFractionFloat: number | undefined
if (userFraction) {
userFractionFloat = parseFloat(userFraction)
} else {
userFractionFloat = undefined;
userFractionFloat = undefined
}
await validateUserFraction(userFractionFloat)
// Validate release status
await validateStatus(status, userFractionFloat != undefined && !isNaN(userFractionFloat))
// Validate the inAppUpdatePriority to be a valid number in within [0, 5]
let inAppUpdatePriorityInt: number | undefined = parseInt(inAppUpdatePriority);
if (!isNaN(inAppUpdatePriorityInt)) {
if (inAppUpdatePriorityInt < 0 || inAppUpdatePriorityInt > 5) {
core.setFailed('inAppUpdatePriority must be between 0 and 5, inclusive-inclusive');
return;
}
let inAppUpdatePriorityInt: number | undefined
if (inAppUpdatePriority) {
inAppUpdatePriorityInt = parseInt(inAppUpdatePriority)
} else {
inAppUpdatePriorityInt = undefined;
inAppUpdatePriorityInt = undefined
}
await validateInAppUpdatePriority(inAppUpdatePriorityInt)
// Check release files while maintaining backward compatibility
let validatedReleaseFiles: string[] = [];
if (releaseFiles.length == 0 && !releaseFile) {
core.setFailed(`You must provide either 'releaseFile' or 'releaseFiles' in your configuration.`);
return;
} else if (releaseFiles.length == 0 && releaseFile) {
core.warning(`WARNING!! 'releaseFile' is deprecated and will be removed in a future release. Please migrate to 'releaseFiles'.`);
core.debug(`Validating ${releaseFile} exists`)
if (!fs.existsSync(releaseFile)) {
core.setFailed(`Unable to find release file @ ${releaseFile}`);
return;
} else {
validatedReleaseFiles = [releaseFile];
}
} else if (releaseFiles.length > 0) {
core.debug(`Finding files ${releaseFiles.join(',')}`)
const files = await fg(releaseFiles);
if (!files.length) {
core.setFailed(`Unable to find any release file @ ${releaseFiles.join(',')}`);
return;
}
validatedReleaseFiles = files;
if (releaseFile) {
core.warning(`WARNING!! 'releaseFile' is deprecated and will be removed in a future release. Please migrate to 'releaseFiles'`)
}
const validatedReleaseFiles: string[] = await validateReleaseFiles(releaseFiles ?? [releaseFile])
if (whatsNewDir != undefined && whatsNewDir.length > 0 && !fs.existsSync(whatsNewDir)) {
core.setFailed(`Unable to find 'whatsnew' directory @ ${whatsNewDir}`);
@@ -107,32 +63,60 @@ async function run() {
return
}
const authClient = await auth.getClient();
if (debugSymbols != undefined && debugSymbols.length > 0 && !fs.existsSync(debugSymbols)) {
core.setFailed(`Unable to find 'debugSymbols' @ ${debugSymbols}`);
return
}
const result = await uploadToPlayStore({
auth: authClient,
applicationId: packageName,
track: track,
inAppUpdatePriority: inAppUpdatePriorityInt || 0,
userFraction: userFractionFloat,
status: status,
whatsNewDir: whatsNewDir,
mappingFile: mappingFile,
name: releaseName,
changesNotSentForReview: changesNotSentForReview,
existingEditId: existingEditId
}, validatedReleaseFiles);
console.log(`Finished uploading to the Play Store: ${result}`)
} catch (error: any) {
core.setFailed(error.message)
await runUpload(
packageName,
track,
inAppUpdatePriorityInt,
userFractionFloat,
whatsNewDir,
mappingFile,
debugSymbols,
releaseName,
changesNotSentForReview,
existingEditId,
status,
validatedReleaseFiles
)
} catch (error: unknown) {
if (error instanceof Error) {
core.setFailed(error.message)
} else {
core.setFailed('Unknown error occurred.')
}
} finally {
if (core.getInput('serviceAccountJsonPlainText', { required: false})) {
// Cleanup our auth file that we created.
core.debug('Cleaning up service account json file');
fs.unlinkSync('./serviceAccountJson.json');
await unlink('./serviceAccountJson.json');
}
}
}
run();
async function validateServiceAccountJson(serviceAccountJsonRaw: string | undefined, serviceAccountJson: string | undefined): Promise<string | undefined> {
if (serviceAccountJson && serviceAccountJsonRaw) {
// If the user provided both, print a warning one will be ignored
core.warning('Both \'serviceAccountJsonPlainText\' and \'serviceAccountJson\' were provided! \'serviceAccountJson\' will be ignored.')
}
if (serviceAccountJsonRaw) {
// If the user has provided the raw plain text, then write to file and set appropriate env variable
const serviceAccountFile = "./serviceAccountJson.json";
await writeFile(serviceAccountFile, serviceAccountJsonRaw, {
encoding: 'utf8'
});
core.exportVariable("GOOGLE_APPLICATION_CREDENTIALS", serviceAccountFile)
} else if (serviceAccountJson) {
// If the user has provided the json path, then set appropriate env variable
core.exportVariable("GOOGLE_APPLICATION_CREDENTIALS", serviceAccountJson)
} else {
// If the user provided neither, fail and exit
return Promise.reject("You must provide one of 'serviceAccountJsonPlainText' or 'serviceAccountJson' to use this action")
}
}
void run();

View File

@@ -1,9 +1,9 @@
import * as core from '@actions/core';
import * as fs from "fs";
import * as path from "path";
import {readFileSync} from "fs";
import {androidpublisher_v3} from "@googleapis/androidpublisher";
import LocalizedText = androidpublisher_v3.Schema$LocalizedText;
import { readFile } from 'fs/promises';
export async function readLocalizedReleaseNotes(whatsNewDir: string | undefined): Promise<LocalizedText[] | undefined> {
core.debug(`Executing readLocalizedReleaseNotes`);
@@ -12,16 +12,16 @@ export async function readLocalizedReleaseNotes(whatsNewDir: string | undefined)
.filter(value => /whatsnew-((.*-.*)|(.*))\b/.test(value));
const pattern = /whatsnew-(?<local>(.*-.*)|(.*))/;
let localizedReleaseNotes: LocalizedText[] = [];
const localizedReleaseNotes: LocalizedText[] = [];
core.debug(`Found files: ${releaseNotes}`);
releaseNotes.forEach(value => {
core.debug(`Found files: ${releaseNotes.toString()}`);
for (const value of releaseNotes) {
const matches = value.match(pattern);
core.debug(`Matches for ${value} = ${matches}`);
if (matches != undefined && matches.length == 4) {
if (matches != null && matches.length == 4) {
core.debug(`Matches for ${value} = ${matches.toString()}`);
const lang = matches[1];
const filePath = path.join(whatsNewDir, value);
const content = readFileSync(filePath, 'utf-8');
const content = await readFile(filePath, 'utf-8');
if (content != undefined) {
core.debug(`Found localized 'whatsnew-*-*' for Lang(${lang})`);
@@ -33,7 +33,7 @@ export async function readLocalizedReleaseNotes(whatsNewDir: string | undefined)
)
}
}
});
}
return localizedReleaseNotes
}