123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189 |
- 'use strict';
- const path = require('path');
- const fs = require('fs');
- const mkdirp = require('make-dir');
- const supportsColor = require('supports-color');
- class ContentWriter {
-
- colorize(str ) {
- return str;
- }
-
- println(str) {
- this.write(`${str}\n`);
- }
-
- close() {}
- }
- class FileContentWriter extends ContentWriter {
- constructor(fd) {
- super();
- this.fd = fd;
- }
- write(str) {
- fs.writeSync(this.fd, str);
- }
- close() {
- fs.closeSync(this.fd);
- }
- }
- let capture = false;
- let output = '';
- class ConsoleWriter extends ContentWriter {
- write(str) {
- if (capture) {
- output += str;
- } else {
- process.stdout.write(str);
- }
- }
- colorize(str, clazz) {
- const colors = {
- low: '31;1',
- medium: '33;1',
- high: '32;1'
- };
-
- if (supportsColor.stdout && colors[clazz]) {
- return `\u001b[${colors[clazz]}m${str}\u001b[0m`;
- }
- return str;
- }
- }
- class FileWriter {
- constructor(baseDir) {
- if (!baseDir) {
- throw new Error('baseDir must be specified');
- }
- this.baseDir = baseDir;
- }
-
- static startCapture() {
- capture = true;
- }
- static stopCapture() {
- capture = false;
- }
- static getOutput() {
- return output;
- }
- static resetOutput() {
- output = '';
- }
-
- writerForDir(subdir) {
- if (path.isAbsolute(subdir)) {
- throw new Error(
- `Cannot create subdir writer for absolute path: ${subdir}`
- );
- }
- return new FileWriter(`${this.baseDir}/${subdir}`);
- }
-
- copyFile(source, dest, header) {
- if (path.isAbsolute(dest)) {
- throw new Error(`Cannot write to absolute path: ${dest}`);
- }
- dest = path.resolve(this.baseDir, dest);
- mkdirp.sync(path.dirname(dest));
- let contents;
- if (header) {
- contents = header + fs.readFileSync(source, 'utf8');
- } else {
- contents = fs.readFileSync(source);
- }
- fs.writeFileSync(dest, contents);
- }
-
- writeFile(file) {
- if (file === null || file === '-') {
- return new ConsoleWriter();
- }
- if (path.isAbsolute(file)) {
- throw new Error(`Cannot write to absolute path: ${file}`);
- }
- file = path.resolve(this.baseDir, file);
- mkdirp.sync(path.dirname(file));
- return new FileContentWriter(fs.openSync(file, 'w'));
- }
- }
- module.exports = FileWriter;
|