@lsbjordao/type-taxon-script 1.1.8 → 1.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,268 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.default = ttsExportToCsv;
16
+ const fs_1 = __importDefault(require("fs"));
17
+ const path_1 = __importDefault(require("path"));
18
+ const child_process_1 = require("child_process");
19
+ const csv_parser_1 = __importDefault(require("csv-parser"));
20
+ const plainjs_1 = require("@json2csv/plainjs");
21
+ const transforms_1 = require("@json2csv/transforms");
22
+ const cli_spinner_1 = require("cli-spinner");
23
+ function deleteJSFiles(folderPath) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ try {
26
+ const files = yield fs_1.default.promises.readdir(folderPath);
27
+ for (const file of files) {
28
+ if (file.endsWith('.js')) {
29
+ yield fs_1.default.promises.unlink(`${folderPath}/${file}`);
30
+ }
31
+ }
32
+ }
33
+ catch (err) {
34
+ console.error('Error deleting files:', err);
35
+ }
36
+ });
37
+ }
38
+ function ttsExportToCsv(genus, load) {
39
+ return __awaiter(this, void 0, void 0, function* () {
40
+ if (genus === '') {
41
+ console.error('\x1b[31m✖ Argument `--genus` cannot be empty.\x1b[0m');
42
+ return;
43
+ }
44
+ if (!fs_1.default.existsSync('./input') && !fs_1.default.existsSync('./output')) {
45
+ console.error("\x1b[31m✖ The ./input and ./output directories are not present within the project.\x1b[0m\n\x1b[36mℹ️ Please run \x1b[33m`tts init`\x1b[36m before attempting to export a database.\x1b[0m");
46
+ return;
47
+ }
48
+ const spinner = new cli_spinner_1.Spinner('\x1b[36mProcessing... %s\x1b[0m');
49
+ spinner.setSpinnerString('|/-\\'); // spinner sequence
50
+ spinner.start();
51
+ const taxa = [];
52
+ fs_1.default.mkdirSync('./temp', { recursive: true });
53
+ if (load === 'all') {
54
+ const directoryPath = `./taxon/${genus}/`;
55
+ fs_1.default.readdir(directoryPath, (err, files) => {
56
+ if (err) {
57
+ spinner.stop();
58
+ console.error('Error reading directory:', err);
59
+ process.exit();
60
+ }
61
+ const taxa = files
62
+ .filter(file => file.endsWith('.ts') && file !== 'index.ts')
63
+ .map(file => path_1.default.parse(file).name);
64
+ const importStatements = taxa.map((species) => {
65
+ return `import { ${species.replace(/\s/g, '_').replace(/\-([a-z])/, (_, match) => match.toUpperCase())} } from '../taxon/${genus}/${species.replace(/\s/g, '_')}'`;
66
+ }).join('\n');
67
+ const speciesCall = taxa.map((species) => {
68
+ return ` ${species.replace(/\s/g, '_').replace(/\-([a-z])/, (_, match) => match.toUpperCase())},`;
69
+ }).join('\n');
70
+ const fileContent = `// Import genus ${genus}
71
+ import { ${genus} } from '../taxon/${genus}'
72
+
73
+ // Import species of ${genus}
74
+ ${importStatements}
75
+
76
+ const ${genus}_species: ${genus}[] = [
77
+ ${speciesCall}
78
+ ]
79
+
80
+ // Export ${genus}DB.json
81
+ //import { writeFileSync } from 'fs'
82
+ const jsonData = JSON.stringify(${genus}_species);
83
+ console.log(jsonData)
84
+ //const inputFilePath = '../output/${genus}DB.json'
85
+ //writeFileSync(inputFilePath, jsonData, 'utf-8')
86
+ //console.log('\\x1b[1m\\x1b[32m✔ Process finished.\\x1b[0m')`;
87
+ const tempFilePath = './temp/exportTemp.ts';
88
+ fs_1.default.writeFileSync(tempFilePath, fileContent, 'utf-8');
89
+ const fileToTranspile = 'exportTemp';
90
+ (0, child_process_1.exec)(`tsc ./temp/${fileToTranspile}.ts`, (error, stdout, stderr) => {
91
+ if (stdout) {
92
+ spinner.stop();
93
+ console.error('\x1b[31m✖ TS Error:\x1b[0m\n\n' + `${stdout}`);
94
+ process.exit();
95
+ }
96
+ if (stderr) {
97
+ spinner.stop();
98
+ console.error('\x1b[31m✖ TS Error:\x1b[0m\n\n' + `${stderr}`);
99
+ process.exit();
100
+ }
101
+ try {
102
+ fs_1.default.unlinkSync(`./temp/${fileToTranspile}.ts`);
103
+ }
104
+ catch (err) {
105
+ spinner.stop();
106
+ console.error(`An error occurred while deleting the file: ${err}`);
107
+ process.exit();
108
+ }
109
+ (0, child_process_1.exec)(`node ./temp/${fileToTranspile}.js > ./output/${genus}DB.json`, (error, stdout, stderr) => {
110
+ // if (error) {
111
+ // spinner.stop()
112
+ // console.error('\x1b[31m✖ JS execution time error:\x1b[0m\n\n' + `${error.message}`)
113
+ // process.exit()
114
+ // }
115
+ if (stdout) {
116
+ spinner.stop();
117
+ console.error('\x1b[31m✖ JS execution time error:\x1b[0m\n\n' + `${stdout}`);
118
+ process.exit();
119
+ }
120
+ if (stderr) {
121
+ spinner.stop();
122
+ console.error('\x1b[31m✖ JS execution time error:\x1b[0m\n\n' + `${stderr}`);
123
+ process.exit();
124
+ }
125
+ deleteJSFiles(`./taxon/${genus}`).then(() => {
126
+ const filePath = './output/';
127
+ try {
128
+ const data = fs_1.default.readFileSync(`./output/${genus}DB.json`, 'utf8');
129
+ const opts = {
130
+ transforms: [
131
+ (0, transforms_1.flatten)({ separator: '.' })
132
+ ]
133
+ };
134
+ const parser = new plainjs_1.Parser(opts);
135
+ const csv = parser.parse(JSON.parse(data));
136
+ fs_1.default.writeFileSync(`./output/${genus}DB.csv`, csv);
137
+ }
138
+ catch (err) {
139
+ console.error('Error reading the file:', err);
140
+ }
141
+ console.log(`\x1b[1m\x1b[32m✔ CSV database exported: \x1b[33m${filePath}${genus}DB.csv\x1b[0m\x1b[1m\x1b[32m\x1b[0m`);
142
+ spinner.stop();
143
+ try {
144
+ fs_1.default.unlinkSync(`./temp/${fileToTranspile}.js`);
145
+ fs_1.default.rm('./temp', { recursive: true }, (err) => {
146
+ if (err) {
147
+ console.error('Error deleting directory:', err);
148
+ process.exit();
149
+ }
150
+ });
151
+ }
152
+ catch (err) {
153
+ console.error(`An error occurred while deleting the file: ${err}`);
154
+ process.exit();
155
+ }
156
+ });
157
+ });
158
+ });
159
+ });
160
+ }
161
+ if (load === 'csv') {
162
+ const inputFilePath = './input/taxaToExport.csv';
163
+ const tempFilePath = './temp/exportTemp.ts';
164
+ fs_1.default.createReadStream(inputFilePath)
165
+ .pipe((0, csv_parser_1.default)({ headers: false }))
166
+ .on('data', (data) => {
167
+ taxa.push(data['0']);
168
+ })
169
+ .on('end', () => __awaiter(this, void 0, void 0, function* () {
170
+ const importStatements = taxa.map((species) => {
171
+ return `import { ${species.replace(/\s/g, '_').replace(/\-([a-z])/, (_, match) => match.toUpperCase())} } from '../taxon/${genus}/${species.replace(/\s/g, '_')}'`;
172
+ }).join('\n');
173
+ const speciesCall = taxa.map((species) => {
174
+ return ` ${species.replace(/\s/g, '_').replace(/\-([a-z])/, (_, match) => match.toUpperCase())},`;
175
+ }).join('\n');
176
+ const fileContent = `// Import genus ${genus}
177
+ import { ${genus} } from '../taxon/${genus}'
178
+
179
+ // Import species of ${genus}
180
+ ${importStatements}
181
+
182
+ const ${genus}_species: ${genus}[] = [
183
+ ${speciesCall}
184
+ ]
185
+
186
+ // Export ${genus}DB.json
187
+ const jsonData = JSON.stringify(${genus}_species);
188
+ console.log(jsonData)
189
+ // import { writeFileSync } from 'fs'
190
+ // const jsonData = JSON.stringify(${genus}_species)
191
+ // const inputFilePath = '../output/${genus}DB.json'
192
+ // writeFileSync(inputFilePath, jsonData, 'utf-8')
193
+ // console.log('\\x1b[1m\\x1b[32m✔ Process finished.\\x1b[0m')`;
194
+ fs_1.default.writeFileSync(tempFilePath, fileContent, 'utf-8');
195
+ const fileToTranspile = 'exportTemp';
196
+ (0, child_process_1.exec)(`tsc ./temp/${fileToTranspile}.ts`, (error, stdout, stderr) => {
197
+ if (stdout) {
198
+ spinner.stop();
199
+ console.error('\x1b[31m✖ TS Error:\x1b[0m\n\n' + `${stdout}`);
200
+ process.exit();
201
+ }
202
+ if (stderr) {
203
+ spinner.stop();
204
+ console.error('\x1b[31m✖ TS Error:\x1b[0m\n\n' + `${stdout}`);
205
+ process.exit();
206
+ }
207
+ try {
208
+ fs_1.default.unlinkSync(`./temp/${fileToTranspile}.ts`);
209
+ }
210
+ catch (err) {
211
+ spinner.stop();
212
+ console.error(`An error occurred while deleting the file: ${err}`);
213
+ process.exit();
214
+ }
215
+ (0, child_process_1.exec)(`node ./temp/${fileToTranspile}.js > ./output/${genus}DB.json`, (error, stdout, stderr) => {
216
+ // if (error) {
217
+ // spinner.stop()
218
+ // console.error('\x1b[31m✖ JS execution time error:\x1b[0m\n\n' + `${error.message}`)
219
+ // process.exit()
220
+ // }
221
+ if (stdout) {
222
+ spinner.stop();
223
+ console.error('\x1b[31m✖ JS execution time error:\x1b[0m\n\n' + `${stdout}`);
224
+ process.exit();
225
+ }
226
+ if (stderr) {
227
+ spinner.stop();
228
+ console.error('\x1b[31m✖ JS execution time error:\x1b[0m\n\n' + `${stderr}`);
229
+ process.exit();
230
+ }
231
+ deleteJSFiles(`./taxon/${genus}`).then(() => {
232
+ const filePath = './output/';
233
+ try {
234
+ const data = fs_1.default.readFileSync(`./output/${genus}DB.json`, 'utf8');
235
+ const opts = {
236
+ transforms: [
237
+ (0, transforms_1.flatten)({ separator: '.' })
238
+ ]
239
+ };
240
+ const parser = new plainjs_1.Parser(opts);
241
+ const csv = parser.parse(JSON.parse(data));
242
+ fs_1.default.writeFileSync(`./output/${genus}DB.csv`, csv);
243
+ }
244
+ catch (err) {
245
+ console.error('Error reading the file:', err);
246
+ }
247
+ console.log(`\x1b[1m\x1b[32m✔ CSV database exported: \x1b[33m${filePath}${genus}DB.csv\x1b[0m\x1b[1m\x1b[32m\x1b[0m`);
248
+ spinner.stop();
249
+ try {
250
+ fs_1.default.unlinkSync(`./temp/${fileToTranspile}.js`);
251
+ fs_1.default.rm('./temp', { recursive: true }, (err) => {
252
+ if (err) {
253
+ console.error('Error deleting directory:', err);
254
+ process.exit();
255
+ }
256
+ });
257
+ }
258
+ catch (err) {
259
+ console.error(`An error occurred while deleting the file: ${err}`);
260
+ process.exit();
261
+ }
262
+ });
263
+ });
264
+ });
265
+ }));
266
+ }
267
+ });
268
+ }
@@ -0,0 +1,58 @@
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.default = ttsfindProperty;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const lodash_1 = __importDefault(require("lodash"));
9
+ function ttsfindProperty(property, genus) {
10
+ if (property === '') {
11
+ console.error('\x1b[31m✖ Argument `--property` cannot be empty.\x1b[0m');
12
+ return;
13
+ }
14
+ if (genus === '') {
15
+ console.error('\x1b[31m✖ Argument `--genus` cannot be empty.\x1b[0m');
16
+ return;
17
+ }
18
+ const filePath = `./output/${genus}DB.json`;
19
+ const propertyPathToFind = property;
20
+ fs_1.default.readFile(filePath, 'utf8', (err, data) => {
21
+ if (err) {
22
+ console.error('Error reading the file:', err);
23
+ return;
24
+ }
25
+ try {
26
+ const jsonData = JSON.parse(data);
27
+ const findPropertyPath = (obj, propertyPath, currentPath = []) => {
28
+ const paths = [];
29
+ const findPathsRecursively = (currentObj, path) => {
30
+ const lastKey = path[path.length - 1];
31
+ if (lodash_1.default.get(currentObj, propertyPath)) {
32
+ if (typeof lastKey !== 'number') {
33
+ paths.push(path.join('.'));
34
+ }
35
+ }
36
+ lodash_1.default.forEach(currentObj, (value, key) => {
37
+ if (lodash_1.default.isObject(value)) {
38
+ findPathsRecursively(value, [...path, key]);
39
+ }
40
+ });
41
+ };
42
+ findPathsRecursively(obj, currentPath);
43
+ return paths;
44
+ };
45
+ const resultIndicesAndPaths = jsonData.flatMap((item, index) => {
46
+ const paths = findPropertyPath(item, propertyPathToFind);
47
+ if (paths.length > 0) {
48
+ return { index, paths, specificEpithet: jsonData[index].specificEpithet };
49
+ }
50
+ return [];
51
+ });
52
+ console.log(`\x1b[36mℹ️ Indices and paths of objects with the property \x1b[33m${propertyPathToFind}\x1b[0m\x1b[36m:\n\n\x1b[0m`, resultIndicesAndPaths);
53
+ }
54
+ catch (jsonErr) {
55
+ console.error('Error parsing JSON:', jsonErr);
56
+ }
57
+ });
58
+ }
@@ -0,0 +1,98 @@
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.default = ttsImportFromCsv;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const csv_parser_1 = __importDefault(require("csv-parser"));
9
+ const mustache_1 = __importDefault(require("mustache"));
10
+ const mapColumns = {
11
+ 'specificEpithet': 'specificEpithet',
12
+ 'descriptionAuthorship': 'descriptionAuthorship',
13
+ 'leaf.bipinnate.pinnae.numberOfPairs.rarelyMin': 'leafBipinnatePinnaeNumberOfPairsRarelyMin',
14
+ 'leaf.bipinnate.pinnae.numberOfPairs.min': 'leafBipinnatePinnaeNumberOfPairsMin',
15
+ 'leaf.bipinnate.pinnae.numberOfPairs.max': 'leafBipinnatePinnaeNumberOfPairsMax',
16
+ 'leaf.bipinnate.pinnae.numberOfPairs.rarelyMax': 'leafBipinnatePinnaeNumberOfPairsRarelyMax',
17
+ 'leaf.bipinnate.pinnae.numberOfPairs.value': 'leafBipinnatePinnaeNumberOfPairsValue',
18
+ 'leaf.bipinnate.pinnae.leaflet.numberOfPairs.rarelyMin': 'leafBipinnatePinnaeLeafletNumberOfPairsRarelyMin',
19
+ 'leaf.bipinnate.pinnae.leaflet.numberOfPairs.min': 'leafBipinnatePinnaeLeafletNumberOfPairsMin',
20
+ 'leaf.bipinnate.pinnae.leaflet.numberOfPairs.max': 'leafBipinnatePinnaeLeafletNumberOfPairsMax',
21
+ 'leaf.bipinnate.pinnae.leaflet.numberOfPairs.rarelyMax': 'leafBipinnatePinnaeLeafletNumberOfPairsRarelyMax',
22
+ 'leaf.bipinnate.pinnae.leaflet.numberOfPairs.value': 'leafBipinnatePinnaeLeafletNumberOfPairsValue',
23
+ 'inflorescence.type': 'inflorescenceType',
24
+ 'inflorescence.shape': 'inflorescenceShape',
25
+ 'flower.merism': 'flowerMerism',
26
+ 'flower.numberWhorlsOfStamens': 'numberWhorlsOfStamens',
27
+ 'flower.calyx.shape': 'flowerCalyxShape',
28
+ 'flower.corolla.shape': 'flowerCorollaShape',
29
+ 'androecium.filaments.colour': 'androeciumFilamentsColour',
30
+ 'timestamp': 'timestamp'
31
+ };
32
+ let genusErrorShown = {};
33
+ function generateDescription(taxon, genus) {
34
+ try {
35
+ const template = fs_1.default.readFileSync(`./taxon/${genus}/${genus}_template.txt`, 'utf-8');
36
+ const outputDir = 'output/';
37
+ const context = {};
38
+ for (const column in mapColumns) {
39
+ const templateColumn = mapColumns[column];
40
+ if (taxon[column]) {
41
+ context[templateColumn] = taxon[column];
42
+ }
43
+ }
44
+ if (taxon['inflorescence.capitate'] === 'yes') {
45
+ context['capitateInflorescence'] = true;
46
+ }
47
+ if (taxon['inflorescence.spicate'] === 'yes') {
48
+ context['spicateInflorescence'] = true;
49
+ }
50
+ let sanitizeSpecificEpithet = taxon['specificEpithet'].replace(/\s/g, '_');
51
+ sanitizeSpecificEpithet = sanitizeSpecificEpithet.replace(/-(\w)/, function (match, p1) {
52
+ return p1.toUpperCase();
53
+ });
54
+ context['specificEpithet'] = sanitizeSpecificEpithet;
55
+ let output = mustache_1.default.render(template, context);
56
+ const specificEpithet = taxon['specificEpithet'];
57
+ const fileName = `${outputDir}${genus}_${specificEpithet.replace(/\s/g, '_')}.ts`;
58
+ // timestamp
59
+ output = output.replace('date:', `date: ` + Math.floor(Date.now() / 1000));
60
+ output = output
61
+ .replace(/'\[/g, '[')
62
+ .replace(/\]'/g, ']')
63
+ .replace(/'/g, '\'');
64
+ if (output.trim() !== '') {
65
+ fs_1.default.writeFileSync(fileName, output);
66
+ console.log(`\x1b[1m\x1b[32m✔ New script file: \x1b[0m\x1b[1m\x1b[33m./${fileName}\x1b[0m`);
67
+ }
68
+ }
69
+ catch (error) {
70
+ if (error.code === 'ENOENT') {
71
+ if (genus !== '' && !genusErrorShown[genus]) {
72
+ console.error(`\x1b[31m✖ A TTS project for genus \x1b[33m\x1b[3m${genus}\x1b[0m\x1b[31m has not been implemented yet.\x1b[0m`);
73
+ console.log('\x1b[36m + ℹ️ To create a new TTS project, visit:\x1b[0m');
74
+ console.log('\x1b[33m https://www.npmjs.com/package/typetaxonscript?activeTab=readme#creating-and-editing-a-genus-template.\x1b[0m');
75
+ genusErrorShown[genus] = true;
76
+ }
77
+ }
78
+ else {
79
+ console.error('An error occurred while reading the file:', error);
80
+ }
81
+ }
82
+ }
83
+ function ttsImportFromCsv(genus) {
84
+ if (genus === '') {
85
+ console.error('\x1b[31m✖ Argument `--genus` cannot be empty.\x1b[0m');
86
+ return;
87
+ }
88
+ fs_1.default.createReadStream('./input/importTaxa.csv')
89
+ .pipe((0, csv_parser_1.default)({ separator: ';' }))
90
+ .on('data', (taxon) => {
91
+ generateDescription(taxon, genus);
92
+ })
93
+ .on('end', () => {
94
+ if (!genusErrorShown[genus]) {
95
+ //console.log('\x1b[1m\x1b[32m✔ Process finished.\x1b[0m')
96
+ }
97
+ });
98
+ }
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.default = ttsInit;
37
+ const fs = __importStar(require("fs"));
38
+ const path = __importStar(require("path"));
39
+ function createInputCSVFiles() {
40
+ const inputDir = 'input';
41
+ if (!fs.existsSync(inputDir)) {
42
+ fs.mkdirSync(inputDir);
43
+ console.log('\x1b[36mℹ️ The', '\x1b[33m./input', '\x1b[36mdirectory has been created.\x1b[0m');
44
+ const taxaToExportContent = `Mimosa afranioi
45
+ Mimosa arenosa var arenosa
46
+ Mimosa aurivillus var calothamnos
47
+ Mimosa bimucronata
48
+ Mimosa blanchetii
49
+ Mimosa caesalpiniifolia
50
+ Mimosa campicola
51
+ Mimosa cordistipula
52
+ Mimosa cubatanensis
53
+ Mimosa debilis var debilis
54
+ Mimosa diplotricha var diplotricha
55
+ Mimosa dolens var dolens
56
+ Mimosa dryandroides var dryandroides
57
+ Mimosa elliptica`;
58
+ const importTaxaContent = `"specificEpithet";"leaf.bipinnate.pinnae.numberOfPairs.rarelyMin";"leaf.bipinnate.pinnae.numberOfPairs.min";"leaf.bipinnate.pinnae.numberOfPairs.max";"leaf.bipinnate.pinnae.numberOfPairs.rarelyMax";"leaf.bipinnate.pinnae.numberOfPairs.value";"leaf.bipinnate.pinnae.leaflet.numberOfPairs.rarelyMin";"leaf.bipinnate.pinnae.leaflet.numberOfPairs.min";"leaf.bipinnate.pinnae.leaflet.numberOfPairs.max";"leaf.bipinnate.pinnae.leaflet.numberOfPairs.rarelyMax";"leaf.bipinnate.pinnae.leaflet.numberOfPairs.value";"inflorescence.spicate";"inflorescence.capitate";"flower.merism";"flower.calyx.shape";"flower.corolla.shape";"flower.numberWhorlsOfStamens";"androecium.filaments.colour";"descriptionAuthorship"
59
+ "arenosa var arenosa";"";"4";"12";"";"";"";"12";"30";"";"";"yes";"";"['4-merous', '5-merous']";"campanulate";"turbinate";"diplostemonous";"withish";"June Doe"
60
+ "artemisiana";"";"7";"12";"";"";"";"15";"29";"";"";"yes";"";"4-merous";"campanulate";"campanulate";"diplostemonous";"withish";"June Doe"
61
+ "ceratonia var pseudo-obovata";"";"2";"4";"5";"";"";"2";"4";"5";"";"";"yes";"3-merous";"campanulate";"turbinate";"diplostemonous";"withish";"June Doe"`;
62
+ const taxaToExportPath = path.join(inputDir, 'taxaToExport.csv');
63
+ const importTaxaPath = path.join(inputDir, 'importTaxa.csv');
64
+ fs.writeFileSync(taxaToExportPath, taxaToExportContent);
65
+ fs.writeFileSync(importTaxaPath, importTaxaContent);
66
+ console.log('\x1b[36mℹ️ The', '\x1b[33m./input/importTaxa.csv', '\x1b[36mfile has been created.\x1b[0m');
67
+ console.log('\x1b[90m + This file is needed to execute the `import` command.\x1b[0m');
68
+ console.log('\x1b[90m + It is a simple headerless CSV with each taxon on a separate line/row.\x1b[0m');
69
+ console.log('\x1b[36mℹ️ The', '\x1b[33m./input/taxaToExport.csv', '\x1b[36mfile has been created.\x1b[0m');
70
+ console.log('\x1b[90m + This file is needed to execute argument `--load csv` of `export` command.\x1b[0m');
71
+ console.log('\x1b[90m + It is used to export a specific list of taxa instead of exporting all, which is the default setting.\x1b[0m');
72
+ }
73
+ }
74
+ function ttsInit() {
75
+ // Checking directories
76
+ fs.readdir('./', (err, dirs) => {
77
+ if (err) {
78
+ console.error('Error reading directories:', err);
79
+ return;
80
+ }
81
+ if (dirs.length === 0) {
82
+ console.error('\x1b[36mℹ️ The directory is empty. Please clone a TTS project first.\x1b[0m');
83
+ console.log('\x1b[36mℹ️ Please, visit:\x1b[0m');
84
+ console.log('\x1b[36m TypeTaxonScript package:', '\x1b[33mhttps://www.npmjs.com/package/@lsbjordao/type-taxon-script.\x1b[0m');
85
+ console.log('\x1b[36m TTS project (Mimosa):', '\x1b[33mhttps://github.com/lsbjordao/TTS-Mimosa.\x1b[0m');
86
+ return;
87
+ }
88
+ if (!dirs.includes('taxon') && !dirs.includes('character')) {
89
+ console.error('\x1b[36mℹ️ The directory does not contain a TTS project.\x1b[0m');
90
+ console.log('\x1b[36mℹ️ Please, visit:\x1b[0m');
91
+ console.log('\x1b[36m TypeTaxonScript package:', '\x1b[33mhttps://www.npmjs.com/package/@lsbjordao/type-taxon-script.\x1b[0m');
92
+ console.log('\x1b[36m TTS project (Mimosa):', '\x1b[33mhttps://github.com/lsbjordao/TTS-Mimosa.\x1b[0m');
93
+ return;
94
+ }
95
+ const requiredDirs = ['input', 'output', 'characters', 'taxon'];
96
+ const allRequiredDirsPresent = requiredDirs.every(dir => dirs.includes(dir));
97
+ if (allRequiredDirsPresent) {
98
+ console.error('\x1b[36mℹ️ The root directory is not clean. Look:\x1b[0m');
99
+ const listDirectoryTree = (dir, prefix = '') => {
100
+ const files = fs.readdirSync(dir);
101
+ files.forEach((file, index) => {
102
+ const filePath = path.join(dir, file);
103
+ const isDirectory = fs.statSync(filePath).isDirectory();
104
+ const isLast = index === files.length - 1;
105
+ console.log(`${prefix}${isLast ? '└──' : '├──'} ${file}`);
106
+ if (isDirectory) {
107
+ const nestedPrefix = `${prefix}${isLast ? ' ' : '│ '}`;
108
+ listDirectoryTree(filePath, nestedPrefix);
109
+ }
110
+ });
111
+ };
112
+ const excludedDirectories = ['node_modules', '.git', 'dist'];
113
+ const hasPreviousProject = (dir, prefix = '') => {
114
+ const files = fs.readdirSync(dir, { withFileTypes: true });
115
+ const directories = files
116
+ .filter(dirent => dirent.isDirectory() && !excludedDirectories.includes(dirent.name))
117
+ .map(dirent => dirent.name);
118
+ directories.forEach((directory, index) => {
119
+ const directoryPath = path.join(dir, directory);
120
+ const isLast = index === directories.length - 1;
121
+ console.log(`${prefix}${isLast ? '└──' : '├──'} ${directory}`);
122
+ const nestedPrefix = `${prefix}${isLast ? ' ' : '│ '}`;
123
+ hasPreviousProject(directoryPath, nestedPrefix);
124
+ });
125
+ };
126
+ hasPreviousProject('./');
127
+ console.error('\x1b[36mℹ️ A previous project is already found.\x1b[0m');
128
+ return;
129
+ }
130
+ else {
131
+ createInputCSVFiles();
132
+ const outputDir = 'output';
133
+ if (!fs.existsSync(outputDir)) {
134
+ fs.mkdirSync(outputDir);
135
+ const gitKeepFile = `${outputDir}/.gitkeep`;
136
+ fs.writeFileSync(gitKeepFile, '');
137
+ console.log('\x1b[36mℹ️ The', '\x1b[33m./output', '\x1b[36mdirectory has been created.\x1b[0m');
138
+ }
139
+ }
140
+ });
141
+ }
@@ -0,0 +1,47 @@
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.default = ttsNewDesc;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const mustache_1 = __importDefault(require("mustache"));
9
+ function ttsNewDesc(genus, species) {
10
+ try {
11
+ if (species === '') {
12
+ console.error('\x1b[31m✖ Argument `--species` cannot be empty.\x1b[0m');
13
+ return;
14
+ }
15
+ if (genus === '') {
16
+ console.error('\x1b[31m✖ Argument `--genus` cannot be empty.\x1b[0m');
17
+ return;
18
+ }
19
+ const outputDir = 'output/';
20
+ const templatePath = `./taxon/${genus}/${genus}_template.txt`;
21
+ if (!fs_1.default.existsSync(templatePath)) {
22
+ console.error(`\x1b[31m✖ A TTS project for genus \x1b[33m\x1b[3m${genus}\x1b[0m\x1b[31m has not been implemented yet.\x1b[0m`);
23
+ console.log('\x1b[36m + ℹ️ To create a new TTS project, visit:\x1b[0m');
24
+ console.log('\x1b[33m https://www.npmjs.com/package/typetaxonscript?activeTab=readme#creating-and-editing-a-genus-template.\x1b[0m');
25
+ return;
26
+ }
27
+ const template = fs_1.default.readFileSync(templatePath, 'utf-8');
28
+ let sanitizeSpecificEpithet = species.replace(/\s/g, '_');
29
+ sanitizeSpecificEpithet = sanitizeSpecificEpithet.replace(/-(\w)/, function (match, p1) {
30
+ return p1.toUpperCase();
31
+ });
32
+ const context = {
33
+ specificEpithet: sanitizeSpecificEpithet
34
+ };
35
+ let output = mustache_1.default.render(template, context);
36
+ const fileName = `${outputDir}${genus}_${species.replace(/\s/g, '_')}.ts`;
37
+ // timestamp
38
+ output = output.replace('date:', `date: ` + Math.floor(Date.now() / 1000));
39
+ if (output.trim() !== '') {
40
+ fs_1.default.writeFileSync(fileName, output);
41
+ console.log(`\x1b[1m\x1b[32m✔ New script file: \x1b[0m\x1b[1m\x1b[33m./${fileName}\x1b[0m`);
42
+ }
43
+ }
44
+ catch (error) {
45
+ console.error('An error occurred:', error);
46
+ }
47
+ }