feat: add rollback_on_failure feature (#88)
Lint / pre-commit Linting (push) Successful in 44s
Test / Run Tests (push) Successful in 1m2s

This PR adds the ability to download existing code before deployment and automatically roll back if the post-deployment monitor detects a failure.

Reviewed-on: #88
Reviewed-by: LLMReview <27+autoreview@noreplay.horstenkamp.eu>
This commit was merged in pull request #88.
This commit is contained in:
Philipp committed 2026-05-17 13:13:58 +02:00
1 parent 076e96f3de
commit d0a08da728
5 files changed
+159 -46

No files matched your search

+1
View File
@@ -6,6 +6,7 @@ This repository is maintained by Gemini.
* **Test-Driven Development (TDD):** Wherever possible, Test-Driven Development principles should be followed. Write tests before writing the code they are intended to validate. * **Test-Driven Development (TDD):** Wherever possible, Test-Driven Development principles should be followed. Write tests before writing the code they are intended to validate.
* **Pre-commit Hooks:** Ensure that `pre-commit` hooks are installed and active before making any commits. This can be done by running `pre-commit install` in your local repository. * **Pre-commit Hooks:** Ensure that `pre-commit` hooks are installed and active before making any commits. This can be done by running `pre-commit install` in your local repository.
* **Note for Gemini:** Git commits trigger pre-commit hooks, which can take several seconds (or minutes) to complete. Checking the command status for git commit is only appropriate every 120s.
## Repository Comparison ## Repository Comparison
+73 -22
View File
@@ -20,6 +20,23 @@ vi.mock("../monitor.js", () => ({
}), }),
})); }));
// Mock screeps-api
vi.mock("screeps-api", () => {
const mockApi = {
auth: vi.fn().mockResolvedValue(),
code: {
get: vi.fn().mockResolvedValue({ ok: 1, modules: { main: "old_code" } }),
set: vi.fn().mockResolvedValue({ ok: 1 }),
},
};
// Use a regular function so it can be called with `new`
return {
ScreepsAPI: vi.fn(function () {
return mockApi;
}),
};
});
import * as core from "@actions/core"; import * as core from "@actions/core";
import { monitorConsole } from "../monitor.js"; import { monitorConsole } from "../monitor.js";
@@ -29,7 +46,9 @@ import {
readReplaceAndWriteFiles, readReplaceAndWriteFiles,
readFilesIntoDict, readFilesIntoDict,
applyOnAction, applyOnAction,
postCode,
} from "../index.js"; } from "../index.js";
import { ScreepsAPI } from "screeps-api";
import fs from "fs"; import fs from "fs";
import path from "path"; import path from "path";
import os from "os"; import os from "os";
@@ -231,31 +250,31 @@ describe("glob functionality", () => {
describe("applyOnAction", () => { describe("applyOnAction", () => {
beforeEach(() => vi.clearAllMocks()); beforeEach(() => vi.clearAllMocks());
it("'ignore' + true → no core call", () => { it("'ignore' + true → no core call, returns false", () => {
applyOnAction("ignore", true, "msg"); expect(applyOnAction("ignore", true, "msg")).toBe(false);
expect(core.warning).not.toHaveBeenCalled(); expect(core.warning).not.toHaveBeenCalled();
expect(core.setFailed).not.toHaveBeenCalled(); expect(core.setFailed).not.toHaveBeenCalled();
}); });
it("'warn' + true → core.warning() called with message", () => { it("'warn' + true → core.warning() called with message, returns false", () => {
applyOnAction("warn", true, "boom"); expect(applyOnAction("warn", true, "boom")).toBe(false);
expect(core.warning).toHaveBeenCalledWith("boom"); expect(core.warning).toHaveBeenCalledWith("boom");
expect(core.setFailed).not.toHaveBeenCalled(); expect(core.setFailed).not.toHaveBeenCalled();
}); });
it("'fail' + true → core.setFailed() called with message", () => { it("'fail' + true → core.setFailed() called with message, returns true", () => {
applyOnAction("fail", true, "boom"); expect(applyOnAction("fail", true, "boom")).toBe(true);
expect(core.setFailed).toHaveBeenCalledWith("boom"); expect(core.setFailed).toHaveBeenCalledWith("boom");
expect(core.warning).not.toHaveBeenCalled(); expect(core.warning).not.toHaveBeenCalled();
}); });
it("'fail' + false → no core call", () => { it("'fail' + false → no core call, returns false", () => {
applyOnAction("fail", false, "boom"); expect(applyOnAction("fail", false, "boom")).toBe(false);
expect(core.setFailed).not.toHaveBeenCalled(); expect(core.setFailed).not.toHaveBeenCalled();
}); });
it("'warn' + false → no core call", () => { it("'warn' + false → no core call, returns false", () => {
applyOnAction("warn", false, "msg"); expect(applyOnAction("warn", false, "msg")).toBe(false);
expect(core.warning).not.toHaveBeenCalled(); expect(core.warning).not.toHaveBeenCalled();
}); });
}); });
@@ -270,28 +289,60 @@ describe("postCode — monitor wiring", () => {
// Default core mocks // Default core mocks
core.getInput.mockImplementation((name) => { core.getInput.mockImplementation((name) => {
if (name === "monitor") return "0"; if (name === "monitor") return "0";
if (name === "token") return "test-token";
if (name === "branch") return "default";
if (name === "on_traceback") return "fail";
return ""; return "";
}); });
core.getBooleanInput.mockReturnValue(false); core.getBooleanInput.mockImplementation((name) => {
if (name === "rollback_on_failure") return false;
return false;
});
}); });
it("does not call monitorConsole when monitor=0 (default)", async () => { it("does not call monitorConsole when monitor=0 (default)", async () => {
// We need to mock the rest of postCode to not fail before it hits the monitor block // We just run postCode with monitor=0 and verify monitorConsole is not called.
// This is a bit complex as postCode is large, but we can mock the inputs to exit early or mock the API await postCode();
// Actually, I'll just check if monitorConsole is called. expect(monitorConsole).not.toHaveBeenCalled();
});
// For this test, I'll make validateAuthentication fail so it returns early but after input check it("rolls back to previous code when monitor detects a failure and rollback_on_failure is true", async () => {
// Setup inputs for monitor and rollback
core.getInput.mockImplementation((name) => { core.getInput.mockImplementation((name) => {
if (name === "monitor") return "0"; if (name === "monitor") return "10";
if (name === "token") return "test-token";
if (name === "branch") return "default";
if (name === "on_traceback") return "fail";
return ""; return "";
}); });
core.getBooleanInput.mockImplementation((name) => {
if (name === "rollback_on_failure") return true;
return false;
});
// We'll just run a partial check or rely on the monitor unit tests for depth // Simulate a failure in monitorConsole
// The wiring in index.js is: monitorConsole.mockResolvedValueOnce({
// const monitorTicks = parseInt(core.getInput("monitor") || "0", 10); sawTraceback: true, // Should trigger "fail" due to on_traceback=fail
// if (monitorTicks > 0) { ... } sawErrorLog: false,
sawWarningLog: false,
});
// Testing the logic inside index.js directly by calling postCode would require full environment mock. await postCode();
// I'll stick to the applyOnAction unit tests and rely on monitor.test.js for the heavy lifting.
// Verify rollback was performed
const mockApiInstance = new ScreepsAPI();
// `code.set` should be called twice:
// 1st time: uploading the new files
// 2nd time: rolling back to oldCode
expect(mockApiInstance.code.set).toHaveBeenCalledTimes(2);
expect(mockApiInstance.code.set).toHaveBeenNthCalledWith(2, "default", {
main: "old_code",
});
// Verify it called core.setFailed due to traceback
expect(core.setFailed).toHaveBeenCalledWith(
"Screeps console: traceback detected",
);
}); });
}); });
+4
View File
@@ -67,6 +67,10 @@ inputs:
description: 'Print a progress update every N ticks when log_to_file=true (default: 10).' description: 'Print a progress update every N ticks when log_to_file=true (default: 10).'
required: false required: false
default: '10' default: '10'
rollback_on_failure:
description: 'Automatically rollback to previous code if the monitor detects failures. Requires monitor > 0. (default: false)'
required: false
default: 'false'
outputs: outputs:
saw_traceback: saw_traceback:
description: true if a JS traceback was detected during monitoring. description: true if a JS traceback was detected during monitoring.
+1 -1
View File
@@ -24,4 +24,4 @@ var E=g(9829);var p=g(6928).extname;var C=/^\s*([^;\s]*)(?:;|\s|$)/;var f=/^text
*/ */
const E=g(9896);const p=g(857);const C=g(6928);const f=g(6982);const Q={fs:E.constants,os:p.constants};const B="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",I=/XXXXXX/,y=3,b=(Q.O_CREAT||Q.fs.O_CREAT)|(Q.O_EXCL||Q.fs.O_EXCL)|(Q.O_RDWR||Q.fs.O_RDWR),D=p.platform()==="win32",R=Q.EBADF||Q.os.errno.EBADF,k=Q.ENOENT||Q.os.errno.ENOENT,S=448,v=384,F="exit",x=[],U=E.rmdirSync.bind(E);let L=false;function rimraf(A,i){return E.rm(A,{recursive:true},i)}function FN_RIMRAF_SYNC(A){return E.rmSync(A,{recursive:true})}function tmpName(A,i){const g=_parseArguments(A,i),p=g[0],C=g[1];_assertAndSanitizeOptions(p,(function(A,i){if(A)return C(A);let g=i.tries;(function _getUniqueName(){try{const A=_generateTmpName(i);E.stat(A,(function(i){if(!i){if(g-- >0)return _getUniqueName();return C(new Error("Could not get a unique tmp filename, max tries reached "+A))}C(null,A)}))}catch(A){C(A)}})()}))}function tmpNameSync(A){const i=_parseArguments(A),g=i[0];const p=_assertAndSanitizeOptionsSync(g);let C=p.tries;do{const A=_generateTmpName(p);try{E.statSync(A)}catch(i){return A}}while(C-- >0);throw new Error("Could not get a unique tmp filename, max tries reached")}function file(A,i){const g=_parseArguments(A,i),p=g[0],C=g[1];tmpName(p,(function _tmpNameCreated(A,i){if(A)return C(A);E.open(i,b,p.mode||v,(function _fileCreated(A,g){if(A)return C(A);if(p.discardDescriptor){return E.close(g,(function _discardCallback(A){return C(A,i,undefined,_prepareTmpFileRemoveCallback(i,-1,p,false))}))}else{const A=p.discardDescriptor||p.detachDescriptor;C(null,i,g,_prepareTmpFileRemoveCallback(i,A?-1:g,p,false))}}))}))}function fileSync(A){const i=_parseArguments(A),g=i[0];const p=g.discardDescriptor||g.detachDescriptor;const C=tmpNameSync(g);let f=E.openSync(C,b,g.mode||v);if(g.discardDescriptor){E.closeSync(f);f=undefined}return{name:C,fd:f,removeCallback:_prepareTmpFileRemoveCallback(C,p?-1:f,g,true)}}function dir(A,i){const g=_parseArguments(A,i),p=g[0],C=g[1];tmpName(p,(function _tmpNameCreated(A,i){if(A)return C(A);E.mkdir(i,p.mode||S,(function _dirCreated(A){if(A)return C(A);C(null,i,_prepareTmpDirRemoveCallback(i,p,false))}))}))}function dirSync(A){const i=_parseArguments(A),g=i[0];const p=tmpNameSync(g);E.mkdirSync(p,g.mode||S);return{name:p,removeCallback:_prepareTmpDirRemoveCallback(p,g,true)}}function _removeFileAsync(A,i){const _handler=function(A){if(A&&!_isENOENT(A)){return i(A)}i()};if(0<=A[0])E.close(A[0],(function(){E.unlink(A[1],_handler)}));else E.unlink(A[1],_handler)}function _removeFileSync(A){let i=null;try{if(0<=A[0])E.closeSync(A[0])}catch(A){if(!_isEBADF(A)&&!_isENOENT(A))throw A}finally{try{E.unlinkSync(A[1])}catch(A){if(!_isENOENT(A))i=A}}if(i!==null){throw i}}function _prepareTmpFileRemoveCallback(A,i,g,E){const p=_prepareRemoveCallback(_removeFileSync,[i,A],E);const C=_prepareRemoveCallback(_removeFileAsync,[i,A],E,p);if(!g.keep)x.unshift(p);return E?p:C}function _prepareTmpDirRemoveCallback(A,i,g){const p=i.unsafeCleanup?rimraf:E.rmdir.bind(E);const C=i.unsafeCleanup?FN_RIMRAF_SYNC:U;const f=_prepareRemoveCallback(C,A,g);const Q=_prepareRemoveCallback(p,A,g,f);if(!i.keep)x.unshift(f);return g?f:Q}function _prepareRemoveCallback(A,i,g,E){let p=false;return function _cleanupCallback(C){if(!p){const f=E||_cleanupCallback;const Q=x.indexOf(f);if(Q>=0)x.splice(Q,1);p=true;if(g||A===U||A===FN_RIMRAF_SYNC){return A(i)}else{return A(i,C||function(){})}}}}function _garbageCollector(){if(!L)return;while(x.length){try{x[0]()}catch(A){}}}function _randomChars(A){let i=[],g=null;try{g=f.randomBytes(A)}catch(i){g=f.pseudoRandomBytes(A)}for(let E=0;E<A;E++){i.push(B[g[E]%B.length])}return i.join("")}function _isUndefined(A){return typeof A==="undefined"}function _parseArguments(A,i){if(typeof A==="function"){return[{},A]}if(_isUndefined(A)){return[{},i]}const g={};for(const i of Object.getOwnPropertyNames(A)){g[i]=A[i]}return[g,i]}function _resolvePath(A,i,g){const p=C.isAbsolute(A)?A:C.join(i,A);E.stat(p,(function(A){if(A){E.realpath(C.dirname(p),(function(A,i){if(A)return g(A);g(null,C.join(i,C.basename(p)))}))}else{E.realpath(p,g)}}))}function _resolvePathSync(A,i){const g=C.isAbsolute(A)?A:C.join(i,A);try{E.statSync(g);return E.realpathSync(g)}catch(A){const i=E.realpathSync(C.dirname(g));return C.join(i,C.basename(g))}}function _generateTmpName(A){const i=A.tmpdir;if(!_isUndefined(A.name)){return C.join(i,A.dir,A.name)}if(!_isUndefined(A.template)){return C.join(i,A.dir,A.template).replace(I,_randomChars(6))}const g=[A.prefix?A.prefix:"tmp","-",process.pid,"-",_randomChars(12),A.postfix?"-"+A.postfix:""].join("");return C.join(i,A.dir,g)}function _assertOptionsBase(A){if(!_isUndefined(A.name)){const i=A.name;if(C.isAbsolute(i))throw new Error(`name option must not contain an absolute path, found "${i}".`);const g=C.basename(i);if(g===".."||g==="."||g!==i)throw new Error(`name option must not contain a path, found "${i}".`)}if(!_isUndefined(A.template)&&!A.template.match(I)){throw new Error(`Invalid template, Line truncated const E=g(9896);const p=g(857);const C=g(6928);const f=g(6982);const Q={fs:E.constants,os:p.constants};const B="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",I=/XXXXXX/,y=3,b=(Q.O_CREAT||Q.fs.O_CREAT)|(Q.O_EXCL||Q.fs.O_EXCL)|(Q.O_RDWR||Q.fs.O_RDWR),D=p.platform()==="win32",R=Q.EBADF||Q.os.errno.EBADF,k=Q.ENOENT||Q.os.errno.ENOENT,S=448,v=384,F="exit",x=[],U=E.rmdirSync.bind(E);let L=false;function rimraf(A,i){return E.rm(A,{recursive:true},i)}function FN_RIMRAF_SYNC(A){return E.rmSync(A,{recursive:true})}function tmpName(A,i){const g=_parseArguments(A,i),p=g[0],C=g[1];_assertAndSanitizeOptions(p,(function(A,i){if(A)return C(A);let g=i.tries;(function _getUniqueName(){try{const A=_generateTmpName(i);E.stat(A,(function(i){if(!i){if(g-- >0)return _getUniqueName();return C(new Error("Could not get a unique tmp filename, max tries reached "+A))}C(null,A)}))}catch(A){C(A)}})()}))}function tmpNameSync(A){const i=_parseArguments(A),g=i[0];const p=_assertAndSanitizeOptionsSync(g);let C=p.tries;do{const A=_generateTmpName(p);try{E.statSync(A)}catch(i){return A}}while(C-- >0);throw new Error("Could not get a unique tmp filename, max tries reached")}function file(A,i){const g=_parseArguments(A,i),p=g[0],C=g[1];tmpName(p,(function _tmpNameCreated(A,i){if(A)return C(A);E.open(i,b,p.mode||v,(function _fileCreated(A,g){if(A)return C(A);if(p.discardDescriptor){return E.close(g,(function _discardCallback(A){return C(A,i,undefined,_prepareTmpFileRemoveCallback(i,-1,p,false))}))}else{const A=p.discardDescriptor||p.detachDescriptor;C(null,i,g,_prepareTmpFileRemoveCallback(i,A?-1:g,p,false))}}))}))}function fileSync(A){const i=_parseArguments(A),g=i[0];const p=g.discardDescriptor||g.detachDescriptor;const C=tmpNameSync(g);let f=E.openSync(C,b,g.mode||v);if(g.discardDescriptor){E.closeSync(f);f=undefined}return{name:C,fd:f,removeCallback:_prepareTmpFileRemoveCallback(C,p?-1:f,g,true)}}function dir(A,i){const g=_parseArguments(A,i),p=g[0],C=g[1];tmpName(p,(function _tmpNameCreated(A,i){if(A)return C(A);E.mkdir(i,p.mode||S,(function _dirCreated(A){if(A)return C(A);C(null,i,_prepareTmpDirRemoveCallback(i,p,false))}))}))}function dirSync(A){const i=_parseArguments(A),g=i[0];const p=tmpNameSync(g);E.mkdirSync(p,g.mode||S);return{name:p,removeCallback:_prepareTmpDirRemoveCallback(p,g,true)}}function _removeFileAsync(A,i){const _handler=function(A){if(A&&!_isENOENT(A)){return i(A)}i()};if(0<=A[0])E.close(A[0],(function(){E.unlink(A[1],_handler)}));else E.unlink(A[1],_handler)}function _removeFileSync(A){let i=null;try{if(0<=A[0])E.closeSync(A[0])}catch(A){if(!_isEBADF(A)&&!_isENOENT(A))throw A}finally{try{E.unlinkSync(A[1])}catch(A){if(!_isENOENT(A))i=A}}if(i!==null){throw i}}function _prepareTmpFileRemoveCallback(A,i,g,E){const p=_prepareRemoveCallback(_removeFileSync,[i,A],E);const C=_prepareRemoveCallback(_removeFileAsync,[i,A],E,p);if(!g.keep)x.unshift(p);return E?p:C}function _prepareTmpDirRemoveCallback(A,i,g){const p=i.unsafeCleanup?rimraf:E.rmdir.bind(E);const C=i.unsafeCleanup?FN_RIMRAF_SYNC:U;const f=_prepareRemoveCallback(C,A,g);const Q=_prepareRemoveCallback(p,A,g,f);if(!i.keep)x.unshift(f);return g?f:Q}function _prepareRemoveCallback(A,i,g,E){let p=false;return function _cleanupCallback(C){if(!p){const f=E||_cleanupCallback;const Q=x.indexOf(f);if(Q>=0)x.splice(Q,1);p=true;if(g||A===U||A===FN_RIMRAF_SYNC){return A(i)}else{return A(i,C||function(){})}}}}function _garbageCollector(){if(!L)return;while(x.length){try{x[0]()}catch(A){}}}function _randomChars(A){let i=[],g=null;try{g=f.randomBytes(A)}catch(i){g=f.pseudoRandomBytes(A)}for(let E=0;E<A;E++){i.push(B[g[E]%B.length])}return i.join("")}function _isUndefined(A){return typeof A==="undefined"}function _parseArguments(A,i){if(typeof A==="function"){return[{},A]}if(_isUndefined(A)){return[{},i]}const g={};for(const i of Object.getOwnPropertyNames(A)){g[i]=A[i]}return[g,i]}function _resolvePath(A,i,g){const p=C.isAbsolute(A)?A:C.join(i,A);E.stat(p,(function(A){if(A){E.realpath(C.dirname(p),(function(A,i){if(A)return g(A);g(null,C.join(i,C.basename(p)))}))}else{E.realpath(p,g)}}))}function _resolvePathSync(A,i){const g=C.isAbsolute(A)?A:C.join(i,A);try{E.statSync(g);return E.realpathSync(g)}catch(A){const i=E.realpathSync(C.dirname(g));return C.join(i,C.basename(g))}}function _generateTmpName(A){const i=A.tmpdir;if(!_isUndefined(A.name)){return C.join(i,A.dir,A.name)}if(!_isUndefined(A.template)){return C.join(i,A.dir,A.template).replace(I,_randomChars(6))}const g=[A.prefix?A.prefix:"tmp","-",process.pid,"-",_randomChars(12),A.postfix?"-"+A.postfix:""].join("");return C.join(i,A.dir,g)}function _assertOptionsBase(A){if(!_isUndefined(A.name)){const i=A.name;if(C.isAbsolute(i))throw new Error(`name option must not contain an absolute path, found "${i}".`);const g=C.basename(i);if(g===".."||g==="."||g!==i)throw new Error(`name option must not contain a path, found "${i}".`)}if(!_isUndefined(A.template)&&!A.template.match(I)){throw new Error(`Invalid template, Line truncated
/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */;const escape=A=>A.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22");const normalizeLinefeeds=A=>A.replace(/\r?\n|\r/g,"\r\n");const E=[];const p=new Uint8Array([13,10]);y=0;let C=false;for(const[i,f]of A){if(typeof f==="string"){const A=H.encode(g+`; name="${escape(normalizeLinefeeds(i))}"`+`\r\n\r\n${normalizeLinefeeds(f)}\r\n`);E.push(A);y+=A.byteLength}else{const A=H.encode(`${g}; name="${escape(normalizeLinefeeds(i))}"`+(f.name?`; filename="${escape(f.name)}"`:"")+"\r\n"+`Content-Type: ${f.type||"application/octet-stream"}\r\n\r\n`);E.push(A,f,p);if(typeof f.size==="number"){y+=A.byteLength+f.size+p.byteLength}else{C=true}}}const f=H.encode(`--${i}--\r\n`);E.push(f);y+=f.byteLength;if(C){y=null}I=A;B=async function*(){for(const A of E){if(A.stream){yield*A.stream()}else{yield A}}};b=`multipart/form-data; boundary=${i}`}else if(C(A)){I=A;y=A.size;if(A.type){b=A.type}}else if(typeof A[Symbol.asyncIterator]==="function"){if(i){throw new TypeError("keepalive")}if(E.isDisturbed(A)||A.locked){throw new TypeError("Response body object should not be disturbed or locked")}g=A instanceof ReadableStream?A:p(A)}if(typeof I==="string"||E.isBuffer(I)){y=Buffer.byteLength(I)}if(B!=null){let i;g=new ReadableStream({async start(){i=B(A)[Symbol.asyncIterator]()},async pull(A){const{value:E,done:p}=await i.next();if(p){queueMicrotask((()=>{A.close();A.byobRequest?.respond(0)}))}else{if(!F(g)){const i=new Uint8Array(E);if(i.byteLength){A.enqueue(i)}}}return A.desiredSize>0},async cancel(A){await i.return()},type:"bytes"})}const D={stream:g,source:I,length:y};return[D,b]}function safelyExtractBody(A,i=false){if(A instanceof ReadableStream){v(!E.isDisturbed(A),"The body has already been consumed.");v(!A.locked,"The stream is locked.")}return extractBody(A,i)}function cloneBody(A,i){const[g,E]=i.stream.tee();i.stream=g;return{stream:E,length:i.length,source:i.source}}function throwIfAborted(A){if(A.aborted){throw new DOMException("The operation was aborted.","AbortError")}}function bodyMixinMethods(A){const i={blob(){return consumeBody(this,(A=>{let i=bodyMimeType(this);if(i===null){i=""}else if(i){i=L(i)}return new S([A],{type:i})}),A)},arrayBuffer(){return consumeBody(this,(A=>new Uint8Array(A).buffer),A)},text(){return consumeBody(this,b,A)},json(){return consumeBody(this,parseJSONFromBytes,A)},formData(){return consumeBody(this,(A=>{const i=bodyMimeType(this);if(i!==null){switch(i.essence){case"multipart/form-data":{const g=M(A,i);if(g==="failure"){throw new TypeError("Failed to parse body as FormData.")}const E=new D;E[R]=g;return E}case"application/x-www-form-urlencoded":{const i=new URLSearchParams(A.toString());const g=new D;for(const[A,E]of i){g.append(A,E)}return g}}}throw new TypeError('Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".')}),A)},bytes(){return consumeBody(this,(A=>new Uint8Array(A)),A)}};return i}function mixinBody(A){Object.assign(A.prototype,bodyMixinMethods(A))}async function consumeBody(A,i,g){k.brandCheck(A,g);if(bodyUnusable(A)){throw new TypeError("Body is unusable: Body has already been read")}throwIfAborted(A[R]);const E=B();const errorSteps=A=>E.reject(A);const successSteps=A=>{try{E.resolve(i(A))}catch(A){errorSteps(A)}};if(A[R].body==null){successSteps(Buffer.allocUnsafe(0));return E.promise}await I(A[R].body,successSteps,errorSteps);return E.promise}function bodyUnusable(A){const i=A[R].body;return i!=null&&(i.stream.locked||E.isDisturbed(i.stream))}function parseJSONFromBytes(A){return JSON.parse(b(A))}function bodyMimeType(A){const i=A[R].headersList;const g=y(i);if(g==="failure"){return null}return g}A.exports={extractBody:extractBody,safelyExtractBody:safelyExtractBody,cloneBody:cloneBody,mixinBody:mixinBody,streamRegistry:Y,hasFinalizationRegistry:G,bodyUnusable:bodyUnusable}},4495:A=>{const i=["GET","HEAD","POST"];const g=new Set(i);const E=[101,204,205,304];const p=[301,302,303,307,308];const C=new Set(p);const f=["1","7","9","11","13","15","17","19","20","21","22","23","25","37","42","43","53","69","77","79","87","95","101","102","103","104","109","110","111","113","115","117","119","123","135","137","139","143","161","179","389","427","465","512","513","514","515","526","530","531","532","540","548","554","556","563","587","601","636","989","990","993","995","1719","1720","1723","2049","3659","4045","4190","5060","5061","6000","6566","6665","6666","6667","6668","6669","6679","6697","10080"];const Q=new Set(f);const B=["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"];const I=new Set(B);const y=["follow","manual","error"];const b=["GET","HEAD","OPTIONS","TRACE"];const D=new Set(b);const R=["navigate","same-origin","no-cors","cors"];const k=["omit","same-origin","include"];const S=["default","no-store","reload","no-cache","force-cLine truncated /*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */;const escape=A=>A.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22");const normalizeLinefeeds=A=>A.replace(/\r?\n|\r/g,"\r\n");const E=[];const p=new Uint8Array([13,10]);y=0;let C=false;for(const[i,f]of A){if(typeof f==="string"){const A=H.encode(g+`; name="${escape(normalizeLinefeeds(i))}"`+`\r\n\r\n${normalizeLinefeeds(f)}\r\n`);E.push(A);y+=A.byteLength}else{const A=H.encode(`${g}; name="${escape(normalizeLinefeeds(i))}"`+(f.name?`; filename="${escape(f.name)}"`:"")+"\r\n"+`Content-Type: ${f.type||"application/octet-stream"}\r\n\r\n`);E.push(A,f,p);if(typeof f.size==="number"){y+=A.byteLength+f.size+p.byteLength}else{C=true}}}const f=H.encode(`--${i}--\r\n`);E.push(f);y+=f.byteLength;if(C){y=null}I=A;B=async function*(){for(const A of E){if(A.stream){yield*A.stream()}else{yield A}}};b=`multipart/form-data; boundary=${i}`}else if(C(A)){I=A;y=A.size;if(A.type){b=A.type}}else if(typeof A[Symbol.asyncIterator]==="function"){if(i){throw new TypeError("keepalive")}if(E.isDisturbed(A)||A.locked){throw new TypeError("Response body object should not be disturbed or locked")}g=A instanceof ReadableStream?A:p(A)}if(typeof I==="string"||E.isBuffer(I)){y=Buffer.byteLength(I)}if(B!=null){let i;g=new ReadableStream({async start(){i=B(A)[Symbol.asyncIterator]()},async pull(A){const{value:E,done:p}=await i.next();if(p){queueMicrotask((()=>{A.close();A.byobRequest?.respond(0)}))}else{if(!F(g)){const i=new Uint8Array(E);if(i.byteLength){A.enqueue(i)}}}return A.desiredSize>0},async cancel(A){await i.return()},type:"bytes"})}const D={stream:g,source:I,length:y};return[D,b]}function safelyExtractBody(A,i=false){if(A instanceof ReadableStream){v(!E.isDisturbed(A),"The body has already been consumed.");v(!A.locked,"The stream is locked.")}return extractBody(A,i)}function cloneBody(A,i){const[g,E]=i.stream.tee();i.stream=g;return{stream:E,length:i.length,source:i.source}}function throwIfAborted(A){if(A.aborted){throw new DOMException("The operation was aborted.","AbortError")}}function bodyMixinMethods(A){const i={blob(){return consumeBody(this,(A=>{let i=bodyMimeType(this);if(i===null){i=""}else if(i){i=L(i)}return new S([A],{type:i})}),A)},arrayBuffer(){return consumeBody(this,(A=>new Uint8Array(A).buffer),A)},text(){return consumeBody(this,b,A)},json(){return consumeBody(this,parseJSONFromBytes,A)},formData(){return consumeBody(this,(A=>{const i=bodyMimeType(this);if(i!==null){switch(i.essence){case"multipart/form-data":{const g=M(A,i);if(g==="failure"){throw new TypeError("Failed to parse body as FormData.")}const E=new D;E[R]=g;return E}case"application/x-www-form-urlencoded":{const i=new URLSearchParams(A.toString());const g=new D;for(const[A,E]of i){g.append(A,E)}return g}}}throw new TypeError('Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".')}),A)},bytes(){return consumeBody(this,(A=>new Uint8Array(A)),A)}};return i}function mixinBody(A){Object.assign(A.prototype,bodyMixinMethods(A))}async function consumeBody(A,i,g){k.brandCheck(A,g);if(bodyUnusable(A)){throw new TypeError("Body is unusable: Body has already been read")}throwIfAborted(A[R]);const E=B();const errorSteps=A=>E.reject(A);const successSteps=A=>{try{E.resolve(i(A))}catch(A){errorSteps(A)}};if(A[R].body==null){successSteps(Buffer.allocUnsafe(0));return E.promise}await I(A[R].body,successSteps,errorSteps);return E.promise}function bodyUnusable(A){const i=A[R].body;return i!=null&&(i.stream.locked||E.isDisturbed(i.stream))}function parseJSONFromBytes(A){return JSON.parse(b(A))}function bodyMimeType(A){const i=A[R].headersList;const g=y(i);if(g==="failure"){return null}return g}A.exports={extractBody:extractBody,safelyExtractBody:safelyExtractBody,cloneBody:cloneBody,mixinBody:mixinBody,streamRegistry:Y,hasFinalizationRegistry:G,bodyUnusable:bodyUnusable}},4495:A=>{const i=["GET","HEAD","POST"];const g=new Set(i);const E=[101,204,205,304];const p=[301,302,303,307,308];const C=new Set(p);const f=["1","7","9","11","13","15","17","19","20","21","22","23","25","37","42","43","53","69","77","79","87","95","101","102","103","104","109","110","111","113","115","117","119","123","135","137","139","143","161","179","389","427","465","512","513","514","515","526","530","531","532","540","548","554","556","563","587","601","636","989","990","993","995","1719","1720","1723","2049","3659","4045","4190","5060","5061","6000","6566","6665","6666","6667","6668","6669","6679","6697","10080"];const Q=new Set(f);const B=["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"];const I=new Set(B);const y=["follow","manual","error"];const b=["GET","HEAD","OPTIONS","TRACE"];const D=new Set(b);const R=["navigate","same-origin","no-cors","cors"];const k=["omit","same-origin","include"];const S=["default","no-store","reload","no-cache","force-cLine truncated
/*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> */Q[f-4]=g[0];Q[f-3]=g[1];Q[f-2]=g[2];Q[f-1]=g[3];Q[1]=C;if(C===126){Q.writeUInt16BE(p,2)}else if(C===127){Q[2]=Q[3]=0;Q.writeUIntBE(p,4,6)}Q[1]|=128;for(let A=0;A<p;++A){Q[f+A]=i[A]^g[A&3]}return Q}}A.exports={WebsocketFrameSend:WebsocketFrameSend}},9469:(A,i,g)=>{const{createInflateRaw:E,Z_DEFAULT_WINDOWBITS:p}=g(8522);const{isValidClientWindowBits:C}=g(8625);const f=Buffer.from([0,0,255,255]);const Q=Symbol("kBuffer");const B=Symbol("kLength");class PerMessageDeflate{#re;#S={};constructor(A){this.#S.serverNoContextTakeover=A.has("server_no_context_takeover");this.#S.serverMaxWindowBits=A.get("server_max_window_bits")}decompress(A,i,g){if(!this.#re){let A=p;if(this.#S.serverMaxWindowBits){if(!C(this.#S.serverMaxWindowBits)){g(new Error("Invalid server_max_window_bits"));return}A=Number.parseInt(this.#S.serverMaxWindowBits)}this.#re=E({windowBits:A});this.#re[Q]=[];this.#re[B]=0;this.#re.on("data",(A=>{this.#re[Q].push(A);this.#re[B]+=A.length}));this.#re.on("error",(A=>{this.#re=null;g(A)}))}this.#re.write(A);if(i){this.#re.write(f)}this.#re.flush((()=>{const A=Buffer.concat(this.#re[Q],this.#re[B]);this.#re[Q].length=0;this.#re[B]=0;g(null,A)}))}}A.exports={PerMessageDeflate:PerMessageDeflate}},1652:(A,i,g)=>{const{Writable:E}=g(7075);const p=g(4589);const{parserStates:C,opcodes:f,states:Q,emptyBuffer:B,sentCloseFrameState:I}=g(736);const{kReadyState:y,kSentClose:b,kResponse:D,kReceivedClose:R}=g(1216);const{channels:k}=g(2414);const{isValidStatusCode:S,isValidOpcode:v,failWebsocketConnection:F,websocketMessageReceived:x,utf8Decode:U,isControlFrame:L,isTextBinaryFrame:M,isContinuationFrame:T}=g(8625);const{WebsocketFrameSend:H}=g(3264);const{closeWebSocketConnection:G}=g(6897);const{PerMessageDeflate:Y}=g(9469);class ByteParser extends E{#n=[];#o=0;#ie=false;#a=C.INFO;#c={};#l=[];#d;constructor(A,i){super();this.ws=A;this.#d=i==null?new Map:i;if(this.#d.has("permessage-deflate")){this.#d.set("permessage-deflate",new Y(i))}}_write(A,i,g){this.#n.push(A);this.#o+=A.length;this.#ie=true;this.run(g)}run(A){while(this.#ie){if(this.#a===C.INFO){if(this.#o<2){return A()}const i=this.consume(2);const g=(i[0]&128)!==0;const E=i[0]&15;const p=(i[1]&128)===128;const Q=!g&&E!==f.CONTINUATION;const B=i[1]&127;const I=i[0]&64;const y=i[0]&32;const b=i[0]&16;if(!v(E)){F(this.ws,"Invalid opcode received");return A()}if(p){F(this.ws,"Frame cannot be masked");return A()}if(I!==0&&!this.#d.has("permessage-deflate")){F(this.ws,"Expected RSV1 to be clear.");return}if(y!==0||b!==0){F(this.ws,"RSV1, RSV2, RSV3 must be clear");return}if(Q&&!M(E)){F(this.ws,"Invalid frame type was fragmented.");return}if(M(E)&&this.#l.length>0){F(this.ws,"Expected continuation frame");return}if(this.#c.fragmented&&Q){F(this.ws,"Fragmented frame exceeded 125 bytes.");return}if((B>125||Q)&&L(E)){F(this.ws,"Control frame either too large or fragmented");return}if(T(E)&&this.#l.length===0&&!this.#c.compressed){F(this.ws,"Unexpected continuation frame");return}if(B<=125){this.#c.payloadLength=B;this.#a=C.READ_DATA}else if(B===126){this.#a=C.PAYLOADLENGTH_16}else if(B===127){this.#a=C.PAYLOADLENGTH_64}if(M(E)){this.#c.binaryType=E;this.#c.compressed=I!==0}this.#c.opcode=E;this.#c.masked=p;this.#c.fin=g;this.#c.fragmented=Q}else if(this.#a===C.PAYLOADLENGTH_16){if(this.#o<2){return A()}const i=this.consume(2);this.#c.payloadLength=i.readUInt16BE(0);this.#a=C.READ_DATA}else if(this.#a===C.PAYLOADLENGTH_64){if(this.#o<8){return A()}const i=this.consume(8);const g=i.readUInt32BE(0);if(g>2**31-1){F(this.ws,"Received payload length > 2^31 bytes.");return}const E=i.readUInt32BE(4);this.#c.payloadLength=(g<<8)+E;this.#a=C.READ_DATA}else if(this.#a===C.READ_DATA){if(this.#o<this.#c.payloadLength){return A()}const i=this.consume(this.#c.payloadLength);if(L(this.#c.opcode)){this.#ie=this.parseControlFrame(i);this.#a=C.INFO}else{if(!this.#c.compressed){this.#l.push(i);if(!this.#c.fragmented&&this.#c.fin){const A=Buffer.concat(this.#l);x(this.ws,this.#c.binaryType,A);this.#l.length=0}this.#a=C.INFO}else{this.#d.get("permessage-deflate").decompress(i,this.#c.fin,((i,g)=>{if(i){G(this.ws,1007,i.message,i.message.length);return}this.#l.push(g);if(!this.#c.fin){this.#a=C.INFO;this.#ie=true;this.run(A);return}x(this.ws,this.#c.binaryType,Buffer.concat(this.#l));this.#ie=true;this.#a=C.INFO;this.#l.length=0;this.run(A)}));this.#ie=false;break}}}}}consume(A){if(A>this.#o){throw new Error("Called consume() before buffers satiated.")}else if(A===0){return B}if(this.#n[0].length===A){this.#o-=this.#n[0].length;return this.#n.shift()}const i=Buffer.allocUnsafe(A);let g=0;while(g!==A){const E=this.#n[0];const{length:p}=E;if(p+g===A){i.set(this.#n.shift(),g);break}else if(p+g>A){i.set(E.subarray(0,A-g),g);this.#n[0]=E.subarray(A-g);break}else{i.set(this.#n.shift(),g);g+=E.length}}this.#o-=A;return i}parseCloseBody(A){p(A.length!==1);let i;if(A.length>=2){i=A.readUInt16BE(0)}if(i!==undefined&&!S(i)){return{code:1002,Line truncated /*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> */Q[f-4]=g[0];Q[f-3]=g[1];Q[f-2]=g[2];Q[f-1]=g[3];Q[1]=C;if(C===126){Q.writeUInt16BE(p,2)}else if(C===127){Q[2]=Q[3]=0;Q.writeUIntBE(p,4,6)}Q[1]|=128;for(let A=0;A<p;++A){Q[f+A]=i[A]^g[A&3]}return Q}}A.exports={WebsocketFrameSend:WebsocketFrameSend}},9469:(A,i,g)=>{const{createInflateRaw:E,Z_DEFAULT_WINDOWBITS:p}=g(8522);const{isValidClientWindowBits:C}=g(8625);const f=Buffer.from([0,0,255,255]);const Q=Symbol("kBuffer");const B=Symbol("kLength");class PerMessageDeflate{#re;#S={};constructor(A){this.#S.serverNoContextTakeover=A.has("server_no_context_takeover");this.#S.serverMaxWindowBits=A.get("server_max_window_bits")}decompress(A,i,g){if(!this.#re){let A=p;if(this.#S.serverMaxWindowBits){if(!C(this.#S.serverMaxWindowBits)){g(new Error("Invalid server_max_window_bits"));return}A=Number.parseInt(this.#S.serverMaxWindowBits)}this.#re=E({windowBits:A});this.#re[Q]=[];this.#re[B]=0;this.#re.on("data",(A=>{this.#re[Q].push(A);this.#re[B]+=A.length}));this.#re.on("error",(A=>{this.#re=null;g(A)}))}this.#re.write(A);if(i){this.#re.write(f)}this.#re.flush((()=>{const A=Buffer.concat(this.#re[Q],this.#re[B]);this.#re[Q].length=0;this.#re[B]=0;g(null,A)}))}}A.exports={PerMessageDeflate:PerMessageDeflate}},1652:(A,i,g)=>{const{Writable:E}=g(7075);const p=g(4589);const{parserStates:C,opcodes:f,states:Q,emptyBuffer:B,sentCloseFrameState:I}=g(736);const{kReadyState:y,kSentClose:b,kResponse:D,kReceivedClose:R}=g(1216);const{channels:k}=g(2414);const{isValidStatusCode:S,isValidOpcode:v,failWebsocketConnection:F,websocketMessageReceived:x,utf8Decode:U,isControlFrame:L,isTextBinaryFrame:M,isContinuationFrame:T}=g(8625);const{WebsocketFrameSend:H}=g(3264);const{closeWebSocketConnection:G}=g(6897);const{PerMessageDeflate:Y}=g(9469);class ByteParser extends E{#n=[];#o=0;#ie=false;#a=C.INFO;#c={};#l=[];#d;constructor(A,i){super();this.ws=A;this.#d=i==null?new Map:i;if(this.#d.has("permessage-deflate")){this.#d.set("permessage-deflate",new Y(i))}}_write(A,i,g){this.#n.push(A);this.#o+=A.length;this.#ie=true;this.run(g)}run(A){while(this.#ie){if(this.#a===C.INFO){if(this.#o<2){return A()}const i=this.consume(2);const g=(i[0]&128)!==0;const E=i[0]&15;const p=(i[1]&128)===128;const Q=!g&&E!==f.CONTINUATION;const B=i[1]&127;const I=i[0]&64;const y=i[0]&32;const b=i[0]&16;if(!v(E)){F(this.ws,"Invalid opcode received");return A()}if(p){F(this.ws,"Frame cannot be masked");return A()}if(I!==0&&!this.#d.has("permessage-deflate")){F(this.ws,"Expected RSV1 to be clear.");return}if(y!==0||b!==0){F(this.ws,"RSV1, RSV2, RSV3 must be clear");return}if(Q&&!M(E)){F(this.ws,"Invalid frame type was fragmented.");return}if(M(E)&&this.#l.length>0){F(this.ws,"Expected continuation frame");return}if(this.#c.fragmented&&Q){F(this.ws,"Fragmented frame exceeded 125 bytes.");return}if((B>125||Q)&&L(E)){F(this.ws,"Control frame either too large or fragmented");return}if(T(E)&&this.#l.length===0&&!this.#c.compressed){F(this.ws,"Unexpected continuation frame");return}if(B<=125){this.#c.payloadLength=B;this.#a=C.READ_DATA}else if(B===126){this.#a=C.PAYLOADLENGTH_16}else if(B===127){this.#a=C.PAYLOADLENGTH_64}if(M(E)){this.#c.binaryType=E;this.#c.compressed=I!==0}this.#c.opcode=E;this.#c.masked=p;this.#c.fin=g;this.#c.fragmented=Q}else if(this.#a===C.PAYLOADLENGTH_16){if(this.#o<2){return A()}const i=this.consume(2);this.#c.payloadLength=i.readUInt16BE(0);this.#a=C.READ_DATA}else if(this.#a===C.PAYLOADLENGTH_64){if(this.#o<8){return A()}const i=this.consume(8);const g=i.readUInt32BE(0);if(g>2**31-1){F(this.ws,"Received payload length > 2^31 bytes.");return}const E=i.readUInt32BE(4);this.#c.payloadLength=(g<<8)+E;this.#a=C.READ_DATA}else if(this.#a===C.READ_DATA){if(this.#o<this.#c.payloadLength){return A()}const i=this.consume(this.#c.payloadLength);if(L(this.#c.opcode)){this.#ie=this.parseControlFrame(i);this.#a=C.INFO}else{if(!this.#c.compressed){this.#l.push(i);if(!this.#c.fragmented&&this.#c.fin){const A=Buffer.concat(this.#l);x(this.ws,this.#c.binaryType,A);this.#l.length=0}this.#a=C.INFO}else{this.#d.get("permessage-deflate").decompress(i,this.#c.fin,((i,g)=>{if(i){G(this.ws,1007,i.message,i.message.length);return}this.#l.push(g);if(!this.#c.fin){this.#a=C.INFO;this.#ie=true;this.run(A);return}x(this.ws,this.#c.binaryType,Buffer.concat(this.#l));this.#ie=true;this.#a=C.INFO;this.#l.length=0;this.run(A)}));this.#ie=false;break}}}}}consume(A){if(A>this.#o){throw new Error("Called consume() before buffers satiated.")}else if(A===0){return B}if(this.#n[0].length===A){this.#o-=this.#n[0].length;return this.#n.shift()}const i=Buffer.allocUnsafe(A);let g=0;while(g!==A){const E=this.#n[0];const{length:p}=E;if(p+g===A){i.set(this.#n.shift(),g);break}else if(p+g>A){i.set(E.subarray(0,A-g),g);this.#n[0]=E.subarray(A-g);break}else{i.set(this.#n.shift(),g);g+=E.length}}this.#o-=A;return i}parseCloseBody(A){p(A.length!==1);let i;if(A.length>=2){i=A.readUInt16BE(0)}if(i!==undefined&&!S(i)){return{code:1002,Line truncated
+80 -23
View File
@@ -118,17 +118,19 @@ export function validateAuthentication(token, username, password) {
* @param {'ignore'|'warn'|'fail'} action * @param {'ignore'|'warn'|'fail'} action
* @param {boolean} flag - Only acts when true * @param {boolean} flag - Only acts when true
* @param {string} message - Passed to core.warning / core.setFailed * @param {string} message - Passed to core.warning / core.setFailed
* @returns {boolean} - Returns true if the action was 'fail' and the flag was true.
*/ */
export function applyOnAction(action, flag, message) { export function applyOnAction(action, flag, message) {
if (!flag) return; if (!flag) return false;
if (action === "warn") { if (action === "warn") {
core.warning(message); core.warning(message);
return; return false;
} }
if (action === "fail") { if (action === "fail") {
core.setFailed(message); core.setFailed(message);
return true;
} }
// 'ignore' → no-op return false;
} }
/** /**
@@ -179,33 +181,72 @@ export async function postCode() {
return; return;
} }
let api = new ScreepsAPI(login_arguments); let api = new ScreepsAPI(login_arguments);
if (token) {
if (!token) {
core.info(`Logging in as user ${username}`);
try {
await api.auth(username, password, login_arguments);
} catch (err) {
core.error(`Authentication error: ${err}`);
throw err;
}
}
let oldCode = null;
let rollbackOnFailure = false;
try {
rollbackOnFailure = core.getBooleanInput("rollback_on_failure");
} catch (e) {
// getBooleanInput throws if not 'true' or 'false', ignore
}
if (rollbackOnFailure) {
core.info(
`Downloading existing code from branch ${branch} for potential rollback...`,
);
try {
const getResponse = await api.code.get(branch);
if (getResponse && getResponse.ok && getResponse.modules) {
oldCode = getResponse.modules;
core.info(
`Successfully downloaded existing code (modules: ${Object.keys(oldCode).join(", ")})`,
);
} else {
core.setFailed(
`Failed to download existing code, but rollback_on_failure is enabled. Aborting deployment.`,
);
return;
}
} catch (err) {
core.setFailed(
`Error downloading existing code: ${err.message}. Aborting deployment.`,
);
return;
}
}
try {
const response = await api.code.set(branch, files_to_push); const response = await api.code.set(branch, files_to_push);
core.info(JSON.stringify(response, null, 2)); core.info(JSON.stringify(response, null, 2));
core.info(`Code set successfully to ${branch}`); core.info(`Code set successfully to ${branch}`);
} else { } catch (err) {
core.info(`Logging in as user ${username}`);
await Promise.resolve()
.then(() => api.auth(username, password, login_arguments))
.then(() => api.code.set(branch, files_to_push))
.then(() => {
core.info(`Code set successfully to ${branch}`);
})
.catch((err) => {
core.error(`Upload error: ${err}`); core.error(`Upload error: ${err}`);
throw err; throw err;
});
} }
// Console monitoring (optional) // Console monitoring (optional)
const monitorTicks = parseInt(core.getInput("monitor") || "0", 10); const monitorTicks = parseInt(core.getInput("monitor") || "0", 10);
if (monitorTicks > 0) { if (monitorTicks > 0) {
const onTraceback = core.getInput("on_traceback") || "fail";
const onErrorLog = core.getInput("on_error_log") || "warn";
const onWarningLog = core.getInput("on_warning_log") || "ignore";
const result = await monitorConsole(api, { const result = await monitorConsole(api, {
monitor: monitorTicks, monitor: monitorTicks,
logToFile: core.getBooleanInput("log_to_file"), logToFile: core.getBooleanInput("log_to_file"),
onTraceback: core.getInput("on_traceback") || "fail", onTraceback,
onErrorLog: core.getInput("on_error_log") || "warn", onErrorLog,
onWarningLog: core.getInput("on_warning_log") || "ignore", onWarningLog,
monitorInterval: parseInt(core.getInput("monitor_interval") || "10", 10), monitorInterval: parseInt(core.getInput("monitor_interval") || "10", 10),
hostname, hostname,
shard: core.getInput("shard") || undefined, shard: core.getInput("shard") || undefined,
@@ -215,21 +256,37 @@ export async function postCode() {
core.setOutput("saw_error_log", String(result.sawErrorLog)); core.setOutput("saw_error_log", String(result.sawErrorLog));
core.setOutput("saw_warning_log", String(result.sawWarningLog)); core.setOutput("saw_warning_log", String(result.sawWarningLog));
applyOnAction( const fail1 = applyOnAction(
core.getInput("on_traceback"), onTraceback,
result.sawTraceback, result.sawTraceback,
"Screeps console: traceback detected", "Screeps console: traceback detected",
); );
applyOnAction( const fail2 = applyOnAction(
core.getInput("on_error_log"), onErrorLog,
result.sawErrorLog, result.sawErrorLog,
"Screeps console: error log output detected", "Screeps console: error log output detected",
); );
applyOnAction( const fail3 = applyOnAction(
core.getInput("on_warning_log"), onWarningLog,
result.sawWarningLog, result.sawWarningLog,
"Screeps console: warning log output detected", "Screeps console: warning log output detected",
); );
const shouldFail = fail1 || fail2 || fail3;
if (shouldFail && rollbackOnFailure && oldCode) {
core.info(
"Action failed based on monitor configuration. Rolling back to previous code...",
);
try {
await api.code.set(branch, oldCode);
core.info(
`Successfully rolled back to previous code on branch ${branch}.`,
);
} catch (err) {
core.error(`Rollback failed: ${err}`);
}
}
} }
} }