All files / src/core util.ts

62.5% Statements 35/56
45% Branches 9/20
50% Functions 5/10
63.63% Lines 28/44

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 63 64 65 66 67 68 69 70 7165x 65x 65x 65x 65x   65x   65x 65x       65x         65x             65x             65x                   32104x 65x         65x   65x 31186x 31186x 31186x 28640x     65x 14586x     65x 5932x     65x 2954x 1922x 1679x    
import * as pathModule from 'path';
import { Buffer, bufferFrom } from '../internal/buffer';
import process from '../process';
import { TDataOut, ENCODING_UTF8 } from '../encoding';
import { ERRSTR } from '../node/constants';
 
export const isWin = process.platform === 'win32';
 
const resolveCrossPlatform = pathModule.resolve;
const { sep } = pathModule.posix ? pathModule.posix : pathModule;
 
type TData = TDataOut | ArrayBufferView | DataView; // Data formats users can give us.
 
const isSeparator = (str, i) => {
  let char = str[i];
  return i > 0 && (char === '/' || (isWin && char === '\\'));
};
 
const removeTrailingSeparator = (str: string): string => {
  let i = str.length - 1;
  Iif (i < 2) return str;
  while (isSeparator(str, i)) i--;
  return str.substr(0, i + 1);
};
 
const normalizePath = (str, stripTrailing): string => {
  Iif (typeof str !== 'string') throw new TypeError('expected a string');
  str = str.replace(/[\\\/]+/g, '/');
  Iif (stripTrailing !== false) str = removeTrailingSeparator(str);
  return str;
};
 
export const unixify = (filepath: string, stripTrailing: boolean = true): string => {
  Iif (isWin) {
    filepath = normalizePath(filepath, stripTrailing);
    return filepath.replace(/^([a-zA-Z]+:|\.\/)/, '');
  }
  return filepath;
};
 
type TResolve = (filename: string, base?: string) => string;
 
let resolve: TResolve = (filename, base = process.cwd()) => resolveCrossPlatform(base, filename);
Iif (isWin) {
  const _resolve = resolve;
  resolve = (filename, base) => unixify(_resolve(filename, base));
}
 
export { resolve };
 
export const filenameToSteps = (filename: string, base?: string): string[] => {
  const fullPath = resolve(filename, base);
  const fullPathSansSlash = fullPath.substring(1);
  if (!fullPathSansSlash) return [];
  return fullPathSansSlash.split(sep);
};
 
export function isFd(path): boolean {
  return path >>> 0 === path;
}
 
export function validateFd(fd) {
  if (!isFd(fd)) throw TypeError(ERRSTR.FD);
}
 
export function dataToBuffer(data: TData, encoding: string = ENCODING_UTF8): Buffer {
  if (Buffer.isBuffer(data)) return data;
  else if (data instanceof Uint8Array) return bufferFrom(data);
  else return bufferFrom(String(data), encoding);
}