Created
April 7, 2016 02:41
-
-
Save deoxxa/4d7aff457058adb44c8f643130bd3c00 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const order = [ | |
| /^lib\//, | |
| /^actions\//, | |
| /^reducers\//, | |
| /^constants\//, | |
| /^containers\//, | |
| /^components\//, | |
| /^schema\/[A-Z]/, | |
| /^schema\//, | |
| /^\.\.?\/[A-Z]/, | |
| /^\.\.?\//, | |
| ]; | |
| function pos(s) { | |
| for (let i = 0; i < order.length; i++) { | |
| if (order[i].test(s)) { | |
| return i; | |
| } | |
| } | |
| return -1; | |
| } | |
| function cmp(a, b) { | |
| const posA = pos(a.source.value); | |
| const posB = pos(b.source.value); | |
| if (posA < posB) { return -1; } | |
| if (posA > posB) { return 1; } | |
| if (a.source.value < b.source.value) { return -1; } | |
| if (a.source.value > b.source.value) { return 1; } | |
| return 0; | |
| } | |
| export default function(file, api) { | |
| const j = api.jscodeshift; | |
| function printImports(a) { | |
| const bits = []; | |
| let lastPos = null; | |
| a.forEach((n) => { | |
| const p = pos(n.source.value); | |
| if (p !== lastPos) { | |
| if (lastPos !== null) { | |
| bits.push(''); | |
| } | |
| lastPos = p; | |
| } | |
| bits.push(j(n).toSource()); | |
| if (n.source.value.indexOf('actions/') === 0) { | |
| bits.push(''); | |
| } | |
| }); | |
| return bits.join('\n').replace(/\n\n\n+/g, '\n\n').trim(); | |
| } | |
| let h = null; | |
| const f = j(file.source); | |
| f.find(j.Program).forEach((p) => { | |
| const imports = p.value.body.filter((e) => e.type === 'ImportDeclaration'); | |
| let leadingComments = null; | |
| if (imports.length > 0) { | |
| // make sure top-of-file comments stay where they are | |
| leadingComments = p.value.body[0].leadingComments; | |
| delete p.value.body[0].leadingComments; | |
| delete p.value.body[0].comments; | |
| } | |
| p.value.body = p.value.body.filter((e) => e.type !== 'ImportDeclaration'); | |
| imports.sort(cmp); | |
| if (imports.length > 0) { | |
| imports[0].leadingComments = leadingComments; | |
| imports[0].comments = leadingComments; | |
| } | |
| h = printImports(imports); | |
| }); | |
| if (h.length > 0) { | |
| return h + '\n\n' + f.toSource(); | |
| } | |
| return null; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment