Skip to content

Commit

Permalink
feat: initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
p-chan committed Feb 5, 2022
0 parents commit 0516a7f
Show file tree
Hide file tree
Showing 13 changed files with 1,777 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .gitignore
@@ -0,0 +1,8 @@
# dependencies
node_modules

# logs
*.log

# output
dist
2 changes: 2 additions & 0 deletions .prettierignore
@@ -0,0 +1,2 @@
# output
dist
1 change: 1 addition & 0 deletions .prettierrc
@@ -0,0 +1 @@
"@stardust-configs/prettier-config"
3 changes: 3 additions & 0 deletions .versionrc
@@ -0,0 +1,3 @@
{
"releaseCommitMessageFormat": "chore: release v{{currentTag}}"
}
1 change: 1 addition & 0 deletions .yarnrc
@@ -0,0 +1 @@
save-prefix ""
29 changes: 29 additions & 0 deletions README.md
@@ -0,0 +1,29 @@
# sort-compiler-options

> Sort tsconfig.json compilerOptions in the same order as [the TSConfig Reference](https://www.typescriptlang.org/tsconfig#compilerOptions)
## Install

```sh
npm i sort-compiler-options -g
```

## Usage

```sh
sort-compiler-options # or sort-co, sco
```

If you specify tsconfig file path, use config option (`-c` or `--config`)

```sh
sort-compiler-options -c tsconfig.server.json
```

## Author

[@p-chan](https://github.com/p-chan)

## License

MIT
56 changes: 56 additions & 0 deletions package.json
@@ -0,0 +1,56 @@
{
"name": "sort-compiler-options",
"version": "0.1.0",
"description": "Sort compilerOptions",
"keywords": [
"typescript",
"tsconfig",
"tsc",
"compilerOptions",
"sort",
"order"
],
"homepage": "https://github.com/p-chan/sort-compiler-options#readme",
"bugs": {
"url": "https://github.com/p-chan/sort-compiler-options/issues"
},
"license": "MIT",
"author": "P-Chan",
"main": "./dist",
"bin": {
"sco": "./dist/index.js",
"sort-co": "./dist/index.js",
"sort-compiler-options": "./dist/index.js"
},
"repository": {
"type": "git",
"url": "https://github.com/p-chan/sort-compiler-options.git"
},
"scripts": {
"build": "tsc",
"clean": "rimraf ./dist",
"dev": "ts-node ./src/index.ts",
"format": "prettier --write .",
"prebuild": "npm run clean",
"prepublishOnly": "npm run build",
"version:major": "standard-version -r major",
"version:minor": "standard-version -r minor",
"version:patch": "standard-version -r patch"
},
"dependencies": {
"cac": "6.7.12",
"consola": "2.15.3",
"prettier": "2.5.1"
},
"devDependencies": {
"@stardust-configs/prettier-config": "0.1.1",
"@stardust-configs/tsconfig": "0.2.0",
"@types/node": "17.0.14",
"@types/prettier": "2.4.3",
"rimraf": "3.0.2",
"standard-version": "9.3.2",
"ts-node": "10.4.0",
"type-fest": "2.11.1",
"typescript": "4.5.5"
}
}
81 changes: 81 additions & 0 deletions src/action.ts
@@ -0,0 +1,81 @@
import { lstat, readFile, writeFile } from 'fs/promises'
import { resolve } from 'path'
import { TsConfigJson } from 'type-fest'
import consola from 'consola'
import prettier from 'prettier'

import { order } from './order'

type Object = {
[key: string]: any
}

type Options = {
'--': any[]
c: string
config: string
}

export const action = async (options: Options) => {
try {
const tsConfigJsonPath = resolve(process.cwd(), (options.c || options.config) ?? 'tsconfig.json')

const isExistsTsConfigJson = await (async () => {
try {
return (await lstat(tsConfigJsonPath)).isFile()
} catch (e) {
return false
}
})()

if (!isExistsTsConfigJson) throw new Error('tsconfig is not found')

const tsConfigJson = JSON.parse(await readFile(tsConfigJsonPath, 'utf-8')) as TsConfigJson

if (tsConfigJson.compilerOptions == undefined) throw new Error('compilerOptions is not defined')

const nextCompilerOptions: Object = {}

Object.keys(tsConfigJson.compilerOptions)
.sort((a, b) => {
let aIndex = order.findIndex((key) => key === a)
let bIndex = order.findIndex((key) => key === b)

aIndex = aIndex >= 0 ? aIndex : Number.MAX_SAFE_INTEGER
bIndex = bIndex >= 0 ? bIndex : Number.MAX_SAFE_INTEGER

if (aIndex > bIndex) return 1
if (aIndex < bIndex) return -1

return 0
})
.forEach((key) => {
nextCompilerOptions[key] = (tsConfigJson.compilerOptions as Object)[key]
})

tsConfigJson.compilerOptions = nextCompilerOptions

const tsConfigJsonString = JSON.stringify(tsConfigJson)

const prettierOptions = await (async () => {
const prettierConfigFilePath = await prettier.resolveConfigFile()

if (prettierConfigFilePath == undefined) return {}

return await prettier.resolveConfig(prettierConfigFilePath)
})()

await writeFile(
tsConfigJsonPath,
prettier.format(tsConfigJsonString, {
parser: 'json-stringify',
...prettierOptions,
}),
'utf-8'
)

consola.success('Sorted compilerOptions')
} catch (error) {
consola.error(error)
}
}
20 changes: 20 additions & 0 deletions src/index.ts
@@ -0,0 +1,20 @@
#!/usr/bin/env node

import { cac } from 'cac'

import { action } from './action'
import { version } from './version'

const cli = cac()

cli
.command('')
.option('-c, --config <path>', 'Specify tsconfig file path', {
default: 'tsconfig.json',
})
.action(action)

cli.help()
cli.version(version)

cli.parse()
109 changes: 109 additions & 0 deletions src/order.ts
@@ -0,0 +1,109 @@
/**
* The order is the same as the TSConfig Reference
*
* @see https://www.typescriptlang.org/tsconfig#compilerOptions
*/
export const order = [
'allowUnreachableCode',
'allowUnusedLabels',
'alwaysStrict',
'exactOptionalPropertyTypes',
'noFallthroughCasesInSwitch',
'noImplicitAny',
'noImplicitOverride',
'noImplicitReturns',
'noImplicitThis',
'noPropertyAccessFromIndexSignature',
'noUncheckedIndexedAccess',
'noUnusedLocals',
'noUnusedParameters',
'strict',
'strictBindCallApply',
'strictFunctionTypes',
'strictNullChecks',
'strictPropertyInitialization',
'useUnknownInCatchVariables',
'allowUmdGlobalAccess',
'baseUrl',
'module',
'moduleResolution',
'noResolve',
'paths',
'resolveJsonModule',
'rootDir',
'rootDirs',
'typeRoots',
'types',
'declaration',
'declarationDir',
'declarationMap',
'downlevelIteration',
'emitBOM',
'emitDeclarationOnly',
'importHelpers',
'importsNotUsedAsValues',
'inlineSourceMap',
'inlineSources',
'mapRoot',
'newLine',
'noEmit',
'noEmitHelpers',
'noEmitOnError',
'outDir',
'outFile',
'preserveConstEnums',
'preserveValueImports',
'removeComments',
'sourceMap',
'sourceRoot',
'stripInternal',
'allowJs',
'checkJs',
'maxNodeModuleJsDepth',
'disableSizeLimit',
'plugins',
'allowSyntheticDefaultImports',
'esModuleInterop',
'forceConsistentCasingInFileNames',
'isolatedModules',
'preserveSymlinks',
'charset',
'keyofStringsOnly',
'noImplicitUseStrict',
'noStrictGenericChecks',
'out',
'suppressExcessPropertyErrors',
'suppressImplicitAnyIndexErrors',
'Language',
'Environment',
'emitDecoratorMetadata',
'experimentalDecorators',
'jsx',
'jsxFactory',
'jsxFragmentFactory',
'jsxImportSource',
'lib',
'noLib',
'reactNamespace',
'target',
'useDefineForClassFields',
'diagnostics',
'explainFiles',
'extendedDiagnostics',
'generateCpuProfile',
'listEmittedFiles',
'listFiles',
'traceResolution',
'composite',
'disableReferencedProjectLoad',
'disableSolutionSearching',
'disableSourceOfProjectReferenceRedirect',
'incremental',
'tsBuildInfoFile',
'noErrorTruncation',
'preserveWatchOutput',
'pretty',
'skipDefaultLibCheck',
'skipLibCheck',
'assumeChangesOnlyAffectDirectDependencies',
]
3 changes: 3 additions & 0 deletions src/version.ts
@@ -0,0 +1,3 @@
const packageJson = require('../package')

export const version = packageJson.version
6 changes: 6 additions & 0 deletions tsconfig.json
@@ -0,0 +1,6 @@
{
"extends": "@stardust-configs/tsconfig/node14.json",
"compilerOptions": {
"outDir": "./dist"
}
}

0 comments on commit 0516a7f

Please sign in to comment.