Philipp Horstenkamp 705d67adec
All checks were successful
Lint / pre-commit Linting (push) Successful in 25s
Refactor the index.js
2025-04-21 22:54:49 +02:00

182 lines
5.3 KiB
JavaScript

const { ScreepsAPI } = require("screeps-api");
const core = require("@actions/core");
const fs = require("fs");
const { glob } = require("glob");
const path = require("path");
function replacePlaceholders(content, hostname) {
const deployTime = new Date().toISOString();
core.debug(
`Replacing placeholders with: GITHUB_SHA=${process.env.GITHUB_SHA}, GITHUB_REF=${process.env.GITHUB_REF}, deployTime=${deployTime}, hostname=${hostname}`,
);
return content
.replace(/{{gitHash}}/g, process.env.GITHUB_SHA)
.replace(/{{gitRef}}/g, process.env.GITHUB_REF)
.replace(/{{deployTime}}/g, deployTime)
.replace(/{{hostname}}/g, hostname);
}
async function readReplaceAndWriteFiles(pattern, prefix, hostname) {
return new Promise((resolve, reject) => {
const globPattern = prefix ? path.join(prefix, pattern) : pattern;
core.info(`Searching files with glob pattern: ${globPattern}`);
glob(globPattern, async (err, files) => {
if (err) {
core.error(`Glob error: ${err}`);
return reject(err);
}
if (files.length === 0) {
core.warning("No files matched the glob pattern.");
}
let processPromises = [];
files.forEach((file) => {
core.debug(`Processing file: ${file}`);
let processPromise = fs.promises
.readFile(file, "utf8")
.then((content) => {
content = replacePlaceholders(content, hostname);
return fs.promises.writeFile(file, content);
})
.then(() => {
core.info(`Replaced and wrote file: ${file}`);
});
processPromises.push(processPromise);
});
try {
await Promise.all(processPromises);
core.info(`Successfully processed ${files.length} files.`);
resolve(files);
} catch (processError) {
core.error(`Error during file processing: ${processError}`);
reject(processError);
}
});
});
}
function readFilesIntoDict(pattern, prefix) {
const globPattern = prefix ? path.join(prefix, pattern) : pattern;
core.info(`Reading files into dict with glob: ${globPattern}`);
return new Promise((resolve, reject) => {
glob(globPattern, (err, files) => {
if (err) {
core.error(`Glob error: ${err}`);
return reject(err);
}
let fileDict = {};
let readPromises = [];
files.forEach((file) => {
core.debug(`Reading file: ${file}`);
let readPromise = fs.promises.readFile(file, "utf8").then((content) => {
let key = file;
if (prefix && file.startsWith(prefix)) {
key = key.slice(prefix.length);
}
key = path.basename(key, path.extname(key));
fileDict[key] = content;
});
readPromises.push(readPromise);
});
Promise.all(readPromises)
.then(() => {
core.debug(`Read ${files.length} files into dictionary.`);
resolve(fileDict);
})
.catch((readErr) => {
core.error(`Error reading files: ${readErr}`);
reject(readErr);
});
});
});
}
function validateAuthentication(token, username, password) {
if (token && (username || password)) {
return "Token is defined along with username and/or password.";
}
if (!token && (!username || !password)) {
return "Username and password must both be defined if token is not used.";
}
return null;
}
async function postCode() {
const protocol = core.getInput("protocol") || "https";
const hostname = core.getInput("hostname") || "screeps.com";
const port = core.getInput("port") || "443";
const path = core.getInput("path") || "/";
const token = core.getInput("token") || undefined;
const username = core.getInput("username") || undefined;
const password = core.getInput("password") || undefined;
const prefix = core.getInput("source-prefix");
const pattern = core.getInput("pattern") || "*.js";
const branch = core.getInput("branch") || "default";
const gitReplace = core.getInput("git-replace") || null;
core.info("Starting Screeps code upload action...");
if (gitReplace) {
core.info(`Replacing placeholders in files matching: ${gitReplace}`);
await readReplaceAndWriteFiles(gitReplace, prefix, hostname);
}
const files_to_push = await readFilesIntoDict(pattern, prefix);
core.info(
`Preparing to upload ${
Object.keys(files_to_push).length
} files to branch: ${branch}`,
);
const login_arguments = {
token,
username,
password,
protocol,
hostname,
port,
path,
};
core.debug(`Login arguments: ${JSON.stringify(login_arguments, null, 2)}`);
const errorMessage = validateAuthentication(token, username, password);
if (errorMessage) {
core.setFailed(errorMessage);
return;
}
let api = new ScreepsAPI(login_arguments);
try {
if (token) {
const response = await api.code.set(branch, files_to_push);
core.info(
`Code uploaded via token. Response: ${JSON.stringify(
response,
null,
2,
)}`,
);
} else {
core.info(`Logging in with username/password for user ${username}`);
await api.auth(username, password, login_arguments);
await api.code.set(branch, files_to_push);
core.info("Code uploaded via basic auth.");
}
} catch (err) {
core.setFailed(`Upload failed: ${err.message || err}`);
}
}
postCode();