@kaynooo/cli-view 0.7.6 → 0.8.0
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.
- package/dist/view.js +89 -1838
- package/package.json +9 -8
- package/src/code.ts +251 -0
- package/src/diff.ts +224 -0
- package/src/index.ts +6 -0
- package/src/markdown.ts +210 -0
- package/src/theme.ts +54 -0
- package/src/view.ts +202 -0
package/src/markdown.ts
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import type { Align } from '@kaynooo/cli-kit'
|
|
2
|
+
import type { Theme } from './theme'
|
|
3
|
+
import { stripAnsi, stripControls, textWidth } from '@kaynooo/cli-kit'
|
|
4
|
+
import { highlight, languageOf } from './code'
|
|
5
|
+
|
|
6
|
+
export interface RenderSettings {
|
|
7
|
+
theme: Theme
|
|
8
|
+
// Columns a line may take.
|
|
9
|
+
width: number
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// A line that holds text to wrap is `FIRST <prefix of its first line> REST <prefix of the others> BODY <text>`. Containers indent the lines they hold without knowing how far the text will reach, so the wrapping waits until the whole document is built.
|
|
13
|
+
const FIRST = '\u0001'
|
|
14
|
+
const REST = '\u0002'
|
|
15
|
+
const BODY = '\u0003'
|
|
16
|
+
// Starts a list nested in a list item, so the item can tell its own text from it.
|
|
17
|
+
const NESTED = '\u0005'
|
|
18
|
+
const CELL = '\u0006'
|
|
19
|
+
const ROW = '\u0007'
|
|
20
|
+
// Starts a block, so a tight list item can tell its text from the block that follows it.
|
|
21
|
+
const BLOCK = '\u0008'
|
|
22
|
+
|
|
23
|
+
const MAX_RULE = 60
|
|
24
|
+
// How far the rules around a code block reach at most, so a wide block does not stretch them across the screen.
|
|
25
|
+
const MAX_CODE_RULE = 12
|
|
26
|
+
const MIN_CODE_RULE = 8
|
|
27
|
+
// The shade of a heading by level along the gradient, the deeper ones toward its end.
|
|
28
|
+
const HEADING_SHADES = [0, 0.35, 0.7, 1]
|
|
29
|
+
const MIN_ROOM = 20
|
|
30
|
+
const MIN_COLUMN = 8
|
|
31
|
+
// How much wider than its average cell a column starts out.
|
|
32
|
+
const TYPICAL = 1.4
|
|
33
|
+
const COLUMN_GAP = 2
|
|
34
|
+
const TRAILING_BREAKS = /\n+$/
|
|
35
|
+
|
|
36
|
+
function block(text: string): string {
|
|
37
|
+
return `${BLOCK}${text}`
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function reflow(text: string, first = '', rest = ''): string {
|
|
41
|
+
return `${FIRST}${first}${REST}${rest}${BODY}${text}`
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function trimmed(block: string): string {
|
|
45
|
+
return block.replace(TRAILING_BREAKS, '')
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// `first` goes before the block's first line, `rest` before every other; a line to wrap carries them in its own prefixes.
|
|
49
|
+
function indent(block: string, first: string, rest: string): string {
|
|
50
|
+
return block.split('\n').map((line, index) => {
|
|
51
|
+
const lead = index === 0 ? first : rest
|
|
52
|
+
|
|
53
|
+
if (!line.startsWith(FIRST))
|
|
54
|
+
return `${lead}${line}`
|
|
55
|
+
|
|
56
|
+
const middle = line.indexOf(REST)
|
|
57
|
+
const body = line.indexOf(BODY)
|
|
58
|
+
|
|
59
|
+
return `${FIRST}${lead}${line.slice(1, middle)}${REST}${rest}${line.slice(middle + 1, body)}${BODY}${line.slice(body + 1)}`
|
|
60
|
+
}).join('\n')
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Wraps every line to wrap to `width`, each wrapped line behind its prefix.
|
|
64
|
+
function finish(block: string, width: number): string {
|
|
65
|
+
return block.split('\n').flatMap((line) => {
|
|
66
|
+
if (!line.startsWith(FIRST))
|
|
67
|
+
return [line.trimEnd()]
|
|
68
|
+
|
|
69
|
+
const middle = line.indexOf(REST)
|
|
70
|
+
const body = line.indexOf(BODY)
|
|
71
|
+
const first = line.slice(1, middle)
|
|
72
|
+
const rest = line.slice(middle + 1, body)
|
|
73
|
+
const room = Math.max(width - Math.max(textWidth(first), textWidth(rest)), MIN_ROOM)
|
|
74
|
+
|
|
75
|
+
return Bun.wrapAnsi(line.slice(body + 1), room).split('\n').map((wrapped, index) => `${index === 0 ? first : rest}${wrapped}`.trimEnd())
|
|
76
|
+
}).join('\n')
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// The columns' widths. A table that fits keeps each column as wide as its widest cell; otherwise a column starts at what its cells typically take, so one long cell wraps instead of widening its whole column, the room left goes to the columns with cells longer than that, and the widest are narrowed one character at a time if even the typical widths do not fit.
|
|
80
|
+
function columnWidths(rows: string[][], width: number): number[] {
|
|
81
|
+
const longest = rows[0]?.map((_, column) => Math.max(...rows.map(row => textWidth(row[column] ?? '')))) ?? []
|
|
82
|
+
const gaps = COLUMN_GAP * Math.max(0, longest.length - 1)
|
|
83
|
+
const sum = (list: number[]) => list.reduce((total, each) => total + each, 0)
|
|
84
|
+
|
|
85
|
+
if (sum(longest) + gaps <= width)
|
|
86
|
+
return longest
|
|
87
|
+
|
|
88
|
+
const typical = longest.map((most, column) => Math.min(most, Math.max(MIN_COLUMN, Math.ceil(TYPICAL * sum(rows.map(row => textWidth(row[column] ?? ''))) / rows.length))))
|
|
89
|
+
const widths = [...typical]
|
|
90
|
+
const room = width - gaps - sum(typical)
|
|
91
|
+
const wanting = longest.map((most, column) => most - typical[column]!)
|
|
92
|
+
|
|
93
|
+
if (room > 0 && sum(wanting) > 0) {
|
|
94
|
+
for (const [column, want] of wanting.entries())
|
|
95
|
+
widths[column]! += Math.min(want, Math.floor(room * want / sum(wanting)))
|
|
96
|
+
|
|
97
|
+
const left = width - gaps - sum(widths)
|
|
98
|
+
const hungriest = wanting.indexOf(Math.max(...wanting))
|
|
99
|
+
|
|
100
|
+
widths[hungriest]! += Math.max(0, Math.min(left, longest[hungriest]! - widths[hungriest]!))
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const total = () => sum(widths) + gaps
|
|
104
|
+
|
|
105
|
+
while (total() > width) {
|
|
106
|
+
const widest = widths.indexOf(Math.max(...widths))
|
|
107
|
+
|
|
108
|
+
if ((widths[widest] ?? 0) <= MIN_COLUMN)
|
|
109
|
+
break
|
|
110
|
+
|
|
111
|
+
widths[widest]!--
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return widths
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// A table with its cells wrapped inside their column, a rule under the header row.
|
|
118
|
+
function renderTable(rows: string[][], aligns: Align[], width: number, theme: Theme): string {
|
|
119
|
+
const widths = columnWidths(rows, width)
|
|
120
|
+
|
|
121
|
+
const wrapped = rows.map(row => widths.map((each, column) => Bun.wrapAnsi(row[column] ?? '', each, { hard: true }).split('\n')))
|
|
122
|
+
// A blank line between the rows once any of them wraps, so each stays one block; a table whose rows all fit on a line stays compact.
|
|
123
|
+
const spaced = wrapped.some(cells => cells.some(cell => cell.length > 1))
|
|
124
|
+
|
|
125
|
+
const lines = rows.flatMap((_, index) => {
|
|
126
|
+
const cells = wrapped[index]!
|
|
127
|
+
const height = Math.max(...cells.map(cell => cell.length))
|
|
128
|
+
|
|
129
|
+
const drawn = Array.from({ length: height }, (_, at) => cells.map((cell, column) => {
|
|
130
|
+
const text = cell[at] ?? ''
|
|
131
|
+
const gap = ' '.repeat(Math.max(0, (widths[column] ?? 0) - textWidth(text)))
|
|
132
|
+
const aligned = aligns[column] === 'right' ? `${gap}${text}` : `${text}${gap}`
|
|
133
|
+
|
|
134
|
+
return index === 0 ? theme.heading(aligned) : aligned
|
|
135
|
+
}).join(' '.repeat(COLUMN_GAP)).trimEnd())
|
|
136
|
+
|
|
137
|
+
if (index === 0)
|
|
138
|
+
return [...drawn, theme.dim('─'.repeat(Math.min(width, widths.reduce((sum, each) => sum + each, 0) + COLUMN_GAP * Math.max(0, widths.length - 1))))]
|
|
139
|
+
|
|
140
|
+
return spaced && index > 1 ? ['', ...drawn] : drawn
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
return lines.join('\n')
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// The text without terminal escapes or control characters that would act on the terminal or collide with the markers above; tabs and line breaks stay.
|
|
147
|
+
function printable(source: string): string {
|
|
148
|
+
return stripControls(stripAnsi(source.replaceAll('\r\n', '\n')))
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function renderMarkdown(source: string, { theme, width }: RenderSettings): string {
|
|
152
|
+
const quote = [`${theme.shade('❝', 0)} `, ' ']
|
|
153
|
+
let aligns: Align[] = []
|
|
154
|
+
|
|
155
|
+
const rendered = Bun.markdown.render(printable(source), {
|
|
156
|
+
heading: (children, { level }) => block(`${reflow(theme.shade(theme.bold(children), HEADING_SHADES[Math.min(level, HEADING_SHADES.length) - 1] ?? 1), theme.dim(`${'#'.repeat(level)} `), ' '.repeat(level + 1))}\n\n`),
|
|
157
|
+
paragraph: children => block(`${reflow(children.replaceAll('\n', ' '))}\n\n`),
|
|
158
|
+
strong: text => theme.shade(theme.bold(text), 0),
|
|
159
|
+
emphasis: theme.italic,
|
|
160
|
+
strikethrough: theme.strike,
|
|
161
|
+
codespan: text => `${theme.dim('`')}${theme.accent(text)}${theme.dim('`')}`,
|
|
162
|
+
link: (children, { href }) => theme.link(children, href),
|
|
163
|
+
image: (children, { src }) => theme.dim(`[image: ${children === '' ? src : children}]`),
|
|
164
|
+
html: children => block(`${theme.dim(trimmed(children))}\n\n`),
|
|
165
|
+
code: (children, meta) => {
|
|
166
|
+
const language = languageOf(meta?.language ?? '')
|
|
167
|
+
const body = trimmed(children)
|
|
168
|
+
const lines = (language === undefined ? body : highlight(body, language, theme)).split('\n')
|
|
169
|
+
const rule = Math.min(width, MAX_CODE_RULE, Math.max(MIN_CODE_RULE, ...lines.map(line => textWidth(line))))
|
|
170
|
+
const label = meta?.language === undefined || meta.language === '' ? '' : `${meta.language} `
|
|
171
|
+
|
|
172
|
+
return block(`${theme.dim(`${label}${'─'.repeat(Math.max(0, rule - textWidth(label)))}`)}\n${lines.join('\n')}\n${theme.dim('─'.repeat(rule))}\n\n`)
|
|
173
|
+
},
|
|
174
|
+
blockquote: children => block(`${indent(trimmed(children.replaceAll(BLOCK, '')), quote[0]!, quote[1]!)}\n\n`),
|
|
175
|
+
hr: () => block(`${theme.dim('─'.repeat(Math.min(width, MAX_RULE)))}\n\n`),
|
|
176
|
+
list: (children, { depth }) => depth > 0 ? `${NESTED}${trimmed(children)}\n\n` : block(`${trimmed(children)}\n\n`),
|
|
177
|
+
listItem: (children, { index, ordered, start, checked }) => {
|
|
178
|
+
const [head = '', ...nested] = children.split(NESTED)
|
|
179
|
+
const blocksAt = head.indexOf(BLOCK)
|
|
180
|
+
const inline = (blocksAt === -1 ? head : head.slice(0, blocksAt)).trim()
|
|
181
|
+
const blocks = blocksAt === -1 ? '' : trimmed(head.slice(blocksAt).replaceAll(BLOCK, ''))
|
|
182
|
+
const text = [inline === '' ? '' : reflow(inline.replaceAll('\n', ' ')), blocks].filter(part => part !== '').join('\n') || reflow('')
|
|
183
|
+
let marker = theme.dim('-')
|
|
184
|
+
|
|
185
|
+
if (checked !== undefined)
|
|
186
|
+
marker = checked ? theme.added('✓') : theme.dim('○')
|
|
187
|
+
else if (ordered)
|
|
188
|
+
marker = theme.dim(`${(start ?? 1) + index}.`)
|
|
189
|
+
|
|
190
|
+
return `${indent([text, ...nested.map(trimmed)].join('\n'), `${marker} `, ' '.repeat(textWidth(marker) + 1))}\n`
|
|
191
|
+
},
|
|
192
|
+
th: (children, meta) => {
|
|
193
|
+
aligns.push(meta?.align === 'right' ? 'right' : 'left')
|
|
194
|
+
|
|
195
|
+
return `${children}${CELL}`
|
|
196
|
+
},
|
|
197
|
+
td: children => `${children}${CELL}`,
|
|
198
|
+
tr: children => `${children}${ROW}`,
|
|
199
|
+
table: (children) => {
|
|
200
|
+
const rows = children.split(ROW).filter(row => row !== '').map(row => row.split(CELL).slice(0, -1))
|
|
201
|
+
const drawn = renderTable(rows, aligns, width, theme)
|
|
202
|
+
|
|
203
|
+
aligns = []
|
|
204
|
+
|
|
205
|
+
return block(`${drawn}\n\n`)
|
|
206
|
+
},
|
|
207
|
+
})
|
|
208
|
+
|
|
209
|
+
return `${finish(trimmed(rendered.replaceAll(BLOCK, '')), width)}\n`
|
|
210
|
+
}
|
package/src/theme.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { Colors } from '@kaynooo/cli-kit'
|
|
2
|
+
import process from 'node:process'
|
|
3
|
+
import { activeTheme, gradientAt, link, paint, role, takesControlCodes, tinted } from '@kaynooo/cli-kit'
|
|
4
|
+
|
|
5
|
+
// What each part of a document is drawn in, the roles every @kaynooo CLI colours its data with.
|
|
6
|
+
export interface Theme {
|
|
7
|
+
heading: (text: string) => string
|
|
8
|
+
code: (text: string) => string
|
|
9
|
+
path: (text: string) => string
|
|
10
|
+
id: (text: string) => string
|
|
11
|
+
dim: (text: string) => string
|
|
12
|
+
bold: (text: string) => string
|
|
13
|
+
italic: (text: string) => string
|
|
14
|
+
strike: (text: string) => string
|
|
15
|
+
added: (text: string) => string
|
|
16
|
+
removed: (text: string) => string
|
|
17
|
+
accent: (text: string) => string
|
|
18
|
+
keyword: (text: string) => string
|
|
19
|
+
string: (text: string) => string
|
|
20
|
+
number: (text: string) => string
|
|
21
|
+
link: (text: string, url: string) => string
|
|
22
|
+
// The text in the shade the kit's gradient has at `ratio`, 0 its first end and 1 its second, the accent where the theme has no gradient.
|
|
23
|
+
// The text in reverse video, the changed words of a line.
|
|
24
|
+
changed: (text: string) => string
|
|
25
|
+
shade: (text: string, ratio: number) => string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface Stream { isTTY?: boolean }
|
|
29
|
+
|
|
30
|
+
export function themeFor(stream: Stream = process.stdout, env: Record<string, string | undefined> = process.env): Theme {
|
|
31
|
+
const colors: Colors = paint(stream, env)
|
|
32
|
+
const accent = role('accent', stream, env)
|
|
33
|
+
const path = role('path', stream, env)
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
heading: text => accent(colors.bold(text)),
|
|
37
|
+
code: role('id', stream, env),
|
|
38
|
+
path,
|
|
39
|
+
id: role('id', stream, env),
|
|
40
|
+
dim: role('label', stream, env),
|
|
41
|
+
bold: colors.bold,
|
|
42
|
+
italic: colors.italic,
|
|
43
|
+
strike: colors.strikethrough,
|
|
44
|
+
changed: colors.inverse,
|
|
45
|
+
added: colors.green,
|
|
46
|
+
removed: colors.red,
|
|
47
|
+
accent,
|
|
48
|
+
keyword: colors.magenta,
|
|
49
|
+
string: colors.green,
|
|
50
|
+
number: colors.yellow,
|
|
51
|
+
link: (text, url) => path(colors.underline(link(text, url, stream, env))),
|
|
52
|
+
shade: (text, ratio) => takesControlCodes(stream, env) ? tinted(colors, gradientAt(activeTheme().theme, ratio) ?? activeTheme().theme.colors.accent, env)(text) : text,
|
|
53
|
+
}
|
|
54
|
+
}
|
package/src/view.ts
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
2
|
+
|
|
3
|
+
import type { ExitRow } from '@kaynooo/cli-kit'
|
|
4
|
+
import type { Name } from './code'
|
|
5
|
+
import type { Theme } from './theme'
|
|
6
|
+
import { existsSync } from 'node:fs'
|
|
7
|
+
import process from 'node:process'
|
|
8
|
+
import { badUsage, canPage, fail, isHumanTerminal, jsonOption, parse, printJson, readInput, runMain, stripAnsi, wholeNumber } from '@kaynooo/cli-kit'
|
|
9
|
+
import { languageOf, renderCode } from './code'
|
|
10
|
+
import { looksLikeDiff, renderDiff } from './diff'
|
|
11
|
+
import { renderMarkdown } from './markdown'
|
|
12
|
+
import { themeFor } from './theme'
|
|
13
|
+
|
|
14
|
+
const DEFAULT_WIDTH = 80
|
|
15
|
+
const MARKDOWN_FILE = /\.(?:md|markdown|mdx)$/i
|
|
16
|
+
const DIFF_FILE = /\.(?:diff|patch)$/i
|
|
17
|
+
const FILE_RANGE = /^(.+):(\d+)(?:-(\d*))?$/
|
|
18
|
+
const TRAILING_NEWLINE = /\n$/
|
|
19
|
+
|
|
20
|
+
const USAGE = `view [options] [file...]: shows markdown files, source files, plain text files or git diffs in the colours of the other @kaynooo CLIs
|
|
21
|
+
|
|
22
|
+
Files (each optionally with a line range such as src/a.ts:10-50), or what is piped on stdin (or - for stdin). A source file is highlighted behind line numbers by its extension or --lang, a diff, a \`git log -p\` or a \`git show\` is recognised by its first line or a .diff or .patch name, .md/.mdx/.markdown files (and stdin by default) are markdown, and unknown or .txt/.log files are shown as plain text preserving line breaks; --diff and --markdown force one.
|
|
23
|
+
Lines wrap to the terminal width and a long output on a terminal goes through $PAGER, unless --no-pager. No colour with NO_COLOR, a pipe or --plain. Control characters of the text, escape sequences included, show as cat -v writes them (^[) in code, text and diffs and are dropped from markdown, --json too.`
|
|
24
|
+
const EXITS: ExitRow[] = [[0, 'it showed the text'], [1, 'there is nothing to show'], [2, 'a usage error or a file that is missing']]
|
|
25
|
+
|
|
26
|
+
const OPTIONS = {
|
|
27
|
+
diff: { type: 'boolean', description: 'show the text as a diff' },
|
|
28
|
+
markdown: { type: 'boolean', description: 'show the text as markdown' },
|
|
29
|
+
lang: { type: 'string', short: 'l', description: 'show the text as code in this language (ts, json, yaml, sh...)' },
|
|
30
|
+
lines: { type: 'boolean', description: 'number the lines of code and text (--no-lines turns it off; on a terminal by default)' },
|
|
31
|
+
width: { type: 'string', short: 'w', description: 'columns to wrap to, instead of the terminal\'s' },
|
|
32
|
+
pager: { type: 'boolean', description: 'page a long output on a terminal (--no-pager turns it off)' },
|
|
33
|
+
json: jsonOption('{kind: code, diff, markdown or text, language, text} (or an array for multiple files), rendered without colour'),
|
|
34
|
+
} as const
|
|
35
|
+
|
|
36
|
+
interface FileSpec {
|
|
37
|
+
raw: string
|
|
38
|
+
path: string
|
|
39
|
+
start?: number
|
|
40
|
+
end?: number
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Parses `path:10-50`, `path:10`, or `path:10-`, leaving a literal path containing `:` intact when that file exists.
|
|
44
|
+
function parseSpec(raw: string): FileSpec {
|
|
45
|
+
if (raw === '-' || existsSync(raw))
|
|
46
|
+
return { raw, path: raw }
|
|
47
|
+
|
|
48
|
+
const match = FILE_RANGE.exec(raw)
|
|
49
|
+
|
|
50
|
+
if (match === null)
|
|
51
|
+
return { raw, path: raw }
|
|
52
|
+
|
|
53
|
+
const start = Number(match[2])
|
|
54
|
+
let end: number | undefined
|
|
55
|
+
|
|
56
|
+
if (match[3] === undefined)
|
|
57
|
+
end = start
|
|
58
|
+
else if (match[3] !== '')
|
|
59
|
+
end = Number(match[3])
|
|
60
|
+
|
|
61
|
+
if (start < 1 || (end !== undefined && end < start))
|
|
62
|
+
badUsage(`invalid line range in '${raw}'`)
|
|
63
|
+
|
|
64
|
+
return { raw, path: match[1]!, start, ...end === undefined ? {} : { end } }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function sliceRange(text: string, start: number | undefined, end: number | undefined): { text: string, startLine: number } {
|
|
68
|
+
if (start === undefined)
|
|
69
|
+
return { text, startLine: 1 }
|
|
70
|
+
|
|
71
|
+
const lines = text.replaceAll('\r\n', '\n').replace(TRAILING_NEWLINE, '').split('\n')
|
|
72
|
+
const slice = lines.slice(start - 1, end)
|
|
73
|
+
|
|
74
|
+
return { text: slice.length === 0 ? '' : `${slice.join('\n')}\n`, startLine: start }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// The width COLUMNS sets off a terminal, when it holds a usable one.
|
|
78
|
+
function columnsOf(variable: string | undefined): number {
|
|
79
|
+
const columns = Number(variable)
|
|
80
|
+
|
|
81
|
+
return Number.isInteger(columns) && columns >= 20 ? columns : DEFAULT_WIDTH
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// $PAGER through the shell, except a bare less, which needs -R for the colours and -F to quit on a short text.
|
|
85
|
+
function pagerCommand(pager = process.env.PAGER): string[] {
|
|
86
|
+
return pager === undefined || pager.trim() === '' || pager.trim() === 'less' ? ['less', '-FRX'] : ['sh', '-c', pager]
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// The text through the pager; a missing pager or one the reader quit leaves the text printed or dropped rather than failing.
|
|
90
|
+
async function page(text: string): Promise<void> {
|
|
91
|
+
try {
|
|
92
|
+
const pager = Bun.spawn(pagerCommand(), { stdin: 'pipe', stdout: 'inherit', stderr: 'inherit' })
|
|
93
|
+
|
|
94
|
+
try {
|
|
95
|
+
void pager.stdin.write(text)
|
|
96
|
+
await pager.stdin.end()
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
// The reader quit before the end.
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
await pager.exited
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
process.stdout.write(text)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
type Kind = 'code' | 'diff' | 'markdown' | 'text'
|
|
110
|
+
|
|
111
|
+
function detectKind(path: string, text: string, language: Name | undefined, forced: { diff: boolean, markdown: boolean, lang: boolean }): Kind {
|
|
112
|
+
if (forced.lang)
|
|
113
|
+
return 'code'
|
|
114
|
+
|
|
115
|
+
if (forced.diff)
|
|
116
|
+
return 'diff'
|
|
117
|
+
|
|
118
|
+
if (forced.markdown)
|
|
119
|
+
return 'markdown'
|
|
120
|
+
|
|
121
|
+
if (MARKDOWN_FILE.test(path))
|
|
122
|
+
return 'markdown'
|
|
123
|
+
|
|
124
|
+
if (DIFF_FILE.test(path) || looksLikeDiff(text))
|
|
125
|
+
return 'diff'
|
|
126
|
+
|
|
127
|
+
if (language !== undefined)
|
|
128
|
+
return 'code'
|
|
129
|
+
|
|
130
|
+
return path === '-' ? 'markdown' : 'text'
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function renderKind(kind: Kind, text: string, language: Name | undefined, theme: Theme, numbered: boolean, width: number, startLine: number): string {
|
|
134
|
+
if (kind === 'code')
|
|
135
|
+
return renderCode(text, language, theme, numbered, startLine)
|
|
136
|
+
|
|
137
|
+
if (kind === 'text')
|
|
138
|
+
return renderCode(text, undefined, theme, numbered, startLine)
|
|
139
|
+
|
|
140
|
+
return kind === 'diff' ? renderDiff(text, theme) : renderMarkdown(text, { theme, width })
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function main(args: string[]): Promise<number> {
|
|
144
|
+
const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, positionals: ['[file...]'], allowNegative: true, replaces: 'cat, bat or less on a markdown or source file, delta on a diff', examples: ['view README.md', 'view src/a.ts:10-40', 'view a.ts b.ts', 'git diff | view'] })
|
|
145
|
+
|
|
146
|
+
if (values.diff === true && values.markdown === true)
|
|
147
|
+
badUsage('--diff and --markdown exclude each other')
|
|
148
|
+
|
|
149
|
+
const forcedLanguage = values.lang === undefined ? undefined : languageOf(values.lang)
|
|
150
|
+
|
|
151
|
+
if (values.lang !== undefined && forcedLanguage === undefined)
|
|
152
|
+
badUsage(`unknown language ${values.lang}`)
|
|
153
|
+
|
|
154
|
+
const specs = (positionals.length === 0 ? ['-'] : positionals).map(parseSpec)
|
|
155
|
+
const human = isHumanTerminal(process.stdout)
|
|
156
|
+
const width = wholeNumber(values.width, 'width', human ? process.stdout.columns || DEFAULT_WIDTH : columnsOf(process.env.COLUMNS), 20)
|
|
157
|
+
const theme = themeFor(process.stdout)
|
|
158
|
+
const plainTheme = themeFor({ isTTY: false })
|
|
159
|
+
const forced = { diff: values.diff === true, markdown: values.markdown === true, lang: values.lang !== undefined }
|
|
160
|
+
const rendered: { spec: FileSpec, kind: Kind, language: Name | undefined, shown: string, plain: string }[] = []
|
|
161
|
+
|
|
162
|
+
for (const spec of specs) {
|
|
163
|
+
const raw = await readInput(spec.path, { noStdin: 'give a file, or pipe the text on stdin' })
|
|
164
|
+
const { text, startLine } = sliceRange(raw, spec.start, spec.end)
|
|
165
|
+
|
|
166
|
+
if (text.trim() === '')
|
|
167
|
+
fail('nothing to show', 1)
|
|
168
|
+
|
|
169
|
+
const language = forcedLanguage ?? (spec.path === '-' ? undefined : languageOf(spec.path))
|
|
170
|
+
const kind = detectKind(spec.path, text, language, forced)
|
|
171
|
+
const shown = renderKind(kind, text, language, theme, values.lines ?? human, width, startLine)
|
|
172
|
+
const plain = stripAnsi(renderKind(kind, text, language, plainTheme, values.lines ?? false, width, startLine))
|
|
173
|
+
|
|
174
|
+
rendered.push({ spec, kind, language, shown, plain })
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (values.json === true) {
|
|
178
|
+
if (rendered.length === 1) {
|
|
179
|
+
const [only] = rendered
|
|
180
|
+
|
|
181
|
+
printJson({ kind: only!.kind, language: only!.kind === 'code' ? only!.language ?? null : null, text: only!.plain })
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
printJson(rendered.map(item => ({ path: item.spec.raw, kind: item.kind, language: item.kind === 'code' ? item.language ?? null : null, text: item.plain })))
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return 0
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const output = rendered.length === 1
|
|
191
|
+
? rendered[0]!.shown
|
|
192
|
+
: rendered.map(item => `${theme.bold(theme.path(item.spec.raw))}\n${item.shown}`).join('\n')
|
|
193
|
+
|
|
194
|
+
if (canPage(process.stdout) && values.pager !== false && output.split('\n').length > (process.stdout.rows || 24))
|
|
195
|
+
await page(output)
|
|
196
|
+
else
|
|
197
|
+
process.stdout.write(output)
|
|
198
|
+
|
|
199
|
+
return 0
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
process.exitCode = await runMain({ name: 'view', run: main })
|