-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs
292 lines (261 loc) · 7.21 KB
/
index.mjs
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import * as fs from 'fs/promises'
import { execSync } from 'child_process'
import { processInstructions } from './processInstructions.js'
import * as readline from 'node:readline/promises'
import path from 'path'
import crypto from 'crypto'
import { readJSON } from '@sanjo/read-json'
import { writeJSON } from '@sanjo/write-json'
import { existsSync as doesFileExist, read } from 'fs'
let filePath = process.argv[2]
let session = await loadSession()
const readLine = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
if (filePath) {
filePath = path.resolve(filePath)
const file = await createFileObject(filePath)
if (isSameFilePathAsInSession(file.path, session)) {
const isContinuingSession = await handleSessionContinuation()
if (!isContinuingSession) {
await startWithANewSession(file)
}
} else {
await startWithANewSession(file)
}
} else {
const isContinuingSession = await handleSessionContinuation()
if (!isContinuingSession) {
console.error('Please provide a path to a Markdown file.')
process.exit(1)
}
}
const fileContents = await fs.readFile(session.filePath, 'utf-8')
const actions = processInstructions(fileContents)
await saveSession(session)
while (session.action < actions.length) {
const action = actions[session.action]
if (action.type === 'instruction') {
console.log(action.instruction)
await readLine.question('Press enter to continue. ')
} else if (action.type === 'information') {
console.log(action.information)
} else if (action.type === 'instructionToWriteCodeInAFile') {
console.log(action.instruction)
const hasFileBeenCreated = await createFile(action.filePath)
if (hasFileBeenCreated) {
await readLine.question('Press enter to continue. ')
}
} else if (action.type === 'runCommand') {
await runCommand(action)
} else if (action.type === 'runCommands') {
await runCommands(action)
} else if (action.type === 'writeCode') {
await createFile(action.filePath, action.code)
}
session.action++
await saveSession(session)
}
await fs.rm(determineSessionFile())
process.exit(0)
async function startWithANewSession(file) {
session = await createNewSessionForFile(file)
printNewSession()
}
function printNewSession() {
console.log('Starting with a new session.')
}
async function createFile(filePath, content = null) {
let question = null
if (doesFileExist(filePath)) {
if (content) {
question = `Would you like me to overwrite the file "${filePath}" with the new code?`
}
} else {
question = `Would you like me to create the file "${filePath}"?`
}
if (question) {
return await askQuestion(readLine, question, [
{
text: 'y',
isDefault: true,
async handler() {
await fs.mkdir(path.dirname(filePath), { recursive: true })
await fs.writeFile(filePath, content ?? '', { encoding: 'utf-8' })
return true
},
},
{
text: 'n',
handler() {
return false
},
},
])
}
return false
}
async function createFileObject(filePath) {
const fileContents = await fs.readFile(filePath, 'utf-8')
return {
path: filePath,
contents: fileContents,
hash: crypto.createHash('md5').update(fileContents).digest('hex'),
}
}
async function loadSession() {
const sessionFilePath = determineSessionFile()
try {
return await readJSON(sessionFilePath)
} catch (error) {}
return createNewSession()
}
async function createNewSessionForFile(file) {
return {
filePath: file.path,
hash: file.hash,
action: 0,
}
}
async function handleSessionContinuation() {
let isContinuingSession
if (isValidSession(session)) {
let fileContents
try {
fileContents = await fs.readFile(session.filePath, 'utf-8')
} catch (error) {
if (error.code === 'ENOENT') {
return
} else {
throw error
}
}
const hash = crypto.createHash('md5').update(fileContents).digest('hex')
if (hash === session.hash) {
await askQuestion(
readLine,
`Would you like to continue the last session (file: "${
session.filePath
}", action: ${session.action + 1})?`,
[
{
text: 'y',
isDefault: true,
handler() {
isContinuingSession = true
},
},
{
text: 'n',
handler() {
isContinuingSession = false
},
},
]
)
}
}
return isContinuingSession
}
function isSameFilePathAsInSession(filePath, session) {
return session.filePath && session.filePath === filePath
}
async function askQuestion(readLine, question, answers) {
const answersText = `(${answers.map(convertAnswerToString).join('/')})`
const questionText = `${question} ${answersText}: `
let handler
do {
const answer = await readLine.question(questionText)
const answerLowerCase = answer.toLowerCase()
handler = answers.find(answer => {
return (
(answer.isDefault && answerLowerCase === '') ||
answerLowerCase === answer.text.toLowerCase()
)
}).handler
} while (!handler)
return await handler()
}
function convertAnswerToString(answer) {
let text = answer.text
if (answer.isDefault) {
text = `[${text}]`
}
return text
}
function isValidSession(session) {
return (
typeof session.filePath === 'string' &&
typeof session.hash === 'string' &&
typeof session.action === 'number' &&
doesFileExist(session.filePath)
)
}
function createNewSession() {
return {
filePath: null,
hash: null,
action: null,
}
}
async function saveSession(session) {
const sessionFilePath = determineSessionFile()
await fs.mkdir(path.dirname(sessionFilePath), { recursive: true })
await writeJSON(sessionFilePath, session)
}
async function runCommand(action) {
await runACommand(action.command, action.instruction)
}
async function runCommands(action) {
console.log(action.instruction)
for (const command of action.commands) {
await runACommand(command)
}
}
async function runACommand(command, instruction = null) {
let thereWasAnError
do {
if (instruction) {
console.log(instruction)
}
const answer = await readLine.question(
`Run \`${command}\` ([y]/n/alternative command): `
)
const answerLowerCase = answer.toLowerCase()
if (answerLowerCase === 'y' || answerLowerCase == '') {
try {
thereWasAnError = false
execSync(command, {
stdio: 'inherit',
})
} catch (error) {
thereWasAnError = true
}
} else if (answerLowerCase === 'n') {
continue
} else {
try {
thereWasAnError = false
execSync(answer, {
stdio: 'inherit',
})
} catch (error) {
thereWasAnError = true
}
}
} while (thereWasAnError)
}
function determineSettingsFolderPath() {
return path.join(
process.env.APPDATA ||
(process.platform === 'darwin'
? process.env.HOME + '/Library/Preferences'
: process.env.HOME + '/.local/share'),
'Sanjo',
'do-steps'
)
}
function determineSessionFile() {
return path.join(determineSettingsFolderPath(), 'session.json')
}