@microsoft/windows-admin-center-sdk
Version:
Microsoft - Windows Admin Center Shell
283 lines (281 loc) • 10.4 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileWriter = void 0;
const logger_1 = require("./logger");
const space_generator_1 = require("./space-generator");
const fs = require('fs');
class FileWriter {
data;
filePath;
needImportHandler = false;
/**
* the getter data.
* @returns the data.
*/
getData() {
return this.data;
}
/**
* the constructor.
* @param path the path.
*/
constructor(path) {
logger_1.Logger.log(path);
this.data = this.readFile(path);
}
/**
* the read file function.
* @param filePath the file path.
* @returns the file content.
*/
readFile(filePath) {
this.filePath = filePath;
return fs.readFileSync(filePath, 'utf8');
}
/**
* the tab to two spaces function.
* @returns this context.
*/
tabToTwoSpaces() {
const lines = this.data.split('\n');
if (lines.length > 1 && /^ /.test(lines[1])) {
this.data = this.data.replace(/ /g, ' ');
}
return this;
}
/**
* replaces the version in version.json
* @param input the input.
* @returns
*/
replaceVersion(input) {
const regexPattern = /"version":\s+"(\d+\.\d+\.\d+)"/g;
for (const [_, newKeyword] of Object.entries(input)) {
logger_1.Logger.log(this.data);
this.data = this.data.replace(regexPattern, newKeyword);
}
return this;
}
/**
* the add content function.
* the default indent count should be matching with addBefore or addAfter.
* @param input the input.
* @param wholeLine the whole line flag.
* @param space the space number.
* @param connector the connector.
* @returns this context.
*/
addContent(input, wholeLine = false, space = 4, connector = ',') {
if (typeof input === 'object' && !Array.isArray(input)) {
for (const [oldKeyword, newKeyword] of Object.entries(input)) {
if (!this.checkIfKeywordExists(newKeyword)) {
const regex = wholeLine ? new RegExp(`^${this.escapeRegExp(oldKeyword)}$`, 'gm') : new RegExp(this.escapeRegExp(oldKeyword), 'g');
this.data = this.data.replace(regex, `${oldKeyword}${connector}\n${(0, space_generator_1.spaceGenerator)(space)}${newKeyword}`);
}
}
}
else {
for (let i = 0; i < input.length; i++) {
let item = input[i];
if (!this.checkIfKeywordExists(item.toBeAdded) && !this.checkIfKeywordExists(item.keyword)) {
let indent = '';
if (item.needImportHandler && (item.toBeAddedBefore && this.checkIfKeywordExists(item.toBeAddedBefore) || item.toBeAddedAfter && this.checkIfKeywordExists(item.toBeAddedAfter))) {
this.needImportHandler = true;
}
if (item.toBeAddedAfter) {
indent = (0, space_generator_1.spaceGenerator)(this.getIndentByKeyword(this.data, item.toBeAddedAfter));
const regex = wholeLine ? new RegExp(`^${this.escapeRegExp(item.toBeAddedAfter)}$`, 'gm') : new RegExp(this.escapeRegExp(item.toBeAddedAfter), 'g');
this.data = this.data.replace(regex, `${item.toBeAddedAfter}${item.connector === undefined ? connector : item.connector}\n${indent}${item.toBeAdded}`);
}
else if (item.toBeAddedBefore) {
if (item.toBeAddedBefore) {
indent = (0, space_generator_1.spaceGenerator)(this.getIndentByKeyword(this.data, item.toBeAddedBefore));
}
const regex = wholeLine ? new RegExp(`^${this.escapeRegExp(item.toBeAddedBefore)}$`, 'gm') : new RegExp(this.escapeRegExp(item.toBeAddedBefore), 'g');
this.data = this.data.replace(regex, `${item.toBeAdded}\n${indent}${item.toBeAddedBefore}`);
}
}
}
}
return this;
}
/**
* the fix imports function.
* @returns this context.
*/
fixImportHandler(imports) {
if (!this.needImportHandler) {
return this;
}
this.needImportHandler = false;
this.importFixer(imports);
logger_1.Logger.log(imports);
return this;
}
/**
* the replace dependency version function.
* @param input the input.
* @returns the this context.
*/
replaceDependencyVersion(input, ignore = false) {
if (ignore) {
return this;
}
for (const [oldKeyword, newKeyword] of Object.entries(input)) {
const oldKeywordRegex = new RegExp(`"${this.escapeRegExp(oldKeyword.match(/"([^"]+)"/)[1])}": "\\d+\\.\\d+\\.\\d+"`, 'g');
this.data = this.data.replace(oldKeywordRegex, newKeyword);
const oldKeywordRegex2 = new RegExp(`"${this.escapeRegExp(oldKeyword.match(/"([^"]+)"/)[1])}": ["^~]+\\d+\\.\\d+\\.\\d+"`, 'g');
this.data = this.data.replace(oldKeywordRegex2, newKeyword);
}
return this;
}
/**
* the remove content function.
* @param input the input array.
* @returns the this context.
*/
removeContent(input) {
if (!input || !input.length) {
return this;
}
if (typeof input[0] === 'string') {
this.data = this.data.split('\n')
.filter(line => {
return !input.some(keyword => line.includes(keyword));
})
.join('\n');
}
else {
let tempData = this.data.split('\n');
for (let i = 0; i < input.length; i++) {
if (!input[i].exactMatch) {
tempData = this.removeByKeyword(tempData, input[i].key, input[i].linesInTotalAfterKey, input[i].toBeRemovedAfter);
}
else {
tempData.splice(tempData.indexOf(input[i].key), input[i].linesInTotalAfterKey);
}
this.data = tempData.join('\n');
}
}
return this;
}
/**
* the write file function.
* @returns the write file result.
*/
writeFile() {
fs.writeFileSync(this.filePath, this.data);
return true;
}
/**
* the replace content function.
* @param input the input object
* @returns the this context
*/
replaceContent(input) {
for (const [oldKeyword, newKeyword] of Object.entries(input)) {
const oldKeywordRegex = new RegExp(`${this.escapeRegExp(oldKeyword)}`, 'gi');
this.data = this.data.replace(oldKeywordRegex, newKeyword);
}
return this;
}
/**
* the replace tsconfig content function.
* @param input the input object
* @returns the this context
*/
replaceTsConfigContent(input) {
for (const [oldKeyword, newKeyword] of Object.entries(input)) {
const oldKeywordRegex = new RegExp(`"${this.escapeRegExp(oldKeyword.match(/"([^"]+)"/)[1])}":\\s*"[^"]+"`, 'gi');
this.data = this.data.replace(oldKeywordRegex, newKeyword);
}
return this;
}
/**
* the escape for RegExp function.
* @param string the string to escape
* @returns the escaped string
*/
escapeRegExp(string) {
if (string && string.length) {
return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&');
}
return string;
}
/**
* the check if dependency exists function.
* @param newKeyword the new keyword to check
* @returns the boolean value
*/
checkIfKeywordExists(newKeyword) {
const regex = new RegExp(this.escapeRegExp(newKeyword), 'g');
return regex.exec(this.data) ? true : false;
}
/**
* removes the next n items after the index of the string containing the keyword
* @param array the file content array
* @param keyword the keyword, removeItem.key
*/
removeByKeyword(array, keyword = '', removeIndex = 1, toBeRemovedAfter = undefined) {
let startIndex = -1;
const indent = (0, space_generator_1.spaceGenerator)(4);
if (toBeRemovedAfter) {
startIndex = array.findIndex((arrayItem) => arrayItem.includes(toBeRemovedAfter));
// If the marker for toBeRemovedAfter is not found, return the original array
// No-op
if (startIndex === -1) {
return array;
}
}
const index = array.findIndex((arrayItem, i) => {
if (arrayItem.includes(keyword)) {
if (i < startIndex) {
return false;
}
else {
return true;
}
}
return false;
});
if (index !== -1) {
if (index < array.length - removeIndex) {
array.splice(index, removeIndex);
logger_1.Logger.log(`Removed the next ${removeIndex} items after index ${index}.`, indent);
}
else {
logger_1.Logger.log(`No ${removeIndex} items to remove after index ${index}.`, indent);
}
}
else {
logger_1.Logger.log(`No string containing '${keyword}' was found.`, indent);
}
return array;
}
getIndentByKeyword(input, target) {
const lines = input.split(/\r?\n/);
let leadingSpaces = 0;
for (let line of lines) {
if (line.includes(target)) {
for (let char of line) {
if (char === ' ') {
leadingSpaces++;
}
else {
break;
}
}
logger_1.Logger.log(`There are ${leadingSpaces} spaces before "${target}" on this line.`);
break;
}
}
return leadingSpaces;
}
importFixer(imports) {
if (!this.data.includes(imports)) {
this.data = imports + '\n' + this.data;
}
}
}
exports.FileWriter = FileWriter;
//# sourceMappingURL=file-writer.js.map