/ commands / keybindings / keybindings.ts
keybindings.ts
 1  import { mkdir, writeFile } from 'fs/promises'
 2  import { dirname } from 'path'
 3  import {
 4    getKeybindingsPath,
 5    isKeybindingCustomizationEnabled,
 6  } from '../../keybindings/loadUserBindings.js'
 7  import { generateKeybindingsTemplate } from '../../keybindings/template.js'
 8  import { getErrnoCode } from '../../utils/errors.js'
 9  import { editFileInEditor } from '../../utils/promptEditor.js'
10  
11  export async function call(): Promise<{ type: 'text'; value: string }> {
12    if (!isKeybindingCustomizationEnabled()) {
13      return {
14        type: 'text',
15        value:
16          'Keybinding customization is not enabled. This feature is currently in preview.',
17      }
18    }
19  
20    const keybindingsPath = getKeybindingsPath()
21  
22    // Write template with 'wx' flag (exclusive create) — fails with EEXIST if
23    // the file already exists. Avoids a stat pre-check (TOCTOU race + extra syscall).
24    let fileExists = false
25    await mkdir(dirname(keybindingsPath), { recursive: true })
26    try {
27      await writeFile(keybindingsPath, generateKeybindingsTemplate(), {
28        encoding: 'utf-8',
29        flag: 'wx',
30      })
31    } catch (e: unknown) {
32      if (getErrnoCode(e) === 'EEXIST') {
33        fileExists = true
34      } else {
35        throw e
36      }
37    }
38  
39    // Open in editor
40    const result = await editFileInEditor(keybindingsPath)
41    if (result.error) {
42      return {
43        type: 'text',
44        value: `${fileExists ? 'Opened' : 'Created'} ${keybindingsPath}. Could not open in editor: ${result.error}`,
45      }
46    }
47    return {
48      type: 'text',
49      value: fileExists
50        ? `Opened ${keybindingsPath} in your editor.`
51        : `Created ${keybindingsPath} with template. Opened in your editor.`,
52    }
53  }