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

feat: keep comment-hack keys above preceding key #211

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
59 changes: 48 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,15 @@ const uniqAndSortArray = pipe([uniq, sortArray])
const onObject = (fn) => (x) => (isPlainObject(x) ? fn(x) : x)
const sortObjectBy = (comparator, deep) => {
const over = onObject((object) => {
object = sortObjectKeys(object, comparator)
const [keys, comments, trailing] = removeAndGatherComments(
Object.keys(object),
isCommentKey,
)
const sortFn = typeof comparator === 'function' ? comparator : undefined
const sortOrder = ((!sortFn && comparator) || [])
.concat(keys.sort(sortFn), trailing)
.reduce((result, key) => result.concat(comments[key] || [], key), [])
object = sortObjectKeys(object, sortOrder)
if (deep) {
for (const [key, value] of Object.entries(object)) {
object[key] = over(value)
Expand Down Expand Up @@ -132,7 +140,10 @@ const defaultNpmScripts = new Set([
])

const sortScripts = onObject((scripts) => {
const names = Object.keys(scripts)
const [names, comments, trailing] = removeAndGatherComments(
Object.keys(scripts),
isCommentKey,
)
const prefixable = new Set()

const keys = names
Expand All @@ -146,13 +157,16 @@ const sortScripts = onObject((scripts) => {
})
.sort()

const order = keys.reduce(
(order, key) =>
order.concat(
prefixable.has(key) ? [`pre${key}`, key, `post${key}`] : [key],
),
[],
)
const order = keys
.reduce(
(order, key) =>
order.concat(
prefixable.has(key) ? [`pre${key}`, key, `post${key}`] : [key],
),
[],
)
.reduce((result, key) => result.concat(comments[key] || [], key), [])
.concat(trailing)

return sortObjectKeys(scripts, order)
})
Expand Down Expand Up @@ -309,6 +323,7 @@ function editStringJSON(json, over) {
}

const isPrivateKey = (key) => key[0] === '_'
const isCommentKey = (key) => key.trim().startsWith('//')
const partition = (array, predicate) =>
array.reduce(
(result, value) => {
Expand All @@ -317,21 +332,43 @@ const partition = (array, predicate) =>
},
[[], []],
)
const removeAndGatherComments = (keys, predicate) =>
keys.reduceRight(
(result, key) => {
const prev = result[0][0]
;(predicate(key)
? prev
? result[1][prev] || (result[1][prev] = [])
: result[2]
: result[0]
).unshift(key)
return result
},
// 0: non-comment keys
// 1: comments that precede a key
// 2: trailing comments
[[], {}, []],
)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems too complicated to me.

['//z', '//x', 'z', ' //name', 'name', 'a', '// end']
 -> keys without `//`: ['z', 'x', 'name', 'a', 'end']
 -> sort: ['a', 'end', 'name', 'x', 'z']
 -> restore: ['a', `// end`, '//name', name, '//x',''x', '//z', 'z' ]

WDYT?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if anyone can think of simpler ways to do this, i'm all ears.

function sortPackageJson(jsonIsh, options = {}) {
return editStringJSON(
jsonIsh,
onObject((json) => {
let sortOrder = options.sortOrder ? options.sortOrder : defaultSortOrder

if (Array.isArray(sortOrder)) {
const keys = Object.keys(json)
const allKeys = Object.keys(json)
const [keys, comments, trailing] = removeAndGatherComments(
allKeys,
isCommentKey,
)
const [privateKeys, publicKeys] = partition(keys, isPrivateKey)
sortOrder = [
...sortOrder,
...defaultSortOrder,
...publicKeys.sort(),
...privateKeys.sort(),
]
...trailing,
].reduce((result, key) => result.concat(comments[key] || [], key), [])
}

return overFields(sortObjectKeys(json, sortOrder))
Expand Down
20 changes: 20 additions & 0 deletions tests/fields.js
Original file line number Diff line number Diff line change
Expand Up @@ -238,3 +238,23 @@ test('badges', (t) => {
'Should sort `badges[]`',
)
})

test('comments', macro.sortObject, {
path: 'repository',
value: {
'// z comment': '',
z: 'z',
a: 'a',
url: 'https://github.com/keithamus/sort-package-json',
type: 'github',
'// trailing comment': '',
},
expect: {
type: 'github',
url: 'https://github.com/keithamus/sort-package-json',
a: 'a',
'// z comment': '',
z: 'z',
'// trailing comment': '',
},
})
6 changes: 6 additions & 0 deletions tests/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,9 @@ test('private keys', macro.sortObject, {
expect: keysToObject(['name', 'a', 'z', '_a', '_z']),
message: 'Should put private keys at bottom',
})

test('comment keys', macro.sortObject, {
value: keysToObject(['//z', '//x', 'z', ' //name', 'name', 'a', '// end']),
expect: keysToObject([' //name', 'name', 'a', '//z', '//x', 'z', '// end']),
message: 'Should keep comment keys above preceding key',
})
2 changes: 2 additions & 0 deletions tests/scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const fixture = {
posttest: 'abc',
pretest: 'xyz',
postprettier: 'echo "so pretty"',
'// preprettier comment': '',
preprettier: 'echo "not pretty"',
prettier: 'prettier -l "**/*.js"',
prepare: 'npm run build',
Expand All @@ -22,6 +23,7 @@ const expect = {
multiply: '2 * 3',
'pre-fetch-info': 'foo',
prepare: 'npm run build',
'// preprettier comment': '',
preprettier: 'echo "not pretty"',
prettier: 'prettier -l "**/*.js"',
postprettier: 'echo "so pretty"',
Expand Down