@kaynooo/cli-view 0.7.7 → 0.9.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 +23 -14
- package/package.json +8 -4
- 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 +165 -0
package/src/code.ts
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import type { Theme } from './theme'
|
|
2
|
+
import { escapeControls } from '@kaynooo/cli-kit'
|
|
3
|
+
|
|
4
|
+
interface Language {
|
|
5
|
+
// What starts a comment that runs to the end of the line.
|
|
6
|
+
line: string[]
|
|
7
|
+
block?: [open: string, close: string]
|
|
8
|
+
quotes: string
|
|
9
|
+
keywords: Set<string>
|
|
10
|
+
// A name at the start of a line followed by the match, drawn as a key: a yaml mapping, a toml or ini setting.
|
|
11
|
+
key?: RegExp
|
|
12
|
+
// Whether the first word of a command, and a flag, are drawn as such: a shell.
|
|
13
|
+
commands?: boolean
|
|
14
|
+
// Whether a quoted string followed by a colon is a key.
|
|
15
|
+
quotedKeys?: boolean
|
|
16
|
+
// A whole line drawn as a heading, such as an ini or toml section.
|
|
17
|
+
section?: RegExp
|
|
18
|
+
// Whether keywords match regardless of case (SQL, Dockerfile).
|
|
19
|
+
caseInsensitive?: boolean
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const WORD_START = /[a-z_$]/i
|
|
23
|
+
const WORD = /^[\w$-]+/
|
|
24
|
+
const NUMBER = /^(?:0x[\da-f_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d+)?)/i
|
|
25
|
+
const PREVIOUS_WORD = /[\w$]$/
|
|
26
|
+
const AFTER_KEY = /^\s*:/
|
|
27
|
+
const YAML_KEY = /^(\s*(?:- )?)([\w.\-/]+)(?=:(?:\s|$))/
|
|
28
|
+
const SETTING_KEY = /^(\s*)([\w.-]+)(?=\s*[=:])/
|
|
29
|
+
const SECTION = /^\s*\[.*\]\s*$/
|
|
30
|
+
const WHITESPACE = /\s/
|
|
31
|
+
const FLAG = /^--?[a-z][\w-]*/i
|
|
32
|
+
const COMMAND_END = /[|&;(]\s*$/
|
|
33
|
+
const PROMPT = /^\s*(?:[$>]\s*)?$/
|
|
34
|
+
const DIGIT = /\d/
|
|
35
|
+
const TRAILING_NEWLINE = /\n$/
|
|
36
|
+
const LEADING_DOT = /^\./
|
|
37
|
+
const TRIPLE_QUOTES = ['"""', '\'\'\'']
|
|
38
|
+
|
|
39
|
+
function words(list: string): Set<string> {
|
|
40
|
+
return new Set(list.split(' '))
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const SLASHES: Pick<Language, 'line' | 'block'> = { line: ['//'], block: ['/*', '*/'] }
|
|
44
|
+
const HASH: Pick<Language, 'line'> = { line: ['#'] }
|
|
45
|
+
const CONSTANTS = 'true false null undefined NaN Infinity'
|
|
46
|
+
|
|
47
|
+
const C_LIKE = 'if else for while do switch case default break continue return throw try catch finally new delete typeof instanceof in of void yield await async static public private protected readonly abstract extends implements super this'
|
|
48
|
+
const SCRIPT = `${C_LIKE} const let var function class import export from as type interface enum namespace declare satisfies keyof is get set ${CONSTANTS}`
|
|
49
|
+
|
|
50
|
+
const LANGUAGES = {
|
|
51
|
+
script: { ...SLASHES, quotes: '"\'`', keywords: words(SCRIPT) },
|
|
52
|
+
json: { line: [], quotes: '"', keywords: words('true false null'), quotedKeys: true },
|
|
53
|
+
jsonc: { ...SLASHES, quotes: '"', keywords: words('true false null'), quotedKeys: true },
|
|
54
|
+
python: { ...HASH, quotes: '"\'', keywords: words('def class return if elif else for while in not and or is import from as with try except finally raise pass break continue lambda yield async await global nonlocal del assert None True False self') },
|
|
55
|
+
shell: { ...HASH, commands: true, quotes: '"\'`', keywords: words('if then else elif fi for while until do done case esac in function return exit local export set unset source alias echo cd end switch begin and or not') },
|
|
56
|
+
yaml: { ...HASH, quotes: '"\'', keywords: words('true false null yes no'), key: YAML_KEY, quotedKeys: true },
|
|
57
|
+
toml: { ...HASH, quotes: '"\'', keywords: words('true false'), key: SETTING_KEY, section: SECTION },
|
|
58
|
+
ini: { line: ['#', ';'], quotes: '"\'', keywords: words('true false yes no on off'), key: SETTING_KEY, section: SECTION },
|
|
59
|
+
css: { line: [], block: ['/*', '*/'], quotes: '"\'', keywords: words('important inherit initial unset auto none') },
|
|
60
|
+
html: { line: [], block: ['<!--', '-->'], quotes: '"\'', keywords: words('') },
|
|
61
|
+
sql: { line: ['--'], block: ['/*', '*/'], quotes: '"\'`', caseInsensitive: true, keywords: words('select from where and or not insert into values update set delete create alter drop table index view join left right inner outer full on group by order having limit offset as distinct union all null is in like between case when then else end primary key foreign references default unique with returning true false') },
|
|
62
|
+
rust: { ...SLASHES, quotes: '"', keywords: words('fn let mut const static struct enum impl trait pub use mod crate self super if else match for while loop break continue return as in ref move async await dyn where type unsafe true false None Some Ok Err') },
|
|
63
|
+
go: { ...SLASHES, quotes: '"\'`', keywords: words('func var const type struct interface map chan package import if else for range switch case default break continue return go defer select fallthrough goto nil true false') },
|
|
64
|
+
php: { ...SLASHES, line: ['//', '#'], quotes: '"\'', keywords: words(`${C_LIKE} function class interface trait namespace use public private protected static final echo array fn match list isset empty require include require_once include_once true false null`) },
|
|
65
|
+
java: { ...SLASHES, quotes: '"\'', keywords: words(`${C_LIKE} class interface enum package import final void int long double float boolean char byte short true false null var record`) },
|
|
66
|
+
c: { ...SLASHES, quotes: '"\'', keywords: words(`${C_LIKE} struct union typedef enum const volatile extern sizeof void int long double float char short unsigned signed auto register inline static include define ifdef ifndef endif pragma true false NULL nullptr class template typename namespace using bool`) },
|
|
67
|
+
ruby: { ...HASH, quotes: '"\'', keywords: words('def end class module if elsif else unless while until for in do begin rescue ensure return yield self nil true false and or not require require_relative include extend attr_accessor attr_reader puts then case when') },
|
|
68
|
+
lua: { line: ['--'], quotes: '"\'', keywords: words('function end if then else elseif for while do repeat until return local break in and or not nil true false') },
|
|
69
|
+
dockerfile: { ...HASH, quotes: '"\'', caseInsensitive: true, keywords: words('from run cmd label expose env add copy entrypoint volume user workdir arg onbuild stopsignal healthcheck shell as') },
|
|
70
|
+
makefile: { ...HASH, quotes: '"\'', keywords: words('ifeq ifneq ifdef ifndef else endif include define endef export') },
|
|
71
|
+
} satisfies Record<string, Language>
|
|
72
|
+
|
|
73
|
+
export type Name = keyof typeof LANGUAGES
|
|
74
|
+
|
|
75
|
+
// The extensions, file names and code block names each language goes by.
|
|
76
|
+
const ALIASES: Record<Name, string[]> = {
|
|
77
|
+
script: ['ts', 'tsx', 'mts', 'cts', 'js', 'jsx', 'mjs', 'cjs', 'typescript', 'javascript', 'vue', 'svelte'],
|
|
78
|
+
json: ['json', 'jsonl', 'ndjson'],
|
|
79
|
+
jsonc: ['jsonc', 'json5'],
|
|
80
|
+
python: ['py', 'python'],
|
|
81
|
+
shell: ['sh', 'bash', 'zsh', 'fish', 'shell', 'console'],
|
|
82
|
+
yaml: ['yml', 'yaml'],
|
|
83
|
+
toml: ['toml'],
|
|
84
|
+
ini: ['ini', 'conf', 'cfg', 'properties', 'editorconfig'],
|
|
85
|
+
css: ['css', 'scss', 'less'],
|
|
86
|
+
html: ['html', 'htm', 'xml', 'svg'],
|
|
87
|
+
sql: ['sql'],
|
|
88
|
+
rust: ['rs', 'rust'],
|
|
89
|
+
go: ['go', 'golang'],
|
|
90
|
+
php: ['php'],
|
|
91
|
+
java: ['java', 'kt', 'kts', 'cs', 'swift', 'dart', 'scala'],
|
|
92
|
+
c: ['c', 'h', 'cpp', 'cc', 'hpp', 'cxx'],
|
|
93
|
+
ruby: ['rb', 'ruby'],
|
|
94
|
+
lua: ['lua'],
|
|
95
|
+
dockerfile: ['dockerfile', 'containerfile'],
|
|
96
|
+
makefile: ['makefile', 'mk', 'just', 'justfile'],
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const BY_NAME = new Map(Object.entries(ALIASES).flatMap(([name, aliases]) => aliases.map(alias => [alias, name as Name])))
|
|
100
|
+
|
|
101
|
+
const EXTENSION = /\.([^./]+)$/
|
|
102
|
+
const BASENAME = /[^/]*$/
|
|
103
|
+
|
|
104
|
+
// The language a code block's info string or a file name stands for, undefined for one view does not know.
|
|
105
|
+
export function languageOf(nameOrPath: string): Name | undefined {
|
|
106
|
+
const base = (BASENAME.exec(nameOrPath)?.[0] ?? '').toLowerCase()
|
|
107
|
+
const extension = EXTENSION.exec(base)?.[1]
|
|
108
|
+
|
|
109
|
+
return BY_NAME.get(extension ?? base) ?? BY_NAME.get(base.replace(LEADING_DOT, ''))
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
type Paint = (text: string) => string
|
|
113
|
+
|
|
114
|
+
// A token painted a line at a time, so a colour never runs over the bar or the gutter in front of the next line.
|
|
115
|
+
function paintLines(text: string, paint: Paint): string {
|
|
116
|
+
return text.split('\n').map(line => line === '' ? line : paint(line)).join('\n')
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function stringEnd(source: string, start: number, quote: string): number {
|
|
120
|
+
const triple = TRIPLE_QUOTES.find(each => source.startsWith(each, start))
|
|
121
|
+
const multiline = quote === '`' || triple !== undefined
|
|
122
|
+
const closer = triple ?? quote
|
|
123
|
+
let at = start + closer.length
|
|
124
|
+
|
|
125
|
+
while (at < source.length) {
|
|
126
|
+
const char = source.charAt(at)
|
|
127
|
+
|
|
128
|
+
if (char === '\\') {
|
|
129
|
+
at += 2
|
|
130
|
+
}
|
|
131
|
+
else if (source.startsWith(closer, at)) {
|
|
132
|
+
return at + closer.length
|
|
133
|
+
}
|
|
134
|
+
else if (char === '\n' && !multiline) {
|
|
135
|
+
return at
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
at++
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return source.length
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// The line starts of a key, a setting or a section, drawn before the rest of the line is read as code.
|
|
146
|
+
function lineLead(line: string, language: Language, theme: Theme): { done: string, rest: string } {
|
|
147
|
+
if (language.section?.test(line) === true)
|
|
148
|
+
return { done: theme.heading(line), rest: '' }
|
|
149
|
+
|
|
150
|
+
const match = language.key?.exec(line)
|
|
151
|
+
|
|
152
|
+
if (match === null || match === undefined)
|
|
153
|
+
return { done: '', rest: line }
|
|
154
|
+
|
|
155
|
+
return { done: `${match[1] ?? ''}${theme.accent(match[2] ?? '')}`, rest: line.slice(match[0].length) }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// The source with comments, strings, numbers, keywords and keys in the roles of the other CLIs; text it does not recognise stays as it is.
|
|
159
|
+
export function highlight(source: string, name: Name, theme: Theme): string {
|
|
160
|
+
const language: Language = LANGUAGES[name]
|
|
161
|
+
const text = source.replaceAll('\r\n', '\n')
|
|
162
|
+
let out = ''
|
|
163
|
+
let at = 0
|
|
164
|
+
|
|
165
|
+
while (at < text.length) {
|
|
166
|
+
const lineStart = at === 0 || text.charAt(at - 1) === '\n'
|
|
167
|
+
|
|
168
|
+
if (lineStart && (language.key !== undefined || language.section !== undefined)) {
|
|
169
|
+
const lineEnd = text.indexOf('\n', at)
|
|
170
|
+
const line = text.slice(at, lineEnd === -1 ? text.length : lineEnd)
|
|
171
|
+
const { done, rest } = lineLead(line, language, theme)
|
|
172
|
+
|
|
173
|
+
if (done !== '') {
|
|
174
|
+
out += done
|
|
175
|
+
at += line.length - rest.length
|
|
176
|
+
|
|
177
|
+
continue
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const char = text.charAt(at)
|
|
182
|
+
const comment = language.line.find(each => text.startsWith(each, at))
|
|
183
|
+
|
|
184
|
+
if (comment !== undefined) {
|
|
185
|
+
const end = text.indexOf('\n', at)
|
|
186
|
+
const stop = end === -1 ? text.length : end
|
|
187
|
+
|
|
188
|
+
out += paintLines(text.slice(at, stop), theme.dim)
|
|
189
|
+
at = stop
|
|
190
|
+
}
|
|
191
|
+
else if (language.block !== undefined && text.startsWith(language.block[0], at)) {
|
|
192
|
+
const end = text.indexOf(language.block[1], at + language.block[0].length)
|
|
193
|
+
const stop = end === -1 ? text.length : end + language.block[1].length
|
|
194
|
+
|
|
195
|
+
out += paintLines(text.slice(at, stop), theme.dim)
|
|
196
|
+
at = stop
|
|
197
|
+
}
|
|
198
|
+
else if (language.quotes.includes(char)) {
|
|
199
|
+
const stop = stringEnd(text, at, char)
|
|
200
|
+
const isKey = language.quotedKeys === true && AFTER_KEY.test(text.slice(stop, !text.includes('\n', stop) ? undefined : text.indexOf('\n', stop)))
|
|
201
|
+
|
|
202
|
+
out += paintLines(text.slice(at, stop), isKey ? theme.accent : theme.string)
|
|
203
|
+
at = stop
|
|
204
|
+
}
|
|
205
|
+
else if (DIGIT.test(char) && !PREVIOUS_WORD.test(text.slice(Math.max(0, at - 1), at))) {
|
|
206
|
+
const number = NUMBER.exec(text.slice(at))?.[0] ?? char
|
|
207
|
+
|
|
208
|
+
out += theme.number(number)
|
|
209
|
+
at += number.length
|
|
210
|
+
}
|
|
211
|
+
else if (language.commands === true && char === '-' && (at === 0 || WHITESPACE.test(text.charAt(at - 1))) && FLAG.test(text.slice(at))) {
|
|
212
|
+
const flag = FLAG.exec(text.slice(at))?.[0] ?? char
|
|
213
|
+
|
|
214
|
+
out += theme.number(flag)
|
|
215
|
+
at += flag.length
|
|
216
|
+
}
|
|
217
|
+
else if (WORD_START.test(char)) {
|
|
218
|
+
const word = WORD.exec(text.slice(at))?.[0] ?? char
|
|
219
|
+
const before = text.slice(text.lastIndexOf('\n', at - 1) + 1, at)
|
|
220
|
+
const command = language.commands === true && (PROMPT.test(before) || COMMAND_END.test(before))
|
|
221
|
+
const lookup = language.caseInsensitive === true ? word.toLowerCase() : word
|
|
222
|
+
|
|
223
|
+
if (language.keywords.has(lookup))
|
|
224
|
+
out += theme.keyword(word)
|
|
225
|
+
else
|
|
226
|
+
out += command && !word.startsWith('$') ? theme.accent(word) : word
|
|
227
|
+
|
|
228
|
+
at += word.length
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
out += char
|
|
232
|
+
at++
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
return out
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// The code behind a gutter of line numbers on a terminal; a `lineNumbers` of false leaves it bare.
|
|
240
|
+
export function renderCode(source: string, name: Name | undefined, theme: Theme, lineNumbers: boolean, startLine = 1): string {
|
|
241
|
+
const text = escapeControls(source.replaceAll('\r\n', '\n')).replace(TRAILING_NEWLINE, '')
|
|
242
|
+
const shown = name === undefined ? text : highlight(text, name, theme)
|
|
243
|
+
|
|
244
|
+
if (!lineNumbers)
|
|
245
|
+
return `${shown}\n`
|
|
246
|
+
|
|
247
|
+
const lines = shown.split('\n')
|
|
248
|
+
const digits = String(startLine + lines.length - 1).length
|
|
249
|
+
|
|
250
|
+
return `${lines.map((line, index) => `${theme.dim(`${String(startLine + index).padStart(digits)} │`)} ${line}`.trimEnd()).join('\n')}\n`
|
|
251
|
+
}
|
package/src/diff.ts
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import type { Name } from './code'
|
|
2
|
+
import type { Theme } from './theme'
|
|
3
|
+
import { escapeControls, stripAnsi } from '@kaynooo/cli-kit'
|
|
4
|
+
import { highlight, languageOf } from './code'
|
|
5
|
+
|
|
6
|
+
const TRAILING_NEWLINE = /\n$/
|
|
7
|
+
const HUNK = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@(.*)$/
|
|
8
|
+
const FILE_HEADER = /^diff --git a\/(.*) b\/(.*)$/
|
|
9
|
+
const NEW_FILE = /^\+\+\+ (?:b\/)?([^\t]*)/
|
|
10
|
+
const COMMIT = /^(commit )([0-9a-f]{7,40})(.*)$/
|
|
11
|
+
const HUNK_LINE = new Set([' ', '+', '-', '\\'])
|
|
12
|
+
const MARKERS = /^(?:--- |\+\+\+ )/
|
|
13
|
+
// The colours git writes into a diff; any other escape sequence belongs to the content and is shown.
|
|
14
|
+
// eslint-disable-next-line no-control-regex -- escape sequences are what it matches
|
|
15
|
+
const GIT_COLOR = /\x1B\[[\d;]*m/g
|
|
16
|
+
const META = /^(?:index |old mode |new mode |deleted file mode |new file mode |similarity index |dissimilarity index |rename from |rename to |copy from |copy to |Binary files |GIT binary patch)/
|
|
17
|
+
const COMMIT_META = /^(?:Author|Date|Merge|AuthorDate|Commit|CommitDate):/
|
|
18
|
+
const TOKEN = /\w+|\s+|[^\w\s]/g
|
|
19
|
+
const WORD_CHAR = /\w/
|
|
20
|
+
// eslint-disable-next-line no-control-regex -- an escape sequence is what it splits
|
|
21
|
+
const ESCAPE = /\x1B\[([0-9;]*)m/g
|
|
22
|
+
// The SGR codes ending a style, for the pair of a colour or an emphasis.
|
|
23
|
+
const CLOSING = new Set(['0', '22', '23', '24', '27', '29', '39', '49'])
|
|
24
|
+
// A pair of lines longer than this in tokens is left as it is, the comparison being quadratic.
|
|
25
|
+
const MAX_TOKENS = 300
|
|
26
|
+
|
|
27
|
+
interface Content {
|
|
28
|
+
mark: '+' | '-'
|
|
29
|
+
text: string
|
|
30
|
+
language: Name | undefined
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Whether the text is a diff, a `git log -p` or a `git show`, by its first line.
|
|
34
|
+
export function looksLikeDiff(text: string): boolean {
|
|
35
|
+
const first = stripAnsi(text).split('\n').find(line => line.trim() !== '') ?? ''
|
|
36
|
+
|
|
37
|
+
return first.startsWith('diff --git ') || first.startsWith('--- ') || first.startsWith('@@ ') || first.startsWith('Index: ') || COMMIT.test(first)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Which characters of each text are not in the longest common run of tokens of the two, undefined when they share no word and so are not a edit of one another.
|
|
41
|
+
function changedChars(a: string, b: string): [boolean[], boolean[]] | undefined {
|
|
42
|
+
const left = a.match(TOKEN) ?? []
|
|
43
|
+
const right = b.match(TOKEN) ?? []
|
|
44
|
+
|
|
45
|
+
if (left.length > MAX_TOKENS || right.length > MAX_TOKENS)
|
|
46
|
+
return undefined
|
|
47
|
+
|
|
48
|
+
const common = Array.from({ length: left.length + 1 }, () => Array.from<number>({ length: right.length + 1 }).fill(0))
|
|
49
|
+
|
|
50
|
+
for (let i = left.length - 1; i >= 0; i--) {
|
|
51
|
+
for (let j = right.length - 1; j >= 0; j--)
|
|
52
|
+
common[i]![j] = left[i] === right[j] ? common[i + 1]![j + 1]! + 1 : Math.max(common[i + 1]![j]!, common[i]![j + 1]!)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const flags = (tokens: string[]): boolean[] => tokens.flatMap(token => Array.from<boolean>({ length: token.length }).fill(true))
|
|
56
|
+
const changedLeft = flags(left)
|
|
57
|
+
const changedRight = flags(right)
|
|
58
|
+
let shared = false
|
|
59
|
+
let i = 0
|
|
60
|
+
let j = 0
|
|
61
|
+
let at = 0
|
|
62
|
+
let to = 0
|
|
63
|
+
|
|
64
|
+
while (i < left.length && j < right.length) {
|
|
65
|
+
if (left[i] === right[j]) {
|
|
66
|
+
shared ||= WORD_CHAR.test(left[i]!)
|
|
67
|
+
changedLeft.fill(false, at, at + left[i]!.length)
|
|
68
|
+
changedRight.fill(false, to, to + right[j]!.length)
|
|
69
|
+
at += left[i]!.length
|
|
70
|
+
to += right[j]!.length
|
|
71
|
+
i++
|
|
72
|
+
j++
|
|
73
|
+
}
|
|
74
|
+
else if (common[i + 1]![j]! >= common[i]![j + 1]!) {
|
|
75
|
+
at += left[i++]!.length
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
to += right[j++]!.length
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return shared ? [changedLeft, changedRight] : undefined
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// The line coloured as an added or removed one, its code highlighted in the file's language and the changed characters emphasised; an uncoloured stretch keeps the line's colour.
|
|
86
|
+
function paintContent({ mark, text, language }: Content, theme: Theme, changed: boolean[] | undefined): string {
|
|
87
|
+
const tone = mark === '+' ? theme.added : theme.removed
|
|
88
|
+
const code = text.slice(1)
|
|
89
|
+
const source = language === undefined ? code : highlight(code, language, theme)
|
|
90
|
+
const cells: { char: string, style: string, changed: boolean }[] = [{ char: mark, style: '', changed: false }]
|
|
91
|
+
let style = ''
|
|
92
|
+
let from = 0
|
|
93
|
+
|
|
94
|
+
for (const escape of source.matchAll(ESCAPE)) {
|
|
95
|
+
for (const char of source.slice(from, escape.index).split(''))
|
|
96
|
+
cells.push({ char, style, changed: changed?.[cells.length - 1] ?? false })
|
|
97
|
+
|
|
98
|
+
style = CLOSING.has(escape[1]!) ? '' : style + escape[0]
|
|
99
|
+
from = escape.index + escape[0].length
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
for (const char of source.slice(from).split(''))
|
|
103
|
+
cells.push({ char, style, changed: changed?.[cells.length - 1] ?? false })
|
|
104
|
+
|
|
105
|
+
let out = ''
|
|
106
|
+
|
|
107
|
+
for (let at = 0; at < cells.length;) {
|
|
108
|
+
let end = at + 1
|
|
109
|
+
|
|
110
|
+
while (end < cells.length && cells[end]!.style === cells[at]!.style && cells[end]!.changed === cells[at]!.changed)
|
|
111
|
+
end++
|
|
112
|
+
|
|
113
|
+
const run = cells.slice(at, end).map(cell => cell.char).join('')
|
|
114
|
+
const shown = cells[at]!.style === '' ? tone(run) : `${cells[at]!.style}${run}\x1B[0m`
|
|
115
|
+
|
|
116
|
+
out += cells[at]!.changed ? theme.changed(shown) : shown
|
|
117
|
+
at = end
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return out
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// The diff coloured with the roles of the other CLIs: file names, hunk ranges, added and removed lines. A hunk's line counts tell its `--- ` content lines from the file headers.
|
|
124
|
+
export function renderDiff(text: string, theme: Theme): string {
|
|
125
|
+
let oldLeft = 0
|
|
126
|
+
let newLeft = 0
|
|
127
|
+
let language: Name | undefined
|
|
128
|
+
|
|
129
|
+
const lines = escapeControls(text.replace(GIT_COLOR, '').replaceAll('\r\n', '\n')).replace(TRAILING_NEWLINE, '').split('\n').map((line): string | Content => {
|
|
130
|
+
// A line that cannot belong to a hunk means its counts were off, so the rest is read as headers again.
|
|
131
|
+
if ((oldLeft > 0 || newLeft > 0) && line !== '' && !HUNK_LINE.has(line[0] ?? ''))
|
|
132
|
+
oldLeft = newLeft = 0
|
|
133
|
+
|
|
134
|
+
if (oldLeft > 0 || newLeft > 0) {
|
|
135
|
+
const mark = line[0]
|
|
136
|
+
|
|
137
|
+
if (mark === '+') {
|
|
138
|
+
newLeft--
|
|
139
|
+
|
|
140
|
+
return { mark, text: line, language }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (mark === '-') {
|
|
144
|
+
oldLeft--
|
|
145
|
+
|
|
146
|
+
return { mark, text: line, language }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (mark === '\\')
|
|
150
|
+
return theme.dim(line)
|
|
151
|
+
|
|
152
|
+
oldLeft--
|
|
153
|
+
newLeft--
|
|
154
|
+
|
|
155
|
+
return line
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const hunk = HUNK.exec(line)
|
|
159
|
+
|
|
160
|
+
if (hunk !== null) {
|
|
161
|
+
oldLeft = Number(hunk[1] ?? 1)
|
|
162
|
+
newLeft = Number(hunk[2] ?? 1)
|
|
163
|
+
|
|
164
|
+
return `${theme.accent(line.slice(0, line.length - (hunk[3] ?? '').length))}${theme.dim(hunk[3] ?? '')}`
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const file = FILE_HEADER.exec(line)
|
|
168
|
+
|
|
169
|
+
if (file !== null) {
|
|
170
|
+
language = languageOf(file[2] ?? '')
|
|
171
|
+
|
|
172
|
+
return `${theme.dim('diff')} ${theme.bold(theme.path(file[2] ?? ''))}`
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const commit = COMMIT.exec(line)
|
|
176
|
+
|
|
177
|
+
if (commit !== null)
|
|
178
|
+
return `${theme.dim(commit[1] ?? '')}${theme.id(commit[2] ?? '')}${theme.dim(commit[3] ?? '')}`
|
|
179
|
+
|
|
180
|
+
const target = NEW_FILE.exec(line)?.[1]
|
|
181
|
+
|
|
182
|
+
if (target !== undefined && target !== '/dev/null')
|
|
183
|
+
language = languageOf(target)
|
|
184
|
+
|
|
185
|
+
return MARKERS.test(line) || META.test(line) || COMMIT_META.test(line) ? theme.dim(line) : line
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
const changes = new Map<number, boolean[]>()
|
|
189
|
+
|
|
190
|
+
// A run of removed lines followed at once by a run of added ones: the first of each, the second of each..., are the same line edited.
|
|
191
|
+
for (let at = 0; at < lines.length;) {
|
|
192
|
+
const first = lines[at]
|
|
193
|
+
const isRemoved = typeof first === 'object' && first.mark === '-'
|
|
194
|
+
|
|
195
|
+
if (!isRemoved) {
|
|
196
|
+
at++
|
|
197
|
+
|
|
198
|
+
continue
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
let split = at
|
|
202
|
+
|
|
203
|
+
while (typeof lines[split] === 'object' && (lines[split] as Content).mark === '-')
|
|
204
|
+
split++
|
|
205
|
+
|
|
206
|
+
let end = split
|
|
207
|
+
|
|
208
|
+
while (typeof lines[end] === 'object' && (lines[end] as Content).mark === '+')
|
|
209
|
+
end++
|
|
210
|
+
|
|
211
|
+
for (let pair = 0; pair < Math.min(split - at, end - split); pair++) {
|
|
212
|
+
const flags = changedChars((lines[at + pair] as Content).text.slice(1), (lines[split + pair] as Content).text.slice(1))
|
|
213
|
+
|
|
214
|
+
if (flags !== undefined) {
|
|
215
|
+
changes.set(at + pair, flags[0])
|
|
216
|
+
changes.set(split + pair, flags[1])
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
at = Math.max(end, at + 1)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
return `${lines.map((line, index) => typeof line === 'string' ? line : paintContent(line, theme, changes.get(index))).join('\n')}\n`
|
|
224
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { highlight, languageOf, renderCode } from './code'
|
|
2
|
+
export type { Name } from './code'
|
|
3
|
+
export { looksLikeDiff, renderDiff } from './diff'
|
|
4
|
+
export { renderMarkdown } from './markdown'
|
|
5
|
+
export { themeFor } from './theme'
|
|
6
|
+
export type { Theme } from './theme'
|