@sap/cds-dk
Version:
Command line client and development toolkit for the SAP Cloud Application Programming Model
62 lines (52 loc) • 1.8 kB
JavaScript
const { read, write, yaml: YAML } = require('../cds').utils
const JSONC = require('./jsonc');
// REVISIT: Consider merging with template util
module.exports = new class FsUtil {
constructor() {
this.copyRenderedJSON = this.copyRenderedJSON.bind(this)
this.copyRenderedYAML = this.copyRenderedYAML.bind(this)
}
async readYAML(src, project) {
let file
try {
file = await read(src, 'utf8')
} catch (e) {
if (e.code === 'ENOENT') return undefined
throw e
}
if (project) {
const Mustache = require('mustache')
const renderedFile = Mustache.render(file, project)
return YAML.parseDocument(renderedFile)
}
return YAML.parseDocument(file)
}
async writeYAML(dst, yaml) {
const content = YAML.stringify(yaml, { collectionStyle: 'block', lineWidth: 150, directives: false })
await write(content).to(dst)
}
async copyRenderedYAML(src, dst, project) {
const yaml = await this.readYAML(src, project)
await write(yaml.toString()).to(dst)
}
async readJSON(src, project) {
const file = await read(src, 'utf8')
if (project) {
const Mustache = require('mustache')
const renderedFile = Mustache.render(file, project)
return JSON.parse(renderedFile)
}
try {
return JSON.parse(file)
} catch (error) {
throw new Error(error.message + '\n' + file)
}
}
async readJSONC(src) {
return JSONC.parse(await read(src, 'utf8'))
}
async copyRenderedJSON(src, dst, project) {
const json = await this.readJSON(src, project)
await write(dst, json, { spaces: 2 })
}
}