|
| 1 | +/* @flow */ |
| 2 | +import { type Uri } from 'vscode'; |
| 3 | +import isWindows from './isWindows'; |
| 4 | + |
| 5 | +const CharCode = { |
| 6 | + Colon: 58, |
| 7 | + Slash: 47, |
| 8 | + A: 65, |
| 9 | + Z: 90, |
| 10 | + a: 97, |
| 11 | + z: 122, |
| 12 | +}; |
| 13 | + |
| 14 | +export default function uriToString(uri: Uri): string { |
| 15 | + return isWindows() ? uriToStringWindows(uri) : uri.toString(true); |
| 16 | +} |
| 17 | + |
| 18 | +// NOTE: default `uri.toString` converts windows drive letters to lower-case |
| 19 | +// which causes issues with flow so below patching toString to return upper-case drive letters |
| 20 | +// see issue https://github.com/flowtype/flow-for-vscode/issues/260 |
| 21 | +function uriToStringWindows(uri: Uri): string { |
| 22 | + const uriString = uri.toString(true); |
| 23 | + const windowsDriveLetter = getWindowsDriveLetter(uri); |
| 24 | + return windowsDriveLetter |
| 25 | + ? makeWindowsDriveLetterUppercase(uriString, windowsDriveLetter) |
| 26 | + : uriString; |
| 27 | +} |
| 28 | + |
| 29 | +function isAlphabet(charCode: number): boolean { |
| 30 | + return ( |
| 31 | + (charCode >= CharCode.A && charCode <= CharCode.Z) || |
| 32 | + (charCode >= CharCode.a && charCode <= CharCode.z) |
| 33 | + ); |
| 34 | +} |
| 35 | + |
| 36 | +function getWindowsDriveLetter(uri: Uri): ?string { |
| 37 | + const { path } = uri; |
| 38 | + |
| 39 | + let driveLetter: ?string = null; |
| 40 | + // path of type '/c:/' |
| 41 | + if ( |
| 42 | + path.length >= 3 && |
| 43 | + path.charCodeAt(0) === CharCode.Slash && |
| 44 | + path.charCodeAt(2) === CharCode.Colon |
| 45 | + ) { |
| 46 | + const code = path.charCodeAt(1); |
| 47 | + if ( |
| 48 | + (code >= CharCode.A && code <= CharCode.Z) || |
| 49 | + (code >= CharCode.a && code <= CharCode.z) |
| 50 | + ) { |
| 51 | + driveLetter = path.charAt(1); |
| 52 | + } |
| 53 | + // path of type 'c:/' |
| 54 | + } else if (path.length >= 2 && path.charCodeAt(1) === CharCode.Colon) { |
| 55 | + const code = path.charCodeAt(0); |
| 56 | + if (isAlphabet(code)) { |
| 57 | + driveLetter = path.charAt(0); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return driveLetter; |
| 62 | +} |
| 63 | + |
| 64 | +function makeWindowsDriveLetterUppercase( |
| 65 | + uriString: string, |
| 66 | + windowsDriveLetter: string, |
| 67 | +): string { |
| 68 | + const lowerCaseDriveLetter = windowsDriveLetter.toLowerCase(); |
| 69 | + const upperCaseDriveLetter = windowsDriveLetter.toUpperCase(); |
| 70 | + return uriString.replace( |
| 71 | + `${lowerCaseDriveLetter}:`, |
| 72 | + `${upperCaseDriveLetter}:`, |
| 73 | + ); |
| 74 | +} |
0 commit comments