为了账号安全,请及时绑定邮箱和手机立即绑定

提升代码质量:SonarScanner和danger集成详解 🚀

解释:

  • 将原标题“Enhance Code Quality: Sonar-Scanner and danger Integration Demystified 🚀”翻译为中文时,我采用了“提升代码质量:SonarScanner和danger集成详解 🚀”。
  • “Enhance Code Quality”翻译为“提升代码质量”,简洁明了地传达了文章的核心内容。
  • “Sonar-Scanner and danger Integration Demystified”翻译为“SonarScanner和danger集成详解”,这样更加符合中文的表达习惯,同时保留了技术术语。
  • 整体标题通俗易懂,符合中文的口语表达习惯。

在我的一篇之前的文章里,我讨论了如何解决npm的peer依赖冲突问题[1]。这次,我想谈谈如何生成关于代码问题的详细报告,特别是如何集成SonarQube,并使用Danger进行自动代码审查。

1. Sonar扫描

SonarQube扫描器(sonar-scanner)是一款用于分析多种编程语言代码质量和安全的工具。它与CI/CD工具如_Jenkins_和_Maven_集成顺畅,提供详细的代码问题报告,增强代码的可维护性,并确保符合最佳编码实践的标准。

下面是如何使用_sonar-scanner_的示例。

    sonar-scanner  
          -Dsonar.projectKey=$sonarQubeProjectKey  
          -Dsonar.login=$sonarQubeToken  
          -Dsonar.sourceEncoding=UTF-8  
          -Dsonar.sources=$npmSonarQubeSources  
          -Dsonar.tests=$npmSonarQubeTests  
          -Dsonar.exclusions=$npmSonarQubeExclusions  
          -Dsonar.test.inclusions=$npmSonarQubeTestInclusions  
          -Dsonar.typescript.lcov.reportPaths=$npmSonarQubeLcovReportPath  
          -Dcom.itestra.cloneview.enabled=false

访问链接: https://docs.sonarsource.com/sonarqube/latest/analyzing-source-code/scanners/sonarscanner-for-npm/introduction/

1.1 Nx 项目的配置

使用 Nx 时,可以使用以下值来填充占位符。

    // 以下为使用 nx 的配置示例
    设置 npmSonarQubeSources = 'apps,libs'  
    设置 npmSonarQubeTests = 'apps,libs'  
    设置 npmSonarQubeExclusions = '**/node_modules/**,**/*-api/**,**/test-setup.ts'  // 排除 node_modules 目录及其子目录、*-api 目录及其子目录、test-setup.ts 文件
    设置 npmSonarQubeTestInclusions = '**/*.spec.ts'  // 包含所有以 .spec.ts 结尾的测试文件
    设置 npmSonarQubeLcovReportPath = 'coverage/lcov.info'  // lcov.info 文件的路径,该文件位于 coverage 文件夹下

因为配置了多个库或应用程序,所以需要把这些覆盖率的报告合并成一个文件。然后可以将这个汇总结果发送到SonarQube

这可以通过下面的代码来实现[2]。但是,为了让它与最新版本的_glob_兼容,需要做一些相应的调整。以下是一个可能的样子。

const {glob} = require('glob'), fs = require('fs'), path = require('path'); // 引入必要的模块

const getLcovFiles = function (src) { // 获取lcov文件列表
    return new Promise((resolve) => { // 返回一个新的Promise对象
        glob(`${src}/**/lcov.info`) // 使用glob查找lcov.info文件
            .then((result) => resolve(result)) // 如果成功解析结果
            .catch(() => resolve([])); // 如果出错返回空数组
    });
};

(async function () { // 异步函数
    const files = await getLcovFiles('coverage'); // 获取coverage目录下的lcov文件
    const mergedReport = files.reduce((mergedReport, currFile) => (mergedReport += fs.readFileSync(currFile)), ''); // 合并所有文件内容

    await fs.writeFile(path.resolve('./coverage/lcov.info'), mergedReport, (err) => { // 写入合并后的报告到文件
        if (err) { throw err; } // 如果有错误,抛出异常
        console.log('文件已经保存!'); // 打印文件已保存的消息
    });
})();

要使用上面的这段脚本,你只需要把 glob 加入依赖。

运行此命令来安装glob包并将其添加到项目的依赖项中: npm install glob --save

1.2. 为其他类型的项目做准备

没有 Nx 这个,这些占位符可以填以下值。

    // 如果没有配置 nxnpmSonarQubeSources = 'src'  
    npmSonarQubeTests = 'src'  
    npmSonarQubeExclusions = '**/node_modules/**,**/*-api/**'  // 排除路径为 '**/node_modules/**,**/*-api/**'  
    npmSonarQubeTestInclusions = '**/*.spec.ts'  // 包含测试文件路径为 '**/*.spec.ts'  
    npmSonarQubeLcovReportPath = 'coverage/lcov.info'  // lcov报告路径为 'coverage/lcov.info'
1.3 配置 Jest

当你用 nxjest(而不是 karma)时,你可以把 coverageReports 选项设置为 lcov,就能轻松生成覆盖率报告。

    // package.json 中的脚本定义

    "coverage:merge": "node merge-coverage.js",  
    "test": "nx run-many --all --target=test --code-coverage --coverageReporters=lcov  // 设置覆盖率报告格式为lcov --parallel=2 --runInBand  // 单线程运行测试 && npm run coverage:merge",  
    "test:ci": "npm run test"  // 在CI环境中运行测试脚本

这里有一个可以用来配置 jest.config 的示例。

// 默认导出配置
export default {  
    displayName: 'common',  
    preset: '../../../jest.preset.js',  
    setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],  
    coverageDirectory: '../../../coverage/libs/common',  
    transform: {  
        '^.+\\.(ts|mjs|js|html)

## 1.4 Karma配置

不过,如果使用 karma 而不是 jest,每个 `karma.conf` 文件都必须包含 `lcovonly` 插件。
module.exports = () => {  
    return {  
        basePath: '',  
        frameworks: ['jasmine', '@angular-devkit/build-angular'],  
        plugins: [  
            require('karma-jasmine'),  
            require('karma-chrome-launcher'),  
            require('karma-jasmine-html-reporter'),  
            require('karma-coverage-istanbul-reporter'),  
            require('@angular-devkit/build-angular/plugins/karma'),  
        ],  
        client: {  
            clearContext: false, // 不清理上下文,以便在浏览器中保留 Jasmine Spec Runner 输出  
        },  
        jasmineHtmlReporter: {  
            suppressAll: true, // 禁用所有跟踪信息  
        },  
        coverageIstanbulReporter: {  
            dir: require('path').join(__dirname, '../../../coverage/common″'),  
            reports: ['html', 'lcovonly'],  
            fixWebpackSourcePaths: true, // 修正 Webpack 源路径  
        },  
        reporters: ['progress', 'kjhtml', 'coverage-istanbul'],  
        ... // 等  
}

并且需要将 `code-coverage` 在 `package.json` 中设置。
"test": "ng test",  
"test:ci": "npm run test -- --watch false --code-coverage=true",
// 运行测试并生成代码覆盖率报告,不启用实时监听

## 第二 危险性。

在 TypeScript 项目中,`danger` 依赖项用于通过检查 `eslint` 规则自动化代码审查流程,帮助通过自动标记拉取请求中的代码规范问题来维持代码质量。集成 `danger` 涉及到设置一个 _Dangerfile_ 文件来定义规则和检查,以确保编码标准的一致性并简化审查过程。

这里有一个 _Dangerfile_ 的例子。
import {danger, fail, schedule, warn} from 'danger';
import {istanbulCoverage} from 'danger-plugin-istanbul-coverage';
import {ESLint} from 'eslint';

// 检查代码的覆盖率
schedule(istanbulCoverage({
    entrySortMethod: 'least-coverage',
    numberOfEntries: 30,
    coveragePath: {path: './coverage/lcov.info', type: 'lcov'},
    reportFileSet: 'createdOrModified',
    reportMode: 'warn',
    threshold: {
        statements: 80,
        branches: 80,
        functions: 80,
        lines: 80
    }
}));

const enum EslintSeverity {
    WARNING = 1,
    ERROR = 2
}

// 检查 ESLint 规则
schedule(async () => {
    try {
        const filesToLint = danger.git.created_files.concat(danger.git.modified_files);
        const eslint = new ESLint({});

        const results = await eslint.lintFiles(filesToLint);

        results.forEach(({filePath, messages}) => {
            messages.forEach(message => {
                if (message.fatal) {
                    warn(`在 ${filePath} 发现致命 ESLint 错误。`);
                    return;
                }

                // 跳过被忽略的文件
                if ((message.message || '').startsWith('File ignored')) {
                    return;
                }

                const fn = reporterFor(message.severity);

                fn(`${filePath} 的第 ${message.line} 行 — ${message.message} (${message.ruleId})`);
            });
        });
    } catch (error) {
        console.error(error);
    }
});

function reporterFor(severity: number): (message: string) => void {
    switch (severity) {
        case EslintSeverity.WARNING:
            return warn;
        case EslintSeverity.ERROR:
            return fail;
        default:
            return () => {};
    }
}

为了能够使用 danger 和代码覆盖率插件,需要将 `danger` 和 `danger-plugin-istanbul-coverage` 添加为依赖。

// 一些较旧的版本的依赖项
"danger": "10.5.3"
"danger-plugin-istanbul-coverage": "^1.6.2"


以下脚本可以加入到 `package.json` 文件中。
"danger:ci": "危险_ci",  
"danger:local": "危险_local"

为了将 `danger` 与 _Gitlab_ 集成在一起,您可以在您的 _CI/CD_ 管道中使用下面的脚本。

export DANGER_GITLAB_HOST=${dangerGitlabHost}
export DANGER_GITLAB_API_BASE_URL=${dangerGitlabApiBaseUrl}

git branch temp_${BRANCHNAME}
git checkout -b ${dangerBaseBranch}
git checkout temp
${BRANCH_NAME}
npm run danger:local -- --base ${dangerBaseBranch}

设置 NODE_TLS_REJECT_UNAUTHORIZED 为 0 以允许不受信任的证书, 运行 danger:ci 并将其恢复为 1

export NODE_TLS_REJECT_UNAUTHORIZED=0
npm run danger:ci
export NODE_TLS_REJECT_UNAUTHORIZED=1


## 最后

我已经演示了如何为Nx中的SonarScanner插件进行配置,以及如何配置其他各种类型的项目。此外,我还强调了使用_Jest_和_Karma_进行测试的区别。通过具体示例,我展示了每种工具的具体配置方案和最佳实践。这种对比意在帮助开发人员更好地制定测试和代码质量策略。

此外,我还展示了如何使用`danger`工具,并将其集成到您的CI/CD流水线中。`danger`通过强制执行_eslint_规则来自动化代码审查过程,通过在拉取请求中标识问题来保持统一的编码标准并简化代码审查流程。

# 链接列表:

[1] <https://medium.com/@robert.maiersilldorff/resolving-npm-peer-dependency-conflicts-70d67f4ca7dc> 解决 npm 依赖冲突的方法

[2] <https://yonatankra.com/如何在Nrwl Nx 单一代码库中创建工作区覆盖率报告/>

# 栈学 🎓

谢谢你看到最后。在你离开前,

* 请为作者**点赞**和**关注**!👏
* 关注我们 [**X**](https://twitter.com/stackademichq) | [**LinkedIn**](https://www.linkedin.com/company/stackademic) | [**YouTube**](https://www.youtube.com/c/stackademic) | [**Discord**](https://discord.gg/in-plain-english-709094664682340443)
* 更多平台等你来:[**In Plain English**](https://plainenglish.io/) | [**CoFeed**](https://cofeed.app/) | [**Differ**](https://differ.blog/)
* 更多内容请浏览我们的网站 [**Stackademic.com**](https://stackademic.com/)
: [  
            'jest-preset-angular',  
            {  
                tsconfig: '<rootDir>/tsconfig.spec.json',  
                stringifyContentPathRegex: '\\.(html|svg)

## 1.4 Karma configuration

However, if using karma instead of jest, each `karma.conf` file needs to include `lcovonly` as a reporter.
module.exports = () => {  
    return {  
        basePath: '',  
        frameworks: ['jasmine', '@angular-devkit/build-angular'],  
        plugins: [  
            require('karma-jasmine'),  
            require('karma-chrome-launcher'),  
            require('karma-jasmine-html-reporter'),  
            require('karma-coverage-istanbul-reporter'),  
            require('@angular-devkit/build-angular/plugins/karma'),  
        ],  
        client: {  
            clearContext: false, // leave Jasmine Spec Runner output visible in browser  
        },  
        jasmineHtmlReporter: {  
            suppressAll: true, // removes the duplicated traces  
        },  
        coverageIstanbulReporter: {  
            dir: require('path').join(__dirname, '../../../coverage/common″'),  
            reports: ['html', 'lcovonly'],  
            fixWebpackSourcePaths: true,  
        },  
        reporters: ['progress', 'kjhtml', 'coverage-istanbul'],  
        ...  
}

And the `code-coverage` option has to be set in the `package.json`.
"test": "ng test",  
"test:ci": "npm run test -- --watch false --code-coverage=true",

## 2\. Danger

In TypeScript projects, the `danger` dependency is used to automate code reviews by checking `eslint` _rules_. It helps maintain code quality by automatically flagging linting issues in pull requests. Integrating `danger` involves setting up a _Dangerfile_ to define the rules and checks, ensuring consistent coding standards and streamlining the review process.

Here’s an example of how a _Dangerfile_ could look like.
import {danger, fail, schedule, warn} from 'danger';  
import {istanbulCoverage} from 'danger-plugin-istanbul-coverage';  
import {ESLint} from 'eslint';  

// Check code coverage  
schedule(istanbulCoverage({  
    entrySortMethod: 'least-coverage',  
    numberOfEntries: 30,  
    coveragePath: {path: './coverage/lcov.info', type: 'lcov'},  
    reportFileSet: 'createdOrModified',  
    reportMode: 'warn',  
    threshold: {  
        statements: 80,  
        branches: 80,  
        functions: 80,  
        lines: 80  
    }  
}));  

const enum EslintSeverity {  
    WARNING = 1,  
    ERROR = 2  
}  

// Check ESLint rules  
schedule(async () => {  
    try {  
        const filesToLint = danger.git.created_files.concat(danger.git.modified_files);  
        const eslint = new ESLint({});  

        const results = await eslint.lintFiles(filesToLint);  

        results.forEach(({filePath, messages}) => {  
            messages.forEach(message => {  
                if (message.fatal) {  
                    warn(`Fatal error linting ${filePath} with eslint.`);  
                    return;  
                }  

                // Skip ignored files  
                if (message.severity === EslintSeverity.WARNING && (message.message || '').startsWith('File ignored')) {  
                    return;  
                }  

                const fn = reporterFor(message.severity);  

                fn(`${filePath} line ${message.line} – ${message.message} (${message.ruleId})`);  
            });  
        });  
    } catch (error) {  
        console.error(error);  
    }  
});  

function reporterFor(severity: number): (message: string) => void {  
    switch (severity) {  
        case EslintSeverity.WARNING:  
            return warn;  
        case EslintSeverity.ERROR:  
            return fail;  
        default:  
            return () => { /* do nothing */  
            };  
    }  
}

In order to use danger and the code-coverage tool, both `danger` and `danger-plugin-istanbul-coverage`have to be added as dependency.
// some older versions  
"danger": "10.5.3",  
"danger-plugin-istanbul-coverage": "^1.6.2",

And the following scripts could be added to the `package.json`.
"danger:ci": "danger ci",  
"danger:local": "danger local"

In order to integrate `danger` with _Gitlab_ , the following script could be used in your _CI/CD_ pipeline.
export DANGER_GITLAB_HOST=${dangerGitlabHost}  
export DANGER_GITLAB_API_BASE_URL=${dangerGitlabApiBaseUrl}  

git branch temp_${BRANCH_NAME}  
git checkout -b ${dangerBaseBranch}  
git checkout temp_${BRANCH_NAME}  
npm run danger:local -- --base ${dangerBaseBranch}  

export NODE_TLS_REJECT_UNAUTHORIZED=0  
npm run danger:ci  
export NODE_TLS_REJECT_UNAUTHORIZED=1

## Summing Up

I have demonstrated how to configure the SonarScanner for Nx and various other types of projects. Furthermore, I have highlighted the differences between using _Jest_ and _Karma_ for testing. By providing examples, I have shown the specific configurations and best practices for each tool. This comparison aims to help developers make informed decisions about their testing and code quality strategies.

Additionally, I have shown the use of `danger` and how to integrate it into your CI/CD pipeline. `danger` helps automate code reviews by enforcing _eslint_ rules, flagging issues in pull requests to maintain consistent coding standards and streamline the review process.

# Links

[1] <https://medium.com/@robert.maiersilldorff/resolving-npm-peer-dependency-conflicts-70d67f4ca7dc>

[2] <https://yonatankra.com/how-to-create-a-workspace-coverage-report-in-nrwl-nx-monorepo/>

# Stackademic 🎓

Thank you for reading until the end. Before you go:

* Please consider **clapping** and **following** the writer! 👏

* Follow us [**X**](https://twitter.com/stackademichq) | [**LinkedIn**](https://www.linkedin.com/company/stackademic) | [**YouTube**](https://www.youtube.com/c/stackademic) | [**Discord**](https://discord.gg/in-plain-english-709094664682340443)

* Visit our other platforms: [**In Plain English**](https://plainenglish.io/) | [**CoFeed**](https://cofeed.app/) | [**Differ**](https://differ.blog/)

* More content at [**Stackademic.com**](https://stackademic.com/)
,  
            },  
        ],  
    },  
    transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$|@datorama/akita)'],  
    snapshotSerializers: [  
        'jest-preset-angular/build/serializers/no-ng-attributes',  
        'jest-preset-angular/build/serializers/ng-snapshot',  
        'jest-preset-angular/build/serializers/html-comment',  
    ],  
    moduleNameMapper: {  
        '^lodash-es

## 1.4 Karma configuration

However, if using karma instead of jest, each `karma.conf` file needs to include `lcovonly` as a reporter.
module.exports = () => {  
    return {  
        basePath: '',  
        frameworks: ['jasmine', '@angular-devkit/build-angular'],  
        plugins: [  
            require('karma-jasmine'),  
            require('karma-chrome-launcher'),  
            require('karma-jasmine-html-reporter'),  
            require('karma-coverage-istanbul-reporter'),  
            require('@angular-devkit/build-angular/plugins/karma'),  
        ],  
        client: {  
            clearContext: false, // leave Jasmine Spec Runner output visible in browser  
        },  
        jasmineHtmlReporter: {  
            suppressAll: true, // removes the duplicated traces  
        },  
        coverageIstanbulReporter: {  
            dir: require('path').join(__dirname, '../../../coverage/common″'),  
            reports: ['html', 'lcovonly'],  
            fixWebpackSourcePaths: true,  
        },  
        reporters: ['progress', 'kjhtml', 'coverage-istanbul'],  
        ...  
}

And the `code-coverage` option has to be set in the `package.json`.
"test": "ng test",  
"test:ci": "npm run test -- --watch false --code-coverage=true",

## 2\. Danger

In TypeScript projects, the `danger` dependency is used to automate code reviews by checking `eslint` _rules_. It helps maintain code quality by automatically flagging linting issues in pull requests. Integrating `danger` involves setting up a _Dangerfile_ to define the rules and checks, ensuring consistent coding standards and streamlining the review process.

Here’s an example of how a _Dangerfile_ could look like.
import {danger, fail, schedule, warn} from 'danger';  
import {istanbulCoverage} from 'danger-plugin-istanbul-coverage';  
import {ESLint} from 'eslint';  

// Check code coverage  
schedule(istanbulCoverage({  
    entrySortMethod: 'least-coverage',  
    numberOfEntries: 30,  
    coveragePath: {path: './coverage/lcov.info', type: 'lcov'},  
    reportFileSet: 'createdOrModified',  
    reportMode: 'warn',  
    threshold: {  
        statements: 80,  
        branches: 80,  
        functions: 80,  
        lines: 80  
    }  
}));  

const enum EslintSeverity {  
    WARNING = 1,  
    ERROR = 2  
}  

// Check ESLint rules  
schedule(async () => {  
    try {  
        const filesToLint = danger.git.created_files.concat(danger.git.modified_files);  
        const eslint = new ESLint({});  

        const results = await eslint.lintFiles(filesToLint);  

        results.forEach(({filePath, messages}) => {  
            messages.forEach(message => {  
                if (message.fatal) {  
                    warn(`Fatal error linting ${filePath} with eslint.`);  
                    return;  
                }  

                // Skip ignored files  
                if (message.severity === EslintSeverity.WARNING && (message.message || '').startsWith('File ignored')) {  
                    return;  
                }  

                const fn = reporterFor(message.severity);  

                fn(`${filePath} line ${message.line} – ${message.message} (${message.ruleId})`);  
            });  
        });  
    } catch (error) {  
        console.error(error);  
    }  
});  

function reporterFor(severity: number): (message: string) => void {  
    switch (severity) {  
        case EslintSeverity.WARNING:  
            return warn;  
        case EslintSeverity.ERROR:  
            return fail;  
        default:  
            return () => { /* do nothing */  
            };  
    }  
}

In order to use danger and the code-coverage tool, both `danger` and `danger-plugin-istanbul-coverage`have to be added as dependency.
// some older versions  
"danger": "10.5.3",  
"danger-plugin-istanbul-coverage": "^1.6.2",

And the following scripts could be added to the `package.json`.
"danger:ci": "danger ci",  
"danger:local": "danger local"

In order to integrate `danger` with _Gitlab_ , the following script could be used in your _CI/CD_ pipeline.
export DANGER_GITLAB_HOST=${dangerGitlabHost}  
export DANGER_GITLAB_API_BASE_URL=${dangerGitlabApiBaseUrl}  

git branch temp_${BRANCH_NAME}  
git checkout -b ${dangerBaseBranch}  
git checkout temp_${BRANCH_NAME}  
npm run danger:local -- --base ${dangerBaseBranch}  

export NODE_TLS_REJECT_UNAUTHORIZED=0  
npm run danger:ci  
export NODE_TLS_REJECT_UNAUTHORIZED=1

## Summing Up

I have demonstrated how to configure the SonarScanner for Nx and various other types of projects. Furthermore, I have highlighted the differences between using _Jest_ and _Karma_ for testing. By providing examples, I have shown the specific configurations and best practices for each tool. This comparison aims to help developers make informed decisions about their testing and code quality strategies.

Additionally, I have shown the use of `danger` and how to integrate it into your CI/CD pipeline. `danger` helps automate code reviews by enforcing _eslint_ rules, flagging issues in pull requests to maintain consistent coding standards and streamline the review process.

# Links

[1] <https://medium.com/@robert.maiersilldorff/resolving-npm-peer-dependency-conflicts-70d67f4ca7dc>

[2] <https://yonatankra.com/how-to-create-a-workspace-coverage-report-in-nrwl-nx-monorepo/>

# Stackademic 🎓

Thank you for reading until the end. Before you go:

* Please consider **clapping** and **following** the writer! 👏

* Follow us [**X**](https://twitter.com/stackademichq) | [**LinkedIn**](https://www.linkedin.com/company/stackademic) | [**YouTube**](https://www.youtube.com/c/stackademic) | [**Discord**](https://discord.gg/in-plain-english-709094664682340443)

* Visit our other platforms: [**In Plain English**](https://plainenglish.io/) | [**CoFeed**](https://cofeed.app/) | [**Differ**](https://differ.blog/)

* More content at [**Stackademic.com**](https://stackademic.com/)
: 'lodash',  
    },  
};
1.4 Karma configuration

However, if using karma instead of jest, each karma.conf file needs to include lcovonly as a reporter.

    module.exports = () => {  
        return {  
            basePath: '',  
            frameworks: ['jasmine', '@angular-devkit/build-angular'],  
            plugins: [  
                require('karma-jasmine'),  
                require('karma-chrome-launcher'),  
                require('karma-jasmine-html-reporter'),  
                require('karma-coverage-istanbul-reporter'),  
                require('@angular-devkit/build-angular/plugins/karma'),  
            ],  
            client: {  
                clearContext: false, // leave Jasmine Spec Runner output visible in browser  
            },  
            jasmineHtmlReporter: {  
                suppressAll: true, // removes the duplicated traces  
            },  
            coverageIstanbulReporter: {  
                dir: require('path').join(__dirname, '../../../coverage/common″'),  
                reports: ['html', 'lcovonly'],  
                fixWebpackSourcePaths: true,  
            },  
            reporters: ['progress', 'kjhtml', 'coverage-istanbul'],  
            ...  
    }

And the code-coverage option has to be set in the package.json.

    "test": "ng test",  
    "test:ci": "npm run test -- --watch false --code-coverage=true",
2. Danger

In TypeScript projects, the danger dependency is used to automate code reviews by checking eslint rules. It helps maintain code quality by automatically flagging linting issues in pull requests. Integrating danger involves setting up a Dangerfile to define the rules and checks, ensuring consistent coding standards and streamlining the review process.

Here’s an example of how a Dangerfile could look like.

    import {danger, fail, schedule, warn} from 'danger';  
    import {istanbulCoverage} from 'danger-plugin-istanbul-coverage';  
    import {ESLint} from 'eslint';  

    // Check code coverage  
    schedule(istanbulCoverage({  
        entrySortMethod: 'least-coverage',  
        numberOfEntries: 30,  
        coveragePath: {path: './coverage/lcov.info', type: 'lcov'},  
        reportFileSet: 'createdOrModified',  
        reportMode: 'warn',  
        threshold: {  
            statements: 80,  
            branches: 80,  
            functions: 80,  
            lines: 80  
        }  
    }));  

    const enum EslintSeverity {  
        WARNING = 1,  
        ERROR = 2  
    }  

    // Check ESLint rules  
    schedule(async () => {  
        try {  
            const filesToLint = danger.git.created_files.concat(danger.git.modified_files);  
            const eslint = new ESLint({});  

            const results = await eslint.lintFiles(filesToLint);  

            results.forEach(({filePath, messages}) => {  
                messages.forEach(message => {  
                    if (message.fatal) {  
                        warn(`Fatal error linting ${filePath} with eslint.`);  
                        return;  
                    }  

                    // Skip ignored files  
                    if (message.severity === EslintSeverity.WARNING && (message.message || '').startsWith('File ignored')) {  
                        return;  
                    }  

                    const fn = reporterFor(message.severity);  

                    fn(`${filePath} line ${message.line} – ${message.message} (${message.ruleId})`);  
                });  
            });  
        } catch (error) {  
            console.error(error);  
        }  
    });  

    function reporterFor(severity: number): (message: string) => void {  
        switch (severity) {  
            case EslintSeverity.WARNING:  
                return warn;  
            case EslintSeverity.ERROR:  
                return fail;  
            default:  
                return () => { /* do nothing */  
                };  
        }  
    }

In order to use danger and the code-coverage tool, both danger and danger-plugin-istanbul-coveragehave to be added as dependency.

    // some older versions  
    "danger": "10.5.3",  
    "danger-plugin-istanbul-coverage": "^1.6.2",

And the following scripts could be added to the package.json.

    "danger:ci": "danger ci",  
    "danger:local": "danger local"

In order to integrate danger with Gitlab , the following script could be used in your CI/CD pipeline.

    export DANGER_GITLAB_HOST=${dangerGitlabHost}  
    export DANGER_GITLAB_API_BASE_URL=${dangerGitlabApiBaseUrl}  

    git branch temp_${BRANCH_NAME}  
    git checkout -b ${dangerBaseBranch}  
    git checkout temp_${BRANCH_NAME}  
    npm run danger:local -- --base ${dangerBaseBranch}  

    export NODE_TLS_REJECT_UNAUTHORIZED=0  
    npm run danger:ci  
    export NODE_TLS_REJECT_UNAUTHORIZED=1
Summing Up

I have demonstrated how to configure the SonarScanner for Nx and various other types of projects. Furthermore, I have highlighted the differences between using Jest and Karma for testing. By providing examples, I have shown the specific configurations and best practices for each tool. This comparison aims to help developers make informed decisions about their testing and code quality strategies.

Additionally, I have shown the use of danger and how to integrate it into your CI/CD pipeline. danger helps automate code reviews by enforcing eslint rules, flagging issues in pull requests to maintain consistent coding standards and streamline the review process.

Links

[1] https://medium.com/@robert.maiersilldorff/resolving-npm-peer-dependency-conflicts-70d67f4ca7dc

[2] https://yonatankra.com/how-to-create-a-workspace-coverage-report-in-nrwl-nx-monorepo/

Stackademic 🎓

Thank you for reading until the end. Before you go:

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消