@hyperlane-xyz/utils
Version:
General utilities and types for the Hyperlane network
59 lines • 1.95 kB
JavaScript
import { mergeJson, readJson, writeJson } from './json.js';
import { mergeYaml, readYaml, writeYaml } from './yaml.js';
/**
* Resolves the file format based on filepath extension or explicit format.
*/
export function resolveFileFormat(filepath, format) {
if (!filepath) {
return format;
}
if (format === 'json' || filepath?.endsWith('.json')) {
return 'json';
}
if (format === 'yaml' ||
filepath?.endsWith('.yaml') ||
filepath?.endsWith('.yml')) {
return 'yaml';
}
return undefined;
}
/**
* Indents a multi-line string by the specified number of spaces.
*/
export function indentYamlOrJson(str, indentLevel) {
const indent = ' '.repeat(indentLevel);
return str
.split('\n')
.map((line) => indent + line)
.join('\n');
}
function resolveYamlOrJsonFn(filepath, jsonFn, yamlFn, format) {
const fileFormat = resolveFileFormat(filepath, format);
if (!fileFormat) {
throw new Error(`Invalid file format for ${filepath}`);
}
if (fileFormat === 'json') {
return jsonFn(filepath);
}
return yamlFn(filepath);
}
/**
* Reads and parses a YAML or JSON file based on extension or explicit format.
*/
export function readYamlOrJson(filepath, format) {
return resolveYamlOrJsonFn(filepath, (readJson), (readYaml), format);
}
/**
* Writes a value as YAML or JSON based on extension or explicit format.
*/
export function writeYamlOrJson(filepath, obj, format) {
resolveYamlOrJsonFn(filepath, (f) => writeJson(f, obj), (f) => writeYaml(f, obj), format);
}
/**
* Merges an object with existing file content and writes the result.
* Format is determined by extension or explicit format (defaults to yaml).
*/
export function mergeYamlOrJson(filepath, obj, format = 'yaml') {
resolveYamlOrJsonFn(filepath, (f) => mergeJson(f, obj), (f) => mergeYaml(f, obj), format);
}
//# sourceMappingURL=format.js.map