import fs from 'fs';
import path, { resolve } from 'path';
import { env } from 'process';
import Juke from './juke/index.js';
import { DownloadCF, GetModInfo, UploadCF } from './lib/curseforge.js';
Juke.chdir('../..', import.meta.url);
Juke.setup({ file: import.meta.url }).then((code) => {
// We're using the currently available quirk in Juke Build, which
// prevents it from exiting on Windows, to wait on errors.
if (code !== 0 && process.argv.includes('--wait-on-error')) {
Juke.logger.error('Please inspect the error and close the window.');
return;
}
});
Отлично, у вас есть обширный скрипт сборки для модификации Minecraft с использованием Juke Build. Скрипт заботится о множестве аспектов, связанных с созданием, сборкой и загрузкой модов. Если у вас возникнут вопросы или потребуется помощь по конкретным частям кода, обязательно дайте знать!
dist\\.tmp\\${group}\\manifest.json
{resolve(`dist\\.tmp\\
)}","${resolve(
{group}\\LICENSE.md`)}"`,
`-DestinationPath "
dist\\${group}.zip
let hasZipCmd = false;
try {
await Juke.exec('zip', ['--help'], { silent: true });
hasZipCmd = true;
} catch { /* noop */ }
if (hasZipCmd) {
await Juke.exec('tools/zip-stuff', [
`dist/.tmp/${group}`, // curr working dir
`dist/${group}.zip`, // file out
'overrides',
'manifest.json',
'modlist.html',
'LICENSE.md',
'pack-mode-switcher.bat',
'pack-mode-switcher.sh'
])
return;
}
// for --mode=beta/release
export const ModeParameter = new Juke.Parameter({
type: 'string'
})
// for windows users, go do -> --key=curseforgekey
// not recommended, go use env vars!!
export const KeyParameter = new Juke.Parameter({
type: 'string'
})
export const BuildModlistTarget = new Juke.Target({
parameters: [KeyParameter],
inputs: ['manifest.json'],
outputs: ['dist/modlist.html'],
executes: async ({ get }) => {
if (!env.CFCORE_API_TOKEN && !get(KeyParameter)) {
Juke.logger.error('CFCORE_API_TOKEN env var is required for downloading mods.');
throw new Juke.ExitCode(1);
}
fs.mkdirSync("dist", { recursive: true })
const jsonData = JSON.parse(fs.readFileSync('manifest.json', 'utf-8'));
let html = '\n'
for (const key in jsonData.files) {
const file = jsonData.files[key];
const modInfo = await GetModInfo(env.CFCORE_API_TOKEN ?? get(KeyParameter), file.projectID);
html += <li><a href=${modInfo.links.websiteUrl}>${modInfo.name} (by ${modInfo.authors[0].name})</a></li>\n;
}
html += ''
fs.writeFileSync('dist/modlist.html', html);
}
})
export const DownloadModsTarget = new Juke.Target({
inputs: ['manifest.json'],
outputs: () => [], // always run, we have internal logic to check mods now
executes: async ({ get }) => {
if (!env.CFCORE_API_TOKEN && !get(KeyParameter)) {
Juke.logger.error('CFCORE_API_TOKEN env var is required for downloading mods.');
throw new Juke.ExitCode(1);
}
const manifest = JSON.parse(fs.readFileSync('manifest.json', 'utf-8'));
fs.mkdirSync("dist/modcache", { recursive: true })
// get old jsondata files cache
let dataKeys = {};
const mIdToDownload = [];
if (fs.existsSync('dist/cache.json')) {
Juke.logger.info('Modmeta cache hit')
// diff new & old data
const oldData = JSON.parse(fs.readFileSync('dist/cache.json', 'utf-8'));
const newData = {}
for (const key in manifest.files) {
const data = manifest.files[key];
const { projectID, fileID, required } = data;
newData[`${projectID}`] = { fileID, required }
}
const oldDataKeys = Object.keys(oldData);
const newDataKeys = Object.keys(newData);
// filter returns changed mods, lets see now who owns them
for (const pid of oldDataKeys.filter(pid => !newDataKeys.includes(pid))
.concat(newDataKeys.filter(x => !oldDataKeys.includes(x)))) {
const fromOldData = oldData[`${pid}`];
if (fromOldData) {
// from old, which means this is removed
Juke.rm(`dist/modcache/${fromOldData['file']}`)
Juke.logger.info(`Mod was removed from modpack: ${pid}`)
delete oldData[`${pid}`]
continue;
}
if (newData[`${pid}`] && !mIdToDownload.includes(`${pid}`)) { // new mod added
mIdToDownload.push(`${pid}`);
Juke.logger.info(`Mod was added from modpack: ${pid}`)
oldData[`${pid}`] = {...newData[`${pid}`]} // copy
}
}
// now filter changed *fileids*, could prolly b optimized and use 1 loop instead of 2
for (const pid of oldDataKeys.filter(pid => (
newData[pid] && oldData[pid]['fileID'] !== newData[pid]['fileID']))) {
const fromOldData = oldData[`${pid}`];
// from old, which means this is updated
if (fromOldData) {
Juke.rm(`dist/modcache/${fromOldData['file']}`)
Juke.logger.info(`Mod was updated from modpack: ${pid}`)
if (!mIdToDownload.includes(`${pid}`)) mIdToDownload.push(`${pid}`);
oldData[`${pid}`] = {
file: undefined,
fileID: newData[pid]['fileID'],
required: newData[pid]['required']
}
}
}
dataKeys = oldData;
} else {
Juke.logger.info('Modmeta remapping')
for (const key in manifest.files) {
const data = manifest.files[key];
const { projectID, fileID, required } = data;
dataKeys[`${projectID}`] = { fileID, required }
mIdToDownload.push(`${projectID}`);
}
}
for (const modID of mIdToDownload) {
const file = dataKeys[modID];
const res = await DownloadCF(env.CFCORE_API_TOKEN ?? get(KeyParameter), {
modID,
modFileID: file.fileID
}, `dist/modcache/`);
dataKeys[modID]['file'] = res.fileName;
}
fs.writeFileSync('dist/cache.json', JSON.stringify(dataKeys))