Skip to content

Commit

Permalink
Fix #1
Browse files Browse the repository at this point in the history
  • Loading branch information
namnm committed Jul 15, 2021
1 parent 76033d7 commit cd626bc
Show file tree
Hide file tree
Showing 3 changed files with 1,058 additions and 158 deletions.
54 changes: 52 additions & 2 deletions lib/rules/sort-keys-fix.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,22 @@ module.exports = {
natual: natual ? 'natural ' : '',
},
fix(fixer) {
const nodeToBeMoved = findNode(node, isValidOrder)
if (nodeToBeMoved === node) {
return []
}
// Save sorted progress on each run
// Use source location as the identifier
const props0 = node.parent.properties
props0.__sortKeysData = props0.__sortKeysData || props0.map(n => getIdFromLoc(n.loc))
const data = props0.__sortKeysData
const id1 = getIdFromLoc(node.loc)
const id2 = getIdFromLoc(nodeToBeMoved.loc)
const i1 = data.indexOf(id1)
const i2 = data.indexOf(id2)
data[i1] = id2
data[i2] = id1
// Perform fixes
const fixes = []
const sourceCode = context.getSourceCode()
const moveProperty = (fromNode, toNode) => {
Expand All @@ -185,8 +201,8 @@ module.exports = {
}
fixes.push(fixer.replaceText(toNode, prevText))
}
moveProperty(node, prevNode)
moveProperty(prevNode, node)
moveProperty(node, nodeToBeMoved)
moveProperty(nodeToBeMoved, node)
return fixes
},
})
Expand All @@ -195,3 +211,37 @@ module.exports = {
}
},
}

const findNode = (node, isValidOrder) => {
// Restore sorting progress from the previous steps if any
const props0 = node.parent.properties
const props = props0.__sortKeysData
? props0.__sortKeysData.map(id => props0.find(p => id === getIdFromLoc(p.loc)))
: props0
// No spread operator, no need to split
if (!props.some(p => !p.key)) {
return findNodeWithProps(node, isValidOrder, props)
}
// Here need to split the props out at the spread operators
const parts = []
let part = []
props.forEach(p => {
if (p.key) {
part.push(p)
} else {
parts.push(part)
part = []
}
})
parts.push(part)
// Find the part which has node
const partHasNode = parts.find(p => p.includes(node))
return findNodeWithProps(node, isValidOrder, partHasNode)
}

const findNodeWithProps = (node, isValidOrder, props) => {
const sorted = [...props].sort((p1, p2) => (isValidOrder(getPropertyName(p1), getPropertyName(p2)) ? -1 : 1))
return props[sorted.indexOf(node)]
}

const getIdFromLoc = l => `l${l.start.line}c${l.start.column}-l${l.end.line}c${l.end.column}`
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"eslint-plugin-prettier": "^3.1.1",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"eslint-plugin-tyrecheck": "https://tycgitlab.tyrecheck.com/leonid.buneev/eslint-plugin-tyrecheck.git",
"eslint-plugin-tyrecheck": "^2.24.0",
"jest": "^25.4.0",
"prettier": "^1.19.1"
},
Expand Down
Loading

0 comments on commit cd626bc

Please sign in to comment.