feat: better multiple file handling

This commit is contained in:
TrèsAbhi committed 2023-11-27 17:50:02 -06:00
1 parent e23f898c5f
commit 6910f3c95e
2 files changed
+119 -86

No files matched your search

+58 -57
View File
@@ -9,38 +9,36 @@ import { TreeTypeString } from '../src/components/Tanks';
import { NATION_IDS } from '../src/constants/nations'; import { NATION_IDS } from '../src/constants/nations';
import commitMultipleFiles, { FileChange } from './commitMultipleFiles'; import commitMultipleFiles, { FileChange } from './commitMultipleFiles';
const LANGUAGE = 'en';
const TEMP = 'temp/blitz';
const publish = argv.includes('--publish'); const publish = argv.includes('--publish');
const apkFile = argv const apkFile = argv
.find((argument) => argument.startsWith('--file')) .find((argument) => argument.startsWith('--file'))
?.split('=')[1]; ?.split('=')[1];
const noRewrite = argv.includes('--no-rewrite'); const noRewrite = argv.includes('--no-rewrite');
const VEHICLE_DEFS = 'assets/Data/XML/item_defs/vehicles';
const STRINGS = 'assets/Data/Strings';
const LANGUAGE = 'en';
const TANK_PARAMETERS = 'assets/Data/3d/Tanks/Parameters';
const SMALL_ICONS = 'assets/Data/Gfx/UI/BattleScreenHUD/SmallTankIcons';
const BIG_ICONS = 'assets/Data/Gfx/UI/BigTankIcons';
const DIRECTORIES_OF_INTEREST = [
VEHICLE_DEFS,
STRINGS,
TANK_PARAMETERS,
SMALL_ICONS,
BIG_ICONS,
];
if (!apkFile) throw new Error('No file specified'); if (!apkFile) throw new Error('No file specified');
const directoriesOfInterest = {
vehicleDefinitions: 'assets/Data/XML/item_defs/vehicles',
strings: 'assets/Data/Strings',
tankParameters: 'assets/Data/3d/Tanks/Parameters',
smallIcons: 'assets/Data/Gfx/UI/BattleScreenHUD/SmallTankIcons',
bigIcons: 'assets/Data/Gfx/UI/BigTankIcons',
};
const directoriesOfInterestArray = Object.values(directoriesOfInterest);
console.log('Removing old tankopedia files...'); console.log('Removing old tankopedia files...');
await rm('dist/tankopedia', { recursive: true, force: true }); await rm('dist/tankopedia', { recursive: true, force: true });
if (!noRewrite) { if (!noRewrite) {
console.log('Removing old temp files...'); console.log('Removing old temp files...');
await rm('temp/blitz', { recursive: true, force: true }); await rm(TEMP, { recursive: true, force: true });
console.log('Extracting Blitz files...'); console.log('Extracting Blitz files...');
await decompress(apkFile, 'temp/blitz', { await decompress(apkFile, TEMP, {
filter: (file) => filter: (file) =>
DIRECTORIES_OF_INTEREST.some((dir) => file.path.startsWith(dir)), directoriesOfInterestArray.some((dir) => file.path.startsWith(dir)),
}); });
} }
@@ -58,20 +56,22 @@ interface BlitzkriegTankopedia {
} }
const strings = await readFile( const strings = await readFile(
`temp/blitz/${STRINGS}/${LANGUAGE}.yaml`, `${TEMP}/${directoriesOfInterest.strings}/${LANGUAGE}.yaml`,
'utf-8', 'utf-8',
).then((data) => load(data) as Record<string, string>); ).then((data) => load(data) as Record<string, string>);
const tankopedia: Record<number, BlitzkriegTankopedia> = {}; const tankopedia: Record<number, BlitzkriegTankopedia> = {};
const tankIds: number[] = []; const tankIds: number[] = [];
const images: Record<number, { big: string; small: string }> = {}; const images: Record<number, { big: string; small: string }> = {};
const nations = await readdir(`temp/blitz/${VEHICLE_DEFS}`); const nations = await readdir(
`${TEMP}/${directoriesOfInterest.vehicleDefinitions}`,
);
Promise.all( Promise.all(
nations nations
.filter((nation) => nation !== 'common') .filter((nation) => nation !== 'common')
.map(async (nation) => { .map(async (nation) => {
const listXML = await readFile( const listXML = await readFile(
`temp/blitz/${VEHICLE_DEFS}/${nation}/list.xml`, `${TEMP}/${directoriesOfInterest.vehicleDefinitions}/${nation}/list.xml`,
'utf-8', 'utf-8',
); );
const list = xml2js(listXML, { compact: true }) as ElementCompact; const list = xml2js(listXML, { compact: true }) as ElementCompact;
@@ -109,15 +109,15 @@ Promise.all(
}; };
// Tank images // Tank images
const parameterPath = `temp/blitz/${TANK_PARAMETERS}/${nation}/${vehicle}.yaml`; const parameterPath = `${TEMP}/${directoriesOfInterest.tankParameters}/${nation}/${vehicle}.yaml`;
const parameterString = await readFile(parameterPath, 'utf-8'); const parameterString = await readFile(parameterPath, 'utf-8');
const { smallIconPath, bigIconPath } = const { smallIconPath, bigIconPath } =
parse(parameterString).resourcesPath; parse(parameterString).resourcesPath;
images[id] = { images[id] = {
small: `temp/blitz/assets/Data/${(smallIconPath as string) small: `${TEMP}/assets/Data/${(smallIconPath as string)
.replace(/~res:\//, '') .replace(/~res:\//, '')
.replace(/\..+/, '')}.packed.webp`, .replace(/\..+/, '')}.packed.webp`,
big: `temp/blitz/assets/Data/${(bigIconPath as string) big: `${TEMP}/assets/Data/${(bigIconPath as string)
.replace(/~res:\//, '') .replace(/~res:\//, '')
.replace(/\..+/, '')}.packed.webp`, .replace(/\..+/, '')}.packed.webp`,
}; };
@@ -133,48 +133,49 @@ Promise.all(
).then(async () => { ).then(async () => {
if (publish) { if (publish) {
const octokit = new Octokit({ auth: env.GH_TOKEN }); const octokit = new Octokit({ auth: env.GH_TOKEN });
const tankopediaChange: FileChange = {
content: JSON.stringify(tankopedia),
path: 'tankopedia.json',
encoding: 'utf-8',
};
const iconsChange = (
await Promise.all(
tankIds.map(async (id) => {
try {
const [contentSmall, contentBig] = await Promise.all([
readFile(images[id].small, { encoding: 'base64' }),
readFile(images[id].big, { encoding: 'base64' }),
]);
// console.log('Writing tankopedia.json'); return [
// commitMultipleFiles( {
// octokit, content: contentBig,
// 'tresabhi', path: `icons/big/${id}.webp`,
// 'blitzkrieg-assets', encoding: 'base64',
// 'main', },
// new Date().toString(), {
// [ content: contentSmall,
// { path: `icons/small/${id}.webp`,
// content: JSON.stringify(tankopedia), encoding: 'base64',
// path: 'tankopedia.json', },
// encoding: 'utf-8', ];
// }, } catch (error) {
// ], console.log(error);
// ); return undefined;
}
}),
)
).flat() as FileChange[];
console.log('Writing big icons...'); console.log('Writing files...');
await commitMultipleFiles( await commitMultipleFiles(
octokit, octokit,
'tresabhi', 'tresabhi',
'blitzkrieg-assets', 'blitzkrieg-assets',
'main', 'main',
new Date().toString(), new Date().toString(),
(await Promise.all( iconsChange,
tankIds.map(async (id) => { true,
try {
const content = await readFile(images[id].big, {
encoding: 'base64',
});
return {
content,
path: `icons/big/${id}.webp`,
encoding: 'base64',
};
} catch (error) {
console.log(error);
return undefined;
}
}),
)) as FileChange[],
); );
} else { } else {
writeFile( writeFile(
+61 -29
View File
@@ -1,5 +1,7 @@
import { Octokit } from '@octokit/rest'; import { Octokit } from '@octokit/rest';
const TIME_PER_BLOB = 2 ** 4 * 1000;
export interface FileChange { export interface FileChange {
path: string; path: string;
content: string; content: string;
@@ -13,41 +15,71 @@ export default async function commitMultipleFiles(
branch: string, branch: string,
message: string, message: string,
changes: FileChange[], changes: FileChange[],
logBlobCreation = false,
) { ) {
// Get the latest commit SHA on the specified branch // Get the latest commit SHA on the specified branch
const { data: refData } = await octokit.git.getRef({ const latestCommitSha = (
owner, await octokit.git.getRef({
repo, owner,
ref: `heads/${branch}`, repo,
}); ref: `heads/${branch}`,
const latestCommitSha = refData.object.sha; })
).data.object.sha;
// Get the tree SHA for the latest commit // Get the tree SHA for the latest commit
const { data: commitData } = await octokit.git.getCommit({ const treeSha = (
owner, await octokit.git.getCommit({
repo, owner,
commit_sha: latestCommitSha, repo,
}); commit_sha: latestCommitSha,
const treeSha = commitData.tree.sha; })
).data.tree.sha;
// Create blobs for each file const blobs: {
const blobs = await Promise.all( sha: string;
changes.map(async (change) => { path: string;
const { data: blobData } = await octokit.git.createBlob({ mode: '100644';
owner, type: 'blob';
repo, }[] = [];
content: change.content,
encoding: change.encoding,
});
return { for (const changeIndexString in changes) {
sha: blobData.sha, const changeIndex = parseInt(changeIndexString);
path: change.path, const change = changes[changeIndex];
mode: '100644', let done = false;
type: 'blob',
} as const; while (!done) {
}), try {
); const { sha } = (
await octokit.git.createBlob({
owner,
repo,
content: change.content,
encoding: change.encoding,
})
).data;
blobs.push({ sha, path: change.path, mode: '100644', type: 'blob' });
done = true;
} catch (error) {
console.warn(
`Failed blob ${changeIndex + 1} / ${
changes.length
}; retrying in ${TIME_PER_BLOB}ms...`,
);
await new Promise((resolve) => setTimeout(resolve, TIME_PER_BLOB));
}
}
if (logBlobCreation) {
console.log(
`Created blob ${changeIndex + 1} / ${changes.length} (${(
(100 * (changeIndex + 1)) /
changes.length
).toFixed(2)}%)`,
);
}
}
// Create a new tree with the new blobs // Create a new tree with the new blobs
const { data: treeData } = await octokit.git.createTree({ const { data: treeData } = await octokit.git.createTree({