mirror of https://github.com/grafana/grafana
Toolkit: moved front end cli scripts to separate package and introduced very early version of plugin tools
* Move cli to grafana-toolkit * Moving packages, fixing ts * Add basics of plugin build task * Add toolkit build task * Circle - use node 10 for test-frontend * Prettier fix * First attempt for having shared tsconfig for plugins * Add enzyme as peer depencency * Do not expose internal commands when using toolkit from npm package * Introduce plugin linting * Fix missing file * Fix shim extenstion * Remove rollup typings * Add tslint as dependency * Toolkit - use the same versions of enzyme and tslint as core does * Remove include property from plugin tsconfig * Take failed suites into consideration when tests failed * Set ts-jest preset for jest * Cleanup tsconfig.plugins * Add plugin:test task * Rename file causing build failute * Fixing those missed renames * Add ts as peer dependency * Remove enzyme dependency and tweak test plugin task * Allow jest options overrides via package.json config * Improvements * Remove rollup node packages * TMP : Fix ts errors when linked * use local tslint if it exists * support coverage commands * Fix merge * fix build * Some minors * Make jest pass when no tests discoveredpull/17798/head^2
parent
ead4b1f5c7
commit
742e0d56eb
@ -0,0 +1,52 @@ |
||||
# Grafana Toolkit |
||||
|
||||
Make sure to run `yarn install` before trying anything! Otherwise you may see unknown command grafana-toolkit and spend a while tracking that down. |
||||
|
||||
## Internal development |
||||
For development use `yarn link`. First, navigate to `packages/grafana-toolkit` and run `yarn link`. Then, in your project use `yarn link @grafana/toolkit` to use linked version. |
||||
|
||||
## Grafana extensions development with grafana-toolkit overview |
||||
|
||||
### Typescript |
||||
To configure Typescript create `tsconfig.json` file in the root dir of your app. grafana-toolkit comes with default tsconfig located in `packages/grafana-toolkit/src/config/tsconfig.plugin.ts`. In order for Typescript to be able to pickup your source files you need to extend that config as follows: |
||||
|
||||
```json |
||||
{ |
||||
"extends": "./node_modules/@grafana/toolkit/src/config/tsconfig.plugin.json", |
||||
"include": ["src"], |
||||
"compilerOptions": { |
||||
"rootDir": "./src", |
||||
"typeRoots": ["./node_modules/@types"] |
||||
} |
||||
} |
||||
``` |
||||
|
||||
### TSLint |
||||
grafana-toolkit comes with default config for TSLint, that's located in `packages/grafana-toolkit/src/config/tslint.plugin.ts`. As for now there is now way to customise TSLint config. |
||||
|
||||
### Tests |
||||
grafana-toolkit comes with Jest as a test runner. It runs tests according to common config locted in `packages/grafana-toolkit/src/config/jest.plugin.config.ts`. |
||||
|
||||
For now the config is not extendable, but our goal is to enable custom jest config via jest.config or package.json file. This might be required in the future if you want to use i.e. `enzyme-to-json` snapshots serializer. For that particular serializer we can also utilise it's API and add initialisation in the setup files (https://github.com/adriantoine/enzyme-to-json#serializer-in-unit-tests). We need to test that approach first. |
||||
|
||||
#### Jest setup |
||||
We are not opinionated about tool used for implmenting tests. Internally at Grafana we use Enzyme. If you want to configure Enzyme as a testing utility, you need to configure enzyme-adapter-react. To do so, you need to create `[YOUR_APP]/config/jest-setup.ts` file that will provide React/Enzyme setup. Simply copy following code into that file to get Enzyme working with React: |
||||
|
||||
```ts |
||||
import { configure } from 'enzyme'; |
||||
import Adapter from 'enzyme-adapter-react-16'; |
||||
|
||||
configure({ adapter: new Adapter() }); |
||||
``` |
||||
|
||||
grafana-toolkit will use that file as Jest's setup file. You can also setup Jest with shims of your needs by creating `jest-shim.ts` file in the same directory: `[YOUR_APP]/config/jest-shim.ts` |
||||
|
||||
Adidtionaly, you can also provide additional Jest config via package.json file. For more details please refer to [Jest docs](https://jest-bot.github.io/jest/docs/configuration.html#verbose-boolean). Currently we support following properties: |
||||
- [`snapshotSerializers`](https://jest-bot.github.io/jest/docs/configuration.html#snapshotserializers-array-string) |
||||
|
||||
## Prettier [todo] |
||||
|
||||
## Development mode [todo] |
||||
TODO |
||||
- Enable rollup watch on extension sources |
||||
|
@ -0,0 +1,5 @@ |
||||
#!/usr/bin/env node
|
||||
|
||||
// This bin is used for cli installed from npm
|
||||
|
||||
require('../src/cli/index.js').run(); |
@ -0,0 +1,13 @@ |
||||
#!/usr/bin/env node
|
||||
|
||||
var path = require('path') ; |
||||
|
||||
// This bin is used for cli executed internally
|
||||
|
||||
var tsProjectPath = path.resolve(__dirname, '../tsconfig.json'); |
||||
|
||||
require('ts-node').register({ |
||||
project: tsProjectPath |
||||
}); |
||||
|
||||
require('../src/cli/index.ts').run(true); |
@ -0,0 +1,71 @@ |
||||
{ |
||||
"name": "@grafana/toolkit", |
||||
"version": "6.3.0-alpha.2", |
||||
"description": "Grafana Toolkit", |
||||
"keywords": [ |
||||
"typescript", |
||||
"react", |
||||
"react-component" |
||||
], |
||||
"bin": { |
||||
"grafana-toolkit": "./bin/grafana-toolkit.js" |
||||
}, |
||||
"scripts": { |
||||
"tslint": "tslint -c tslint.json --project tsconfig.json", |
||||
"typecheck": "tsc --noEmit", |
||||
"precommit": "npm run tslint & npm run typecheck", |
||||
"clean": "rimraf ./dist ./compiled" |
||||
}, |
||||
"author": "Grafana Labs", |
||||
"license": "Apache-2.0", |
||||
"dependencies": { |
||||
"@types/execa": "^0.9.0", |
||||
"@types/inquirer": "^6.0.3", |
||||
"@types/jest": "24.0.13", |
||||
"@types/jest-cli": "^23.6.0", |
||||
"@types/node": "^12.0.4", |
||||
"@types/prettier": "^1.16.4", |
||||
"@types/semver": "^6.0.0", |
||||
"axios": "0.19.0", |
||||
"chalk": "^2.4.2", |
||||
"commander": "^2.20.0", |
||||
"concurrently": "4.1.0", |
||||
"execa": "^1.0.0", |
||||
"glob": "^7.1.4", |
||||
"inquirer": "^6.3.1", |
||||
"jest-cli": "^24.8.0", |
||||
"lodash": "4.17.11", |
||||
"ora": "^3.4.0", |
||||
"prettier": "^1.17.1", |
||||
"replace-in-file": "^4.1.0", |
||||
"rollup": "^1.14.2", |
||||
"rollup-plugin-commonjs": "^10.0.0", |
||||
"rollup-plugin-copy-glob": "^0.3.0", |
||||
"rollup-plugin-json": "^4.0.0", |
||||
"rollup-plugin-node-builtins": "^2.1.2", |
||||
"rollup-plugin-node-globals": "^1.4.0", |
||||
"rollup-plugin-node-resolve": "^5.1.0", |
||||
"rollup-plugin-sourcemaps": "^0.4.2", |
||||
"rollup-plugin-terser": "^5.0.0", |
||||
"rollup-plugin-typescript2": "^0.21.1", |
||||
"rollup-plugin-visualizer": "^1.1.1", |
||||
"semver": "^6.1.1", |
||||
"simple-git": "^1.112.0", |
||||
"ts-node": "^8.2.0", |
||||
"tslint": "5.14.0" |
||||
}, |
||||
"peerDependencies": { |
||||
"jest": "24.8.0", |
||||
"ts-jest": "24.0.2", |
||||
"tslib": "1.10.0", |
||||
"typescript": "3.5.1" |
||||
}, |
||||
"resolutions": { |
||||
"@types/lodash": "4.14.119", |
||||
"rollup-plugin-typescript2": "0.21.1" |
||||
}, |
||||
"devDependencies": { |
||||
"@types/glob": "^7.1.1", |
||||
"rollup-watch": "^4.3.1" |
||||
} |
||||
} |
@ -0,0 +1,166 @@ |
||||
// @ts-ignore
|
||||
import program from 'commander'; |
||||
import { execTask } from './utils/execTask'; |
||||
import chalk from 'chalk'; |
||||
import { startTask } from './tasks/core.start'; |
||||
import { buildTask } from './tasks/grafanaui.build'; |
||||
import { releaseTask } from './tasks/grafanaui.release'; |
||||
import { changelogTask } from './tasks/changelog'; |
||||
import { cherryPickTask } from './tasks/cherrypick'; |
||||
import { precommitTask } from './tasks/precommit'; |
||||
import { templateTask } from './tasks/template'; |
||||
import { pluginBuildTask } from './tasks/plugin.build'; |
||||
import { toolkitBuildTask } from './tasks/toolkit.build'; |
||||
import { pluginTestTask } from './tasks/plugin.tests'; |
||||
import { searchTestDataSetupTask } from './tasks/searchTestDataSetup'; |
||||
import { closeMilestoneTask } from './tasks/closeMilestone'; |
||||
import { pluginDevTask } from './tasks/plugin.dev'; |
||||
|
||||
export const run = (includeInternalScripts = false) => { |
||||
if (includeInternalScripts) { |
||||
program.option('-d, --depreciate <scripts>', 'Inform about npm script deprecation', v => v.split(',')); |
||||
program |
||||
.command('core:start') |
||||
.option('-h, --hot', 'Run front-end with HRM enabled') |
||||
.option('-t, --watchTheme', 'Watch for theme changes and regenerate variables.scss files') |
||||
.description('Starts Grafana front-end in development mode with watch enabled') |
||||
.action(async cmd => { |
||||
await execTask(startTask)({ |
||||
watchThemes: cmd.watchTheme, |
||||
hot: cmd.hot, |
||||
}); |
||||
}); |
||||
|
||||
program |
||||
.command('gui:build') |
||||
.description('Builds @grafana/ui package to packages/grafana-ui/dist') |
||||
.action(async cmd => { |
||||
// @ts-ignore
|
||||
await execTask(buildTask)(); |
||||
}); |
||||
|
||||
program |
||||
.command('gui:release') |
||||
.description('Prepares @grafana/ui release (and publishes to npm on demand)') |
||||
.option('-p, --publish', 'Publish @grafana/ui to npm registry') |
||||
.option('-u, --usePackageJsonVersion', 'Use version specified in package.json') |
||||
.option('--createVersionCommit', 'Create and push version commit') |
||||
.action(async cmd => { |
||||
await execTask(releaseTask)({ |
||||
publishToNpm: !!cmd.publish, |
||||
usePackageJsonVersion: !!cmd.usePackageJsonVersion, |
||||
createVersionCommit: !!cmd.createVersionCommit, |
||||
}); |
||||
}); |
||||
|
||||
program |
||||
.command('changelog') |
||||
.option('-m, --milestone <milestone>', 'Specify milestone') |
||||
.description('Builds changelog markdown') |
||||
.action(async cmd => { |
||||
if (!cmd.milestone) { |
||||
console.log('Please specify milestone, example: -m <milestone id from github milestone URL>'); |
||||
return; |
||||
} |
||||
|
||||
await execTask(changelogTask)({ |
||||
milestone: cmd.milestone, |
||||
}); |
||||
}); |
||||
|
||||
program |
||||
.command('cherrypick') |
||||
.description('Helps find commits to cherry pick') |
||||
.action(async cmd => { |
||||
await execTask(cherryPickTask)({}); |
||||
}); |
||||
|
||||
program |
||||
.command('precommit') |
||||
.description('Executes checks') |
||||
.action(async cmd => { |
||||
await execTask(precommitTask)({}); |
||||
}); |
||||
|
||||
program |
||||
.command('debug:template') |
||||
.description('Just testing') |
||||
.action(async cmd => { |
||||
await execTask(templateTask)({}); |
||||
}); |
||||
|
||||
program |
||||
.command('toolkit:build') |
||||
.description('Prepares grafana/toolkit dist package') |
||||
.action(async cmd => { |
||||
// @ts-ignore
|
||||
await execTask(toolkitBuildTask)(); |
||||
}); |
||||
|
||||
program |
||||
.command('searchTestData') |
||||
.option('-c, --count <number_of_dashboards>', 'Specify number of dashboards') |
||||
.description('Setup test data for search') |
||||
.action(async cmd => { |
||||
await execTask(searchTestDataSetupTask)({ count: cmd.count }); |
||||
}); |
||||
|
||||
program |
||||
.command('close-milestone') |
||||
.option('-m, --milestone <milestone>', 'Specify milestone') |
||||
.description('Helps ends a milestone by removing the cherry-pick label and closing it') |
||||
.action(async cmd => { |
||||
if (!cmd.milestone) { |
||||
console.log('Please specify milestone, example: -m <milestone id from github milestone URL>'); |
||||
return; |
||||
} |
||||
|
||||
await execTask(closeMilestoneTask)({ |
||||
milestone: cmd.milestone, |
||||
}); |
||||
}); |
||||
} |
||||
|
||||
program |
||||
.command('plugin:build') |
||||
.description('Prepares plugin dist package') |
||||
.action(async cmd => { |
||||
await execTask(pluginBuildTask)({}); |
||||
}); |
||||
|
||||
program |
||||
.command('plugin:dev') |
||||
.description('Starts plugin dev mode') |
||||
.action(async cmd => { |
||||
await execTask(pluginDevTask)({ |
||||
watch: true, |
||||
}); |
||||
}); |
||||
|
||||
program |
||||
.command('plugin:test') |
||||
.option('-u, --updateSnapshot', 'Run snapshots update') |
||||
.option('--coverage', 'Run code coverage') |
||||
.description('Executes plugin tests') |
||||
.action(async cmd => { |
||||
await execTask(pluginTestTask)({ |
||||
updateSnapshot: !!cmd.updateSnapshot, |
||||
coverage: !!cmd.coverage, |
||||
}); |
||||
}); |
||||
|
||||
program.on('command:*', () => { |
||||
console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' ')); |
||||
process.exit(1); |
||||
}); |
||||
|
||||
program.parse(process.argv); |
||||
|
||||
if (program.depreciate && program.depreciate.length === 2) { |
||||
console.log( |
||||
chalk.yellow.bold( |
||||
`[NPM script depreciation] ${program.depreciate[0]} is deprecated! Use ${program.depreciate[1]} instead!` |
||||
) |
||||
); |
||||
} |
||||
}; |
@ -0,0 +1,84 @@ |
||||
import { Task, TaskRunner } from './task'; |
||||
// @ts-ignore
|
||||
import execa = require('execa'); |
||||
import path = require('path'); |
||||
import fs = require('fs'); |
||||
import glob = require('glob'); |
||||
import * as rollup from 'rollup'; |
||||
import { inputOptions, outputOptions } from '../../config/rollup.plugin.config'; |
||||
|
||||
import { useSpinner } from '../utils/useSpinner'; |
||||
import { Linter, Configuration, RuleFailure } from 'tslint'; |
||||
import { testPlugin } from './plugin/tests'; |
||||
interface PrecommitOptions {} |
||||
|
||||
// @ts-ignore
|
||||
export const clean = useSpinner<void>('Cleaning', async () => await execa('rimraf', ['./dist'])); |
||||
|
||||
// @ts-ignore
|
||||
const typecheckPlugin = useSpinner<void>('Typechecking', async () => { |
||||
await execa('tsc', ['--noEmit']); |
||||
}); |
||||
|
||||
// @ts-ignore
|
||||
const lintPlugin = useSpinner<void>('Linting', async () => { |
||||
let tsLintConfigPath = path.resolve(process.cwd(), 'tslint.json'); |
||||
if (!fs.existsSync(tsLintConfigPath)) { |
||||
tsLintConfigPath = path.resolve(__dirname, '../../config/tslint.plugin.json'); |
||||
} |
||||
const globPattern = path.resolve(process.cwd(), 'src/**/*.+(ts|tsx)'); |
||||
const sourcesToLint = glob.sync(globPattern); |
||||
const options = { |
||||
fix: true, // or fail
|
||||
formatter: 'json', |
||||
}; |
||||
|
||||
const configuration = Configuration.findConfiguration(tsLintConfigPath).results; |
||||
|
||||
const lintResults = sourcesToLint |
||||
.map(fileName => { |
||||
const linter = new Linter(options); |
||||
const fileContents = fs.readFileSync(fileName, 'utf8'); |
||||
linter.lint(fileName, fileContents, configuration); |
||||
return linter.getResult(); |
||||
}) |
||||
.filter(result => { |
||||
return result.errorCount > 0 || result.warningCount > 0; |
||||
}); |
||||
|
||||
if (lintResults.length > 0) { |
||||
console.log('\n'); |
||||
const failures = lintResults.reduce<RuleFailure[]>((failures, result) => { |
||||
return [...failures, ...result.failures]; |
||||
}, []); |
||||
failures.forEach(f => { |
||||
// tslint:disable-next-line
|
||||
console.log( |
||||
`${f.getRuleSeverity() === 'warning' ? 'WARNING' : 'ERROR'}: ${f.getFileName().split('src')[1]}[${ |
||||
f.getStartPosition().getLineAndCharacter().line |
||||
}:${f.getStartPosition().getLineAndCharacter().character}]: ${f.getFailure()}` |
||||
); |
||||
}); |
||||
console.log('\n'); |
||||
throw new Error(`${failures.length} linting errors found in ${lintResults.length} files`); |
||||
} |
||||
}); |
||||
|
||||
const bundlePlugin = useSpinner<void>('Bundling plugin', async () => { |
||||
// @ts-ignore
|
||||
const bundle = await rollup.rollup(inputOptions()); |
||||
// TODO: we can work on more verbose output
|
||||
await bundle.generate(outputOptions); |
||||
await bundle.write(outputOptions); |
||||
}); |
||||
|
||||
const pluginBuildRunner: TaskRunner<PrecommitOptions> = async () => { |
||||
await clean(); |
||||
// @ts-ignore
|
||||
await lintPlugin(); |
||||
await testPlugin({ updateSnapshot: false, coverage: false }); |
||||
// @ts-ignore
|
||||
await bundlePlugin(); |
||||
}; |
||||
|
||||
export const pluginBuildTask = new Task<PrecommitOptions>('Build plugin', pluginBuildRunner); |
@ -0,0 +1,9 @@ |
||||
import { Task, TaskRunner } from './task'; |
||||
import { bundlePlugin, PluginBundleOptions } from './plugin/bundle'; |
||||
|
||||
const pluginDevRunner: TaskRunner<PluginBundleOptions> = async options => { |
||||
const result = await bundlePlugin(options); |
||||
return result; |
||||
}; |
||||
|
||||
export const pluginDevTask = new Task<PluginBundleOptions>('Dev plugin', pluginDevRunner); |
@ -0,0 +1,8 @@ |
||||
import { Task, TaskRunner } from './task'; |
||||
import { testPlugin, PluginTestOptions } from './plugin/tests'; |
||||
|
||||
const pluginTestRunner: TaskRunner<PluginTestOptions> = async options => { |
||||
await testPlugin(options); |
||||
}; |
||||
|
||||
export const pluginTestTask = new Task<PluginTestOptions>('Test plugin', pluginTestRunner); |
@ -0,0 +1,29 @@ |
||||
import path = require('path'); |
||||
import * as jestCLI from 'jest-cli'; |
||||
import * as rollup from 'rollup'; |
||||
import { inputOptions, outputOptions } from '../../../config/rollup.plugin.config'; |
||||
|
||||
export interface PluginBundleOptions { |
||||
watch: boolean; |
||||
} |
||||
|
||||
export const bundlePlugin = async ({ watch }: PluginBundleOptions) => { |
||||
if (watch) { |
||||
const watcher = rollup.watch([ |
||||
{ |
||||
...inputOptions(), |
||||
output: outputOptions, |
||||
watch: { |
||||
chokidar: true, |
||||
clearScreen: true, |
||||
}, |
||||
}, |
||||
]); |
||||
} else { |
||||
// @ts-ignore
|
||||
const bundle = await rollup.rollup(inputOptions()); |
||||
// TODO: we can work on more verbose output
|
||||
await bundle.generate(outputOptions); |
||||
await bundle.write(outputOptions); |
||||
} |
||||
}; |
@ -0,0 +1,22 @@ |
||||
import path = require('path'); |
||||
import * as jestCLI from 'jest-cli'; |
||||
import { useSpinner } from '../../utils/useSpinner'; |
||||
import { jestConfig } from '../../../config/jest.plugin.config'; |
||||
|
||||
export interface PluginTestOptions { |
||||
updateSnapshot: boolean; |
||||
coverage: boolean; |
||||
} |
||||
|
||||
export const testPlugin = useSpinner<PluginTestOptions>('Running tests', async ({ updateSnapshot, coverage }) => { |
||||
const testConfig = jestConfig(); |
||||
|
||||
testConfig.updateSnapshot = updateSnapshot; |
||||
testConfig.coverage = coverage; |
||||
|
||||
const results = await jestCLI.runCLI(testConfig as any, [process.cwd()]); |
||||
|
||||
if (results.results.numFailedTests > 0 || results.results.numFailedTestSuites > 0) { |
||||
throw new Error('Tests failed'); |
||||
} |
||||
}); |
@ -0,0 +1,9 @@ |
||||
import { Task, TaskRunner } from './task'; |
||||
|
||||
interface TemplateOptions {} |
||||
|
||||
const templateRunner: TaskRunner<TemplateOptions> = async () => { |
||||
console.log('Template task'); |
||||
}; |
||||
|
||||
export const templateTask = new Task<TemplateOptions>('Template task', templateRunner); |
@ -0,0 +1,91 @@ |
||||
import execa = require('execa'); |
||||
import * as fs from 'fs'; |
||||
import { changeCwdToGrafanaUi, restoreCwd, changeCwdToGrafanaToolkit } from '../utils/cwd'; |
||||
import chalk from 'chalk'; |
||||
import { useSpinner } from '../utils/useSpinner'; |
||||
import { Task, TaskRunner } from './task'; |
||||
|
||||
let distDir: string, cwd: string; |
||||
|
||||
// @ts-ignore
|
||||
export const clean = useSpinner<void>('Cleaning', async () => await execa('npm', ['run', 'clean'])); |
||||
|
||||
// @ts-ignore
|
||||
const compile = useSpinner<void>('Compiling sources', async () => { |
||||
try { |
||||
await execa('tsc', ['-p', './tsconfig.json']); |
||||
} catch (e) { |
||||
console.log(e); |
||||
throw e; |
||||
} |
||||
}); |
||||
|
||||
// @ts-ignore
|
||||
export const savePackage = useSpinner<{ |
||||
path: string; |
||||
pkg: {}; |
||||
// @ts-ignore
|
||||
}>('Updating package.json', async ({ path, pkg }) => { |
||||
return new Promise((resolve, reject) => { |
||||
fs.writeFile(path, JSON.stringify(pkg, null, 2), err => { |
||||
if (err) { |
||||
reject(err); |
||||
return; |
||||
} |
||||
resolve(); |
||||
}); |
||||
}); |
||||
}); |
||||
|
||||
const preparePackage = async (pkg: any) => { |
||||
pkg.bin = { |
||||
'grafana-toolkit': './bin/grafana-toolkit.dist.js', |
||||
}; |
||||
|
||||
await savePackage({ |
||||
path: `${cwd}/dist/package.json`, |
||||
pkg, |
||||
}); |
||||
}; |
||||
|
||||
const moveFiles = () => { |
||||
const files = [ |
||||
'README.md', |
||||
'CHANGELOG.md', |
||||
'bin/grafana-toolkit.dist.js', |
||||
'src/config/tsconfig.plugin.json', |
||||
'src/config/tslint.plugin.json', |
||||
]; |
||||
// @ts-ignore
|
||||
return useSpinner<void>(`Moving ${files.join(', ')} files`, async () => { |
||||
const promises = files.map(file => { |
||||
return new Promise((resolve, reject) => { |
||||
fs.copyFile(`${cwd}/${file}`, `${distDir}/${file}`, err => { |
||||
if (err) { |
||||
reject(err); |
||||
return; |
||||
} |
||||
resolve(); |
||||
}); |
||||
}); |
||||
}); |
||||
|
||||
await Promise.all(promises); |
||||
})(); |
||||
}; |
||||
|
||||
const toolkitBuildTaskRunner: TaskRunner<void> = async () => { |
||||
cwd = changeCwdToGrafanaToolkit(); |
||||
distDir = `${cwd}/dist`; |
||||
const pkg = require(`${cwd}/package.json`); |
||||
console.log(chalk.yellow(`Building ${pkg.name} (package.json version: ${pkg.version})`)); |
||||
|
||||
await clean(); |
||||
await compile(); |
||||
await preparePackage(pkg); |
||||
fs.mkdirSync('./dist/bin'); |
||||
await moveFiles(); |
||||
restoreCwd(); |
||||
}; |
||||
|
||||
export const toolkitBuildTask = new Task<void>('@grafana/toolkit build', toolkitBuildTaskRunner); |
@ -0,0 +1,6 @@ |
||||
{ |
||||
"extends": "../../../tsconfig.json", |
||||
"compilerOptions": { |
||||
"module": "commonjs" |
||||
} |
||||
} |
@ -0,0 +1,45 @@ |
||||
import path = require('path'); |
||||
import fs = require('fs'); |
||||
|
||||
const whitelistedJestConfigOverrides = ['snapshotSerializers']; |
||||
|
||||
export const jestConfig = () => { |
||||
const jestConfigOverrides = require(path.resolve(process.cwd(), 'package.json')).jest; |
||||
const blacklistedOverrides = jestConfigOverrides |
||||
? Object.keys(jestConfigOverrides).filter(override => whitelistedJestConfigOverrides.indexOf(override) === -1) |
||||
: []; |
||||
if (blacklistedOverrides.length > 0) { |
||||
console.error("\ngrafana-toolkit doesn't support following Jest options: ", blacklistedOverrides); |
||||
console.log('Supported Jest options are: ', JSON.stringify(whitelistedJestConfigOverrides)); |
||||
throw new Error('Provided Jest config is not supported'); |
||||
} |
||||
|
||||
const shimsFilePath = path.resolve(process.cwd(), 'config/jest-shim.ts'); |
||||
const setupFilePath = path.resolve(process.cwd(), 'config/jest-setup.ts'); |
||||
|
||||
const setupFile = fs.existsSync(setupFilePath) ? setupFilePath : undefined; |
||||
const shimsFile = fs.existsSync(shimsFilePath) ? shimsFilePath : undefined; |
||||
const setupFiles = [setupFile, shimsFile].filter(f => f); |
||||
const defaultJestConfig = { |
||||
preset: 'ts-jest', |
||||
verbose: false, |
||||
transform: { |
||||
'^.+\\.(ts|tsx)$': 'ts-jest', |
||||
}, |
||||
moduleDirectories: ['node_modules', 'src'], |
||||
rootDir: process.cwd(), |
||||
roots: ['<rootDir>/src'], |
||||
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'], |
||||
setupFiles, |
||||
globals: { 'ts-jest': { isolatedModules: true } }, |
||||
coverageReporters: ['json-summary', 'text', 'lcov'], |
||||
collectCoverageFrom: ['src/**/*.{ts,tsx}', '!**/node_modules/**', '!**/vendor/**'], |
||||
updateSnapshot: false, |
||||
passWithNoTests: true, |
||||
}; |
||||
|
||||
return { |
||||
...defaultJestConfig, |
||||
...jestConfigOverrides, |
||||
}; |
||||
}; |
@ -0,0 +1,160 @@ |
||||
// @ts-ignore
|
||||
import resolve from 'rollup-plugin-node-resolve'; |
||||
// @ts-ignore
|
||||
import commonjs from 'rollup-plugin-commonjs'; |
||||
// @ts-ignore
|
||||
import sourceMaps from 'rollup-plugin-sourcemaps'; |
||||
// @ts-ignore
|
||||
import typescript from 'rollup-plugin-typescript2'; |
||||
// @ts-ignore
|
||||
import json from 'rollup-plugin-json'; |
||||
// @ts-ignore
|
||||
import copy from 'rollup-plugin-copy-glob'; |
||||
// @ts-ignore
|
||||
import { terser } from 'rollup-plugin-terser'; |
||||
// @ts-ignore
|
||||
import visualizer from 'rollup-plugin-visualizer'; |
||||
|
||||
// @ts-ignore
|
||||
const replace = require('replace-in-file'); |
||||
const pkg = require(`${process.cwd()}/package.json`); |
||||
const path = require('path'); |
||||
const fs = require('fs'); |
||||
const tsConfig = require(`${__dirname}/tsconfig.plugin.json`); |
||||
import { OutputOptions, InputOptions, GetManualChunk } from 'rollup'; |
||||
const { PRODUCTION } = process.env; |
||||
|
||||
export const outputOptions: OutputOptions = { |
||||
dir: 'dist', |
||||
format: 'amd', |
||||
sourcemap: true, |
||||
chunkFileNames: '[name].js', |
||||
}; |
||||
|
||||
const findModuleTs = (base: string, files?: string[], result?: string[]) => { |
||||
files = files || fs.readdirSync(base); |
||||
result = result || []; |
||||
|
||||
if (files) { |
||||
files.forEach(file => { |
||||
const newbase = path.join(base, file); |
||||
if (fs.statSync(newbase).isDirectory()) { |
||||
result = findModuleTs(newbase, fs.readdirSync(newbase), result); |
||||
} else { |
||||
if (file.indexOf('module.ts') > -1) { |
||||
// @ts-ignore
|
||||
result.push(newbase); |
||||
} |
||||
} |
||||
}); |
||||
} |
||||
return result; |
||||
}; |
||||
|
||||
const getModuleFiles = () => { |
||||
return findModuleTs(path.resolve(process.cwd(), 'src')); |
||||
}; |
||||
|
||||
const getManualChunk: GetManualChunk = (id: string) => { |
||||
// id == absolute path
|
||||
if (id.endsWith('module.ts')) { |
||||
const idx = id.indexOf('/src/'); |
||||
if (idx > 0) { |
||||
const p = id.substring(idx + 5, id.lastIndexOf('.')); |
||||
console.log('MODULE:', id, p); |
||||
return p; |
||||
} |
||||
} |
||||
console.log('shared:', id); |
||||
return 'shared'; |
||||
}; |
||||
|
||||
const getExternals = () => { |
||||
// Those are by default exported by Grafana
|
||||
const defaultExternals = [ |
||||
'jquery', |
||||
'lodash', |
||||
'moment', |
||||
'rxjs', |
||||
'd3', |
||||
'react', |
||||
'react-dom', |
||||
'@grafana/ui', |
||||
'@grafana/runtime', |
||||
'@grafana/data', |
||||
]; |
||||
const toolkitConfig = require(path.resolve(process.cwd(), 'package.json')).grafanaToolkit; |
||||
const userDefinedExternals = (toolkitConfig && toolkitConfig.externals) || []; |
||||
return [...defaultExternals, ...userDefinedExternals]; |
||||
}; |
||||
|
||||
export const inputOptions = (): InputOptions => { |
||||
const inputFiles = getModuleFiles(); |
||||
return { |
||||
input: inputFiles, |
||||
manualChunks: inputFiles.length > 1 ? getManualChunk : undefined, |
||||
external: getExternals(), |
||||
plugins: [ |
||||
// Allow json resolution
|
||||
json(), |
||||
// globals(),
|
||||
// builtins(),
|
||||
|
||||
// Compile TypeScript files
|
||||
typescript({ |
||||
typescript: require('typescript'), |
||||
objectHashIgnoreUnknownHack: true, |
||||
tsconfigDefaults: tsConfig, |
||||
}), |
||||
|
||||
// Allow node_modules resolution, so you can use 'external' to control
|
||||
// which external modules to include in the bundle
|
||||
// https://github.com/rollup/rollup-plugin-node-resolve#usage
|
||||
resolve(), |
||||
|
||||
// Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs)
|
||||
commonjs(), |
||||
|
||||
// Resolve source maps to the original source
|
||||
sourceMaps(), |
||||
|
||||
// Minify
|
||||
PRODUCTION && terser(), |
||||
|
||||
// Copy files
|
||||
copy([{ files: 'src/**/*.{json,svg,png,html}', dest: 'dist' }], { verbose: true }), |
||||
|
||||
// Help avoid including things accidentally
|
||||
visualizer({ |
||||
filename: 'dist/stats.html', |
||||
title: 'Plugin Stats', |
||||
}), |
||||
|
||||
// Custom callback when we are done
|
||||
finish(), |
||||
], |
||||
}; |
||||
}; |
||||
|
||||
function finish() { |
||||
return { |
||||
name: 'finish', |
||||
buildEnd() { |
||||
const files = 'dist/plugin.json'; |
||||
replace.sync({ |
||||
files: files, |
||||
from: /%VERSION%/g, |
||||
to: pkg.version, |
||||
}); |
||||
replace.sync({ |
||||
files: files, |
||||
from: /%TODAY%/g, |
||||
to: new Date().toISOString().substring(0, 10), |
||||
}); |
||||
|
||||
if (PRODUCTION) { |
||||
console.log('*minified*'); |
||||
} |
||||
}, |
||||
}; |
||||
} |
@ -0,0 +1,30 @@ |
||||
{ |
||||
"compilerOptions": { |
||||
"moduleResolution": "node", |
||||
"target": "es5", |
||||
"lib": ["es6", "dom"], |
||||
"module": "esnext", |
||||
"strict": true, |
||||
"alwaysStrict": true, |
||||
"noImplicitAny": true, |
||||
"noImplicitReturns": true, |
||||
"noImplicitThis": true, |
||||
"noImplicitUseStrict": false, |
||||
"noUnusedLocals": true, |
||||
"strictNullChecks": true, |
||||
"skipLibCheck": true, |
||||
"removeComments": false, |
||||
"jsx": "react", |
||||
"allowSyntheticDefaultImports": true, |
||||
"esModuleInterop": true, |
||||
"forceConsistentCasingInFileNames": true, |
||||
"importHelpers": true, |
||||
"noEmitHelpers": true, |
||||
"inlineSourceMap": false, |
||||
"sourceMap": true, |
||||
"emitDecoratorMetadata": false, |
||||
"experimentalDecorators": true, |
||||
"downlevelIteration": true, |
||||
"pretty": true |
||||
} |
||||
} |
@ -0,0 +1,75 @@ |
||||
{ |
||||
"rules": { |
||||
"array-type": [true, "array-simple"], |
||||
"arrow-return-shorthand": true, |
||||
"ban": [true, { "name": "Array", "message": "tsstyle#array-constructor" }], |
||||
"ban-types": [ |
||||
true, |
||||
["Object", "Use {} instead."], |
||||
["String", "Use 'string' instead."], |
||||
["Number", "Use 'number' instead."], |
||||
["Boolean", "Use 'boolean' instead."] |
||||
], |
||||
"interface-name": [true, "never-prefix"], |
||||
"no-string-throw": true, |
||||
"no-unused-expression": true, |
||||
"no-unused-variable": false, |
||||
"no-use-before-declare": false, |
||||
"no-duplicate-variable": true, |
||||
"curly": true, |
||||
"class-name": true, |
||||
"semicolon": [true, "always", "ignore-bound-class-methods"], |
||||
"triple-equals": [true, "allow-null-check"], |
||||
"comment-format": [false, "check-space"], |
||||
"eofline": true, |
||||
"forin": false, |
||||
"indent": [true, "spaces", 2], |
||||
"jsdoc-format": true, |
||||
"label-position": true, |
||||
"max-line-length": [true, 150], |
||||
"member-access": [true, "no-public"], |
||||
"new-parens": true, |
||||
"no-angle-bracket-type-assertion": true, |
||||
"no-arg": true, |
||||
"no-bitwise": false, |
||||
"no-conditional-assignment": true, |
||||
"no-console": [true, "debug", "info", "time", "timeEnd", "trace"], |
||||
"no-construct": true, |
||||
"no-debugger": true, |
||||
"no-empty": false, |
||||
"no-eval": true, |
||||
"no-inferrable-types": true, |
||||
"no-namespace": [true, "allow-declarations"], |
||||
"no-reference": true, |
||||
"no-shadowed-variable": false, |
||||
"no-string-literal": false, |
||||
"no-switch-case-fall-through": false, |
||||
"no-trailing-whitespace": true, |
||||
"no-var-keyword": true, |
||||
"object-literal-sort-keys": false, |
||||
"one-line": [true, "check-open-brace", "check-catch", "check-else"], |
||||
"only-arrow-functions": [true, "allow-declarations", "allow-named-functions"], |
||||
"prefer-const": true, |
||||
"radix": true, |
||||
"typedef-whitespace": [ |
||||
true, |
||||
{ |
||||
"call-signature": "nospace", |
||||
"index-signature": "nospace", |
||||
"parameter": "nospace", |
||||
"property-declaration": "nospace", |
||||
"variable-declaration": "nospace" |
||||
} |
||||
], |
||||
"variable-name": [ |
||||
true, |
||||
"check-format", |
||||
"ban-keywords", |
||||
"allow-leading-underscore", |
||||
"allow-trailing-underscore", |
||||
"allow-pascal-case" |
||||
], |
||||
"use-isnan": true, |
||||
"whitespace": [true, "check-branch", "check-decl", "check-type", "check-preblock"] |
||||
} |
||||
} |
@ -0,0 +1,18 @@ |
||||
{ |
||||
"include": ["src/**/*.ts"], |
||||
"exclude": ["dist", "node_modules"], |
||||
"compilerOptions": { |
||||
"module": "commonjs", |
||||
"rootDirs": ["."], |
||||
"outDir": "dist/src", |
||||
"strict": true, |
||||
"alwaysStrict": true, |
||||
"noImplicitAny": true, |
||||
"strictNullChecks": true, |
||||
"typeRoots": ["./node_modules/@types"], |
||||
"skipLibCheck": true, // Temp workaround for Duplicate identifier tsc errors, |
||||
"removeComments": false, |
||||
"esModuleInterop": true, |
||||
"lib": ["es2015", "es2017.string"] |
||||
} |
||||
} |
@ -0,0 +1,6 @@ |
||||
{ |
||||
"extends": "../../tslint.json", |
||||
"rules": { |
||||
"import-blacklist": [true, ["^@grafana/runtime.*"]] |
||||
} |
||||
} |
@ -1,108 +0,0 @@ |
||||
import program from 'commander'; |
||||
import { execTask } from './utils/execTask'; |
||||
import chalk from 'chalk'; |
||||
import { startTask } from './tasks/core.start'; |
||||
import { buildTask } from './tasks/grafanaui.build'; |
||||
import { releaseTask } from './tasks/grafanaui.release'; |
||||
import { changelogTask } from './tasks/changelog'; |
||||
import { cherryPickTask } from './tasks/cherrypick'; |
||||
import { closeMilestoneTask } from './tasks/closeMilestone'; |
||||
import { precommitTask } from './tasks/precommit'; |
||||
import { searchTestDataSetupTask } from './tasks/searchTestDataSetup'; |
||||
|
||||
program.option('-d, --depreciate <scripts>', 'Inform about npm script deprecation', v => v.split(',')); |
||||
|
||||
program |
||||
.command('core:start') |
||||
.option('-h, --hot', 'Run front-end with HRM enabled') |
||||
.option('-t, --watchTheme', 'Watch for theme changes and regenerate variables.scss files') |
||||
.description('Starts Grafana front-end in development mode with watch enabled') |
||||
.action(async cmd => { |
||||
await execTask(startTask)({ |
||||
watchThemes: cmd.watchTheme, |
||||
hot: cmd.hot, |
||||
}); |
||||
}); |
||||
|
||||
program |
||||
.command('gui:build') |
||||
.description('Builds @grafana/ui package to packages/grafana-ui/dist') |
||||
.action(async cmd => { |
||||
await execTask(buildTask)(); |
||||
}); |
||||
|
||||
program |
||||
.command('gui:release') |
||||
.description('Prepares @grafana/ui release (and publishes to npm on demand)') |
||||
.option('-p, --publish', 'Publish @grafana/ui to npm registry') |
||||
.option('-u, --usePackageJsonVersion', 'Use version specified in package.json') |
||||
.option('--createVersionCommit', 'Create and push version commit') |
||||
.action(async cmd => { |
||||
await execTask(releaseTask)({ |
||||
publishToNpm: !!cmd.publish, |
||||
usePackageJsonVersion: !!cmd.usePackageJsonVersion, |
||||
createVersionCommit: !!cmd.createVersionCommit, |
||||
}); |
||||
}); |
||||
|
||||
program |
||||
.command('changelog') |
||||
.option('-m, --milestone <milestone>', 'Specify milestone') |
||||
.description('Builds changelog markdown') |
||||
.action(async cmd => { |
||||
if (!cmd.milestone) { |
||||
console.log('Please specify milestone, example: -m <milestone id from github milestone URL>'); |
||||
return; |
||||
} |
||||
|
||||
await execTask(changelogTask)({ |
||||
milestone: cmd.milestone, |
||||
}); |
||||
}); |
||||
|
||||
program |
||||
.command('cherrypick') |
||||
.description('Helps find commits to cherry pick') |
||||
.action(async cmd => { |
||||
await execTask(cherryPickTask)({}); |
||||
}); |
||||
|
||||
program |
||||
.command('close-milestone') |
||||
.option('-m, --milestone <milestone>', 'Specify milestone') |
||||
.description('Helps ends a milestone by removing the cherry-pick label and closing it') |
||||
.action(async cmd => { |
||||
if (!cmd.milestone) { |
||||
console.log('Please specify milestone, example: -m <milestone id from github milestone URL>'); |
||||
return; |
||||
} |
||||
|
||||
await execTask(closeMilestoneTask)({ |
||||
milestone: cmd.milestone, |
||||
}); |
||||
}); |
||||
|
||||
program |
||||
.command('precommit') |
||||
.description('Executes checks') |
||||
.action(async cmd => { |
||||
await execTask(precommitTask)({}); |
||||
}); |
||||
|
||||
program |
||||
.command('searchTestData') |
||||
.option('-c, --count <number_of_dashboards>', 'Specify number of dashboards') |
||||
.description('Setup test data for search') |
||||
.action(async cmd => { |
||||
await execTask(searchTestDataSetupTask)({ count: cmd.count }); |
||||
}); |
||||
|
||||
program.parse(process.argv); |
||||
|
||||
if (program.depreciate && program.depreciate.length === 2) { |
||||
console.log( |
||||
chalk.yellow.bold( |
||||
`[NPM script depreciation] ${program.depreciate[0]} is deprecated! Use ${program.depreciate[1]} instead!` |
||||
) |
||||
); |
||||
} |
Loading…
Reference in new issue