UNPKG

node-loc

Version:

ts-lib [![npm](https://img.shields.io/npm/v/npm.svg)](https://www.npmjs.com/package/ts-lib)

81 lines 2.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Fs = require("fs-extra"); const Path = require("path"); const languages_1 = require("./languages"); const DefaultLine = { total: 0, code: 0, comment: 0 }; const DefaultFileInfo = { name: '', lang: '', size: 0, lines: DefaultLine }; class LocFile { constructor(filePath) { if (!Fs.existsSync(filePath)) { throw new Error('Error in File: file now exits.'); } this.path = filePath; this.data = this.getFileInfo(); } static getType(path) { const fileExtension = '.' + path.split('.').pop(); if (!Object.keys(languages_1.Languages.extensionMap).length) { const detector = new languages_1.Languages(); } return languages_1.Languages.extensionMap[fileExtension] || ''; } static filteData(data) { const lines = data.split(/\n/); const lineData = Object.assign({}, DefaultLine, { total: lines.length, code: lines.length }); lines.map(line => { if (!line) { lineData.code--; } }); return lineData; } getFileInfo(data) { const info = Object.assign({}, DefaultFileInfo); const name = this.path.split(Path.sep).pop() || ''; let stat; let lines; try { stat = Fs.statSync(this.path); data = data || Fs.readFileSync(this.path, 'utf-8'); } catch (err) { throw new Error('read file failed.'); } lines = data.split(/\n/); info.name = name; info.size = stat && stat.size || 0; info.lang = LocFile.getType(this.path); info.lines = LocFile.filteData(data); return info; } getPath() { return this.path; } getInfo() { return this.data; } static getFileInfoByContent(name, data) { const info = Object.assign({}, DefaultFileInfo); let lines; lines = data.split(/\n/); info.name = name; info.lang = LocFile.getType(name); info.lines = LocFile.filteData(data); return info; } } exports.LocFile = LocFile; //# sourceMappingURL=file.js.map