-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
150 lines (125 loc) · 4.38 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import child_process from 'child_process';
import fs from 'fs/promises';
import fsSync from 'fs';
import path from 'path';
import ts from 'typescript';
import inquirer from 'inquirer';
import inquirerFileTreeSelection from 'inquirer-file-tree-selection-prompt';
export const FILE_EXTS = ['.ts', '.tsx', '.js', '.jsx', '.mjs'];
export const pbcopy = data => {
const proc = child_process.spawn('pbcopy');
proc.stdin.write(data);
proc.stdin.end();
}
export const getAllFilesWithinDirectory = async (dir, extensions) => {
let results = [];
const items = await fs.readdir(dir);
for (const item of items) {
const itemPath = path.join(dir, item);
const stat = await fs.stat(itemPath);
if (stat.isFile() && extensions.includes(path.extname(item))) {
results.push(itemPath);
}
else if (stat.isDirectory()) {
results = results.concat(getAllFilesWithinDirectory(itemPath, extensions));
}
}
return results;
}
export const includeDirectoryFiles = async (files, extensions) => {
const data = await files.reduce(async (accuP, file) => {
const accu = await accuP;
const stat = await fs.stat(file);
if (stat.isFile()) {
accu.push(file);
} else if (stat.isDirectory()) {
const files = await getAllFilesWithinDirectory(file, extensions);
accu.push(...files);
}
return accu;
}, Promise.resolve([]));
return data;
};
export const getFilesContents = async files => {
const data = await files.reduce(async (accuPromise, file) => {
const accu = await accuPromise;
const contents = await fs.readFile(file, 'utf8');
accu[file] = contents;
return accu;
}, Promise.resolve({}));
return data;
};
export function compile(fileNames, options) {
const createdFiles = {};
const host = ts.createCompilerHost(options);
host.writeFile = (fileName, contents) => createdFiles[fileName] = contents;
const program = ts.createProgram(fileNames, options, host);
program.emit();
return createdFiles;
}
export const saveListToFile = async list => {
const filepath = path.resolve('./', 'codeContextTemp.log');
const fileHandle = await fs.open(filepath, 'w');
await fileHandle.writeFile(JSON.stringify(list));
await fileHandle.close();
};
export const loadListFromFile = async () => {
try {
const filepath = path.resolve('./', 'codeContextTemp.log');
const fileHandle = await fs.open(filepath, 'r');
const data = await fileHandle.readFile();
await fileHandle.close();
const parsedData = JSON.parse(data);
if (!parsedData.every(file => typeof file === 'string')) {
throw new Error('Invalid saved data');
}
return parsedData;
} catch (error) {
return [];
}
}
export const prepareCodeContext = async (directory, { clearHistory = false, returnJson = false, returnContents = false } = {}) => {
console.log('Using directory:', path.resolve(directory));
inquirer.registerPrompt('file-tree-selection', inquirerFileTreeSelection)
const initialList = clearHistory ? [] : await loadListFromFile();
const answers = await inquirer
.prompt([
{
type: 'file-tree-selection',
name: 'files',
root: directory,
onlyShowValid: true,
multiple: true,
default: initialList,
validate: file => FILE_EXTS.includes(path.extname(file)) || fsSync.lstatSync(file).isDirectory(),
transformer: file => path.relative(path.resolve(directory), file),
}
]);
await saveListToFile(answers.files);
const files = await includeDirectoryFiles(answers.files, FILE_EXTS);
console.log(`${returnContents ? 'Getting contents of' : 'Generating declarations for'} files:`);
files.forEach(file => console.log(` - ${path.relative(directory, file)}`));
const createdFiles = returnContents
? await getFilesContents(files)
: compile(files, {
allowJs: true,
declaration: true,
emitDeclarationOnly: true,
});
if (returnJson) {
const declarations = Object.entries(createdFiles).reduce((accu, [filePath, declaration]) => {
accu[path.relative(directory, filePath)] = declaration;
return accu;
}, {});
const declarationsString = JSON.stringify(declarations, null, 2);
pbcopy(declarationsString);
console.log('\nSuccess! Declarations copied to clipboard.');
return declarationsString;
}
const declarationsString = Object.entries(createdFiles)
.map(([filePath, declaration]) => `${path.relative(directory, filePath)}\n\`\`\`\n${declaration}\n\`\`\``)
.join('\n\n');
pbcopy(declarationsString);
console.log('\nSuccess! Declarations copied to clipboard.');
return declarationsString;
};