Skip to content

Commit 9af553e

Browse files
committed
Make nbin bundling work and improve watching
1 parent f6ba177 commit 9af553e

11 files changed

+86
-72
lines changed

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
"scripts": {
1010
"postinstall": "yarn build:rules",
1111
"build": "yarn task build",
12+
"bundle": "yarn task bundle",
1213
"start": "npm-run-all --parallel watch build:run",
1314
"watch": "yarn task build true",
1415
"build:run": "cd ./out && node ./packages/server/src/cli # TODO: restart on change",

packages/server/src/bootstrap.ts

+25-3
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,33 @@
1-
import * as tsConfig from "../../../tsconfig.json";
1+
import * as path from "path";
2+
3+
const rootPath = path.resolve(__dirname, "../../../..");
4+
5+
// tslint:disable-next-line no-any
6+
if ((process.versions as any).nbin) {
7+
require("nbin").shimNativeFs(rootPath);
8+
}
9+
210
import * as tsConfigPaths from "tsconfig-paths";
311

412
// Prevent vscode from trying to load original-fs from electron.
513
delete process.env.ELECTRON_RUN_AS_NODE;
614

715
// This will advise Node so it can resolve paths based on our aliases.
816
tsConfigPaths.register({
9-
baseUrl: tsConfig.compilerOptions.baseUrl,
10-
paths: tsConfig.compilerOptions.paths,
17+
baseUrl: rootPath,
18+
paths: {
19+
"@coder/*": [
20+
"./out/packages/*/src",
21+
],
22+
"vs/*": [
23+
"./lib/vscode/out/vs/*",
24+
],
25+
electron: [
26+
"./out/packages/server/src/modules/electron",
27+
],
28+
},
1129
});
30+
31+
if (!process.env.IS_FORK) {
32+
require("./cli");
33+
}

packages/server/src/cli.ts

+3-23
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import * as fse from "fs-extra";
88
import * as os from "os";
99
import * as path from "path";
1010
import * as WebSocket from "ws";
11-
import { buildDir, cacheHome, dataHome, isCli } from "./constants";
11+
import { libPath, tmpPath, cacheHome, dataHome } from "./constants";
1212
import { createApp } from "./server";
1313
import { forkModule } from "./vscode/bootstrapFork";
1414
import { SharedProcess, SharedProcessState } from "./vscode/sharedProcess";
@@ -41,11 +41,6 @@ commander.version(process.env.VERSION || "development")
4141
.arguments("Specify working directory.")
4242
.parse(process.argv);
4343

44-
Error.stackTraceLimit = Infinity;
45-
if (isCli) {
46-
require("nbin").shimNativeFs(buildDir);
47-
require("nbin").shimNativeFs("/node_modules");
48-
}
4944
// Makes strings or numbers bold in stdout
5045
const bold = (text: string | number): string | number => {
5146
return `\u001B[1m${text}\u001B[0m`;
@@ -86,11 +81,11 @@ const bold = (text: string | number): string | number => {
8681

8782
const dataDir = path.resolve(options.userDataDir || options.dataDir || path.join(dataHome, "code-server"));
8883
const extensionsDir = options.extensionsDir ? path.resolve(options.extensionsDir) : path.resolve(dataDir, "extensions");
89-
const builtInExtensionsDir = path.resolve(buildDir || path.join(__dirname, ".."), "build/extensions");
84+
const builtInExtensionsDir = path.resolve(path.resolve(libPath, "extensions"));
9085
const extraExtensionDirs = options.extraExtensionsDir ? options.extraExtensionsDir.map((p) => path.resolve(p)) : [];
9186
const extraBuiltinExtensionDirs = options.extraBuiltinExtensionsDir ? options.extraBuiltinExtensionsDir.map((p) => path.resolve(p)) : [];
9287
const workingDir = path.resolve(args[0] || process.cwd());
93-
const dependenciesDir = path.join(os.tmpdir(), "code-server/dependencies");
88+
const dependenciesDir = path.join(tmpPath, "dependencies");
9489

9590
if (!fs.existsSync(dataDir)) {
9691
const oldDataDir = path.resolve(path.join(os.homedir(), ".code-server"));
@@ -110,21 +105,6 @@ const bold = (text: string | number): string | number => {
110105
...extraBuiltinExtensionDirs.map((p) => fse.mkdirp(p)),
111106
]);
112107

113-
// const unpackExecutable = (binaryName: string): void => {
114-
// const memFile = path.join(isCli ? buildDir! : path.join(__dirname, ".."), "build/dependencies", binaryName);
115-
// const diskFile = path.join(dependenciesDir, binaryName);
116-
// if (!fse.existsSync(diskFile)) {
117-
// fse.writeFileSync(diskFile, fse.readFileSync(memFile));
118-
// }
119-
// fse.chmodSync(diskFile, "755");
120-
// };
121-
122-
// TODO: should this just be a dependency instead of bundled? If not, we'll
123-
// still need to patch (maybe we can get it working without it though).
124-
// unpackExecutable("rg");
125-
// tslint:disable-next-line no-any
126-
// (<any>global).RIPGREP_LOCATION = path.join(dependenciesDir, "rg");
127-
128108
if (!process.env.VSCODE_LOGS) {
129109
process.env.VSCODE_LOGS = path.join(cacheHome, "code-server/logs", new Date().toISOString().replace(/[-:.TZ]/g, ""));
130110
}

packages/server/src/constants.ts

+15-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
11
import * as path from "path";
22
import * as os from "os";
33

4-
export const isCli = typeof process.env.CLI !== "undefined" && process.env.CLI !== "false";
5-
export const buildDir = process.env.BUILD_DIR ? path.resolve(process.env.BUILD_DIR) : "";
4+
/**
5+
* Application root.
6+
*/
7+
export const rootPath = path.resolve(__dirname, "../../../..");
8+
9+
/**
10+
* Contains vscode and built-in extensions.
11+
*/
12+
export const libPath = path.join(rootPath, "lib");
13+
14+
/**
15+
* Place all temporary files here.
16+
*/
17+
export const tmpPath = path.join(os.tmpdir(), "code-server");
18+
619
const xdgResolve = (primary: string | undefined, fallback: string): string => {
720
return primary ? path.resolve(primary) : path.resolve(process.env.HOME || os.homedir(), fallback);
821
};

packages/server/src/index.ts

-1
This file was deleted.

packages/server/src/server.ts

+2-3
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import * as pem from "pem";
1818
import * as util from "util";
1919
import * as url from "url";
2020
import * as ws from "ws";
21-
import { buildDir } from "./constants";
21+
import { rootPath } from "./constants";
2222
import { createPortScanner } from "./portScanner";
2323
import safeCompare = require("safe-compare");
2424

@@ -208,8 +208,7 @@ export const createApp = async (options: CreateAppOptions): Promise<{
208208
return res.redirect(code, newUrlString);
209209
};
210210

211-
const baseDir = buildDir || path.join(__dirname, "..");
212-
const staticGzip = expressStaticGzip(path.join(baseDir, "build/web"));
211+
const staticGzip = expressStaticGzip(path.join(rootPath, "out/packages/web/src"));
213212

214213
app.use((req, res, next) => {
215214
logger.trace(`\u001B[1m${req.method} ${res.statusCode} \u001B[0m${req.originalUrl}`, field("host", req.hostname), field("ip", req.ip));

packages/server/src/vscode/bootstrapFork.ts

+1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ export const forkModule = (modulePath: string, args?: string[], options?: cp.For
2727
env: {
2828
...process.env, ...(options && options.env || {}),
2929
AMD_ENTRYPOINT: modulePath,
30+
IS_FORK: "true",
3031
},
3132
};
3233

packages/server/src/vscode/sharedProcess.ts

+10-5
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { retry, withEnv } from "@coder/protocol";
44
import { fork, ChildProcess } from "child_process";
55
import * as os from "os";
66
import * as path from "path";
7+
import { tmpPath } from "../constants";
78
import { IpcHandler } from "../ipc";
89

910
// tslint:disable-next-line completed-docs pretty obvious what this is
@@ -33,8 +34,8 @@ export type SharedProcessEvent = {
3334
*/
3435
export class SharedProcess {
3536
public readonly socketPath: string = os.platform() === "win32"
36-
? path.join("\\\\?\\pipe", os.tmpdir(), `.code-server${Math.random().toString()}`)
37-
: path.join(os.tmpdir(), `.code-server${Math.random().toString()}`);
37+
? path.join("\\\\?\\pipe", tmpPath, `shared-process-${Math.random().toString()}`)
38+
: path.join(tmpPath, `shared-process-${Math.random().toString()}`);
3839
private _state: SharedProcessState = SharedProcessState.Stopped;
3940
private activeProcess: ChildProcess | undefined;
4041
private ipcHandler: IpcHandler | undefined;
@@ -100,9 +101,13 @@ export class SharedProcess {
100101
this.activeProcess.kill();
101102
}
102103

103-
const activeProcess = fork(path.join(__dirname, "shared-process"), [
104-
"--user-data-dir", this.userDataDir,
105-
], withEnv({ env: { VSCODE_ALLOW_IO: "true" } }),
104+
const activeProcess = fork(
105+
path.join(__dirname, "shared-process"),
106+
[ "--user-data-dir", this.userDataDir ],
107+
withEnv({ env: {
108+
VSCODE_ALLOW_IO: "true",
109+
IS_FORK: "true",
110+
}}),
106111
);
107112
this.activeProcess = activeProcess;
108113

scripts/tasks.ts

+28-18
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { Binary } from "@coder/nbin";
22
import { field } from "@coder/logger";
33
import { register, run } from "@coder/runner";
44

5+
import * as cp from "child_process";
56
import * as fs from "fs";
67
import * as fse from "fs-extra";
78
import * as https from "https";
@@ -11,8 +12,9 @@ import * as tar from "tar";
1112

1213
import { platform } from "./platform";
1314

14-
const libPath = path.join(__dirname, "../lib");
15-
const releasePath = path.resolve(__dirname, "../release");
15+
const rootPath = path.resolve(__dirname, "..");
16+
const libPath = path.join(rootPath, "lib");
17+
const releasePath = path.join(rootPath, "release");
1618
const target = `${platform()}-${os.arch()}`;
1719
const vscodeVersion = process.env.VSCODE_VERSION || "1.35.0";
1820

@@ -30,25 +32,34 @@ register("build", async (runner, logger, shouldWatch: string) => {
3032
const outPath = path.join(__dirname, "../out");
3133
const compile = async (): Promise<void> => {
3234
fse.removeSync(path.resolve(outPath));
33-
34-
runner.cwd = path.resolve(__dirname, "..");
35-
const resp = await runner.execute(
36-
"tsc",
37-
["--project", "tsconfig.build.json"].concat(watch ? ["--watch"] : []),
38-
);
39-
if (resp.exitCode !== 0) {
40-
throw new Error(`Failed to build: ${resp.stderr}`);
35+
if (watch) {
36+
const proc = cp.spawn("tsc", ["--project", "tsconfig.build.json", "--watch", "--preserveWatchOutput"], {
37+
cwd: rootPath,
38+
});
39+
await new Promise((resolve, reject): void => {
40+
proc.stdout.setEncoding("utf8");
41+
proc.stdout.on("data", (data: string) => {
42+
logger.info(data.split("\n").filter((l) => !!l).join("\n"));
43+
});
44+
proc.on("exit", resolve);
45+
proc.on("error", reject);
46+
});
47+
} else {
48+
runner.cwd = rootPath;
49+
const resp = await runner.execute("tsc", ["--project", "tsconfig.build.json"]);
50+
if (resp.exitCode !== 0) {
51+
throw new Error(`Failed to build: ${resp.stderr}`);
52+
}
4153
}
4254
};
4355

4456
const copy = async (): Promise<void> => {
4557
// TODO: If watching, copy every time they change.
4658
await Promise.all([
4759
"packages/protocol/src/proto",
48-
["tsconfig.runtime.json", "tsconfig.json"],
4960
].map((p) => fse.copy(
50-
path.resolve(__dirname, "..", Array.isArray(p) ? p[0] : p),
51-
path.resolve(outPath, Array.isArray(p) ? p[1] : p),
61+
path.resolve(rootPath, p),
62+
path.resolve(outPath, p),
5263
)));
5364
fse.unlinkSync(path.resolve(outPath, "packages/protocol/src/proto/index.ts"));
5465
};
@@ -64,15 +75,14 @@ register("build", async (runner, logger, shouldWatch: string) => {
6475
* Bundle built code into a binary with nbin.
6576
*/
6677
register("bundle", async () => {
67-
const root = path.join(__dirname, "..");
6878
const bin = new Binary({
69-
mainFile: path.join(root, "out/packages/server/src/cli.js"),
79+
mainFile: path.join(rootPath, "out/packages/server/src/bootstrap.js"),
7080
target: platform() === "darwin" ? "darwin" : platform() === "musl" ? "alpine" : "linux",
7181
});
7282

73-
bin.writeFiles(path.join(root, "lib/**"));
74-
bin.writeFiles(path.join(root, "out/**"));
75-
bin.writeFiles(path.join(root, "**/node_modules"));
83+
bin.writeFiles(path.join(rootPath, "lib/**"));
84+
bin.writeFiles(path.join(rootPath, "out/**"));
85+
bin.writeFiles(path.join(rootPath, "**/node_modules/**"));
7686

7787
fse.mkdirpSync(releasePath);
7888

tsconfig.build.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"incremental": true
55
},
66
"include": [
7-
"packages/server/src/index.ts",
7+
"packages/server/src/cli.ts",
88
"packages/server/src/vscode/bootstrap-fork.ts",
99
"packages/server/src/vscode/shared-process.ts",
1010
"packages/server/src/modules/electron.ts"

tsconfig.runtime.json

-16
This file was deleted.

0 commit comments

Comments
 (0)