-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
85 lines (81 loc) · 2.14 KB
/
cli.ts
File metadata and controls
85 lines (81 loc) · 2.14 KB
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
import { run } from './index'
import fs from 'fs'
const filename = process.argv[2]
if (!filename) {
console.log('Usage: node cli.js <filename>')
process.exit(1)
}
try {
const fileContent = fs.readFileSync(filename, 'utf8')
let [result, error] = run(filename, fileContent)
if (error) {
console.log(error.asString())
} else if (result !== null && result !== undefined) {
let shouldPrint = true
if (
result.constructor &&
result.constructor.name === 'ListValue' &&
Array.isArray(result.elements)
) {
const filtered = result.elements.filter(
(e: any) =>
e !== null &&
e !== undefined &&
!(
typeof e.asString === 'function' &&
(e.asString() === '' || e.asString() === '[]')
)
)
// Heuristic: if file content is a single line and starts with '[', treat as list literal
if (fileContent.trim().startsWith('[')) {
console.log(
'[' +
filtered
.map((e: any) =>
typeof e.asString === 'function'
? e.asString()
: String(e)
)
.join(', ') +
']'
)
shouldPrint = false
} else if (filtered.length > 0) {
const last = filtered[filtered.length - 1]
// If the last statement is a print statement, don't print its value again
const lines = fileContent
.trim()
.split(/\r?\n/)
.filter((l) => l.trim() !== '')
const lastLine = lines[lines.length - 1].trim()
if (/^print\s*\(/.test(lastLine)) {
shouldPrint = false
}
if (shouldPrint) {
if (last && typeof last.asString === 'function') {
console.log(last.asString())
} else {
console.log(last)
}
}
shouldPrint = false
}
} else if (
typeof result.asString === 'function' &&
result.asString() !== '' &&
result.asString() !== '[]'
) {
// If the file is a single print statement, don't print again
const lines = fileContent
.trim()
.split(/\r?\n/)
.filter((l) => l.trim() !== '')
const lastLine = lines[lines.length - 1].trim()
if (!/^print\s*\(/.test(lastLine)) {
console.log(result.asString())
}
}
}
} catch (err) {
console.log(`Error reading file: ${(err as Error).message}`)
}