Automatic formatting pass

This commit is contained in:
Zoë Hoekstra 2022-08-25 23:57:49 +02:00
parent afb9ceccab
commit b7c0761822
No known key found for this signature in database
GPG key ID: F9B7B7D8130F3323
7 changed files with 131 additions and 131 deletions

View file

@ -3,72 +3,72 @@ import { existsSync } from "fs";
// Define a schema
export let config = convict({
allowedFiletypes: {
doc: 'Filetypes that are synchronized to the game.',
format: 'Array',
default: [".js", ".script", ".txt"]
},
allowDeletingFiles: {
doc: 'Allow deleting files in game if they get deleted off disk.',
format: 'Boolean',
default: false
},
port: {
doc: 'The port to bind to.',
format: 'Number',
default: 12525,
env: 'BB_PORT',
arg: 'port'
},
scriptsFolder: {
doc: 'The to be synchronized folder.',
format: 'String',
default: '.',
env: 'BB_SCRIPTFOLDER',
arg: "folder"
},
quiet: {
doc: 'Log less internal events to stdout.',
format: 'Boolean',
env: 'BB_VERBOSE',
default: false
},
dry: {
doc: 'Only print the files to be synchronised.',
format: 'Boolean',
env: 'BB_DRY',
default: false
},
definitionFile: {
update: {
doc: 'Automatically pull the definition file from the game.',
format: 'Boolean',
env: 'BB_UPDATE_DEF',
default: false
allowedFiletypes: {
doc: 'Filetypes that are synchronized to the game.',
format: 'Array',
default: [".js", ".script", ".txt"]
},
location: {
doc: 'Location/name of where the definition file gets placed.',
format: 'String',
env: 'BB_LOCATION_DEF',
default: "./NetScriptDefinitions.d.ts"
allowDeletingFiles: {
doc: 'Allow deleting files in game if they get deleted off disk.',
format: 'Boolean',
default: false
},
port: {
doc: 'The port to bind to.',
format: 'Number',
default: 12525,
env: 'BB_PORT',
arg: 'port'
},
scriptsFolder: {
doc: 'The to be synchronized folder.',
format: 'String',
default: '.',
env: 'BB_SCRIPTFOLDER',
arg: "folder"
},
quiet: {
doc: 'Log less internal events to stdout.',
format: 'Boolean',
env: 'BB_VERBOSE',
default: false
},
dry: {
doc: 'Only print the files to be synchronised.',
format: 'Boolean',
env: 'BB_DRY',
default: false
},
definitionFile: {
update: {
doc: 'Automatically pull the definition file from the game.',
format: 'Boolean',
env: 'BB_UPDATE_DEF',
default: false
},
location: {
doc: 'Location/name of where the definition file gets placed.',
format: 'String',
env: 'BB_LOCATION_DEF',
default: "./NetScriptDefinitions.d.ts"
}
}
}
});
export function loadConfig() {
const configFile = "filesync.json";
if (existsSync(configFile)) {
try {
config.loadFile(configFile);
} catch (e) {
throw new Error(`Unable to load configuration file at ${configFile}: ${e}`);
const configFile = "filesync.json";
if (existsSync(configFile)) {
try {
config.loadFile(configFile);
} catch (e) {
throw new Error(`Unable to load configuration file at ${configFile}: ${e}`);
}
} else if (!config.get("quiet")) {
console.log("No configuration file found.")
}
} else if (!config.get("quiet")) {
console.log("No configuration file found.")
}
// Perform validation
config.validate({ allowed: 'strict' });
// Perform validation
config.validate({ allowed: 'strict' });
}

View file

@ -1,7 +1,7 @@
export class EventType {
static ConnectionMade = "ConnectionMade";
static FileChanged = "FileChanged";
static FileDeleted = "FileDeleted";
static MessageReceived = "MessageReceived";
static MessageSend = "MessageSend";
static ConnectionMade = "ConnectionMade";
static FileChanged = "FileChanged";
static FileDeleted = "FileDeleted";
static MessageReceived = "MessageReceived";
static MessageSend = "MessageSend";
}

View file

@ -1,12 +1,12 @@
import CheapWatch from "cheap-watch";
import {config} from "./config.js";
import {EventType} from "./eventTypes.js";
import {resolve } from "path";
import { config } from "./config.js";
import { EventType } from "./eventTypes.js";
import { resolve } from "path";
function fileFilter(file) {
if(config.get("allowedFiletypes").some(extension => file.path.endsWith(extension)))
if (config.get("allowedFiletypes").some(extension => file.path.endsWith(extension)))
return true;
if(file.stats.isDirectory())
if (file.stats.isDirectory())
return true;
return false;
}
@ -19,18 +19,18 @@ const watch = new CheapWatch({
export async function setupWatch(signaller) {
if(!config.get("quiet")) console.log("Watching folder", resolve(config.get("scriptsFolder")))
if (!config.get("quiet")) console.log("Watching folder", resolve(config.get("scriptsFolder")))
watch.on('+', fileEvent => {if (fileEvent.stats.isFile()) signaller.emit(EventType.FileChanged, fileEvent)});
watch.on('-', fileEvent => {if (fileEvent.stats.isFile()) signaller.emit(EventType.FileDeleted, fileEvent)});
watch.on('+', fileEvent => { if (fileEvent.stats.isFile()) signaller.emit(EventType.FileChanged, fileEvent) });
watch.on('-', fileEvent => { if (fileEvent.stats.isFile()) signaller.emit(EventType.FileDeleted, fileEvent) });
// Wait 'till filewatcher is ready to go
await watch.init();
if(config.get("dry")) {
console.log("Watch would've synchronised:\n", watch.paths)
process.exit();
}
if (config.get("dry")) {
console.log("Watch would've synchronised:\n", watch.paths)
process.exit();
}
return watch;
}

View file

@ -1,48 +1,48 @@
import {readFileSync} from "fs";
import {config} from "../config.js";
import {join} from "path";
import { readFileSync } from "fs";
import { config } from "../config.js";
import { join } from "path";
let messageCounter = 0;
export function fileChangeEventToMsg({path}){
export function fileChangeEventToMsg({ path }) {
return {
"jsonrpc":"2.0",
"method":"pushFile",
"params":{
"server":"home",
"filename":"/"+path,
"content":readFileSync(join(config.get("scriptsFolder"), path)).toString()
"jsonrpc": "2.0",
"method": "pushFile",
"params": {
"server": "home",
"filename": "/" + path,
"content": readFileSync(join(config.get("scriptsFolder"), path)).toString()
},
"id":messageCounter++
"id": messageCounter++
}
}
export function fileRemovalEventToMsg({path}){
export function fileRemovalEventToMsg({ path }) {
return {
"jsonrpc":"2.0",
"jsonrpc": "2.0",
"method": "deleteFile",
"params":{
"params": {
"filename": path,
},
"id":messageCounter++
"id": messageCounter++
}
}
export function requestDefinitionFile(){
export function requestDefinitionFile() {
return {
"jsonrpc": "2.0",
"method": "getDefinitionFile",
"id":messageCounter++
"id": messageCounter++
}
}
export function requestFilenames(){
export function requestFilenames() {
return {
"jsonrpc": "2.0",
"method": "getFileNames",
"params": {
"server": "home",
},
"id":messageCounter++
"id": messageCounter++
}
}

View file

@ -8,8 +8,8 @@ import { fileChangeEventToMsg } from "./messageGenerators.js";
export function messageHandler(signaller, msg) {
let incoming;
try {incoming = JSON.parse(msg.toString());}
catch (err) {return console.log(err);}
try { incoming = JSON.parse(msg.toString()); }
catch (err) { return console.log(err); }
console.log(incoming)
if (incoming.id == undefined) return;
@ -26,17 +26,17 @@ export function messageHandler(signaller, msg) {
if (request.method &&
request.method == "getFileNames"
&& incoming.result) {
const gameFiles = incoming.result.map(file => removeLeadingSlash(file));
const gameFiles = incoming.result.map(file => removeLeadingSlash(file));
watchedFiles().forEach((stats, fileName) => {
if(!stats.isDirectory() && !gameFiles.includes(fileName))
signaller.emit(EventType.MessageSend, fileChangeEventToMsg({path:fileName}));
})
}
watchedFiles().forEach((stats, fileName) => {
if (!stats.isDirectory() && !gameFiles.includes(fileName))
signaller.emit(EventType.MessageSend, fileChangeEventToMsg({ path: fileName }));
})
}
}
}
function removeLeadingSlash(path){
function removeLeadingSlash(path) {
const reg = /^\//;
return path.replace(reg, "")
}

View file

@ -1,19 +1,19 @@
class MessageTracker {
data = new Map()
#maxLength = 200
data = new Map()
#maxLength = 200
push(msg) {
this.data.set(msg.id, msg);
push(msg) {
this.data.set(msg.id, msg);
if (this.data.size > this.#maxLength){
const [firstKey] = map.keys();
this.data.delete(firstKey);
if (this.data.size > this.#maxLength) {
const [firstKey] = map.keys();
this.data.delete(firstKey);
}
}
}
get(index) {
return this.data.get(index);
}
get(index) {
return this.data.get(index);
}
}
export const messageTracker = new MessageTracker();

View file

@ -1,29 +1,29 @@
import { WebSocketServer } from 'ws';
import {config} from "../config.js";
import {EventType} from "../eventTypes.js"
import { config } from "../config.js";
import { EventType } from "../eventTypes.js"
import { requestDefinitionFile } from './messageGenerators.js';
import {messageTracker} from "./messageTracker.js"
import { messageTracker } from "./messageTracker.js"
export function setupSocket(signaller){
export function setupSocket(signaller) {
const wss = new WebSocketServer({ port: config.get("port") });
wss.on('connection', function connection(ws) {
function sendMessage(msg) {
messageTracker.push(msg);
ws.send(JSON.stringify(msg));
}
function sendMessage(msg) {
messageTracker.push(msg);
ws.send(JSON.stringify(msg));
}
ws.on('message', (msg) => {
signaller.emit(EventType.MessageReceived, msg);
});
ws.on('message', (msg) => {
signaller.emit(EventType.MessageReceived, msg);
});
signaller.on(EventType.MessageSend, msg => {
sendMessage(msg);
});
signaller.on(EventType.MessageSend, msg => {
sendMessage(msg);
});
signaller.trigger(EventType.ConnectionMade);
signaller.trigger(EventType.ConnectionMade);
});
return wss;