simple-file-templater 1.0.1 → 1.0.3

Sign up to get free protection for your applications and to get access to all the features.
package/.DS_Store ADDED
Binary file
package/.gitignore ADDED
@@ -0,0 +1,38 @@
1
+ # See http://help.github.com/ignore-files/ for more about ignoring files.
2
+
3
+ # compiled output
4
+ /dist
5
+ tmp/
6
+ cache/
7
+
8
+ # dependencies
9
+ node_modules
10
+
11
+ # IDEs and editors
12
+ /.idea
13
+ .project
14
+ .classpath
15
+ *.launch
16
+ .settings/
17
+
18
+ # misc
19
+ /.sass-cache
20
+ /connect.lock
21
+ /coverage/*
22
+ /libpeerconnection.log
23
+ npm-debug.log
24
+ testem.log
25
+ /typings
26
+ tests/env.json
27
+ env.json
28
+
29
+ # e2e
30
+ /e2e/*.js
31
+ /e2e/*.map
32
+
33
+ #System Files
34
+ .DS_Store
35
+ Thumbs.db
36
+
37
+ #visual studio history
38
+ /.history
package/LICENSE CHANGED
File without changes
@@ -0,0 +1,34 @@
1
+ /** Get the content of a folder and move it with option to replace in files or in fileNames as you go */
2
+ export declare function templater(
3
+ /** absolute url of template (it can be a folder) */
4
+ from: string,
5
+ /** absolute url of folder/file to be copied (it can be a folder) */
6
+ to: string,
7
+ /** list of variables to interpolates
8
+ * * {myVar : myReplacement}
9
+ * * OR [[/myRegExp/g, 'myString'], ['myString1', 'myString2']...]
10
+ * * DON'T forget the g flag when using regexps
11
+ */
12
+ replaceInFiles?: any[],
13
+ /** same as above but for fileNames (only valid when copying folders) */
14
+ replaceInFileNames?: any[],
15
+ /** regexp array to check against path. Eg: /node_module/ <= file paths that includes the word node_module will not be taken in account */
16
+ ignorePaths?: any[]): string[];
17
+ /** Inject content into a file at specified place */
18
+ export declare function injector(
19
+ /** url of the file where the content will be injected */
20
+ filePath: string, data: string,
21
+ /** Number == lineNumber || RegExp == will replace the first matching group || String == will place content after the string
22
+ * NOTE: don't forget **the g flag** for regexp if you want to match all occurences
23
+ */
24
+ after: number | string | RegExp): boolean;
25
+ /** Turns a file content into a list of lines */
26
+ export declare function fileToLines(
27
+ /** absolute path of file */
28
+ filePath: string,
29
+ /** get only lines from the first matching group */
30
+ regexp: any,
31
+ /** still count as a line; avoid conflicting with regexp, for ex if regexp match all inside \(.*\), and a comment with "// 1] blah" is found is in the middle */
32
+ ignoreInlineComments?: boolean,
33
+ /** Will trime each line */
34
+ trim?: boolean): [lineNumber: number, content: string][];
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.fileToLines = exports.injector = exports.templater = void 0;
7
+ const fs_extra_1 = __importDefault(require("fs-extra"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const fast_glob_1 = __importDefault(require("fast-glob"));
10
+ /** Get the content of a folder and move it with option to replace in files or in fileNames as you go */
11
+ function templater(
12
+ /** absolute url of template (it can be a folder) */
13
+ from,
14
+ /** absolute url of folder/file to be copied (it can be a folder) */
15
+ to,
16
+ /** list of variables to interpolates
17
+ * * {myVar : myReplacement}
18
+ * * OR [[/myRegExp/g, 'myString'], ['myString1', 'myString2']...]
19
+ * * DON'T forget the g flag when using regexps
20
+ */
21
+ replaceInFiles = [],
22
+ /** same as above but for fileNames (only valid when copying folders) */
23
+ replaceInFileNames = [],
24
+ /** regexp array to check against path. Eg: /node_module/ <= file paths that includes the word node_module will not be taken in account */
25
+ ignorePaths = []) {
26
+ try {
27
+ err500IfNotSet({ from, to, varz: replaceInFiles });
28
+ // convert all replacement data to array [ [regExpToReplace, replacer], ... ]
29
+ if (isObject(replaceInFiles))
30
+ replaceInFiles = Object.entries(replaceInFiles);
31
+ replaceInFiles.forEach(([toReplace, replacer], i, arr) => toReplace instanceof RegExp || (arr[i] = [new RegExp(toReplace, 'g'), replacer]));
32
+ if (isObject(replaceInFileNames))
33
+ replaceInFileNames = Object.entries(replaceInFileNames);
34
+ replaceInFileNames.forEach(([toReplace, replacer], i, arr) => toReplace instanceof RegExp || (arr[i] = [new RegExp(toReplace, 'g'), replacer]));
35
+ const createdPath = [];
36
+ let files = [from];
37
+ const templateIsDirectory = fs_extra_1.default.statSync(from).isDirectory();
38
+ // get directory structure
39
+ if (templateIsDirectory) {
40
+ if (fs_extra_1.default.existsSync(to) && !fs_extra_1.default.statSync(to).isDirectory())
41
+ throw '"from" argument is a directory but "to" arg is a file';
42
+ files = fast_glob_1.default.sync(`${from}/**/*`, { dot: true });
43
+ }
44
+ else if (fs_extra_1.default.existsSync(to) && fs_extra_1.default.statSync(to).isDirectory())
45
+ throw '"to" argument is a directory but "from" arg is a file';
46
+ for (const fileFullPath of files) {
47
+ if (ignorePaths.some(reg => reg.test(fileFullPath)))
48
+ continue;
49
+ let newFileFullPath = to;
50
+ if (templateIsDirectory) {
51
+ const [, filePath, fileName] = fileFullPath.match(/(.*)\/(.*)$/) || [];
52
+ const newFilePath = filePath.replace(from, to);
53
+ const newFileName = replaceInFileNames.reduce((str, [toReplace, replacer]) => str.replace(toReplace, replacer), fileName);
54
+ newFileFullPath = path_1.default.join(newFilePath, newFileName);
55
+ }
56
+ const oldFileContent = fs_extra_1.default.readFileSync(fileFullPath, 'utf-8');
57
+ const newFileContent = replaceInFiles.reduce((str, [toReplace, replacer]) => str.replace(toReplace, replacer), oldFileContent);
58
+ fs_extra_1.default.outputFileSync(newFileFullPath, newFileContent);
59
+ createdPath.push(newFileFullPath);
60
+ }
61
+ return createdPath;
62
+ }
63
+ catch (err) {
64
+ console.error(err);
65
+ }
66
+ }
67
+ exports.templater = templater;
68
+ /** Inject content into a file at specified place */
69
+ function injector(
70
+ /** url of the file where the content will be injected */
71
+ filePath, data,
72
+ /** Number == lineNumber || RegExp == will replace the first matching group || String == will place content after the string
73
+ * NOTE: don't forget **the g flag** for regexp if you want to match all occurences
74
+ */
75
+ after) {
76
+ try {
77
+ err500IfNotSet({ filePath, data, after });
78
+ if (!fs_extra_1.default.existsSync(filePath))
79
+ throw 'file for injection do not exist';
80
+ const fileContent = fs_extra_1.default.readFileSync(filePath, 'utf-8');
81
+ let newFileContent;
82
+ if (after instanceof RegExp) {
83
+ newFileContent = fileContent.replace(after, (f, m1) => f.replace(m1, data));
84
+ }
85
+ else if (typeof after === 'number') {
86
+ newFileContent = fileContent.split('\n');
87
+ newFileContent.splice(after, 0, data);
88
+ newFileContent = newFileContent.join('\n');
89
+ }
90
+ else if (typeof after === 'string') {
91
+ newFileContent = fileContent.split(after).join(after + data);
92
+ }
93
+ else
94
+ throw 'Wrong type for after argument';
95
+ fs_extra_1.default.writeFileSync(filePath, newFileContent);
96
+ return true;
97
+ }
98
+ catch (err) {
99
+ console.error(err);
100
+ }
101
+ }
102
+ exports.injector = injector;
103
+ /** Turns a file content into a list of lines */
104
+ function fileToLines(
105
+ /** absolute path of file */
106
+ filePath,
107
+ /** get only lines from the first matching group */
108
+ regexp,
109
+ /** still count as a line; avoid conflicting with regexp, for ex if regexp match all inside \(.*\), and a comment with "// 1] blah" is found is in the middle */
110
+ ignoreInlineComments = true,
111
+ /** Will trime each line */
112
+ trim = true) {
113
+ try {
114
+ err500IfNotSet({ filePath });
115
+ if (!fs_extra_1.default.existsSync(filePath))
116
+ throw 'file for injection do not exist';
117
+ let fileContent = fs_extra_1.default.readFileSync(filePath, 'utf-8');
118
+ if (ignoreInlineComments)
119
+ fileContent = fileContent.replace(/\/\/.*/g, '<$COMMENT$>');
120
+ let lines, lineBegin = 0;
121
+ if (isset(regexp) && regexp instanceof RegExp) {
122
+ fileContent.replace(regexp, (f, m1, index, chain) => {
123
+ const linesBefore = chain.substring(0, index).split('\n');
124
+ lineBegin = linesBefore.length;
125
+ lines = m1.split('\n');
126
+ });
127
+ if (!isset(lines))
128
+ throw `regexp doesn't match the subject string`;
129
+ }
130
+ else {
131
+ lines = fileContent.split('\n');
132
+ }
133
+ if (lines[0] === '')
134
+ lines[0] = 'First line';
135
+ return lines
136
+ .map((lineContent, i) => [lineBegin + i, trim ? lineContent.trim() : lineContent])
137
+ .filter(([, content]) => content && !content.includes('<$COMMENT$>'));
138
+ }
139
+ catch (err) {
140
+ console.error(err);
141
+ }
142
+ }
143
+ exports.fileToLines = fileToLines;
144
+ function isset(...elms) {
145
+ return elms.every(elm => typeof elm !== 'undefined' && elm !== null);
146
+ }
147
+ function isObject(obj) { return isset(obj) && typeof obj === 'object' && Object.getPrototypeOf(obj) === Object.prototype; }
148
+ function err500IfNotSet(objectWithVarDescription) {
149
+ Object.entries(objectWithVarDescription).forEach(([name, value], i) => {
150
+ if (!isset(value))
151
+ throw new Error(`Param number ${i} (${name}) is not set in templater function.`);
152
+ });
153
+ }
154
+ //# sourceMappingURL=templater.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"templater.js","sourceRoot":"","sources":["../templater.ts"],"names":[],"mappings":";;;;;;AAAA,wDAAyB;AACzB,gDAAuB;AACvB,0DAA0B;AAG1B,wGAAwG;AACxG,SAAgB,SAAS;AACrB,oDAAoD;AACpD,IAAY;AACZ,oEAAoE;AACpE,EAAU;AACV;;;;EAIE;AACF,cAAc,GAAG,EAAE;AACnB,wEAAwE;AACxE,kBAAkB,GAAG,EAAE;AACvB,0IAA0I;AAC1I,WAAW,GAAG,EAAE;IAEhB,IAAI,CAAC;QACD,cAAc,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC,CAAA;QAElD,6EAA6E;QAC7E,IAAI,QAAQ,CAAC,cAAc,CAAC;YAAE,cAAc,GAAG,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;QAC9E,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,EAAE,QAAQ,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,CAAC,SAAS,YAAY,MAAM,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,SAAS,EAAE,GAAG,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC5I,IAAI,QAAQ,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AC,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC,CAAC;IAC9E,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QAAC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAAC,CAAC;AACzC,CAAC;AAlCD,kCAkCC;AAGD,SAAS,KAAK,CAAC,GAAG,IAAI;IAClB,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,OAAO,GAAG,KAAK,WAAW,IAAI,GAAG,KAAK,IAAI,CAAC,CAAC;AACzE,CAAC;AACD,SAAS,QAAQ,CAAC,GAAG,IAAI,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,KAAK,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC;AAE3H,SAAS,cAAc,CAAC,wBAAwB;IAC5C,MAAM,CAAC,OAAO,CAAC,wBAAwB,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE;QAClE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC,KAAK,IAAI,qCAAqC,CAAC,CAAA;IACvG,CAAC,CAAC,CAAA;AACN,CAAC"}
package/package.json CHANGED
@@ -1,30 +1,39 @@
1
1
  {
2
2
  "name": "simple-file-templater",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "Simple templating system for file. Pattern replacer, file name replacer...",
5
- "main": "templater.js",
5
+ "main": "./dist/templater.js",
6
6
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1",
8
- "bump:major": "node node_modules/@cawita/bump-simple/bump-simple.js --major",
9
- "bump:minor": "node node_modules/@cawita/bump-simple/bump-simple.js --minor",
10
- "bump:patch": "node node_modules/@cawita/bump-simple/bump-simple.js --patch"
7
+ "build": "tsc",
8
+ "bump:major": "node node_modules/bump-simple/bump-simple.js --major",
9
+ "bump:minor": "node node_modules/bump-simple/bump-simple.js --minor",
10
+ "bump:patch": "node node_modules/bump-simple/bump-simple.js --patch"
11
11
  },
12
12
  "author": "538ROMEO",
13
13
  "license": "ISC",
14
14
  "repository": {
15
15
  "type": "git",
16
- "url": "git+https://gitlab.com/cawita-technologies/modules/templater.git"
16
+ "url": "git+https://github.com/top-kat/simple-file-templater.git"
17
17
  },
18
18
  "bugs": {
19
- "url": "https://gitlab.com/cawita-technologies/modules/templater/issues"
19
+ "url": "https://github.com/top-kat/simple-file-templater/issues"
20
20
  },
21
- "homepage": "https://gitlab.com/cawita-technologies/modules/templater#readme",
21
+ "homepage": "https://github.com/top-kat/simple-file-templater",
22
22
  "dependencies": {
23
- "topkat-utils": "^1.0.64",
24
23
  "fast-glob": "^3.0.4",
25
24
  "fs-extra": "^8.1.0"
26
25
  },
27
26
  "devDependencies": {
27
+ "@types/node": "^22.10.1",
28
28
  "bump-simple": "^1.0.0"
29
- }
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "files": [
34
+ "*.ts",
35
+ "model-types/*.ts",
36
+ "constants/*.ts",
37
+ "*"
38
+ ]
30
39
  }
@@ -1,25 +1,25 @@
1
- const fs = require('fs-extra');
2
- const path = require('path');
3
- const fg = require('fast-glob');
4
-
5
- module.exports = {
6
- templater,
7
- injector,
8
- fileToLines,
9
- };
10
-
11
- /**
12
- * @param {String} from absolute url of template (it can be a folder)
13
- * @param {String} to absolute url of folder/file to be copied (it can be a folder)
14
- * @param {Object|Array} replaceInFiles list of variables to interpolates
15
- * * {myVar : myReplacement}
16
- * * OR [[/myRegExp/g, 'myString'], ['myString1', 'myString2']...]
17
- * * DON'T forget the g flag when using regexps
18
- * @param {Object|Array} replaceInFileNames same as above but for fileNames (only valid when copying folders)
19
- * @param {RegExp[]} ignorePaths regexp array to check against path. Eg: /node_module/ <= file paths that includes the word node_module will not be taken in account
20
- * @return {Array} createdPaths
21
- */
22
- function templater(from, to, replaceInFiles = [], replaceInFileNames = [], ignorePaths = []) {
1
+ import fs from 'fs-extra'
2
+ import path from 'path'
3
+ import fg from 'fast-glob'
4
+
5
+
6
+ /** Get the content of a folder and move it with option to replace in files or in fileNames as you go */
7
+ export function templater(
8
+ /** absolute url of template (it can be a folder) */
9
+ from: string,
10
+ /** absolute url of folder/file to be copied (it can be a folder) */
11
+ to: string,
12
+ /** list of variables to interpolates
13
+ * * {myVar : myReplacement}
14
+ * * OR [[/myRegExp/g, 'myString'], ['myString1', 'myString2']...]
15
+ * * DON'T forget the g flag when using regexps
16
+ */
17
+ replaceInFiles = [],
18
+ /** same as above but for fileNames (only valid when copying folders) */
19
+ replaceInFileNames = [],
20
+ /** regexp array to check against path. Eg: /node_module/ <= file paths that includes the word node_module will not be taken in account */
21
+ ignorePaths = []
22
+ ) {
23
23
  try {
24
24
  err500IfNotSet({ from, to, varz: replaceInFiles })
25
25
 
@@ -29,8 +29,9 @@ function templater(from, to, replaceInFiles = [], replaceInFileNames = [], ignor
29
29
  if (isObject(replaceInFileNames)) replaceInFileNames = Object.entries(replaceInFileNames);
30
30
  replaceInFileNames.forEach(([toReplace, replacer], i, arr) => toReplace instanceof RegExp || (arr[i] = [new RegExp(toReplace, 'g'), replacer]));
31
31
 
32
- const createdPath = [];
33
- let files = [from];
32
+ const createdPath = [] as string[]
33
+
34
+ let files = [from]
34
35
  const templateIsDirectory = fs.statSync(from).isDirectory();
35
36
  // get directory structure
36
37
  if (templateIsDirectory) {
@@ -55,17 +56,20 @@ function templater(from, to, replaceInFiles = [], replaceInFileNames = [], ignor
55
56
  createdPath.push(newFileFullPath);
56
57
  }
57
58
 
58
- return createdPath;
59
+ return createdPath
59
60
  } catch (err) { console.error(err); }
60
61
  }
61
62
 
62
- /** Inject content into a file at specified place
63
- * @param {String} filePath url of the file where the content will be injected
64
- * @param {String} data
65
- * @param {Number|RegExp|String} after Number == lineNumber || RegExp == will replace the first matching group || String == will place content after the string
66
- * NOTE: don't forget **the g flag** for regexp if you want to match all occurences
67
- */
68
- function injector(filePath, data, after) {
63
+ /** Inject content into a file at specified place */
64
+ export function injector(
65
+ /** url of the file where the content will be injected */
66
+ filePath: string,
67
+ data: string,
68
+ /** Number == lineNumber || RegExp == will replace the first matching group || String == will place content after the string
69
+ * NOTE: don't forget **the g flag** for regexp if you want to match all occurences
70
+ */
71
+ after: number | string | RegExp
72
+ ) {
69
73
  try {
70
74
  err500IfNotSet({ filePath, data, after });
71
75
  if (!fs.existsSync(filePath)) throw 'file for injection do not exist';
@@ -89,13 +93,17 @@ function injector(filePath, data, after) {
89
93
  } catch (err) { console.error(err); }
90
94
  }
91
95
 
92
- /** Turns a file content into a list of lines
93
- * @param {String} filePath absolute path of file
94
- * @param {RegExp} regexp get only lines from the first matching group
95
- * @param {Boolean} ignoreInlineComments still count as a line; avoid conflicting with regexp, for ex if regexp match all inside \(.*\), and a comment with "// 1] blah" is found is in the middle
96
- * @return {array[]} [ [2, 'lineContentString' ], [3, 'line2']... ] lineNumber, content
97
- */
98
- function fileToLines(filePath, regexp, ignoreInlineComments = true, trim = true) {
96
+ /** Turns a file content into a list of lines */
97
+ export function fileToLines(
98
+ /** absolute path of file */
99
+ filePath: string,
100
+ /** get only lines from the first matching group */
101
+ regexp,
102
+ /** still count as a line; avoid conflicting with regexp, for ex if regexp match all inside \(.*\), and a comment with "// 1] blah" is found is in the middle */
103
+ ignoreInlineComments = true,
104
+ /** Will trime each line */
105
+ trim = true
106
+ ): [lineNumber: number, content: string][] {
99
107
  try {
100
108
  err500IfNotSet({ filePath });
101
109
  if (!fs.existsSync(filePath)) throw 'file for injection do not exist';
package/tsconfig.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2021",
4
+ "module": "CommonJS",
5
+ "lib": [
6
+ "es2021"
7
+ ],
8
+ "esModuleInterop": true,
9
+ "allowSyntheticDefaultImports": true,
10
+ "allowJs": false,
11
+ "skipLibCheck": true,
12
+ "resolveJsonModule": true,
13
+ "noImplicitAny": false,
14
+ "noImplicitThis": true,
15
+ "declaration": true,
16
+ "moduleResolution": "node",
17
+ "sourceMap": true,
18
+ "outDir": "dist",
19
+ // "baseUrl": "./",
20
+ "paths": {
21
+ "*": [
22
+ "./node_modules/*"
23
+ ],
24
+ "src/*": [
25
+ "./src/*"
26
+ ]
27
+ },
28
+ "types": [
29
+ "node"
30
+ ]
31
+ },
32
+ }