@charcoal-ui/tailwind-diff 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022 pixiv Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,17 @@
1
+ # `@charcoal-ui/tailwind-diff-cli`
2
+
3
+ Tailwind.css の config 変更やバージョンアップに伴うクラスの変更(新しいクラスの追加、削除など)を検知します。
4
+
5
+ ## インストール
6
+
7
+ npm
8
+
9
+ ```
10
+ npm i --save-dev @charcoal-ui/tailwind-diff-cli
11
+ ```
12
+
13
+ yarn
14
+
15
+ ```
16
+ yarn add -D @charcoal-ui/tailwind-diff-cli
17
+ ```
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+
3
+ require('../dist/index')
@@ -0,0 +1,8 @@
1
+ export interface CheckConfig {
2
+ format: 'default' | 'json';
3
+ beforeConfig?: string;
4
+ afterConfig?: string;
5
+ packages?: readonly string[];
6
+ }
7
+ export declare function check({ format, beforeConfig, afterConfig, packages, }: CheckConfig): Promise<void>;
8
+ //# sourceMappingURL=check.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"check.d.ts","sourceRoot":"","sources":["../../src/commands/check.ts"],"names":[],"mappings":"AAkCA,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,SAAS,GAAG,MAAM,CAAA;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CAC7B;AAED,wBAAsB,KAAK,CAAC,EAC1B,MAAM,EACN,YAAY,EACZ,WAAW,EACX,QAAa,GACd,EAAE,WAAW,iBAyFb"}
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.check = void 0;
7
+ const child_process_1 = __importDefault(require("child_process"));
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const os_1 = __importDefault(require("os"));
10
+ const path_1 = __importDefault(require("path"));
11
+ const postcss_1 = __importDefault(require("postcss"));
12
+ const defer_1 = require("../defer");
13
+ const packageManager_1 = require("../packageManager");
14
+ const style_1 = require("../style");
15
+ const withPackages_1 = require("../withPackages");
16
+ function processDone(child) {
17
+ return new Promise((resolve, reject) => {
18
+ child
19
+ .once('error', (err) => {
20
+ reject(err);
21
+ })
22
+ .once('exit', (code, signal) => {
23
+ if (code == null) {
24
+ return;
25
+ }
26
+ if (code === 0) {
27
+ resolve();
28
+ }
29
+ else if (signal != null) {
30
+ reject(new Error(`Subprocess failed with code: ${code}, signal: ${signal}`));
31
+ }
32
+ else {
33
+ reject(new Error(`Subprocess failed with code: ${code}`));
34
+ }
35
+ });
36
+ });
37
+ }
38
+ async function check({ format, beforeConfig, afterConfig, packages = [], }) {
39
+ const packageManager = (0, packageManager_1.detectPackageManager)(process.cwd());
40
+ const selfPath = path_1.default.resolve(__dirname, '../index.js');
41
+ const deferer = (0, defer_1.createDefer)();
42
+ const { defer, dispose } = deferer;
43
+ process.on('SIGINT', dispose);
44
+ try {
45
+ const tmpdir = fs_1.default.mkdtempSync(path_1.default.resolve(os_1.default.tmpdir(), 'tailwind-diff-css'));
46
+ defer(() => {
47
+ const files = fs_1.default.readdirSync(tmpdir);
48
+ for (const file of files) {
49
+ fs_1.default.unlinkSync(path_1.default.resolve(tmpdir, file));
50
+ }
51
+ fs_1.default.rmdirSync(tmpdir);
52
+ });
53
+ const beforeCSSPath = path_1.default.resolve(tmpdir, 'before.css');
54
+ defer(() => {
55
+ if (fs_1.default.existsSync(beforeCSSPath)) {
56
+ fs_1.default.unlinkSync(beforeCSSPath);
57
+ }
58
+ });
59
+ await processDone(child_process_1.default.fork(selfPath, [
60
+ 'dump',
61
+ '--output',
62
+ beforeCSSPath,
63
+ ...(beforeConfig != null ? ['--config', beforeConfig] : []),
64
+ ]));
65
+ const afterCSSPath = path_1.default.resolve(tmpdir, 'after.css');
66
+ defer(() => {
67
+ if (fs_1.default.existsSync(afterCSSPath)) {
68
+ fs_1.default.unlinkSync(afterCSSPath);
69
+ }
70
+ });
71
+ await (0, withPackages_1.withPackages)(packageManager, packages, async () => {
72
+ await processDone(child_process_1.default.fork(selfPath, [
73
+ 'dump',
74
+ '--output',
75
+ afterCSSPath,
76
+ ...(afterConfig != null ? ['--config', afterConfig] : []),
77
+ ]));
78
+ });
79
+ const beforeStyles = (0, style_1.collectClassNamesAndStyles)(postcss_1.default
80
+ .parse(fs_1.default.readFileSync(beforeCSSPath, { encoding: 'utf8' }))
81
+ .toResult());
82
+ const afterStyles = (0, style_1.collectClassNamesAndStyles)(postcss_1.default
83
+ .parse(fs_1.default.readFileSync(afterCSSPath, { encoding: 'utf8' }))
84
+ .toResult());
85
+ const diffs = (0, style_1.diffsBetweenStyles)(beforeStyles, afterStyles);
86
+ if (format === 'json') {
87
+ const json = diffs.map((item) => ({
88
+ ...item,
89
+ css: item.css.map((rule) => rule.toString()),
90
+ }));
91
+ process.stdout.write(JSON.stringify(json));
92
+ }
93
+ else {
94
+ let added = 0;
95
+ let removed = 0;
96
+ for (const item of diffs) {
97
+ if (item.status === 'added') {
98
+ added++;
99
+ }
100
+ else {
101
+ removed++;
102
+ }
103
+ }
104
+ console.log(`${added} classes added, ${removed} classes removed.`);
105
+ }
106
+ }
107
+ finally {
108
+ dispose();
109
+ process.off('SIGINT', dispose);
110
+ }
111
+ }
112
+ exports.check = check;
@@ -0,0 +1,6 @@
1
+ export interface DumpConfig {
2
+ output?: string;
3
+ config?: string;
4
+ }
5
+ export declare function dump({ output, config }: DumpConfig): Promise<void>;
6
+ //# sourceMappingURL=dump.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dump.d.ts","sourceRoot":"","sources":["../../src/commands/dump.ts"],"names":[],"mappings":"AAYA,MAAM,WAAW,UAAU;IACzB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAED,wBAAsB,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,UAAU,iBA2BxD"}
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.dump = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const stream_1 = __importDefault(require("stream"));
10
+ const import_from_1 = __importDefault(require("import-from"));
11
+ const sourceCSS = `
12
+ @tailwind base;
13
+ @tailwind components;
14
+ @tailwind utilities;
15
+ `;
16
+ async function dump({ output, config }) {
17
+ const targetDir = process.cwd();
18
+ const postcss = (0, import_from_1.default)(targetDir, 'postcss');
19
+ const tailwindcss = (0, import_from_1.default)(targetDir, 'tailwindcss');
20
+ const tailwindConfig = import_from_1.default.silent(targetDir, config != null ? config : 'tailwind.config.js');
21
+ const result = await postcss([tailwindcss(tailwindConfig)]).process(sourceCSS, {
22
+ from: undefined,
23
+ to: undefined,
24
+ map: false,
25
+ });
26
+ const sink = output != null
27
+ ? fs_1.default.createWriteStream(path_1.default.resolve(targetDir, output))
28
+ : process.stdout;
29
+ stream_1.default.Readable.from(result.css).pipe(sink);
30
+ }
31
+ exports.dump = dump;
@@ -0,0 +1,5 @@
1
+ export declare function createDefer(): {
2
+ readonly defer: (deferFn: () => void) => void;
3
+ readonly dispose: () => void;
4
+ };
5
+ //# sourceMappingURL=defer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defer.d.ts","sourceRoot":"","sources":["../src/defer.ts"],"names":[],"mappings":"AAAA,wBAAgB,WAAW;8BAGD,MAAM,IAAI;;EAuBnC"}
package/dist/defer.js ADDED
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createDefer = void 0;
4
+ function createDefer() {
5
+ const defers = [];
6
+ const defer = (deferFn) => {
7
+ defers.push(deferFn);
8
+ };
9
+ const dispose = () => {
10
+ // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition
11
+ while (true) {
12
+ const deferFn = defers.pop();
13
+ if (deferFn == null) {
14
+ return;
15
+ }
16
+ try {
17
+ deferFn();
18
+ }
19
+ catch (err) {
20
+ console.error('Uncaught defer error:', err);
21
+ }
22
+ }
23
+ };
24
+ return {
25
+ defer,
26
+ dispose,
27
+ };
28
+ }
29
+ exports.createDefer = createDefer;
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
package/dist/index.js ADDED
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const yargs_1 = __importDefault(require("yargs"));
7
+ const check_1 = require("./commands/check");
8
+ const dump_1 = require("./commands/dump");
9
+ void yargs_1.default
10
+ .scriptName('tailwind-diff')
11
+ .command('check', 'checks diffs due to package updates', () => yargs_1.default
12
+ .option('config', {
13
+ type: 'string',
14
+ description: 'tailwind config file',
15
+ })
16
+ .alias('c', 'config')
17
+ .option('before-config', {
18
+ type: 'string',
19
+ description: 'tailwind config used in first build',
20
+ })
21
+ .option('after-config', {
22
+ type: 'string',
23
+ description: 'tailwind config used in second build',
24
+ })
25
+ .option('packages', {
26
+ type: 'array',
27
+ description: 'packages to be update',
28
+ })
29
+ .option('json', {
30
+ type: 'boolean',
31
+ description: 'print result as JSON format',
32
+ }), ({ config, 'after-config': afterConfig, 'before-config': beforeConfig, packages, json = false, }) => {
33
+ void (0, check_1.check)({
34
+ format: json ? 'json' : 'default',
35
+ beforeConfig: beforeConfig != null ? beforeConfig : config,
36
+ afterConfig: afterConfig != null ? afterConfig : config,
37
+ packages: packages != null ? packages.map((v) => `${v}`) : undefined,
38
+ });
39
+ })
40
+ .command('dump', 'dump Tailwind CSS with config', () => yargs_1.default
41
+ .option('output', { type: 'string', description: 'output file' })
42
+ .alias('o', 'output')
43
+ .option('config', {
44
+ type: 'string',
45
+ description: 'tailwind config file',
46
+ })
47
+ .alias('c', 'config'), ({ output, config }) => {
48
+ void (0, dump_1.dump)({
49
+ output,
50
+ config,
51
+ });
52
+ })
53
+ .demandCommand()
54
+ .help()
55
+ .parse();
@@ -0,0 +1,9 @@
1
+ declare type PackageManagerType = 'npm' | 'yarn' | 'pnpm';
2
+ export interface PackageManagerInfo {
3
+ type: PackageManagerType;
4
+ packageJSONPath: string;
5
+ lockfilePath: string | undefined;
6
+ }
7
+ export declare function detectPackageManager(base: string): PackageManagerInfo;
8
+ export {};
9
+ //# sourceMappingURL=packageManager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"packageManager.d.ts","sourceRoot":"","sources":["../src/packageManager.ts"],"names":[],"mappings":"AAIA,aAAK,kBAAkB,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,CAAA;AAEjD,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,kBAAkB,CAAA;IACxB,eAAe,EAAE,MAAM,CAAA;IACvB,YAAY,EAAE,MAAM,GAAG,SAAS,CAAA;CACjC;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,kBAAkB,CA+CrE"}
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.detectPackageManager = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const os_1 = __importDefault(require("os"));
9
+ const path_1 = __importDefault(require("path"));
10
+ function detectPackageManager(base) {
11
+ const upperbounds = [os_1.default.homedir(), path_1.default.resolve('/')];
12
+ let dir = fs_1.default.statSync(base).isDirectory() ? base : path_1.default.dirname(base);
13
+ while (!fs_1.default.existsSync(path_1.default.join(dir, 'package.json'))) {
14
+ const parent = path_1.default.dirname(dir);
15
+ if (upperbounds.includes(parent)) {
16
+ throw new Error('No node project found.');
17
+ }
18
+ dir = parent;
19
+ }
20
+ const packageJSONPath = path_1.default.join(dir, 'package.json');
21
+ let type = 'npm';
22
+ let lockfilePath;
23
+ do {
24
+ let lockfile;
25
+ lockfile = path_1.default.join(dir, 'package-lock.json');
26
+ if (fs_1.default.existsSync(lockfile)) {
27
+ lockfilePath = lockfile;
28
+ type = 'npm';
29
+ break;
30
+ }
31
+ lockfile = path_1.default.join(dir, 'yarn.lock');
32
+ if (fs_1.default.existsSync(lockfile)) {
33
+ lockfilePath = lockfile;
34
+ type = 'yarn';
35
+ break;
36
+ }
37
+ lockfile = path_1.default.join(dir, 'pnpm-lock.yaml');
38
+ if (fs_1.default.existsSync(lockfile)) {
39
+ lockfilePath = lockfile;
40
+ type = 'pnpm';
41
+ break;
42
+ }
43
+ dir = path_1.default.dirname(dir);
44
+ } while (!upperbounds.includes(dir));
45
+ return {
46
+ type,
47
+ packageJSONPath,
48
+ lockfilePath,
49
+ };
50
+ }
51
+ exports.detectPackageManager = detectPackageManager;
@@ -0,0 +1,11 @@
1
+ import type { Result, Rule } from 'postcss';
2
+ declare type ClassToStyles = Map<string, Rule[]>;
3
+ export declare function collectClassNamesAndStyles(result: Result): ClassToStyles;
4
+ export interface TailwindDiffItem {
5
+ className: string;
6
+ css: Rule[];
7
+ status: 'added' | 'removed';
8
+ }
9
+ export declare function diffsBetweenStyles(before: ClassToStyles, after: ClassToStyles): TailwindDiffItem[];
10
+ export {};
11
+ //# sourceMappingURL=style.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"style.d.ts","sourceRoot":"","sources":["../src/style.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAA;AAG3C,aAAK,aAAa,GAAG,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAA;AAIxC,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,MAAM,GAAG,aAAa,CAiBxE;AAED,MAAM,WAAW,gBAAgB;IAC/B,SAAS,EAAE,MAAM,CAAA;IACjB,GAAG,EAAE,IAAI,EAAE,CAAA;IACX,MAAM,EAAE,OAAO,GAAG,SAAS,CAAA;CAC5B;AA6BD,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,aAAa,EACrB,KAAK,EAAE,aAAa,sBA0BrB"}
package/dist/style.js ADDED
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.diffsBetweenStyles = exports.collectClassNamesAndStyles = void 0;
7
+ const postcss_selector_parser_1 = __importDefault(require("postcss-selector-parser"));
8
+ const selectorParser = (0, postcss_selector_parser_1.default)();
9
+ function collectClassNamesAndStyles(result) {
10
+ const classToStyles = new Map();
11
+ result.root.walkRules((rule) => {
12
+ selectorParser.astSync(rule.selector).walkClasses((node) => {
13
+ const className = node.value.trim();
14
+ const styles = classToStyles.get(className);
15
+ if (styles != null) {
16
+ styles.push(rule);
17
+ }
18
+ else {
19
+ classToStyles.set(className, [rule]);
20
+ }
21
+ });
22
+ });
23
+ return classToStyles;
24
+ }
25
+ exports.collectClassNamesAndStyles = collectClassNamesAndStyles;
26
+ // :の後ろが同じものが並んでほしいのでそれを前にしてソートする
27
+ const tailwindClassNameSortMapper = (className) => {
28
+ if (className.includes(':')) {
29
+ const items = className.split(':');
30
+ let result = '';
31
+ result += items.pop();
32
+ result += `:${items.join(':')}`;
33
+ return result;
34
+ }
35
+ else {
36
+ return className;
37
+ }
38
+ };
39
+ const tailwindDiffItemSortMapper = (item) => tailwindClassNameSortMapper(item.className);
40
+ const mappedSorter = (mapper) => (lhs, rhs) => {
41
+ const mappedLhs = mapper(lhs);
42
+ const mappedRhs = mapper(rhs);
43
+ if (mappedLhs < mappedRhs) {
44
+ return -1;
45
+ }
46
+ if (mappedLhs > mappedRhs) {
47
+ return 1;
48
+ }
49
+ return 0;
50
+ };
51
+ function diffsBetweenStyles(before, after) {
52
+ const diffs = [];
53
+ for (const afterClassName of after.keys()) {
54
+ if (!before.has(afterClassName)) {
55
+ diffs.push({
56
+ className: afterClassName,
57
+ status: 'added',
58
+ css: after.get(afterClassName),
59
+ });
60
+ }
61
+ }
62
+ for (const beforeClassName of before.keys()) {
63
+ if (!after.has(beforeClassName)) {
64
+ diffs.push({
65
+ className: beforeClassName,
66
+ status: 'removed',
67
+ css: before.get(beforeClassName),
68
+ });
69
+ }
70
+ }
71
+ diffs.sort(mappedSorter(tailwindDiffItemSortMapper));
72
+ return diffs;
73
+ }
74
+ exports.diffsBetweenStyles = diffsBetweenStyles;
@@ -0,0 +1,9 @@
1
+ import { PackageManagerInfo } from './packageManager';
2
+ /**
3
+ * 指定したバージョンのパッケージが存在する状態で処理を行う
4
+ *
5
+ * @param packageDescripters 欲しいパッケージの一覧
6
+ * @param callback 実行したい処理
7
+ */
8
+ export declare function withPackages<T>(packageManagerInfo: PackageManagerInfo, packageDescripters: readonly string[], callback: () => T | Promise<T>): Promise<T>;
9
+ //# sourceMappingURL=withPackages.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"withPackages.d.ts","sourceRoot":"","sources":["../src/withPackages.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAA;AAErD;;;;;GAKG;AACH,wBAAsB,YAAY,CAAC,CAAC,EAClC,kBAAkB,EAAE,kBAAkB,EACtC,kBAAkB,EAAE,SAAS,MAAM,EAAE,EACrC,QAAQ,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAC7B,OAAO,CAAC,CAAC,CAAC,CAuEZ"}
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.withPackages = void 0;
7
+ const child_process_1 = __importDefault(require("child_process"));
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const os_1 = __importDefault(require("os"));
10
+ const path_1 = __importDefault(require("path"));
11
+ const defer_1 = require("./defer");
12
+ /**
13
+ * 指定したバージョンのパッケージが存在する状態で処理を行う
14
+ *
15
+ * @param packageDescripters 欲しいパッケージの一覧
16
+ * @param callback 実行したい処理
17
+ */
18
+ async function withPackages(packageManagerInfo, packageDescripters, callback) {
19
+ if (packageDescripters.length === 0) {
20
+ return callback();
21
+ }
22
+ const deferer = (0, defer_1.createDefer)();
23
+ const { defer, dispose } = deferer;
24
+ process.on('SIGINT', dispose);
25
+ try {
26
+ const tmpdir = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'tailwind-diff-packages-'));
27
+ defer(() => {
28
+ const files = fs_1.default.readdirSync(tmpdir);
29
+ for (const file of files) {
30
+ fs_1.default.unlinkSync(path_1.default.resolve(tmpdir, file));
31
+ }
32
+ fs_1.default.rmdirSync(tmpdir);
33
+ });
34
+ const backupPackageJSONPath = path_1.default.join(tmpdir, 'package.json');
35
+ fs_1.default.copyFileSync(packageManagerInfo.packageJSONPath, backupPackageJSONPath);
36
+ const packageLock = packageManagerInfo.lockfilePath != null
37
+ ? {
38
+ path: packageManagerInfo.lockfilePath,
39
+ backup: path_1.default.join(tmpdir, path_1.default.basename(packageManagerInfo.lockfilePath)),
40
+ }
41
+ : undefined;
42
+ if (packageLock != null) {
43
+ fs_1.default.copyFileSync(packageLock.path, packageLock.backup);
44
+ }
45
+ let cmd, recoverCmd;
46
+ switch (packageManagerInfo.type) {
47
+ case 'npm':
48
+ cmd = `npm install ${packageDescripters.join(' ')}`;
49
+ recoverCmd = 'npm install';
50
+ break;
51
+ case 'yarn':
52
+ cmd = `yarn add ${packageDescripters.join(' ')}`;
53
+ recoverCmd = 'yarn install';
54
+ break;
55
+ case 'pnpm':
56
+ cmd = `pnpm add ${packageDescripters.join(' ')}`;
57
+ recoverCmd = 'pnpm install';
58
+ break;
59
+ }
60
+ // execに失敗してもファイルは回復してほしい
61
+ defer(() => {
62
+ fs_1.default.unlinkSync(packageManagerInfo.packageJSONPath);
63
+ fs_1.default.copyFileSync(backupPackageJSONPath, packageManagerInfo.packageJSONPath);
64
+ if (packageLock != null) {
65
+ fs_1.default.unlinkSync(packageLock.path);
66
+ fs_1.default.copyFileSync(packageLock.backup, packageLock.path);
67
+ }
68
+ child_process_1.default.execSync(recoverCmd);
69
+ });
70
+ child_process_1.default.execSync(cmd);
71
+ return callback();
72
+ }
73
+ finally {
74
+ dispose();
75
+ process.off('SIGINT', dispose);
76
+ }
77
+ }
78
+ exports.withPackages = withPackages;
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@charcoal-ui/tailwind-diff",
3
+ "version": "1.0.0-alpha.1",
4
+ "bin": "bin/tailwind-diff.js",
5
+ "scripts": {
6
+ "build": "tsc",
7
+ "typecheck": "tsc --noEmit"
8
+ },
9
+ "dependencies": {
10
+ "import-from": "^4.0.0",
11
+ "postcss": "^8.4.5",
12
+ "postcss-selector-parser": "^6.0.9",
13
+ "yargs": "^17.3.1"
14
+ },
15
+ "devDependencies": {
16
+ "@types/tailwindcss": "^2.2.4",
17
+ "@types/yargs": "^17.0.8",
18
+ "typescript": "^4.5.5"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "gitHead": "1d09e09a796f92782be600672efb5c80a6a7b51b"
24
+ }
@@ -0,0 +1,136 @@
1
+ import child_process from 'child_process'
2
+ import type { ChildProcess } from 'child_process'
3
+ import fs from 'fs'
4
+ import os from 'os'
5
+ import path from 'path'
6
+ import postcss from 'postcss'
7
+ import { createDefer } from '../defer'
8
+ import { detectPackageManager } from '../packageManager'
9
+ import { collectClassNamesAndStyles, diffsBetweenStyles } from '../style'
10
+ import { withPackages } from '../withPackages'
11
+
12
+ function processDone(child: ChildProcess) {
13
+ return new Promise<void>((resolve, reject) => {
14
+ child
15
+ .once('error', (err) => {
16
+ reject(err)
17
+ })
18
+ .once('exit', (code, signal) => {
19
+ if (code == null) {
20
+ return
21
+ }
22
+ if (code === 0) {
23
+ resolve()
24
+ } else if (signal != null) {
25
+ reject(
26
+ new Error(`Subprocess failed with code: ${code}, signal: ${signal}`)
27
+ )
28
+ } else {
29
+ reject(new Error(`Subprocess failed with code: ${code}`))
30
+ }
31
+ })
32
+ })
33
+ }
34
+
35
+ export interface CheckConfig {
36
+ format: 'default' | 'json'
37
+ beforeConfig?: string
38
+ afterConfig?: string
39
+ packages?: readonly string[]
40
+ }
41
+
42
+ export async function check({
43
+ format,
44
+ beforeConfig,
45
+ afterConfig,
46
+ packages = [],
47
+ }: CheckConfig) {
48
+ const packageManager = detectPackageManager(process.cwd())
49
+
50
+ const selfPath = path.resolve(__dirname, '../index.js')
51
+
52
+ const deferer = createDefer()
53
+ const { defer, dispose } = deferer
54
+ process.on('SIGINT', dispose)
55
+ try {
56
+ const tmpdir = fs.mkdtempSync(
57
+ path.resolve(os.tmpdir(), 'tailwind-diff-css')
58
+ )
59
+ defer(() => {
60
+ const files = fs.readdirSync(tmpdir)
61
+ for (const file of files) {
62
+ fs.unlinkSync(path.resolve(tmpdir, file))
63
+ }
64
+ fs.rmdirSync(tmpdir)
65
+ })
66
+
67
+ const beforeCSSPath = path.resolve(tmpdir, 'before.css')
68
+ defer(() => {
69
+ if (fs.existsSync(beforeCSSPath)) {
70
+ fs.unlinkSync(beforeCSSPath)
71
+ }
72
+ })
73
+
74
+ await processDone(
75
+ child_process.fork(selfPath, [
76
+ 'dump',
77
+ '--output',
78
+ beforeCSSPath,
79
+ ...(beforeConfig != null ? ['--config', beforeConfig] : []),
80
+ ])
81
+ )
82
+
83
+ const afterCSSPath = path.resolve(tmpdir, 'after.css')
84
+ defer(() => {
85
+ if (fs.existsSync(afterCSSPath)) {
86
+ fs.unlinkSync(afterCSSPath)
87
+ }
88
+ })
89
+
90
+ await withPackages(packageManager, packages, async () => {
91
+ await processDone(
92
+ child_process.fork(selfPath, [
93
+ 'dump',
94
+ '--output',
95
+ afterCSSPath,
96
+ ...(afterConfig != null ? ['--config', afterConfig] : []),
97
+ ])
98
+ )
99
+ })
100
+
101
+ const beforeStyles = collectClassNamesAndStyles(
102
+ postcss
103
+ .parse(fs.readFileSync(beforeCSSPath, { encoding: 'utf8' }))
104
+ .toResult()
105
+ )
106
+ const afterStyles = collectClassNamesAndStyles(
107
+ postcss
108
+ .parse(fs.readFileSync(afterCSSPath, { encoding: 'utf8' }))
109
+ .toResult()
110
+ )
111
+
112
+ const diffs = diffsBetweenStyles(beforeStyles, afterStyles)
113
+
114
+ if (format === 'json') {
115
+ const json = diffs.map((item) => ({
116
+ ...item,
117
+ css: item.css.map((rule) => rule.toString()),
118
+ }))
119
+ process.stdout.write(JSON.stringify(json))
120
+ } else {
121
+ let added = 0
122
+ let removed = 0
123
+ for (const item of diffs) {
124
+ if (item.status === 'added') {
125
+ added++
126
+ } else {
127
+ removed++
128
+ }
129
+ }
130
+ console.log(`${added} classes added, ${removed} classes removed.`)
131
+ }
132
+ } finally {
133
+ dispose()
134
+ process.off('SIGINT', dispose)
135
+ }
136
+ }
@@ -0,0 +1,45 @@
1
+ import fs from 'fs'
2
+ import path from 'path'
3
+ import stream from 'stream'
4
+ import importFrom from 'import-from'
5
+ import type { TailwindConfig } from 'tailwindcss/tailwind-config'
6
+
7
+ const sourceCSS = `
8
+ @tailwind base;
9
+ @tailwind components;
10
+ @tailwind utilities;
11
+ `
12
+
13
+ export interface DumpConfig {
14
+ output?: string
15
+ config?: string
16
+ }
17
+
18
+ export async function dump({ output, config }: DumpConfig) {
19
+ const targetDir = process.cwd()
20
+ const postcss = importFrom(
21
+ targetDir,
22
+ 'postcss'
23
+ ) as typeof import('postcss').default
24
+ const tailwindcss = importFrom(
25
+ targetDir,
26
+ 'tailwindcss'
27
+ ) as typeof import('tailwindcss')
28
+ const tailwindConfig = importFrom.silent(
29
+ targetDir,
30
+ config != null ? config : 'tailwind.config.js'
31
+ ) as TailwindConfig
32
+ const result = await postcss([tailwindcss(tailwindConfig)]).process(
33
+ sourceCSS,
34
+ {
35
+ from: undefined,
36
+ to: undefined,
37
+ map: false,
38
+ }
39
+ )
40
+ const sink =
41
+ output != null
42
+ ? fs.createWriteStream(path.resolve(targetDir, output))
43
+ : process.stdout
44
+ stream.Readable.from(result.css).pipe(sink)
45
+ }
package/src/defer.ts ADDED
@@ -0,0 +1,27 @@
1
+ export function createDefer() {
2
+ const defers: (() => void)[] = []
3
+
4
+ const defer = (deferFn: () => void) => {
5
+ defers.push(deferFn)
6
+ }
7
+
8
+ const dispose = () => {
9
+ // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition
10
+ while (true) {
11
+ const deferFn = defers.pop()
12
+ if (deferFn == null) {
13
+ return
14
+ }
15
+ try {
16
+ deferFn()
17
+ } catch (err: unknown) {
18
+ console.error('Uncaught defer error:', err)
19
+ }
20
+ }
21
+ }
22
+
23
+ return {
24
+ defer,
25
+ dispose,
26
+ } as const
27
+ }
package/src/index.ts ADDED
@@ -0,0 +1,69 @@
1
+ import yargs from 'yargs'
2
+ import { check } from './commands/check'
3
+ import { dump } from './commands/dump'
4
+
5
+ void yargs
6
+ .scriptName('tailwind-diff')
7
+ .command(
8
+ 'check',
9
+ 'checks diffs due to package updates',
10
+ () =>
11
+ yargs
12
+ .option('config', {
13
+ type: 'string',
14
+ description: 'tailwind config file',
15
+ })
16
+ .alias('c', 'config')
17
+ .option('before-config', {
18
+ type: 'string',
19
+ description: 'tailwind config used in first build',
20
+ })
21
+ .option('after-config', {
22
+ type: 'string',
23
+ description: 'tailwind config used in second build',
24
+ })
25
+ .option('packages', {
26
+ type: 'array',
27
+ description: 'packages to be update',
28
+ })
29
+ .option('json', {
30
+ type: 'boolean',
31
+ description: 'print result as JSON format',
32
+ }),
33
+ ({
34
+ config,
35
+ 'after-config': afterConfig,
36
+ 'before-config': beforeConfig,
37
+ packages,
38
+ json = false,
39
+ }) => {
40
+ void check({
41
+ format: json ? 'json' : 'default',
42
+ beforeConfig: beforeConfig != null ? beforeConfig : config,
43
+ afterConfig: afterConfig != null ? afterConfig : config,
44
+ packages: packages != null ? packages.map((v) => `${v}`) : undefined,
45
+ })
46
+ }
47
+ )
48
+ .command(
49
+ 'dump',
50
+ 'dump Tailwind CSS with config',
51
+ () =>
52
+ yargs
53
+ .option('output', { type: 'string', description: 'output file' })
54
+ .alias('o', 'output')
55
+ .option('config', {
56
+ type: 'string',
57
+ description: 'tailwind config file',
58
+ })
59
+ .alias('c', 'config'),
60
+ ({ output, config }) => {
61
+ void dump({
62
+ output,
63
+ config,
64
+ })
65
+ }
66
+ )
67
+ .demandCommand()
68
+ .help()
69
+ .parse()
@@ -0,0 +1,60 @@
1
+ import fs from 'fs'
2
+ import os from 'os'
3
+ import path from 'path'
4
+
5
+ type PackageManagerType = 'npm' | 'yarn' | 'pnpm'
6
+
7
+ export interface PackageManagerInfo {
8
+ type: PackageManagerType
9
+ packageJSONPath: string
10
+ lockfilePath: string | undefined
11
+ }
12
+
13
+ export function detectPackageManager(base: string): PackageManagerInfo {
14
+ const upperbounds = [os.homedir(), path.resolve('/')]
15
+ let dir = fs.statSync(base).isDirectory() ? base : path.dirname(base)
16
+
17
+ while (!fs.existsSync(path.join(dir, 'package.json'))) {
18
+ const parent = path.dirname(dir)
19
+ if (upperbounds.includes(parent)) {
20
+ throw new Error('No node project found.')
21
+ }
22
+ dir = parent
23
+ }
24
+ const packageJSONPath = path.join(dir, 'package.json')
25
+
26
+ let type: PackageManagerType = 'npm'
27
+ let lockfilePath: string | undefined
28
+ do {
29
+ let lockfile: string
30
+
31
+ lockfile = path.join(dir, 'package-lock.json')
32
+ if (fs.existsSync(lockfile)) {
33
+ lockfilePath = lockfile
34
+ type = 'npm'
35
+ break
36
+ }
37
+
38
+ lockfile = path.join(dir, 'yarn.lock')
39
+ if (fs.existsSync(lockfile)) {
40
+ lockfilePath = lockfile
41
+ type = 'yarn'
42
+ break
43
+ }
44
+
45
+ lockfile = path.join(dir, 'pnpm-lock.yaml')
46
+ if (fs.existsSync(lockfile)) {
47
+ lockfilePath = lockfile
48
+ type = 'pnpm'
49
+ break
50
+ }
51
+
52
+ dir = path.dirname(dir)
53
+ } while (!upperbounds.includes(dir))
54
+
55
+ return {
56
+ type,
57
+ packageJSONPath,
58
+ lockfilePath,
59
+ }
60
+ }
package/src/style.ts ADDED
@@ -0,0 +1,88 @@
1
+ import type { Result, Rule } from 'postcss'
2
+ import postcssSelectorParser from 'postcss-selector-parser'
3
+
4
+ type ClassToStyles = Map<string, Rule[]>
5
+
6
+ const selectorParser = postcssSelectorParser()
7
+
8
+ export function collectClassNamesAndStyles(result: Result): ClassToStyles {
9
+ const classToStyles = new Map<string, Rule[]>()
10
+
11
+ result.root.walkRules((rule) => {
12
+ selectorParser.astSync(rule.selector).walkClasses((node) => {
13
+ const className = node.value.trim()
14
+
15
+ const styles = classToStyles.get(className)
16
+ if (styles != null) {
17
+ styles.push(rule)
18
+ } else {
19
+ classToStyles.set(className, [rule])
20
+ }
21
+ })
22
+ })
23
+
24
+ return classToStyles
25
+ }
26
+
27
+ export interface TailwindDiffItem {
28
+ className: string
29
+ css: Rule[]
30
+ status: 'added' | 'removed'
31
+ }
32
+
33
+ // :の後ろが同じものが並んでほしいのでそれを前にしてソートする
34
+ const tailwindClassNameSortMapper = (className: string) => {
35
+ if (className.includes(':')) {
36
+ const items = className.split(':')
37
+ let result = ''
38
+ result += items.pop()
39
+ result += `:${items.join(':')}`
40
+ return result
41
+ } else {
42
+ return className
43
+ }
44
+ }
45
+ const tailwindDiffItemSortMapper = (item: TailwindDiffItem) =>
46
+ tailwindClassNameSortMapper(item.className)
47
+ const mappedSorter =
48
+ <A, B>(mapper: (value: A) => B) =>
49
+ (lhs: A, rhs: A) => {
50
+ const mappedLhs = mapper(lhs)
51
+ const mappedRhs = mapper(rhs)
52
+ if (mappedLhs < mappedRhs) {
53
+ return -1
54
+ }
55
+ if (mappedLhs > mappedRhs) {
56
+ return 1
57
+ }
58
+ return 0
59
+ }
60
+ export function diffsBetweenStyles(
61
+ before: ClassToStyles,
62
+ after: ClassToStyles
63
+ ) {
64
+ const diffs: TailwindDiffItem[] = []
65
+
66
+ for (const afterClassName of after.keys()) {
67
+ if (!before.has(afterClassName)) {
68
+ diffs.push({
69
+ className: afterClassName,
70
+ status: 'added',
71
+ css: after.get(afterClassName)!,
72
+ })
73
+ }
74
+ }
75
+ for (const beforeClassName of before.keys()) {
76
+ if (!after.has(beforeClassName)) {
77
+ diffs.push({
78
+ className: beforeClassName,
79
+ status: 'removed',
80
+ css: before.get(beforeClassName)!,
81
+ })
82
+ }
83
+ }
84
+
85
+ diffs.sort(mappedSorter(tailwindDiffItemSortMapper))
86
+
87
+ return diffs
88
+ }
@@ -0,0 +1,89 @@
1
+ import child_process from 'child_process'
2
+ import fs from 'fs'
3
+ import os from 'os'
4
+ import path from 'path'
5
+ import { createDefer } from './defer'
6
+ import { PackageManagerInfo } from './packageManager'
7
+
8
+ /**
9
+ * 指定したバージョンのパッケージが存在する状態で処理を行う
10
+ *
11
+ * @param packageDescripters 欲しいパッケージの一覧
12
+ * @param callback 実行したい処理
13
+ */
14
+ export async function withPackages<T>(
15
+ packageManagerInfo: PackageManagerInfo,
16
+ packageDescripters: readonly string[],
17
+ callback: () => T | Promise<T>
18
+ ): Promise<T> {
19
+ if (packageDescripters.length === 0) {
20
+ return callback()
21
+ }
22
+
23
+ const deferer = createDefer()
24
+ const { defer, dispose } = deferer
25
+ process.on('SIGINT', dispose)
26
+
27
+ try {
28
+ const tmpdir = fs.mkdtempSync(
29
+ path.join(os.tmpdir(), 'tailwind-diff-packages-')
30
+ )
31
+ defer(() => {
32
+ const files = fs.readdirSync(tmpdir)
33
+ for (const file of files) {
34
+ fs.unlinkSync(path.resolve(tmpdir, file))
35
+ }
36
+ fs.rmdirSync(tmpdir)
37
+ })
38
+
39
+ const backupPackageJSONPath = path.join(tmpdir, 'package.json')
40
+ fs.copyFileSync(packageManagerInfo.packageJSONPath, backupPackageJSONPath)
41
+
42
+ const packageLock =
43
+ packageManagerInfo.lockfilePath != null
44
+ ? {
45
+ path: packageManagerInfo.lockfilePath,
46
+ backup: path.join(
47
+ tmpdir,
48
+ path.basename(packageManagerInfo.lockfilePath)
49
+ ),
50
+ }
51
+ : undefined
52
+ if (packageLock != null) {
53
+ fs.copyFileSync(packageLock.path, packageLock.backup)
54
+ }
55
+
56
+ let cmd: string, recoverCmd: string
57
+ switch (packageManagerInfo.type) {
58
+ case 'npm':
59
+ cmd = `npm install ${packageDescripters.join(' ')}`
60
+ recoverCmd = 'npm install'
61
+ break
62
+ case 'yarn':
63
+ cmd = `yarn add ${packageDescripters.join(' ')}`
64
+ recoverCmd = 'yarn install'
65
+ break
66
+ case 'pnpm':
67
+ cmd = `pnpm add ${packageDescripters.join(' ')}`
68
+ recoverCmd = 'pnpm install'
69
+ break
70
+ }
71
+
72
+ // execに失敗してもファイルは回復してほしい
73
+ defer(() => {
74
+ fs.unlinkSync(packageManagerInfo.packageJSONPath)
75
+ fs.copyFileSync(backupPackageJSONPath, packageManagerInfo.packageJSONPath)
76
+ if (packageLock != null) {
77
+ fs.unlinkSync(packageLock.path)
78
+ fs.copyFileSync(packageLock.backup, packageLock.path)
79
+ }
80
+ child_process.execSync(recoverCmd)
81
+ })
82
+ child_process.execSync(cmd)
83
+
84
+ return callback()
85
+ } finally {
86
+ dispose()
87
+ process.off('SIGINT', dispose)
88
+ }
89
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "module": "commonjs",
5
+ "outDir": "./dist"
6
+ },
7
+ "include": ["./src"]
8
+ }