Skip to content

Commit bef3aff

Browse files
authored
Add --wait to code-server's own CLI (#8117)
1 parent 568a58f commit bef3aff

5 files changed

Lines changed: 141 additions & 22 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ Code v99.99.999
2424

2525
Code v1.145.3
2626

27+
### Added
28+
29+
- New flag `--wait` that waits for the opened files to be closed before
30+
returning, so `code-server --wait` can be used as `EDITOR` or `GIT_EDITOR`.
31+
Before, code-server's own script failed with `Unknown option --wait`, so this
32+
only worked when the integrated terminal found the `remote-cli` script first.
33+
2734
### Changed
2835

2936
- Update to Code 1.145.3

‎src/node/cli.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ export interface UserProvidedArgs extends UserProvidedCodeArgs {
9494
"skip-auth-preflight"?: boolean
9595
"reuse-window"?: boolean
9696
"new-window"?: boolean
97+
wait?: boolean
9798
"ignore-last-opened"?: boolean
9899
verbose?: boolean
99100
"app-name"?: string
@@ -305,6 +306,10 @@ export const options: Options<Required<UserProvidedArgs>> = {
305306
short: "r",
306307
description: "Force to open a file or folder in an already opened window.",
307308
},
309+
wait: {
310+
type: "boolean",
311+
description: "Wait for the files to be closed before returning. Requires an already opened window.",
312+
},
308313

309314
log: { type: LogLevel },
310315
verbose: { type: "boolean", short: "vvv", description: "Enable verbose logging." },
@@ -916,11 +921,11 @@ export const shouldOpenInExistingInstance = async (
916921
// existing instance since these flags have no effect otherwise. That means
917922
// if there is no existing instance we should error rather than falling back
918923
// to spawning code-server normally.
919-
const openInFlagCount = ["reuse-window", "new-window"].reduce((prev, cur) => {
924+
const openInFlagCount = ["reuse-window", "new-window", "wait"].reduce((prev, cur) => {
920925
return args[cur as keyof UserProvidedArgs] ? prev + 1 : prev
921926
}, 0)
922927
if (openInFlagCount > 0) {
923-
logger.debug("Found --reuse-window or --new-window")
928+
logger.debug("Found --reuse-window, --new-window or --wait")
924929
const socketPath = await client.getConnectedSocketPath(paths[0])
925930
if (!socketPath) {
926931
throw new Error(`No opened code-server instances found to handle ${paths[0]}`)

‎src/node/main.ts‎

Lines changed: 51 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
import { field, logger } from "@coder/logger"
2+
import { promises as fs } from "fs"
23
import http from "http"
34
import * as os from "os"
45
import * as path from "path"
56
import { Disposable } from "../common/emitter"
6-
import { plural } from "../common/util"
7+
import { generateUuid, plural } from "../common/util"
78
import { createApp, ensureAddress } from "./app"
89
import { AuthType, DefaultedArgs, Feature, toCodeArgs, UserProvidedArgs } from "./cli"
9-
import { commit, version, vsRootPath } from "./constants"
10+
import { commit, tmpdir, version, vsRootPath } from "./constants"
1011
import { loadCustomStrings } from "./i18n"
1112
import { register } from "./routes"
1213
import { VSCodeModule } from "./routes/vscode"
13-
import { isDirectory, open } from "./util"
14+
import { isDirectory, isFile, isNodeJSErrnoException, open } from "./util"
1415
import { wrapper } from "./wrapper"
1516

1617
/**
@@ -100,23 +101,53 @@ export const openInExistingInstance = async (args: DefaultedArgs, socketPath: st
100101
logger.error("Please specify at least one file or folder")
101102
process.exit(1)
102103
}
103-
const vscode = http.request(
104-
{
105-
path: "/",
106-
method: "POST",
107-
socketPath,
108-
},
109-
(response) => {
110-
response.on("data", (message) => {
111-
logger.debug("got message from Code", field("message", message.toString()))
112-
})
113-
},
114-
)
115-
vscode.on("error", (error: unknown) => {
116-
logger.error("got error from Code", field("error", error))
117-
})
118-
vscode.write(JSON.stringify(pipeArgs))
119-
vscode.end()
104+
let marker: string | undefined
105+
if (args.wait) {
106+
if (pipeArgs.fileURIs.length === 0) {
107+
logger.error("--wait requires at least one file")
108+
process.exit(1)
109+
}
110+
marker = path.join(tmpdir, generateUuid(16))
111+
await fs.mkdir(tmpdir, { recursive: true })
112+
await fs.writeFile(marker, "")
113+
pipeArgs.waitMarkerFilePath = marker
114+
}
115+
try {
116+
await new Promise<void>((resolve, reject) => {
117+
const vscode = http.request(
118+
{
119+
path: "/",
120+
method: "POST",
121+
socketPath,
122+
},
123+
(response) => {
124+
response.on("data", (message) => {
125+
logger.debug("got message from Code", field("message", message.toString()))
126+
})
127+
response.on("end", resolve)
128+
},
129+
)
130+
vscode.on("error", reject)
131+
vscode.write(JSON.stringify(pipeArgs))
132+
vscode.end()
133+
})
134+
} catch (error) {
135+
// Try to clean up the marker, but do not let removal errors override the original error.
136+
if (marker) {
137+
try {
138+
await fs.rm(marker)
139+
} catch (rmError) {
140+
if (!isNodeJSErrnoException(rmError) || rmError.code !== "ENOENT") {
141+
logger.error("failed to clean up wait marker", field("error", rmError))
142+
}
143+
}
144+
}
145+
throw error
146+
}
147+
// Code deletes the marker file once the opened files are closed.
148+
while (marker && (await isFile(marker))) {
149+
await new Promise((resolve) => setTimeout(resolve, 1000))
150+
}
120151
}
121152

122153
export const runCodeServer = async (

‎test/unit/node/cli.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -697,6 +697,14 @@ describe("cli", () => {
697697
vscodeSockets.close()
698698
})
699699

700+
it("should not start a new instance if --wait is set", async () => {
701+
const sessionSocket = path.join(tmpDirPath, "session-socket")
702+
const args: UserProvidedArgs = { wait: true, _: ["./file"] }
703+
// There is no instance to open the file in, so this must fail rather than
704+
// falling back to starting code-server.
705+
await expect(shouldOpenInExistingInstance(args, sessionSocket)).rejects.toThrow()
706+
})
707+
700708
it("should use existing if --new-window is set", async () => {
701709
const sessionSocket = path.join(tmpDirPath, "session-socket")
702710
const server = await makeEditorSessionManagerServer(sessionSocket, new EditorSessionManager())

‎test/unit/node/main.test.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import { promises as fs } from "fs"
2+
import * as http from "http"
23
import * as path from "path"
34
import { setDefaults, parse } from "../../../src/node/cli"
45
import { loadCustomStrings } from "../../../src/node/i18n"
6+
import type { OpenCommandPipeArgs } from "../../../src/node/main"
57
import { tmpdir } from "../../utils/helpers"
68

79
// Mock the i18n module
@@ -173,4 +175,70 @@ describe("main", () => {
173175
expect(mockedLoadCustomStrings).toHaveBeenCalledWith(nonExistentFile)
174176
})
175177
})
178+
179+
describe("openInExistingInstance", () => {
180+
it("should wait for the file to be closed with --wait", async () => {
181+
const file = path.join(tempDir, "git-rebase-todo")
182+
await fs.writeFile(file, "")
183+
184+
// Stand in for the socket Code listens on for CLI requests.
185+
let pipeArgs: OpenCommandPipeArgs | undefined
186+
let onRequest = () => {}
187+
const requested = new Promise<void>((resolve) => (onRequest = resolve))
188+
const server = http.createServer((req, res) => {
189+
let body = ""
190+
req.on("data", (chunk) => (body += chunk))
191+
req.on("end", () => {
192+
pipeArgs = JSON.parse(body)
193+
res.end()
194+
onRequest()
195+
})
196+
})
197+
const socketPath =
198+
process.platform === "win32"
199+
? String.raw`\\.\pipe\vscode-${path.basename(tempDir)}`
200+
: path.join(tempDir, "vscode.sock")
201+
await new Promise<void>((resolve) => server.listen(socketPath, resolve))
202+
203+
// Run the wait loop's poll timer as soon as it has been scheduled.
204+
const runNextPoll = async () => {
205+
while (jest.getTimerCount() === 0) {
206+
await fs.stat(tempDir)
207+
}
208+
jest.runOnlyPendingTimers()
209+
}
210+
211+
jest.useFakeTimers()
212+
try {
213+
const args = await setDefaults(
214+
parse([`--config=${path.join(tempDir, "config.yaml")}`, `--user-data-dir=${tempDir}`, "--wait", file]),
215+
)
216+
const mainModule = await import("../../../src/node/main")
217+
let returned = false
218+
const opening = mainModule.openInExistingInstance(args, socketPath).then(() => {
219+
returned = true
220+
})
221+
222+
await requested
223+
expect(pipeArgs?.fileURIs).toStrictEqual([file])
224+
const marker = pipeArgs?.waitMarkerFilePath
225+
expect(marker).toBeDefined()
226+
expect((await fs.stat(marker!)).isFile()).toBe(true)
227+
228+
// Still waiting while the file is open.
229+
await runNextPoll()
230+
await runNextPoll()
231+
expect(returned).toBe(false)
232+
233+
// Code deletes the marker once the file is closed.
234+
await fs.rm(marker!)
235+
await runNextPoll()
236+
await opening
237+
expect(returned).toBe(true)
238+
} finally {
239+
jest.useRealTimers()
240+
server.close()
241+
}
242+
})
243+
})
176244
})

0 commit comments

Comments
 (0)