Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove trailing spaces and empty contexts from yaml #71

Merged
merged 2 commits into from
Jul 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 43 additions & 2 deletions src/utils/yamlConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,49 @@ function removeNullValues(obj: unknown): unknown {
return obj === null ? '' : obj;
}

// If the Context field is empty, omit the key from the output
function filterEmptyContext(data: unknown): unknown {
if (Array.isArray(data)) {
return data.map((item) => filterEmptyContext(item));
} else if (data !== null && typeof data === 'object') {
const filteredEntries = Object.entries(data)
.map(([key, value]) => {
if (key === 'context' && value === '') {
return null;
}
return [key, filterEmptyContext(value)];
})
.filter((entry): entry is [string, unknown] => entry !== null);
return Object.fromEntries(filteredEntries);
}
return data;
}

function trimTrailingSpaces(yamlString: string): string {
const hasTrailingNewline = yamlString.endsWith('\n');
const lines = yamlString.split('\n');
const trimmedLines = lines.map((line, index) => {
if (index === lines.length - 1 && line === '' && hasTrailingNewline) {
return line;
}
// Preserve empty lines
if (line.trim() === '') return '';
// Trim trailing spaces, preserving indentation
const match = line.match(/^(\s*)(.*)$/);
if (match) {
const [, indent, content] = match;
return indent + content.trimEnd();
}
return line;
});

return trimmedLines.join('\n');
}

export function dumpYaml(data: unknown, options: Partial<YamlDumpOptions> = {}): string {
const mergedOptions: YamlDumpOptions = { ...defaultYamlDumpOptions, ...options };
const processedData = removeNullValues(data);
return yaml.dump(processedData, mergedOptions);
const filteredData = filterEmptyContext(data);
const processedData = removeNullValues(filteredData);
const yamlString = yaml.dump(processedData, mergedOptions);
return trimTrailingSpaces(yamlString);
}