()
| 51 | * @returns The system encoding as a string, or null if detection fails. |
| 52 | */ |
| 53 | export function getSystemEncoding(): string | null { |
| 54 | // Windows |
| 55 | if (os.platform() === 'win32') { |
| 56 | try { |
| 57 | const output = execSync('chcp', { encoding: 'utf8' }); |
| 58 | const match = output.match(/:\s*(\d+)/); |
| 59 | if (match) { |
| 60 | const codePage = parseInt(match[1], 10); |
| 61 | if (!isNaN(codePage)) { |
| 62 | return windowsCodePageToEncoding(codePage); |
| 63 | } |
| 64 | } |
| 65 | // Only warn if we can't parse the output format, not if windowsCodePageToEncoding fails |
| 66 | throw new Error( |
| 67 | `Unable to parse Windows code page from 'chcp' output "${output.trim()}". `, |
| 68 | ); |
| 69 | } catch (error) { |
| 70 | console.warn( |
| 71 | `Failed to get Windows code page using 'chcp' command: ${error instanceof Error ? error.message : String(error)}. ` + |
| 72 | `Will attempt to detect encoding from command output instead.`, |
| 73 | ); |
| 74 | } |
| 75 | return null; |
| 76 | } |
| 77 | |
| 78 | // Unix-like |
| 79 | // Use environment variables LC_ALL, LC_CTYPE, and LANG to determine the |
| 80 | // system encoding. However, these environment variables might not always |
| 81 | // be set or accurate. Handle cases where none of these variables are set. |
| 82 | const env = process.env; |
| 83 | let locale = env['LC_ALL'] || env['LC_CTYPE'] || env['LANG'] || ''; |
| 84 | |
| 85 | // Fallback to querying the system directly when environment variables are missing |
| 86 | if (!locale) { |
| 87 | try { |
| 88 | locale = execSync('locale charmap', { encoding: 'utf8' }) |
| 89 | .toString() |
| 90 | .trim(); |
| 91 | } catch (_e) { |
| 92 | console.warn('Failed to get locale charmap.'); |
| 93 | return null; |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | const match = locale.match(/\.(.+)/); // e.g., "en_US.UTF-8" |
| 98 | if (match && match[1]) { |
| 99 | return match[1].toLowerCase(); |
| 100 | } |
| 101 | |
| 102 | // Handle cases where locale charmap returns just the encoding name (e.g., "UTF-8") |
| 103 | if (locale && !locale.includes('.')) { |
| 104 | return locale.toLowerCase(); |
| 105 | } |
| 106 | |
| 107 | return null; |
| 108 | } |
| 109 | |
| 110 | /** |
no test coverage detected