sortier
Version:
An opinionated code sorter
81 lines (80 loc) • 3.15 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.sortAttributes = sortAttributes;
const sort_utils_js_1 = require("../../utilities/sort-utils.js");
const string_utils_js_1 = require("../../utilities/string-utils.js");
function sortAttributes(node, fileContents) {
// No-op scenarios
if (node == null || node.attrs == null) {
return fileContents;
}
const attrs = node.attrs;
if (attrs.length <= 1) {
return fileContents;
}
// Split attributes into context blocks
const contextBarrierIndices = string_utils_js_1.StringUtils.getBlankLineLocations(fileContents, node.sourceSpan.start.offset, node.sourceSpan.end.offset);
const attributeInfos = attrs.map((value) => {
const startOffset = value.sourceSpan.start.offset;
const endOffset = value.sourceSpan.end.offset;
const result = {
endOffset,
source: fileContents.substring(startOffset, endOffset),
startOffset,
};
return result;
});
const groupedAttributes = [];
let currentGroup = [];
while (0 < contextBarrierIndices.length) {
const barrierIndex = contextBarrierIndices.shift();
if (barrierIndex == null) {
break;
}
while (0 < attributeInfos.length) {
const attributeInfo = attributeInfos.shift();
if (attributeInfo == null) {
break;
}
if (attributeInfo.startOffset > barrierIndex) {
if (currentGroup.length !== 0) {
groupedAttributes.push(currentGroup);
currentGroup = [];
}
}
currentGroup.push(attributeInfo);
}
}
if (currentGroup.length !== 0) {
groupedAttributes.push(currentGroup);
}
if (attributeInfos.length !== 0) {
groupedAttributes.push(attributeInfos);
}
// Actual sorting
let newFileContents = fileContents;
for (const group of groupedAttributes) {
const newOrder = group.slice();
newOrder.sort((a, b) => {
return (0, sort_utils_js_1.compare)(a.source, b.source);
});
newFileContents = reorderValues(newFileContents, group, newOrder);
}
return newFileContents;
}
function reorderValues(fileContents, unsortedTypes, sortedTypes) {
if (unsortedTypes.length !== sortedTypes.length) {
throw new Error("Sortier ran into a problem - Expected the same number of unsorted types and sorted types to be provided");
}
let offsetCorrection = 0;
let newFileContents = fileContents.slice();
for (let x = 0; x < unsortedTypes.length; x++) {
const unsorted = unsortedTypes[x];
const sorted = sortedTypes[x];
const beginning = newFileContents.slice(0, unsorted.startOffset + offsetCorrection);
const end = newFileContents.slice(unsorted.endOffset + offsetCorrection);
newFileContents = beginning + sorted.source + end;
offsetCorrection += sorted.source.length - (unsorted.endOffset - unsorted.startOffset);
}
return newFileContents;
}