All files / src/cli/helpers openInDefaultEditor.ts

20.63% Statements 13/63
100% Branches 0/0
0% Functions 0/1
20.63% Lines 13/63

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 631x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                    
/* eslint-disable no-console */
import { spawn } from 'child_process'
import { exec } from 'child_process'
import fs from 'fs'
import { luigi } from './luigi.bot'
import { C } from 'topkat-utils'
import Path from 'path'
 
let openFileWarning = false
 
/**
 * Opens a file in VS Code if available, otherwise in the system's default editor.
 */
export function openInDefaultEditor(absolutePath: string, silent = false): void {
  try {
    spawn('code', ['--reuse-window', '--goto', absolutePath], {
      detached: true,
      stdio: 'ignore',
    }).unref()

    luigi.success(`Opening file: ${Path.relative(process.cwd(), absolutePath)}`)

    if (!silent && !openFileWarning) {
      openFileWarning = true
      luigi.warn(`Known issue:` + C.dim(` if the file is not openning in your main editor it may be because a program changed your path to the code command. If you are in VSCode or Cursor IDE, press F1 and search for "Install code command in path" `))
    }

    return
  } catch {
    console.warn('Could not determine `code` path. Searching for VS Code...')
  }

  // 🎯 Try to locate VS Code manually
  const vsCodePaths = [
    '/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code', // macOS
    process.env.LOCALAPPDATA + '\\Programs\\Microsoft VS Code\\Code.exe', // Windows
    '/usr/share/code/bin/code', // Linux
    '/usr/bin/code', // Alternative Linux
  ].filter(Boolean) as string[]

  for (const vsCodePath of vsCodePaths) {
    if (fs.existsSync(vsCodePath)) {
      console.log('Found VS Code at:', vsCodePath)
      spawn(vsCodePath, ['--reuse-window', '--goto', absolutePath], {
        detached: true,
        stdio: 'ignore',
      }).unref()
      return
    }
  }

  console.warn('VS Code not found, using system default editor...')

  // 🖥️ Open in default system editor as last fallback
  const openCmd =
    process.platform === 'win32'
      ? 'start'
      : process.platform === 'darwin'
        ? 'open'
        : 'xdg-open'

  exec(`${openCmd} "${absolutePath}"`)
}