garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/src/lib/highlight.test.ts

raw

import {describe, expect, test} from 'bun:test'

import {code, shell, tokens} from '@/lib/highlight'

const kinds = (src: string) => shell(src).filter((t) => t.k !== 'text').map((t) => `${t.k}:${t.t}`)

describe('shell', () => {
    test('the command of each step, its flags, strings and operators', () => {
        expect(kinds(`find tiles -name '*.mvt' | xargs wc -c`)).toEqual([
            'cmd:find',
            'flag:-name',
            "str:'*.mvt'",
            'op:|',
            'cmd:xargs',
            'cmd:wc',
            'flag:-c',
        ])
    })

    test('variables, also inside double quotes, and VAR=x before the command', () => {
        // A plain string: a template literal would fill in ${T} itself.
        expect(kinds('RUST_LOG=debug cargo test -p "$CRATE" --release 2>&1 && echo "done in ${T}s"')).toEqual([
            'var:RUST_LOG',
            'cmd:cargo',
            'flag:-p',
            'str:"',
            'var:$CRATE',
            'str:"',
            'flag:--release',
            'op:2>&1',
            'op:&&',
            'cmd:echo',
            'str:"done in ',
            'var:${T}',
            'str:s"',
        ])
    })

    test('comments, keywords, and a command inside $( )', () => {
        expect(kinds(`for f in $(ls *.rs); do wc -l "$f"; done # count`)).toEqual([
            'kw:for',
            'kw:in',
            'op:$(',
            'cmd:ls',
            'op:)',
            'op:;',
            'kw:do',
            'cmd:wc',
            'flag:-l',
            'str:"',
            'var:$f',
            'str:"',
            'op:;',
            'kw:done',
            'com:# count',
        ])
    })

    test('a flag with a value keeps the value plain, and the text is all there', () => {
        const src = `sudo midas update --wait --src=~/code/midas\n  ls -la`
        // sudo runs the next word: that is the command too; a new line starts another.
        expect(kinds(src)).toEqual(['cmd:sudo', 'cmd:midas', 'flag:--wait', 'flag:--src', 'cmd:ls', 'flag:-la'])
        expect(shell(src).map((t) => t.t).join('')).toBe(src)
    })
})

describe('code', () => {
    test('rust: keywords, strings, comments, numbers', () => {
        const k = code(`let n = 42; // the answer\nfn f() -> &str { "hi" }`, 'rs').filter((t) => t.k !== 'text').map((t) => `${t.k}:${t.t}`)
        expect(k).toEqual(['kw:let', 'num:42', 'com:// the answer', 'kw:fn', 'str:"hi"'])
    })

    test('json keys apart from values', () => {
        const k = code(`{"a": "b", "n": 1, "ok": true}`, 'json').filter((t) => t.k !== 'text').map((t) => `${t.k}:${t.t}`)
        expect(k).toEqual(['key:"a"', 'str:"b"', 'key:"n"', 'num:1', 'key:"ok"', 'kw:true'])
    })

    test('an unknown language stays as it is', () => {
        expect(tokens('whatever <b>x</b>', 'cobol')).toEqual([{t: 'whatever <b>x</b>', k: 'text'}])
    })
})