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(cli): add Button codemods #596

Merged
merged 12 commits into from
Jun 4, 2020
Merged
5 changes: 2 additions & 3 deletions .cz-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,8 @@ module.exports = {
{ name: 'components' },
{ name: 'utils' },
{ name: 'docs' },
{ name: 'theme' },
{ name: 'configs' },
{ name: 'scripts' }
{ name: 'cli' },
{ name: 'configs' }
],

allowCustomScopes: true,
Expand Down
15 changes: 14 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,19 @@ module.exports = require('@sumup/foundry/eslint')(
},
parserOptions: {
project: ['./tsconfig.eslint.json']
}
},
overrides: [
{
files: [
'**/__testfixtures__/**/*.input.*',
'**/__testfixtures__/**/*.output.*'
],
rules: {
'import/no-unresolved': 'off',
'notice/notice': 'off',
'@typescript-eslint/no-unused-vars': 'off'
}
}
]
}
);
9 changes: 8 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
"description": "SumUp's React UI component library",
"main": "dist/cjs/index.js",
"module": "dist/es/index.js",
"bin": {
"circuit-ui": "./dist/cjs/cli/index.js"
},
"files": [
"dist",
"README.md"
Expand All @@ -13,7 +16,7 @@
"commit": "git-cz",
"start": "start-storybook -p 6006 -s .storybook/public",
"dev": "tsc --watch",
"build": "tsc && tsc --project tsconfig.cjs.json",
"build": "tsc && tsc --project tsconfig.cjs.json && chmod +x ./dist/cjs/cli/index.js",
"create:component": "foundry run plop component",
"static-styles": "cross-env BABEL_ENV=static babel-node --extensions '.js,.ts,.tsx' ./scripts/static-styles/cli.js",
"build:docs": "yarn build:storybook && yarn build:stylesheets",
Expand Down Expand Up @@ -54,6 +57,8 @@
},
"homepage": "https://github.com/sumup-oss/circuit-ui#readme",
"dependencies": {
"cross-spawn": "^7.0.3",
"jscodeshift": "^0.9.0",
"lodash": "^4.17.11",
"moment": "^2.24.0",
"no-scroll": "^2.1.1",
Expand Down Expand Up @@ -104,8 +109,10 @@
"@testing-library/react": "^9.1.4",
"@testing-library/react-hooks": "^3.2.1",
"@testing-library/user-event": "^7.0.1",
"@types/cross-spawn": "^6.0.2",
"@types/jest": "^25.2.1",
"@types/jest-axe": "^3.2.2",
"@types/jscodeshift": "^0.7.1",
"@types/lodash": "^4.14.149",
"@types/react": "^16.9.32",
"@types/react-dom": "^16.9.6",
Expand Down
64 changes: 64 additions & 0 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#!/usr/bin/env node

/**
* Copyright 2020, SumUp Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import yargs from 'yargs';

import { migrate, listTransforms } from './migrate';

type CommandType = 'migrate';

// eslint-disable-next-line @typescript-eslint/no-unused-expressions
yargs
.command(
'migrate',
"Automatically transforms your source code to Circuit UI's latest APIs",
yrgs =>
yrgs
.option('transform', {
alias: 't',
desc: 'The transform to be applied to the source code',
choices: listTransforms(),
type: 'string',
required: true
})
.option('language', {
alias: 'l',
desc: 'The programming language of the files to be transformed',
choices: ['TypeScript', 'JavaScript'],
type: 'string',
required: true
})
.option('path', {
alias: 'p',
desc:
'A path to the folder that contains the files to be transformed',
type: 'string',
default: '.'
}),
args => execute('migrate', args)
)
.showHelpOnFail(true)
.demandCommand(1, '')
.help()
.version().argv;

function execute(command: CommandType, args: any): void {
const commands = { migrate };
const commandFn = commands[command];

commandFn(args);
}
34 changes: 34 additions & 0 deletions src/cli/migrate/__testfixtures__/button-props.input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import React from 'react';
import styled from '@emotion/styled';
import { Button, LoadingButton, Text } from '@sumup/circuit-ui';

const Primary = () => <Button primary>primary</Button>;

const Secondary = () => <Button secondary>Secondary</Button>;

const RedButton = styled(Button)`
color: red;
`;

const BlueButton = styled(Button)`
color: blue;
`;

const BlueText = styled(Text)`
color: blue;
`;

const Styled = () => (
<>
<RedButton secondary>Secondary red</RedButton>
<BlueButton primary>Primary blue</BlueButton>
<Text secondary>Text</Text>
<BlueText secondary>Text blue</BlueText>
</>
);

const Flat = () => <Button flat>Flat</Button>;

const Loading = () => (
<LoadingButton secondary>Secondary Loading Button</LoadingButton>
);
34 changes: 34 additions & 0 deletions src/cli/migrate/__testfixtures__/button-props.output.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import React from 'react';
import styled from '@emotion/styled';
import { Button, LoadingButton, Text } from '@sumup/circuit-ui';

const Primary = () => <Button variant="primary">primary</Button>;

const Secondary = () => <Button variant="secondary">Secondary</Button>;

const RedButton = styled(Button)`
color: red;
`;

const BlueButton = styled(Button)`
color: blue;
`;

const BlueText = styled(Text)`
color: blue;
`;

const Styled = () => (
<>
<RedButton variant="secondary">Secondary red</RedButton>
<BlueButton variant="primary">Primary blue</BlueButton>
<Text secondary>Text</Text>
<BlueText secondary>Text blue</BlueText>
</>
);

const Flat = () => <Button>Flat</Button>;

const Loading = () => (
<LoadingButton variant="secondary">Secondary Loading Button</LoadingButton>
);
20 changes: 20 additions & 0 deletions src/cli/migrate/__tests__/button-props.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Copyright 2020, SumUp Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { defineTest } from 'jscodeshift/dist/testUtils';

jest.autoMockOff();

defineTest(__dirname, 'button-props');
80 changes: 80 additions & 0 deletions src/cli/migrate/button-props.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* Copyright 2020, SumUp Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { Transform, JSCodeshift, Collection } from 'jscodeshift';

import { findImportsByPath, findStyledComponentNames } from './utils';

function transformFactory(
j: JSCodeshift,
root: Collection,
buttonName: string
): void {
const imports = findImportsByPath(j, root, '@sumup/circuit-ui');

const buttonImport = imports.find(i => i.name === buttonName);

if (!buttonImport) {
return;
}

const localName = buttonImport.local;

const styledButtons = findStyledComponentNames(j, root, localName);

const components = [localName, ...styledButtons];

components.forEach(component => {
// Change variants from boolean to enum prop
['primary', 'secondary'].forEach(variant => {
root
.findJSXElements(component)
.find(j.JSXAttribute, {
name: {
type: 'JSXIdentifier',
name: variant
}
})
.replaceWith(() =>
j.jsxAttribute(j.jsxIdentifier('variant'), j.stringLiteral(variant))
);
});

// Remove flat variant
root
.findJSXElements(component)
.find(j.JSXAttribute, {
name: {
type: 'JSXIdentifier',
name: 'flat'
}
})
.remove();

// TODO: Replace plain variant with Anchor component
});
}

const transform: Transform = (file, api) => {
const j = api.jscodeshift;
const root = j(file.source);

transformFactory(j, root, 'Button');
transformFactory(j, root, 'LoadingButton');

return root.toSource();
};

export default transform;
64 changes: 64 additions & 0 deletions src/cli/migrate/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* Copyright 2020, SumUp Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import fs from 'fs';
import { sync as spawn } from 'cross-spawn';

export interface MigrateArgs {
transform: string;
language: 'TypeScript' | 'JavaScript';
path: string;
}

const TRANSFORM_DIR = __dirname;
const PARSERS = {
JavaScript: 'babel',
TypeScript: 'tsx'
};

export function migrate({ transform, language, path }: MigrateArgs): void {
const availableTransforms = listTransforms();

if (!availableTransforms.includes(transform)) {
throw new Error(`Unknown codemod ${transform}. Run --help for options.`);
}

if (!['TypeScript', 'JavaScript'].includes(language)) {
throw new Error(`Unknown language ${language}. Run --help for options.`);
}

const parser = PARSERS[language];

spawn(
'npx',
[
'jscodeshift',
'--transform',
`${TRANSFORM_DIR}/${transform}.js`,
'--parser',
parser,
path
],
{ stdio: 'inherit' }
);
}

export function listTransforms(): string[] {
return fs
.readdirSync(TRANSFORM_DIR)
.filter(fname => fname.endsWith('.js'))
.filter(fname => fname !== 'index.js')
.map(fname => fname.replace('.js', ''));
}
Loading