Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 33 additions & 53 deletions lib/src/main/resources/com/diffplug/spotless/npm/common-serve.js
Original file line number Diff line number Diff line change
@@ -1,65 +1,45 @@
// this file will be glued to the top of the specific xy-serve.js file
const debug_serve = false; // set to true for debug log output in node process
const shutdownServer = require("http-graceful-shutdown");
const express = require("express");
const app = express();
const fs = require("fs");
const shutdownServer = require("http-graceful-shutdown");

app.use(express.json({limit: "50mb"}));
// this file will be glued to the top of the specific xy-serve.js file

const fs = require("fs");
function streamServerOutput(instanceId, port) {
debugLog(`Server running on port ${port} for instance ${instanceId}`);
fs.writeFile("server.port.tmp", port, err => {
if (err) return console.log(err);
fs.rename("server.port.tmp", `server-${instanceId}.port`, err => {
if (err) console.log(err);
});
});
}

function debugLog() {
if (debug_serve) {
console.log.apply(this, arguments)
}
if (false) console.log.apply(this, arguments);
}

function getInstanceId() {
const args = process.argv.slice(2);

// Look for the --node-server-instance-id option
let instanceId;
const app = express();

args.forEach(arg => {
if (arg.startsWith('--node-server-instance-id=')) {
instanceId = arg.split('=')[1];
}
});
app.use(express.json({ limit: "50mb" }));

// throw if instanceId is not set
if (!instanceId) {
throw new Error("Missing --node-server-instance-id argument");
}
return instanceId;
}

var listener = app.listen(0, "127.0.0.1", () => {
const instanceId = getInstanceId();
debugLog("Server running on port " + listener.address().port + " for instance " + instanceId);
fs.writeFile("server.port.tmp", "" + listener.address().port, function (err) {
if (err) {
return console.log(err);
} else {
fs.rename("server.port.tmp", `server-${instanceId}.port`, function (err) {
if (err) {
return console.log(err);
}
}); // try to be as atomic as possible
}
});
});
const shutdown = shutdownServer(listener, {
forceExit: false, // let the event loop clear
finally: () => debugLog("graceful shutdown finished."),
});
const server = app.listen(0,"127.0.0.1", () =>
streamServerOutput(
process.argv.slice(2).find(arg => arg.startsWith("--node-server-instance-id="))?.split("=")[1]
|| (() => { throw new Error("Missing --node-server-instance-id argument"); })(),
server.address().port
)
);

app.post("/shutdown", (req, res) => {
res.status(200).send("Shutting down");
setTimeout(async () => {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

assuming if we fail here we still would have send out 200 before.

try {
await shutdown();
} catch (err) {
console.error("Error during shutdown:", err);
}
}, 200);
setTimeout(async () => {
try {
await shutdownServer(server, {
forceExit: false,
finally: () => debugLog("graceful shutdown finished.")
})();
} catch (err) {
console.error("Error during shutdown:", err);
}
}, 200);
res.ok().send("Graceful shutdown.");
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should be safe to make this the last call. The only potential issue is if a third-party tool relies on the current log parsing, but that’s unlikely. We’re updating it to present tense for consistency with standard logging.

});
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,13 @@ app.post("/prettier/config-options", (req, res) => {

app.post("/prettier/format", async (req, res) => {
const format_data = req.body;

let formatted_file_content = "";
try {
formatted_file_content = await prettierFormat(format_data.file_content, format_data.config_options);
res.set("Content-Type", "text/plain");
res.send(await prettierFormat(format_data.file_content, format_data.config_options));
} catch(err) {
res.status(500).send("Error while formatting: " + err);
return;
}
res.set("Content-Type", "text/plain");
res.send(formatted_file_content);
});

const prettierFormat = async function(file_content, config_options) {
Expand Down Expand Up @@ -62,7 +59,7 @@ const mergeConfigOptions = function(resolved_config_options, config_options) {
const extend = function() {
// Variables
const extended = {};
let i = 0;
const i = 0;
const length = arguments.length;

// Merge the object into the extended object
Expand Down
18 changes: 1 addition & 17 deletions lib/src/main/resources/com/diffplug/spotless/npm/tsfmt-serve.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,7 @@
const tsfmt = require("typescript-formatter");

app.post("/tsfmt/format", (req, res) => {
var format_data = req.body;
tsfmt.processString("spotless-format-string.ts", format_data.file_content, format_data.config_options).then(resultMap => {
/*
export interface ResultMap {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we still need this?

[fileName: string]: Result;
}
export interface Result {
fileName: string;
settings: ts.FormatCodeSettings | null;
message: string;
error: boolean;
src: string;
dest: string;
}
*/
// result contains 'message' (String), 'error' (boolean), 'dest' (String) => formatted
tsfmt.processString("spotless-format-string.ts", req.body.file_content, req.body.config_options).then(resultMap => {
if (resultMap.error !== undefined && resultMap.error) {
res.status(400).send(resultMap.message);
return;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2023 DiffPlug
* Copyright 2023-2025 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -25,6 +25,8 @@

public class NpmTestsWithDynamicallyInstalledNpmInstallationTest extends MavenIntegrationHarness {

public static final String TS = "typescript";

@Test
void useDownloadedNpmInstallation() throws Exception {
writePomWithPrettierSteps(
Expand All @@ -34,15 +36,11 @@ void useDownloadedNpmInstallation() throws Exception {
" <npmExecutable>" + installedNpmPath() + "</npmExecutable>",
"</prettier>");

String kind = "typescript";
String suffix = "ts";
String configPath = ".prettierrc.yml";
setFile(configPath).toResource("npm/prettier/filetypes/" + kind + "/" + ".prettierrc.yml");
String path = "src/main/" + kind + "/test." + suffix;
setFile(path).toResource("npm/prettier/filetypes/" + kind + "/" + kind + ".dirty");

String path = "src/main/" + TS + "/test.ts";
setFile(path).toResource("npm/prettier/filetypes/" + TS + "/" + TS + ".dirty");
setFile(".prettierrc.yml").toResource("npm/prettier/filetypes/" + TS + "/" + ".prettierrc.yml");
mavenRunner().withArguments(installNpmMavenGoal(), "spotless:apply").runNoError();
assertFile(path).sameAsResource("npm/prettier/filetypes/" + kind + "/" + kind + ".clean");
assertFile(path).sameAsResource("npm/prettier/filetypes/" + TS + "/" + TS + ".clean");
}

}
6 changes: 3 additions & 3 deletions testlib/src/main/resources/clang/example.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
var numbers=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
const numbers=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
];

const p = {
Expand All @@ -10,9 +10,9 @@ const p = {
const str = "Hello, world!"
;

var str2=str.charAt(3)+str[0];
const str2=str.charAt(3)+str[0];

var multilinestr = "Hello \
const multilinestr = "Hello \
World"
;

Expand Down
Loading