Skip to content

Commit

Permalink
feat: preserve comments after tsconfig update
Browse files Browse the repository at this point in the history
  • Loading branch information
Mirko Kruschke committed Feb 19, 2023
1 parent 24536aa commit 1165a9b
Show file tree
Hide file tree
Showing 10 changed files with 62 additions and 67 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#IDE's
.idea
.vscode

# Logs
logs
Expand Down
4 changes: 3 additions & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ node_modules
test-run
test-scenarios
.github
*.log
*.log
.vscode
.eslintrc.js
6 changes: 0 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ npx update-ts-references --help
--check Checks if updates would be necessary (without applying them)
--help Show help
--cwd Set working directory. Default: [current path]
--discardComments Discards comments when updating tsconfigs. Default: false
--verbose Show verbose output. Default: false
```

Expand All @@ -44,11 +43,6 @@ or you add it as dev dependency and include it in the `postinstall` script in th

_update-ts-references_ is currently not supporting [Referencing workspace packages through aliases](https://pnpm.js.org/workspaces#referencing-workspace-packages-through-aliases) yet. See issue #13

### Where are the comments from my tsconfig?

_update-ts-references_ is **not** able to preserve comments in tsconfig files when it is updating the references. If you need comments for the case like, explaining why compiler options are set, please move this part including comments into a second file and use the `extends` functionallity (see [here](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#tsconfig-bases)).


# License

Copyright 2023 mobile.de
Expand Down
6 changes: 2 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "update-ts-references",
"version": "2.5.1",
"version": "2.6.0",
"description": "Updates TypeScript references automatically while using workspaces",
"bin": "src/index.js",
"scripts": {
Expand All @@ -20,6 +20,7 @@
],
"dependencies": {
"@formatjs/cli": "^2.3.1",
"comment-json": "^4.2.3",
"glob": "^7.1.6",
"js-yaml": "^4.0.0",
"minimatch": "^3.0.4",
Expand All @@ -33,9 +34,6 @@
"exec-sh": "^0.3.4",
"jest": "^26.4.0"
},
"peerDependencies": {
"typescript": ">=3.8.0"
},
"engines": {
"node": ">=14.0.0"
},
Expand Down
2 changes: 1 addition & 1 deletion scripts/prepareTests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ Invoke-Expression "yarn link"
Remove-Item .\test-run -Confirm:$false -Force -Recurse -ErrorAction Ignore
Copy-Item .\test-scenarios -Destination .\test-run -Recurse
$prevLocation = Get-Location
Get-ChildItem .\test-run | ForEach-Object { Set-Location $_.FullName; Invoke-Expression "yarn"; Invoke-Expression "yarn link update-ts-references" }
Get-ChildItem .\test-run | ForEach-Object { Set-Location $_.FullName; Invoke-Expression "yarn link update-ts-references" }
Set-Location $prevLocation
2 changes: 1 addition & 1 deletion scripts/prepareTests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
yarn link
rm -rf test-run
cp -R test-scenarios test-run
find test-run -maxdepth 1 -type d \( ! -name 'test-run' \) -exec bash -c "cd {} && yarn && yarn link update-ts-references " \;
find test-run -maxdepth 1 -type d \( ! -name 'test-run' \) -exec bash -c "cd {} && yarn link update-ts-references " \;
3 changes: 0 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ const {
verbose = defaultOptions.verbose,
help = defaultOptions.help,
h = defaultOptions.help,
discardComments = defaultOptions.discardComments,
check = defaultOptions.check,
} = minimist(process.argv.slice(2));

Expand All @@ -22,7 +21,6 @@ if (help || h) {
--check Checks if updates would be necessary (without applying them)
--help Show help
--cwd Set working directory. Default: ${defaultOptions.cwd}
--discardComments Discards comments when updating tsconfigs. Default: ${defaultOptions.discardComments}
--verbose Show verbose output. Default: ${defaultOptions.verbose}
`);
process.exit(0);
Expand All @@ -33,7 +31,6 @@ const run = async () => {
const changesCount = await execute({
cwd,
verbose,
discardComments,
check,
configName,
});
Expand Down
51 changes: 13 additions & 38 deletions src/update-ts-references.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
const glob = require('glob');
const path = require('path');
const fs = require('fs');
const ts = require('typescript');
const yaml = require('js-yaml');
const minimatch = require('minimatch');
const readlineSync = require('readline-sync');
const {
parse,
stringify,
assign
} = require('comment-json')
const assert = require('assert').strict;

const PACKAGE_JSON = 'package.json';
Expand All @@ -14,7 +17,6 @@ const defaultOptions = {
configName: 'tsconfig.json',
cwd: process.cwd(),
verbose: false,
discardComments: false,
help: false,
check: false,
};
Expand Down Expand Up @@ -137,35 +139,14 @@ const ensurePosixPathStyle = (reference) => ({
const updateTsConfig = (
configName,
win32OrPosixReferences,
discardComments,
check,
{ packageDir } = { packageDir: process.cwd() }
) => {
const references = (win32OrPosixReferences || []).map(ensurePosixPathStyle);
const tsconfigFilePath = path.join(packageDir, configName);
let pureJson = true;
try {
require(tsconfigFilePath);
} catch (e) {
pureJson = false;
}

const { config, error } = ts.readConfigFile(
tsconfigFilePath,
ts.sys.readFile
);

if (!error) {
if (check === false && pureJson === false && discardComments === false) {
if (
!readlineSync.keyInYN(
`Found comments in the tsconfig.${tsconfigFilePath}
Do you want to discard them and proceed ? `
)
) {
process.exit(0);
}
}
try {
const config = parse(fs.readFileSync(tsconfigFilePath).toString());

const currentReferences = config.references || [];

Expand All @@ -176,35 +157,31 @@ Do you want to discard them and proceed ? `

let isEqual = false;
try {
assert.deepEqual(currentReferences, mergedReferences);
assert.deepEqual(JSON.parse(JSON.stringify(currentReferences)), mergedReferences);
isEqual = true;
} catch (e) {
// ignore me
}
if (!isEqual) {
if (check === false) {
const newTsConfig = JSON.stringify(
const newTsConfig = assign(config,
{
...config,
references: mergedReferences.length ? mergedReferences : undefined,
},
null,
2
}
);
fs.writeFileSync(tsconfigFilePath, newTsConfig + '\n');
fs.writeFileSync(tsconfigFilePath, stringify(newTsConfig, null, 2) + '\n');
}
return 1;
}
return 0;
} else {
} catch (error) {
console.error(`could not read ${tsconfigFilePath}`, error);
}
};

const execute = async ({
cwd,
verbose,
discardComments,
check,
configName,
}) => {
Expand All @@ -228,7 +205,7 @@ const execute = async ({

if (!workspaces) {
throw new Error(
'could not detect yarn workspaces or lerna in this repository'
'could not detect yarn/npm/pnpm workspaces or lerna in this repository'
);
}

Expand Down Expand Up @@ -268,7 +245,6 @@ const execute = async ({
changesCount += updateTsConfig(
detectedConfig,
references,
discardComments,
check,
packageEntry
);
Expand All @@ -284,7 +260,6 @@ const execute = async ({
changesCount += updateTsConfig(
configName,
rootReferences,
discardComments,
check
);

Expand Down
28 changes: 15 additions & 13 deletions tests/update-ts-references.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const execSh = require('exec-sh').promise;
const path = require('path');
const fs = require('fs');
const { parse } = require("comment-json")

const rootFolderYarn = path.join(process.cwd(), 'test-run', 'yarn-ws');
const rootFolderYarnNohoist = path.join(
Expand Down Expand Up @@ -35,7 +36,7 @@ const setup = async (rootFolder, configName) => {

try {
await execSh(
`npx update-ts-references --verbose --discardComments${
`npx update-ts-references --verbose${
configName ? ` --configName ${configName}` : ''
}`,
{
Expand Down Expand Up @@ -195,9 +196,13 @@ test('Support yarn and npm workspaces', async () => {
const [configPath, config] = tsconfig;

expect(
require(path.join(rootFolderYarn, configPath, 'tsconfig.json'))
parse(fs.readFileSync(path.join(rootFolderYarn, configPath, 'tsconfig.json')).toString())
).toEqual(config);


});
// still has the comment
expect(fs.readFileSync(path.join(rootFolderYarn, 'tsconfig.json')).toString()).toMatch(/\/\* Basic Options \*\//)
});

test('Support lerna', async () => {
Expand All @@ -207,7 +212,7 @@ test('Support lerna', async () => {
const [configPath, config] = tsconfig;

expect(
require(path.join(rootFolderLerna, configPath, 'tsconfig.json'))
parse(fs.readFileSync(path.join(rootFolderLerna, configPath, 'tsconfig.json')).toString())
).toEqual(config);
});
});
Expand All @@ -219,7 +224,7 @@ test('Support yarn and npm workspaces with noHoist', async () => {
const [configPath, config] = tsconfig;

expect(
require(path.join(rootFolderYarnNohoist, configPath, 'tsconfig.json'))
parse(fs.readFileSync(path.join(rootFolderYarnNohoist, configPath, 'tsconfig.json')).toString())
).toEqual(config);
});
});
Expand All @@ -231,7 +236,7 @@ test('Support pnpm workspaces', async () => {
const [configPath, config] = tsconfig;

expect(
require(path.join(rootFolderPnpm, configPath, 'tsconfig.json'))
parse(fs.readFileSync(path.join(rootFolderPnpm, configPath, 'tsconfig.json')).toString())
).toEqual(config);
});
});
Expand All @@ -253,8 +258,7 @@ test('Detect changes with the --check option', async () => {
const [configPath] = tsconfig;

expect(
require(path.join(rootFolderYarnCheck, configPath, 'tsconfig.json'))
.references
parse(fs.readFileSync(path.join(rootFolderYarnCheck, configPath, 'tsconfig.json')).toString()).references
).toBeFalsy();
});
});
Expand All @@ -276,11 +280,7 @@ test('No changes detected with the --check option', async () => {
const [configPath, config] = tsconfig;

expect(
require(path.join(
rootFolderYarnCheckNoChanges,
configPath,
'tsconfig.json'
))
parse(fs.readFileSync(path.join(rootFolderYarnCheckNoChanges, configPath, 'tsconfig.json')).toString())
).toEqual(config);
});
});
Expand Down Expand Up @@ -376,7 +376,9 @@ test('Support custom tsconfig names', async () => {

tsconfigs.forEach((tsconfig) => {
const [configPath, config, configNameOverride] = tsconfig;
expect(require(path.join(rootFolder, configPath, configNameOverride || configName))).toEqual(
expect(
parse(fs.readFileSync(path.join(rootFolder, configPath, configNameOverride || configName)).toString())
).toEqual(
config
);
});
Expand Down
26 changes: 26 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -814,6 +814,11 @@ array-find-index@^1.0.1:
resolved "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz"
integrity sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=

array-timsort@^1.0.3:
version "1.0.3"
resolved "https://registry.yarnpkg.com/array-timsort/-/array-timsort-1.0.3.tgz#3c9e4199e54fb2b9c3fe5976396a21614ef0d926"
integrity sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ==

array-unique@^0.3.2:
version "0.3.2"
resolved "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz"
Expand Down Expand Up @@ -1141,6 +1146,17 @@ [email protected]:
resolved "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz"
integrity sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==

comment-json@^4.2.3:
version "4.2.3"
resolved "https://registry.yarnpkg.com/comment-json/-/comment-json-4.2.3.tgz#50b487ebbf43abe44431f575ebda07d30d015365"
integrity sha512-SsxdiOf064DWoZLH799Ata6u7iV658A11PlWtZATDlXPpKGJnbJZ5Z24ybixAi+LUUqJ/GKowAejtC5GFUG7Tw==
dependencies:
array-timsort "^1.0.3"
core-util-is "^1.0.3"
esprima "^4.0.1"
has-own-prop "^2.0.0"
repeat-string "^1.6.1"

component-emitter@^1.2.1:
version "1.3.0"
resolved "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz"
Expand Down Expand Up @@ -1168,6 +1184,11 @@ [email protected]:
resolved "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz"
integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=

core-util-is@^1.0.3:
version "1.0.3"
resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.3.tgz#a6042d3634c2b27e9328f837b965fac83808db85"
integrity sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==

cross-spawn@^6.0.0:
version "6.0.5"
resolved "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz"
Expand Down Expand Up @@ -1884,6 +1905,11 @@ has-flag@^4.0.0:
resolved "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz"
integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==

has-own-prop@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/has-own-prop/-/has-own-prop-2.0.0.tgz#f0f95d58f65804f5d218db32563bb85b8e0417af"
integrity sha512-Pq0h+hvsVm6dDEa8x82GnLSYHOzNDt7f0ddFa3FqcQlgzEiptPqL+XrOJNavjOzSYiYWIrgeVYYgGlLmnxwilQ==

has-symbols@^1.0.0, has-symbols@^1.0.1:
version "1.0.1"
resolved "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz"
Expand Down

0 comments on commit 1165a9b

Please sign in to comment.