serverless/lib/utils/fs/parse.js
Austen 158f644cd0
feat: Refactor logging to reduce complexity (#12432)
* chore: Change logger

* chore: continue refactor

* chore: WIP

* chore: Sync
2024-04-17 13:26:31 -07:00

39 lines
1.0 KiB
JavaScript

import jc from 'json-cycle';
import yaml from 'js-yaml';
import _ from 'lodash';
import cloudformationSchema from '@serverless/utils/cloudformation-schema.js';
const loadYaml = (contents, options) => {
let data;
let error;
try {
data = yaml.load(contents.toString(), options || {});
} catch (exception) {
error = exception;
}
return { data, error };
};
function parse(filePath, contents) {
// Auto-parse JSON
if (filePath.endsWith('.json') || filePath.endsWith('.tfstate')) {
return jc.parse(contents);
} else if (filePath.endsWith('.yml') || filePath.endsWith('.yaml')) {
const options = {
filename: filePath,
};
let result = loadYaml(contents.toString(), options);
if (result.error && result.error.name === 'YAMLException') {
_.merge(options, { schema: cloudformationSchema });
result = loadYaml(contents.toString(), options);
}
if (result.error) {
throw result.error;
}
return result.data;
}
return contents.toString().trim();
}
export default parse;