Skip to content

Commit

Permalink
Merge pull request #217 from oceanbase/dengfuping-dev
Browse files Browse the repository at this point in the history
feat(codemod): Add less-to-token transform
  • Loading branch information
dengfuping authored Oct 25, 2023
2 parents ae1db25 + a249190 commit 33c2877
Show file tree
Hide file tree
Showing 11 changed files with 224 additions and 70 deletions.
15 changes: 10 additions & 5 deletions packages/codemod/bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const commandExistsSync = require('command-exists').sync;
const pkg = require('../package.json');
const pkgUpgradeList = require('./upgrade-list');
const { getDependencies } = require('../transforms/utils/marker');
const { lessToToken } = require('../transforms/less-to-token');

// jscodeshift codemod scripts dir
const transformersDir = path.join(__dirname, '../transforms');
Expand All @@ -31,6 +32,7 @@ const transformers = [
'obutil-to-oceanbase-util',
'page-container-to-oceanbase-ui',
'style-to-token',
'less-to-token',
];

const dependencyProperties = [
Expand Down Expand Up @@ -113,12 +115,15 @@ async function transform(transformer, parser, filePath, options) {
});

try {
if (process.env.NODE_ENV === 'local') {
console.log(`Running jscodeshift with: ${JSON.stringify(args)}`);
if (transformer === 'less-to-token') {
await lessToToken(filePath);
} else {
if (process.env.NODE_ENV === 'local') {
console.log(`Running jscodeshift with: ${JSON.stringify(args)}`);
}
// js part
await jscodeshift(transformerPath, [filePath], args);
}

// js part
await jscodeshift(transformerPath, [filePath], args);
console.log();
} catch (err) {
console.error(err);
Expand Down
2 changes: 2 additions & 0 deletions packages/codemod/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
"is-git-clean": "^1.1.0",
"jscodeshift": "^0.15.0",
"lodash": "^4.17.21",
"postcss": "^8.4.31",
"postcss-less": "^6.0.0",
"prettier": "^3.0.3",
"read-pkg-up": "^10.1.0",
"semver": "^7.5.4",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
.container {
color: #1890ff;
background: #52c41a;
background-color: #faad14;
border-color: #ff4D4F;
.content {
color: rgba(0, 0, 0, 0.85);
background: rgba(0, 0, 0,0.65);
background-color: rgba(0,0,0,0.45);
border-color: #fafafa;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
@import '~@oceanbase/design/es/theme/index.less';
.container {
color: @colorInfo;
background: @colorSuccess;
background-color: @colorWarning;
border-color: @colorError;
.content {
color: @colorText;
background: @colorTextSecondary;
background-color: @colorTextTertiary;
border-color: @colorBgLayout;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
@import '~@alipay/ob-ui/es/theme/index.less';

.container {
color: @colorInfo;
background: @colorSuccess;
background-color: @colorWarning;
border-color: @colorError;
.content {
color: rgba(0, 0, 0, 0.85);
background: rgba(0, 0, 0,0.65);
background-color: rgba(0,0,0,0.45);
border-color: #fafafa;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
@import '~@oceanbase/design/es/theme/index.less';
.container {
color: @colorInfo;
background: @colorSuccess;
background-color: @colorWarning;
border-color: @colorError;
.content {
color: @colorText;
background: @colorTextSecondary;
background-color: @colorTextTertiary;
border-color: @colorBgLayout;
}
}
16 changes: 16 additions & 0 deletions packages/codemod/transforms/__tests__/less-to-token.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import fs from 'fs';
import path from 'path';
import { transform } from '../less-to-token';

const testUnit = 'less-to-token';
const tests = ['antd-v4-less-to-token', 'obui-less-to-token'];

describe(testUnit, () => {
tests.forEach(test => {
it(test, async () => {
const result = await transform(path.join(__dirname, `../__testfixtures__/less-to-token/${test}.input.less`))
const output = fs.readFileSync(path.join(__dirname, `../__testfixtures__/less-to-token/${test}.output.less`), 'utf-8');
expect(result).toEqual(output);
})
});
});
86 changes: 86 additions & 0 deletions packages/codemod/transforms/less-to-token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
const path = require('path');
const fs = require('fs');
const postcss = require('postcss');
const postcssLess = require('postcss-less');
const isDirectory = require('is-directory');
const { TOKEN_MAP, formatValue } = require('./utils/token');

/**
* 搜索目录下所有的less文件
* @param dir
* @returns
*/
const findAllLessFiles = dir => {
const lessFiles = [];
const isDir = isDirectory.sync(dir);
if (isDir) {
const files = fs.readdirSync(dir);
files.forEach(file => {
const filePath = path.join(dir, file);
if (isDirectory.sync(filePath)) {
if (filePath.includes('.umi')) {
return;
}
lessFiles.push(...findAllLessFiles(filePath));
} else if (file.endsWith('.less')) {
lessFiles.push(filePath);
}
});
} else {
lessFiles.push(dir);
}
return lessFiles;
};

/**
* 将 lesscode 转化为 ast
* @returns ASR
*/
const less2AST = code =>
postcss([])
.process(code, {
parser: postcssLess.parse,
from: undefined,
})
.then(result => result.root);

async function transform(file) {
const content = fs.readFileSync(file, 'utf-8');
const ast = await less2AST(content);
let modified = false;
let tokenLessImported = false;
// 遍历 AST
ast.walk(node => {
if (node.type === 'decl' && TOKEN_MAP[formatValue(node.value)]) {
node.value = `@${TOKEN_MAP[formatValue(node.value)]}`;
modified = true;
} else if (node.type === 'atrule' && node.name === 'import') {
if (node.params === "'~@oceanbase/design/es/theme/index.less'") {
tokenLessImported = true;
} else if (node.params === "'~@alipay/ob-ui/es/theme/index.less'") {
node.remove();
}
}
});
// prepend @import '~@oceanbase/design/es/theme/index.less';
if (modified && !tokenLessImported) {
ast.prepend({
name: 'import',
params: "'~@oceanbase/design/es/theme/index.less'",
});
}
return ast.toString();
}

async function lessToToken(file) {
const allLessFiles = findAllLessFiles(file);
for await (const item of allLessFiles) {
const content = await transform(item);
fs.writeFileSync(file, content);
}
}

module.exports = {
transform,
lessToToken,
};
50 changes: 1 addition & 49 deletions packages/codemod/transforms/style-to-token.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,7 @@
const { toLower } = require('lodash');
const { addSubmoduleImport } = require('./utils');
const { TOKEN_MAP, formatValue } = require('./utils/token');
const { printOptions } = require('./utils/config');

const TOKEN_MAP = {
// antd fixed style => antd v5 token
'#f0f2f5': 'colorBgLayout',
'#fafafa': 'colorBgLayout',
'#fff': 'colorBgContainer',
'#ffffff': 'colorBgContainer',
'#1890ff': 'colorInfo',
'#52c41a': 'colorSuccess',
'#73d13d': 'colorSuccess',
'#faad14': 'colorWarning',
'#ff4d4f': 'colorError',
'#F5222D': 'colorError',
'#F8636B': 'colorError',
'#d9d9d9': 'colorBorder',
'#bfbfbf': 'colorBorder',
'rgba(0,0,0,0.85)': 'colorText',
'rgba(0,0,0,0.65)': 'colorTextSecondary',
'rgba(0,0,0,0.45)': 'colorTextTertiary',
'rgba(0,0,0,0.25)': 'colorTextQuaternary',
'rgba(0,0,0,0.2)': 'colorFillQuaternary',
'rgba(0,0,0,0.04)': 'colorBgLayout',
};

function trimAll(str) {
return str?.replace(/(\s)*/g, '');
}

function formatValue(value) {
return trimAll(toLower(value));
}

function importComponent(j, root, options) {
let hasChanged = false;

Expand Down Expand Up @@ -76,23 +45,6 @@ function importComponent(j, root, options) {
});
}
}

// const name = path.value.declarations[0].id.name;
// if (/^[A-Z]/.test(name)) {
// const init = path.value.declarations[0].init;
// const initCode = generate(path.value).code;
// if (
// init &&
// initCode.includes('token.') &&
// // avoid duplicate statement
// !initCode.includes('useToken()') &&
// init.type === 'ArrowFunctionExpression'
// ) {
// const codeBody = init.body;
// const importStyleString = `const { token } = theme.useToken();`;
// codeBody.body.unshift(j.blockStatement(importStyleString).program.body[0]);
// }
// }
});
}

Expand Down
38 changes: 38 additions & 0 deletions packages/codemod/transforms/utils/token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const { toLower } = require('lodash');

const TOKEN_MAP = {
// antd fixed style => antd v5 token
'#f0f2f5': 'colorBgLayout',
'#fafafa': 'colorBgLayout',
'#fff': 'colorBgContainer',
'#ffffff': 'colorBgContainer',
'#1890ff': 'colorInfo',
'#52c41a': 'colorSuccess',
'#73d13d': 'colorSuccess',
'#faad14': 'colorWarning',
'#ff4d4f': 'colorError',
'#F5222D': 'colorError',
'#F8636B': 'colorError',
'#d9d9d9': 'colorBorder',
'#bfbfbf': 'colorBorder',
'rgba(0,0,0,0.85)': 'colorText',
'rgba(0,0,0,0.65)': 'colorTextSecondary',
'rgba(0,0,0,0.45)': 'colorTextTertiary',
'rgba(0,0,0,0.25)': 'colorTextQuaternary',
'rgba(0,0,0,0.2)': 'colorFillQuaternary',
'rgba(0,0,0,0.04)': 'colorBgLayout',
};

function trimAll(str) {
return str?.replace(/(\s)*/g, '');
}

function formatValue(value) {
return trimAll(toLower(value));
}

module.exports = {
TOKEN_MAP,
trimAll,
formatValue,
};
Loading

0 comments on commit 33c2877

Please sign in to comment.