mirror of
https://github.com/harttle/liquidjs.git
synced 2026-09-18 22:10:41 -07:00
feat: support in-memory template mapping, inspired by @jg-rp #714
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
import { MapFS } from './map-fs'
|
||||
|
||||
describe('MapFS', () => {
|
||||
const fs = new MapFS({})
|
||||
it('should resolve relative file paths', () => {
|
||||
expect(fs.resolve('foo/bar', 'coo', '')).toEqual('foo/bar/coo')
|
||||
})
|
||||
it('should resolve to parent', () => {
|
||||
expect(fs.resolve('foo/bar', '../coo', '')).toEqual('foo/coo')
|
||||
})
|
||||
it('should resolve to root', () => {
|
||||
expect(fs.resolve('foo/bar', '../../coo', '')).toEqual('coo')
|
||||
})
|
||||
it('should resolve exceeding root', () => {
|
||||
expect(fs.resolve('foo/bar', '../../../coo', '')).toEqual('coo')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
import { isNil } from '../util'
|
||||
|
||||
export class MapFS {
|
||||
constructor (private mapping: {[key: string]: string}) {}
|
||||
|
||||
public sep = '/'
|
||||
|
||||
async exists (filepath: string) {
|
||||
return this.existsSync(filepath)
|
||||
}
|
||||
|
||||
existsSync (filepath: string) {
|
||||
return !isNil(this.mapping[filepath])
|
||||
}
|
||||
|
||||
async readFile (filepath: string) {
|
||||
return this.readFileSync(filepath)
|
||||
}
|
||||
|
||||
readFileSync (filepath: string) {
|
||||
const content = this.mapping[filepath]
|
||||
if (isNil(content)) throw new Error(`ENOENT: ${filepath}`)
|
||||
return content
|
||||
}
|
||||
|
||||
dirname (filepath: string) {
|
||||
const segments = filepath.split(this.sep)
|
||||
segments.pop()
|
||||
return segments.join(this.sep)
|
||||
}
|
||||
|
||||
resolve (dir: string, file: string, ext: string) {
|
||||
file += ext
|
||||
if (dir === '.') return file
|
||||
const segments = dir.split(this.sep)
|
||||
for (const segment of file.split(this.sep)) {
|
||||
if (segment === '.' || segment === '') continue
|
||||
else if (segment === '..') segments.pop()
|
||||
else segments.push(segment)
|
||||
}
|
||||
return segments.join(this.sep)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user