Convert Figma logo to code with AI

oxsecurity logomegalinter

🦙 MegaLinter analyzes 50 languages, 22 formats, 21 tooling formats, excessive copy-pastes, spelling mistakes and security issues in your repository sources with a GitHub Action, other CI tools or locally.

1,907
235
1,907
85

Top Related Projects

Fast linters runner for Go

⚙️ A curated list of static analysis (SAST) tools and linters for all programming languages, config files, build tools, and more. The focus is on tools which improve code quality.

3,552

coala provides a unified command-line interface for linting and fixing all your code, regardless of the programming languages you use.

Quick Overview

MegaLinter is a powerful, open-source tool for linting and formatting code across multiple languages and frameworks. It combines various linters and formatters into a single, easy-to-use package, helping developers maintain consistent code quality across their projects.

Pros

  • Supports a wide range of programming languages and file types
  • Highly customizable with numerous configuration options
  • Integrates easily with CI/CD pipelines
  • Provides detailed reports and suggestions for code improvements

Cons

  • Can be resource-intensive when running on large codebases
  • Initial setup and configuration may be complex for some users
  • May produce false positives or conflicting suggestions in certain scenarios
  • Requires regular updates to keep linters and formatters current

Getting Started

To use MegaLinter in your project, follow these steps:

  1. Create a .mega-linter.yml file in your repository root:
ENABLE:
  - JAVASCRIPT
  - PYTHON
  - MARKDOWN
JAVASCRIPT_DEFAULT_STYLE: prettier
PYTHON_BLACK_ARGUMENTS: --line-length 100
  1. Add a GitHub Actions workflow file (e.g., .github/workflows/mega-linter.yml):
name: MegaLinter

on:
  pull_request:
    branches: [main]

jobs:
  build:
    name: MegaLinter
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: MegaLinter
        uses: oxsecurity/megalinter@v6
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  1. Commit and push these files to your repository. MegaLinter will now run on every pull request to the main branch, checking your code for style and quality issues.

Competitor Comparisons

Fast linters runner for Go

Pros of golangci-lint

  • Specialized for Go language, offering deeper and more tailored linting
  • Faster execution due to its focus on a single language
  • Extensive configuration options for fine-tuning linting rules

Cons of golangci-lint

  • Limited to Go projects, lacking support for other languages
  • May require more setup and configuration compared to MegaLinter's out-of-the-box approach

Code Comparison

MegaLinter configuration:

ENABLE_LINTERS:
  - GOLANG_GOLANGCI_LINT

golangci-lint configuration:

linters:
  enable:
    - gofmt
    - golint
    - govet

Both tools can be integrated into CI/CD pipelines, but MegaLinter provides a more comprehensive solution for multi-language projects. golangci-lint excels in Go-specific linting, offering deeper analysis and performance optimizations.

MegaLinter supports a wide range of programming languages and file types, making it suitable for diverse projects. However, this versatility may come at the cost of depth in language-specific linting.

golangci-lint's focused approach allows for more advanced Go-specific features and optimizations, but limits its applicability to Go-only projects.

Ultimately, the choice between these tools depends on the project's scope and requirements. For Go-centric projects, golangci-lint may be the preferred option, while MegaLinter is better suited for multi-language environments.

⚙️ A curated list of static analysis (SAST) tools and linters for all programming languages, config files, build tools, and more. The focus is on tools which improve code quality.

Pros of static-analysis

  • Comprehensive list of static analysis tools for various programming languages
  • Community-driven project with regular updates and contributions
  • Provides detailed information about each tool, including language, license, and description

Cons of static-analysis

  • Not an integrated solution; requires manual setup of individual tools
  • Lacks standardized output format across different tools
  • No built-in CI/CD integration or automated workflow

Code comparison

MegaLinter:

MEGALINTER_CONFIG:
  ENABLE:
    - JAVASCRIPT
    - PYTHON
  JAVASCRIPT_DEFAULT_STYLE: prettier
  PYTHON_BLACK_ARGUMENTS: --line-length 100

static-analysis:

- [ESLint](https://github.com/eslint/eslint) - Fully pluggable tool for identifying and reporting on patterns in JavaScript
- [Pylint](https://github.com/PyCQA/pylint) - Fully customizable source code analyzer for Python

MegaLinter provides an integrated configuration for multiple linters, while static-analysis offers a curated list of individual tools that users can choose from and set up separately.

3,552

coala provides a unified command-line interface for linting and fixing all your code, regardless of the programming languages you use.

Pros of coala

  • Language-agnostic design allows for analyzing multiple languages in a single project
  • Highly customizable with a wide range of built-in and external linters
  • Extensible plugin system for creating custom rules and linters

Cons of coala

  • Less active development and community support compared to MegaLinter
  • Steeper learning curve for configuration and usage
  • Limited out-of-the-box support for modern CI/CD integrations

Code Comparison

coala configuration example:

[all]
files = **/*.py
bears = PEP8Bear, PyUnusedCodeBear
use_spaces = True

MegaLinter configuration example:

PYTHON_BLACK_ARGUMENTS: "--line-length=100"
PYTHON_PYLINT_ARGUMENTS: "--max-line-length=100"
VALIDATE_ALL_CODEBASE: true

Both tools offer configuration options, but MegaLinter's approach is more straightforward and aligned with modern CI/CD practices. coala's configuration is more flexible but requires more in-depth knowledge of the tool.

While coala excels in language-agnostic analysis and customization, MegaLinter provides a more user-friendly experience with better integration capabilities for modern development workflows. The choice between the two depends on specific project requirements and team preferences.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

MegaLinter, by OX Security

GitHub release Docker Pulls Downloads/week GitHub stars MegaLinter codecov

Generated by github-dependents-info Secured with Trivy GitHub contributors GitHub Sponsors PRs Welcome Tweet

MegaLinter is an Open-Source tool for CI/CD workflows that analyzes the consistency of your code, IAC, configuration, and scripts in your repository sources, to ensure all your projects sources are clean and formatted whatever IDE/toolbox is used by their developers, powered by OX Security.

Supporting 62 languages, 23 formats, 20 tooling formats and ready to use out of the box, as a GitHub action or any CI system, highly configurable and free for all uses.

MegaLinter has native integrations with many of the major CI/CD tools of the market.

GitHub Gitlab Azure Bitbucket Jenkins Drone Concourse Docker SARIF Grafana

MegaLinter Presentation GIF

Upgrade to MegaLinter v8 :)

Upgrade to v8 Video

Before going below, see Online Documentation Web Site which has a much easier user navigation than this README

Table of Contents

Why MegaLinter

Projects need to contain clean code, in order to avoid technical debt, that makes evolutive maintenance harder and time consuming.

By using code formatters and code linters, you ensure that your code base is easier to read and respects best practices, from the kick-off to each step of the project lifecycle

Not all developers have the good habit to use linters in their IDEs, making code reviews harder and longer to process

By using MegaLinter, you'll enjoy the following benefits for you and your team:

  • At each pull request it will automatically analyze all updated code in all languages
  • Reading error logs, developers learn best practices of the language they're using
  • MegaLinter documentation provides the list of IDE plugins integrating each linter, so developers know which linter and plugins to install
  • MegaLinter is ready out of the box after a quick setup
  • Formatting and fixes can be automatically applied on the git branch or provided in reports
  • This tool is 100% open-source and free for all uses (personal, professional, public and private repositories)
  • MegaLinter can run on any CI tool and be run locally: no need to authorize an external application, and your code base never leaves your tooling ecosystem

Quick Start

  • Run npx mega-linter-runner --install to generate configuration files (you need node.js to be installed)
  • Commit, push, and create a pull request
  • Watch !

Runner Install

Notes:

  • This repo is a hard-fork of GitHub Super-Linter, rewritten in python to add lots of additional features
  • If you are a Super-Linter user, you can transparently switch to MegaLinter and keep the same configuration (just replace super-linter/super-linter@v3 by oxsecurity/megalinter@v8 in your GitHub Action YML file, like on this PR)
  • If you want to use MegaLinter extra features (recommended), please take 5 minutes to use MegaLinter assisted installation
  • For a hand-holdy example of getting started with mega-linter check out this blog post by Alec Johnson

Supported Linters

All linters are integrated in the MegaLinter docker image, which is frequently upgraded with their latest versions

Languages

LanguageLinterAdditional
BASHbash-exec
BASH_EXEC
BASHshellcheck
BASH_SHELLCHECK
GitHub stars sarif
BASHshfmt
BASH_SHFMT
GitHub stars formatter
Ccpplint
C_CPPLINT
GitHub stars
Cclang-format
C_CLANG_FORMAT
GitHub stars autofix
CLOJUREclj-kondo
CLOJURE_CLJ_KONDO
GitHub stars
CLOJUREcljstyle
CLOJURE_CLJSTYLE
GitHub stars autofix
COFFEEcoffeelint
COFFEE_COFFEELINT
GitHub stars
C++ (CPP)cpplint
CPP_CPPLINT
GitHub stars
C++ (CPP)clang-format
CPP_CLANG_FORMAT
GitHub stars autofix
C# (CSHARP)dotnet-format
CSHARP_DOTNET_FORMAT
GitHub stars formatter
C# (CSHARP)csharpier
CSHARP_CSHARPIER
GitHub stars formatter
C# (CSHARP)roslynator
CSHARP_ROSLYNATOR
GitHub stars formatter
DARTdartanalyzer
DART_DARTANALYZER
downgraded version GitHub stars
GOgolangci-lint
GO_GOLANGCI_LINT
GitHub stars autofix
GOrevive
GO_REVIVE
GitHub stars sarif
GROOVYnpm-groovy-lint
GROOVY_NPM_GROOVY_LINT
GitHub stars autofix sarif
JAVAcheckstyle
JAVA_CHECKSTYLE
GitHub stars sarif
JAVApmd
JAVA_PMD
GitHub stars sarif
JAVASCRIPTeslint
JAVASCRIPT_ES
GitHub stars autofix sarif
JAVASCRIPTstandard
JAVASCRIPT_STANDARD
GitHub stars autofix
JAVASCRIPTprettier
JAVASCRIPT_PRETTIER
GitHub stars formatter
JSXeslint
JSX_ESLINT
GitHub stars autofix sarif
KOTLINktlint
KOTLIN_KTLINT
GitHub stars autofix sarif
KOTLINdetekt
KOTLIN_DETEKT
GitHub stars
LUAluacheck
LUA_LUACHECK
GitHub stars
LUAselene
LUA_SELENE
GitHub stars
LUAstylua
LUA_STYLUA
GitHub stars
MAKEFILEcheckmake
MAKEFILE_CHECKMAKE
GitHub stars
PERLperlcritic
PERL_PERLCRITIC
GitHub stars
PHPphpcs
PHP_PHPCS
GitHub stars sarif
PHPphpstan
PHP_PHPSTAN
downgraded version GitHub stars sarif
PHPpsalm
PHP_PSALM
GitHub stars sarif
PHPphplint
PHP_PHPLINT
GitHub stars sarif
PHPphp-cs-fixer
PHP_PHPCSFIXER
GitHub stars
POWERSHELLpowershell
POWERSHELL_POWERSHELL
GitHub stars autofix
POWERSHELLpowershell_formatter
POWERSHELL_POWERSHELL_FORMATTER
GitHub stars formatter
PYTHONpylint
PYTHON_PYLINT
GitHub stars
PYTHONblack
PYTHON_BLACK
GitHub stars formatter
PYTHONflake8
PYTHON_FLAKE8
GitHub stars
PYTHONisort
PYTHON_ISORT
GitHub stars formatter
PYTHONbandit
PYTHON_BANDIT
GitHub stars sarif
PYTHONmypy
PYTHON_MYPY
GitHub stars
PYTHONpyright
PYTHON_PYRIGHT
GitHub stars
PYTHONruff
PYTHON_RUFF
GitHub stars autofix sarif
Rlintr
R_LINTR
GitHub stars
RAKUraku
RAKU_RAKU
GitHub stars
RUBYrubocop
RUBY_RUBOCOP
GitHub stars autofix
RUSTclippy
RUST_CLIPPY
GitHub stars
SALESFORCEsfdx-scanner-apex
SALESFORCE_SFDX_SCANNER_APEX
GitHub stars
SALESFORCEsfdx-scanner-aura
SALESFORCE_SFDX_SCANNER_AURA
GitHub stars
SALESFORCEsfdx-scanner-lwc
SALESFORCE_SFDX_SCANNER_LWC
GitHub stars
SALESFORCElightning-flow-scanner
SALESFORCE_LIGHTNING_FLOW_SCANNER
GitHub stars
SCALAscalafix
SCALA_SCALAFIX
GitHub stars
SQLsqlfluff
SQL_SQLFLUFF
GitHub stars
SQLtsqllint
SQL_TSQLLINT
GitHub stars
SWIFTswiftlint
SWIFT_SWIFTLINT
GitHub stars autofix
TSXeslint
TSX_ESLINT
GitHub stars autofix sarif
TYPESCRIPTeslint
TYPESCRIPT_ES
GitHub stars autofix sarif
TYPESCRIPTts-standard
TYPESCRIPT_STANDARD
GitHub stars autofix
TYPESCRIPTprettier
TYPESCRIPT_PRETTIER
GitHub stars formatter
Visual Basic .NET (VBDOTNET)dotnet-format
VBDOTNET_DOTNET_FORMAT
GitHub stars formatter

Formats

FormatLinterAdditional
CSSstylelint
CSS_STYLELINT
GitHub stars autofix
ENVdotenv-linter
ENV_DOTENV_LINTER
GitHub stars autofix
GRAPHQLgraphql-schema-linter
GRAPHQL_GRAPHQL_SCHEMA_LINTER
GitHub stars
HTMLdjlint
HTML_DJLINT
GitHub stars
HTMLhtmlhint
HTML_HTMLHINT
GitHub stars
JSONjsonlint
JSON_JSONLINT
GitHub stars
JSONeslint-plugin-jsonc
JSON_ESLINT_PLUGIN_JSONC
GitHub stars autofix sarif
JSONv8r
JSON_V8R
GitHub stars
JSONprettier
JSON_PRETTIER
GitHub stars formatter
JSONnpm-package-json-lint
JSON_NPM_PACKAGE_JSON_LINT
GitHub stars
LATEXchktex
LATEX_CHKTEX
MARKDOWNmarkdownlint
MARKDOWN_MARKDOWNLINT
GitHub stars formatter
MARKDOWNremark-lint
MARKDOWN_REMARK_LINT
GitHub stars formatter
MARKDOWNmarkdown-link-check
MARKDOWN_MARKDOWN_LINK_CHECK
GitHub stars
MARKDOWNmarkdown-table-formatter
MARKDOWN_MARKDOWN_TABLE_FORMATTER
GitHub stars formatter
PROTOBUFprotolint
PROTOBUF_PROTOLINT
GitHub stars autofix
RSTrst-lint
RST_RST_LINT
GitHub stars
RSTrstcheck
RST_RSTCHECK
GitHub stars
RSTrstfmt
RST_RSTFMT
formatter
XMLxmllint
XML_XMLLINT
autofix
YAMLprettier
YAML_PRETTIER
GitHub stars formatter
YAMLyamllint
YAML_YAMLLINT
GitHub stars
YAMLv8r
YAML_V8R
GitHub stars

Tooling formats

Tooling formatLinterAdditional
ACTIONactionlint
ACTION_ACTIONLINT
GitHub stars
ANSIBLEansible-lint
ANSIBLE_ANSIBLE_LINT
GitHub stars sarif
APIspectral
API_SPECTRAL
GitHub stars
ARMarm-ttk
ARM_ARM_TTK
GitHub stars
BICEPbicep_linter
BICEP_BICEP_LINTER
GitHub stars
CLOUDFORMATIONcfn-lint
CLOUDFORMATION_CFN_LINT
GitHub stars sarif
DOCKERFILEhadolint
DOCKERFILE_HADOLINT
GitHub stars sarif
EDITORCONFIGeditorconfig-checker
EDITORCONFIG_EDITORCONFIG_CHECKER
GitHub stars
GHERKINgherkin-lint
GHERKIN_GHERKIN_LINT
GitHub stars
KUBERNETESkubeconform
KUBERNETES_KUBECONFORM
GitHub stars
KUBERNETEShelm
KUBERNETES_HELM
GitHub stars
KUBERNETESkubescape
KUBERNETES_KUBESCAPE
downgraded version GitHub stars sarif
PUPPETpuppet-lint
PUPPET_PUPPET_LINT
GitHub stars autofix
SNAKEMAKEsnakemake
SNAKEMAKE_LINT
GitHub stars
SNAKEMAKEsnakefmt
SNAKEMAKE_SNAKEFMT
GitHub stars formatter
TEKTONtekton-lint
TEKTON_TEKTON_LINT
GitHub stars
TERRAFORMtflint
TERRAFORM_TFLINT
GitHub stars sarif
TERRAFORMterrascan
TERRAFORM_TERRASCAN
downgraded version GitHub stars sarif
TERRAFORMterragrunt
TERRAFORM_TERRAGRUNT
GitHub stars autofix
TERRAFORMterraform-fmt
TERRAFORM_TERRAFORM_FMT
GitHub stars formatter

Other

Code quality checkerLinterAdditional
COPYPASTEjscpd
COPYPASTE_JSCPD
GitHub stars
REPOSITORYcheckov
REPOSITORY_CHECKOV
GitHub stars sarif
REPOSITORYdevskim
REPOSITORY_DEVSKIM
GitHub stars sarif
REPOSITORYdustilock
REPOSITORY_DUSTILOCK
GitHub stars sarif
REPOSITORYgit_diff
REPOSITORY_GIT_DIFF
GitHub stars
REPOSITORYgitleaks
REPOSITORY_GITLEAKS
GitHub stars sarif
REPOSITORYgrype
REPOSITORY_GRYPE
downgraded version GitHub stars sarif
REPOSITORYkics
REPOSITORY_KICS
GitHub stars sarif
REPOSITORYls-lint
REPOSITORY_LS_LINT
GitHub stars
REPOSITORYsecretlint
REPOSITORY_SECRETLINT
GitHub stars sarif
REPOSITORYsemgrep
REPOSITORY_SEMGREP
GitHub stars sarif
REPOSITORYsyft
REPOSITORY_SYFT
GitHub stars sarif
REPOSITORYtrivy
REPOSITORY_TRIVY
GitHub stars sarif
REPOSITORYtrivy-sbom
REPOSITORY_TRIVY_SBOM
GitHub stars sarif
REPOSITORYtrufflehog
REPOSITORY_TRUFFLEHOG
GitHub stars
SPELLcspell
SPELL_CSPELL
GitHub stars
SPELLproselint
SPELL_PROSELINT
GitHub stars
SPELLvale
SPELL_VALE
GitHub stars
SPELLlychee
SPELL_LYCHEE
GitHub stars

Installation

Assisted installation

Just run npx mega-linter-runner --install at the root of your repository and answer questions, it will generate ready to use configuration files for MegaLinter :)

Runner Install

Which version to use ?

The following instructions examples are using latest MegaLinter stable version (v8 , always corresponding to the latest release)

  • Docker image: oxsecurity/megalinter:v8
  • GitHub Action: oxsecurity/megalinter@v8

You can also use beta version (corresponding to the content of main branch)

  • Docker image: oxsecurity/megalinter:beta
  • GitHub Action: oxsecurity/megalinter@beta

GitHub Action

  1. Create a new file in your repository called .github/workflows/mega-linter.yml
  2. Copy the example workflow from below into that new file, no extra configuration required
  3. Commit that file to a new branch
  4. Open up a pull request and observe the action working
  5. Enjoy your more stable, and cleaner code base

NOTES:

  • If you pass the Environment variable GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} in your workflow, then the MegaLinter will mark the status of each individual linter run in the Checks section of a pull request. Without this you will only see the overall status of the full run. There is no need to set the GitHub Secret as it's automatically set by GitHub, it only needs to be passed to the action.
  • You can also use it outside of GitHub Actions (CircleCI, Azure Pipelines, Jenkins, GitLab, or even locally with a docker run) , and have status on Github Pull Request if GITHUB_TARGET_URL environment variable exists.

In your repository you should have a .github/workflows folder with GitHub Action similar to below:

  • .github/workflows/mega-linter.yml
This file should have this code
---
# MegaLinter GitHub Action configuration file
# More info at https://megalinter.io
name: MegaLinter

on:
  # Trigger mega-linter at every push. Action will also be visible from Pull Requests to main
  push: # Comment this line to trigger action only on pull-requests (not recommended if you don't pay for GH Actions)
  pull_request:
    branches: [master, main]

env: # Comment env block if you don't want to apply fixes
  # Apply linter fixes configuration
  APPLY_FIXES: all # When active, APPLY_FIXES must also be defined as environment variable (in github/workflows/mega-linter.yml or other CI tool)
  APPLY_FIXES_EVENT: pull_request # Decide which event triggers application of fixes in a commit or a PR (pull_request, push, all)
  APPLY_FIXES_MODE: commit # If APPLY_FIXES is used, defines if the fixes are directly committed (commit) or posted in a PR (pull_request)

concurrency:
  group: ${{ github.ref }}-${{ github.workflow }}
  cancel-in-progress: true

jobs:
  megalinter:
    name: MegaLinter
    runs-on: ubuntu-latest
    permissions:
      # Give the default GITHUB_TOKEN write permission to commit and push, comment issues & post new PR
      # Remove the ones you do not need
      contents: write
      issues: write
      pull-requests: write
    steps:
      # Git Checkout
      - name: Checkout Code
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.PAT || secrets.GITHUB_TOKEN }}
          fetch-depth: 0 # If you use VALIDATE_ALL_CODEBASE = true, you can remove this line to improve performances

      # MegaLinter
      - name: MegaLinter
        id: ml
        # You can override MegaLinter flavor used to have faster performances
        # More info at https://megalinter.io/flavors/
        uses: oxsecurity/megalinter@v8
        env:
          # All available variables are described in documentation
          # https://megalinter.io/configuration/
          VALIDATE_ALL_CODEBASE: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }} # Validates all source when push on main, else just the git diff with main. Override with true if you always want to lint all sources
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          # ADD YOUR CUSTOM ENV VARIABLES HERE OR DEFINE THEM IN A FILE .mega-linter.yml AT THE ROOT OF YOUR REPOSITORY
          # DISABLE: COPYPASTE,SPELL # Uncomment to disable copy-paste and spell checks

      # Upload MegaLinter artifacts
      - name: Archive production artifacts
        if: success() || failure()
        uses: actions/upload-artifact@v4
        with:
          name: MegaLinter reports
          path: |
            megalinter-reports
            mega-linter.log

      # Create pull request if applicable (for now works only on PR from same repository, not from forks)
      - name: Create Pull Request with applied fixes
        id: cpr
        if: steps.ml.outputs.has_updated_sources == 1 && (env.APPLY_FIXES_EVENT == 'all' || env.APPLY_FIXES_EVENT == github.event_name) && env.APPLY_FIXES_MODE == 'pull_request' && (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) && !contains(github.event.head_commit.message, 'skip fix')
        uses: peter-evans/create-pull-request@v6
        with:
          token: ${{ secrets.PAT || secrets.GITHUB_TOKEN }}
          commit-message: "[MegaLinter] Apply linters automatic fixes"
          title: "[MegaLinter] Apply linters automatic fixes"
          labels: bot
      - name: Create PR output
        if: steps.ml.outputs.has_updated_sources == 1 && (env.APPLY_FIXES_EVENT == 'all' || env.APPLY_FIXES_EVENT == github.event_name) && env.APPLY_FIXES_MODE == 'pull_request' && (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) && !contains(github.event.head_commit.message, 'skip fix')
        run: |
          echo "Pull Request Number - ${{ steps.cpr.outputs.pull-request-number }}"
          echo "Pull Request URL - ${{ steps.cpr.outputs.pull-request-url }}"

      # Push new commit if applicable (for now works only on PR from same repository, not from forks)
      - name: Prepare commit
        if: steps.ml.outputs.has_updated_sources == 1 && (env.APPLY_FIXES_EVENT == 'all' || env.APPLY_FIXES_EVENT == github.event_name) && env.APPLY_FIXES_MODE == 'commit' && github.ref != 'refs/heads/main' && (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) && !contains(github.event.head_commit.message, 'skip fix')
        run: sudo chown -Rc $UID .git/
      - name: Commit and push applied linter fixes
        if: steps.ml.outputs.has_updated_sources == 1 && (env.APPLY_FIXES_EVENT == 'all' || env.APPLY_FIXES_EVENT == github.event_name) && env.APPLY_FIXES_MODE == 'commit' && github.ref != 'refs/heads/main' && (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) && !contains(github.event.head_commit.message, 'skip fix')
        uses: stefanzweifel/git-auto-commit-action@v4
        with:
          branch: ${{ github.event.pull_request.head.ref || github.head_ref || github.ref }}
          commit_message: "[MegaLinter] Apply linters fixes"
          commit_user_name: megalinter-bot
          commit_user_email: nicolas.vuillamy@ox.security

GitLab CI

Manual setup

Create or update .gitlab-ci.yml file at the root of your repository

# MegaLinter GitLab CI job configuration file
# More info at https://megalinter.io/

mega-linter:
  stage: test
  # You can override MegaLinter flavor used to have faster performances
  # More info at https://megalinter.io/flavors/
  image: oxsecurity/megalinter:v8
  script: [ "true" ] # if script: ["true"] doesn't work, you may try ->  script: [ "/bin/bash /entrypoint.sh" ]
  variables:
    # All available variables are described in documentation
    # https://megalinter.io/configuration/
    DEFAULT_WORKSPACE: $CI_PROJECT_DIR
    # ADD YOUR CUSTOM ENV VARIABLES HERE TO OVERRIDE VALUES OF .mega-linter.yml AT THE ROOT OF YOUR REPOSITORY
  artifacts:
    when: always
    paths:
      - megalinter-reports
    expire_in: 1 week

Create a Gitlab access token and define it in a variable GITLAB_ACCESS_TOKEN_MEGALINTER in the project CI/CD masked variables. Make sure your token (e.g. if a project token) as the appropriate role for commenting a merge request (at least developer).

config-gitlab-access-token

Screenshot

Using R2Devops

R2Devops Logo

Our friends at R2Devops have packaged a Gitlab-CI MegaLinter workflow on their open-source templates marketplace, and it can post MegaLinter results in Gitlab Code Quality Reports !

Screenshot

Azure Pipelines

Use the following Azure Pipelines YAML template

You can configure a build validation branch policy against a single repository or across all repositories. If you configure across all repositories then your pipeline is stored in a central repository.

Single Repository

Add the following to an azure-pipelines.yaml file within your code repository:

  # Run MegaLinter to detect linting and security issues
  - job: MegaLinter
    pool:
      vmImage: ubuntu-latest
    steps:
      # Checkout repo
      - checkout: self

      # Pull MegaLinter docker image
      - script: docker pull oxsecurity/megalinter:v8
        displayName: Pull MegaLinter

      # Run MegaLinter
      - script: |
          docker run -v $(System.DefaultWorkingDirectory):/tmp/lint \
            --env-file <(env | grep -e SYSTEM_ -e BUILD_ -e TF_ -e AGENT_) \
            -e SYSTEM_ACCESSTOKEN=$(System.AccessToken) \
            -e GIT_AUTHORIZATION_BEARER=$(System.AccessToken) \
            oxsecurity/megalinter:v8
        displayName: Run MegaLinter

      # Upload MegaLinter reports
      - task: PublishPipelineArtifact@1
        condition: succeededOrFailed()
        displayName: Upload MegaLinter reports
        inputs:
          targetPath: "$(System.DefaultWorkingDirectory)/megalinter-reports/"
          artifactName: MegaLinterReport

Central Repository

Add the following to an azure-pipelines.yaml file within a separate repository e.g. 'MegaLinter' repository:

# Run MegaLinter to detect linting and security issues

trigger: none

pool:
  vmImage: ubuntu-latest

variables:
  repoName: $[ split(variables['System.PullRequest.SourceRepositoryURI'], '/')[6] ]

steps:
  # Checkout triggering repo
  - checkout: git://$(System.TeamProject)/$(repoName)@$(System.PullRequest.SourceBranch)
    displayName: Checkout Triggering Repository

  # Pull MegaLinter docker image
  - script: docker pull oxsecurity/megalinter:v8
    displayName: Pull MegaLinter

  # Run MegaLinter
  - script: |
      docker run -v $(System.DefaultWorkingDirectory):/tmp/lint \
        --env-file <(env | grep -e SYSTEM_ -e BUILD_ -e TF_ -e AGENT_) \
        -e SYSTEM_ACCESSTOKEN=$(System.AccessToken) \
        -e GIT_AUTHORIZATION_BEARER=$(System.AccessToken) \
        oxsecurity/megalinter:v8
    displayName: Run MegaLinter

  # Upload MegaLinter reports
  - task: PublishPipelineArtifact@1
    condition: succeededOrFailed()
    displayName: MegaLinter Report
    inputs:
      targetPath: $(System.DefaultWorkingDirectory)/megalinter-reports/
      artifactName: MegaLinterReport

Pull Request Comments

To benefit from Pull Request comments, please follow configuration instructions

Detailed Tutorial

You can also follow this detailed tutorial by DonKoning

Bitbucket Pipelines

  1. Create a bitbucket-pipelines.yml file on the root directory of your repository

  2. Copy and paste the following template or add the step to your existing pipeline.

image: atlassian/default-image:3
pipelines:
  default:
    - parallel:
      - step:
          name: Run MegaLinter
          image: oxsecurity/megalinter:v8
          script:
            - export DEFAULT_WORKSPACE=$BITBUCKET_CLONE_DIR && bash /entrypoint.sh
          artifacts:
            -  megalinter-reports/**

Jenkins

Add the following stage in your Jenkinsfile

You may activate File.io reporter or E-mail reporter to access detailed logs and fixed source

// Lint with MegaLinter: https://megalinter.io/
stage('MegaLinter') {
    agent {
        docker {
            image 'oxsecurity/megalinter:v8'
            args "-u root -e VALIDATE_ALL_CODEBASE=true -v ${WORKSPACE}:/tmp/lint --entrypoint=''"
            reuseNode true
        }
    }
    steps {
        sh '/entrypoint.sh'
    }
    post {
        always {
            archiveArtifacts allowEmptyArchive: true, artifacts: 'mega-linter.log,megalinter-reports/**/*', defaultExcludes: false, followSymlinks: false
        }
    }
}

CloudBees themselves made a nice tutorial about how to use MegaLinter with Jenkins !

Concourse

Pipeline step

Use the following job.step in your pipeline template

Note: make sure you have job.plan.get step which gets repo containing your repository as shown in example

---

  - name: linting
    plan:
      - get: repo
      - task: linting
        config:
          platform: linux
          image_resource:
            type: docker-image
            source:
              repository: oxsecurity/megalinter
              tag: v8
          inputs:
            - name: repo
          run:
            path: bash
            args:
            - -cxe
            - |
              cd repo
              export DEFAULT_WORKSPACE=$(pwd)
              bash -ex /entrypoint.sh
              ## doing this because concourse doesn't work as other CI systems
          # params:
            # PARALLEL: true
            # DISABLE: SPELL
            # APPLY_FIXES: all
            # DISABLE_ERRORS: true
            # VALIDATE_ALL_CODEBASE: true

OR

Use it as reusable task

Create reusable concourse task which can be used with multiple pipelines

  1. Create task file task-linting.yaml
---
platform: linux
image_resource:
  type: docker-image
  source:
    repository: oxsecurity/megalinter
    tag: v8

inputs:
- name: repo

## uncomment this if you want reports as task output
# output:
# - name: reports
#   path: repo/megalinter-reports

run:
  path: bash
  args:
  - -cxe
  - |
    cd repo
    export DEFAULT_WORKSPACE=$(pwd)
    bash -ex /entrypoint.sh
  1. Use that task-linting.yaml task in pipeline

Note:

  1. make sure task-linting.yaml is available in that repo input at root

  2. task output is not shown here

resources:

  - name: linting
    plan:
      - get: repo
      - task: linting
        file: repo/task-linting.yaml
        # params:
        #   PARALLEL: true
        #   DISABLE: SPELL
        #   APPLY_FIXES: all
        #   DISABLE_ERRORS: true
        #   VALIDATE_ALL_CODEBASE: true

Drone CI

Warning: Drone CI support is experimental and is undergoing heavy modifications (see issue #2047).

  1. Create a .drone.yml file on the root directory of your repository

  2. Copy and paste the following template:

kind: pipeline
type: docker
name: MegaLinter

workspace:
  path: /tmp/lint

steps:

- name: megalinter
  image: oxsecurity/megalinter:v8
  environment:
    DEFAULT_WORKSPACE: /tmp/lint

This uses the Drone CI docker runner, so it's needed to install and configure it beforehand on your Drone CI server.

(Optional) Adjusting trigger rules

The Drone CI workflow should trigger automatically for every scenario (push, pull request, sync…) however, you can optionally change this behavior by changing the trigger. For example:

kind: pipeline
type: docker
name: MegaLinter

workspace:
  path: /tmp/lint

steps:

- name: megalinter
  image: oxsecurity/megalinter:v8
  environment:
    DEFAULT_WORKSPACE: /tmp/lint

trigger:
  event:
  - push

The workflow above should only trigger on push, not on any other situation. For more information about how to configure Drone CI trigger rules, click here.

Docker container

You can also run megalinter with its Docker container, just execute this command:

docker run --rm -v /var/run/docker.sock:/var/run/docker.sock:rw -v $(pwd):/tmp/lint:rw oxsecurity/megalinter:v8

No extra arguments are needed, however, megalinter will lint all of the files inside the /tmp/lint folder, so it may be needed to configure your tool of choice to use the /tmp/lint folder as workspace. This can also be changed:

Example:

docker run --rm -v /var/run/docker.sock:/var/run/docker.sock:rw -v $(pwd):/example/folder:rw oxsecurity/megalinter:v8

Run MegaLinter locally

Version Downloads/week Downloads/total

You can use mega-linter-runner to locally run MegaLinter with the same configuration defined in .mega-linter.yml file

See mega-linter-runner installation instructions

Example

npx mega-linter-runner --flavor salesforce -e "'ENABLE=DOCKERFILE,MARKDOWN,YAML'" -e 'SHOW_ELAPSED_TIME=true'

Note: You can also use such command line in your custom CI/CD pipelines

Configuration

.mega-linter.yml file

MegaLinter configuration variables are defined in a .mega-linter.yml file at the root of the repository or with environment variables. You can see an example config file in this repo: .mega-linter.yml

Configuration is assisted with autocompletion and validation in most commonly used IDEs, thanks to JSON schema stored on schemastore.org

  • VSCode: You need a VSCode extension like Red Hat YAML
  • IDEA family: Auto-completion natively supported

You can also define variables as environment variables.

  • In case a variable exists in both ENV and .mega-linter.yml file, priority is given to ENV variable.

Assisted configuration

Common variables

ENV VARDefault ValueNotes
ADDITIONAL_EXCLUDED_DIRECTORIES[]List of additional excluded directory basenames. they're excluded at any nested level.
APPLY_FIXESnoneActivates formatting and autofix (more info)
CLEAR_REPORT_FOLDERfalseFlag to clear files from report folder (usually megalinter-reports) before starting the linting process
CONFIG_PROPERTIES_TO_APPEND[]List of configuration properties to append their values (instead of replacing them) in case of using EXTENDS.
DEFAULT_BRANCHHEADDeprecated: The name of the repository's default branch.
DEFAULT_WORKSPACE/tmp/lintThe location containing files to lint if you are running locally.
DISABLE_ERRORSfalseFlag to have the linter complete with exit code 0 even if errors were detected.
DISABLEList of disabled descriptors keys (more info)
DISABLE_LINTERSList of disabled linters keys (more info)
DISABLE_ERRORS_LINTERSList of enabled but not blocking linters keys (more info)
ENABLEList of enabled descriptors keys (more info)
ENABLE_LINTERSList of enabled linters keys (more info)
EXCLUDED_DIRECTORIES[…many values…]List of excluded directory basenames. they're excluded at any nested level.
EXTENDSBase mega-linter.yml config file(s) to extend local configuration from. Can be a single URL or a list of .mega-linter.yml config files URLs. Later files take precedence.
FAIL_IF_MISSING_LINTER_IN_FLAVORfalseIf set to true, MegaLinter fails if a linter is missing in the selected flavor
FAIL_IF_UPDATED_SOURCESfalseIf set to true, MegaLinter fails if a linter or formatter has autofixed sources, even if there are no errors
FILTER_REGEX_EXCLUDEnoneRegular expression defining which files will be excluded from linting (more info) .ex: .*src/test.*)
FILTER_REGEX_INCLUDEallRegular expression defining which files will be processed by linters (more info) .ex: .*src/.*)
FLAVOR_SUGGESTIONStrueProvides suggestions about different MegaLinter flavors to use to improve runtime performances
FORMATTERS_DISABLE_ERRORStrueFormatter errors will be reported as errors (and not warnings) if this variable is set to false
GIT_AUTHORIZATION_BEARERIf set, calls git with Authorization: Bearer+value
GITHUB_WORKSPACEBase directory for REPORT_OUTPUT_FOLDER, for user-defined linter rules location, for location of linted files if DEFAULT_WORKSPACE isn't set
IGNORE_GENERATED_FILESfalseIf set to true, MegaLinter will skip files containing @generated marker but without @not-generated marker (more info at https://generated.at)
IGNORE_GITIGNORED_FILEStrueIf set to true, MegaLinter will skip files ignored by git using .gitignore file
JAVASCRIPT_DEFAULT_STYLEstandardJavascript default style to check/apply. standard,prettier
LINTER_RULES_PATH.github/lintersDirectory for all linter configuration rules.
Can be a local folder or a remote URL (ex: https://raw.githubusercontent.com/some_org/some_repo/mega-linter-rules )
LOG_FILEmega-linter.logThe file name for outputting logs. All output is sent to the log file regardless of LOG_LEVEL. Use none to not generate this file.
LOG_LEVELINFOHow much output the script will generate to the console. One of INFO, DEBUG, WARNING or ERROR.
MARKDOWN_DEFAULT_STYLEmarkdownlintMarkdown default style to check/apply. markdownlint,remark-lint
MEGALINTER_CONFIG.mega-linter.ymlName of MegaLinter configuration file. Can be defined remotely, in that case set this environment variable with the remote URL of .mega-linter.yml config file
MEGALINTER_FILES_TO_LINT[]Comma-separated list of files to analyze. Using this variable will bypass other file listing methods
PARALLELtrueProcess linters in parallel to improve overall MegaLinter performance. If true, linters of same language or formats are grouped in the same parallel process to avoid lock issues if fixing the same files
PARALLEL_PROCESS_NUMBERAll available cores are used by default. If there are too many, you need to decrease the number of used cores in order to enhance performances (example: 4)
PLUGINS[]List of plugin urls to install and run during MegaLinter run
POST_COMMANDS[]Custom bash commands to run after linters
PRE_COMMANDS[]Custom bash commands to run before linters
PRINT_ALPACAtrueEnable printing alpaca image to console
PRINT_ALL_FILESfalseDisplay all files analyzed by the linter instead of only the number
REPORT_OUTPUT_FOLDER${GITHUB_WORKSPACE}/megalinter-reportsDirectory for generating report files. Set to none to not generate reports
SECURED_ENV_VARIABLES[]Additional list of secured environment variables to hide when calling linters.
SECURED_ENV_VARIABLES_DEFAULTMegaLinter & CI platforms sensitive variablesList of secured environment variables to hide when calling linters. Default list. This is not recommended to override this variable, use SECURED_ENV_VARIABLES
SHOW_ELAPSED_TIMEfalseDisplays elapsed time in reports
SHOW_SKIPPED_LINTERStrueDisplays all disabled linters mega-linter could have run
SKIP_CLI_LINT_MODES[]Comma-separated list of cli_lint_modes. To use if you want to skip linters with some CLI lint modes (ex: file,project). Available values: file,cli_lint_mode,project.
TYPESCRIPT_DEFAULT_STYLEstandardTypescript default style to check/apply. standard,prettier
VALIDATE_ALL_CODEBASEtrueWill parse the entire repository and find all files to validate across all types. NOTE: When set to false, only new or edited files will be parsed for validation.

Activation and deactivation

MegaLinter have all linters enabled by default, but allows to enable only some, or disable only some

  • If ENABLE isn't set, all descriptors are activated by default. If set, all linters of listed descriptors will be activated by default
  • If ENABLE_LINTERS is set, only listed linters will be processed
  • If DISABLE is set, the linters in the listed descriptors will be skipped
  • If DISABLE_LINTERS is set, the listed linters will be skipped
  • If DISABLE_ERRORS_LINTERS is set, the listed linters will be run, but if errors are found, they will be considered as non blocking

Examples:

  • Run all javascript and groovy linters except STANDARD javascript linter. DevSkim errors will be non-blocking
ENABLE: JAVASCRIPT,GROOVY
DISABLE_LINTERS: JAVASCRIPT_STANDARD
DISABLE_ERRORS_LINTERS: REPOSITORY_DEVSKIM
  • Run all linters except PHP linters (PHP_BUILTIN, PHP_PHPCS, PHP_PHPSTAN, PHP_PSALM)
DISABLE: PHP
  • Run all linters except PHP_PHPSTAN and PHP_PSALM linters
DISABLE_LINTERS:
  - PHP_PHPSTAN
  - PHP_PSALM

Filter linted files

If you need to lint only a folder or exclude some files from linting, you can use optional environment parameters FILTER_REGEX_INCLUDE and FILTER_REGEX_EXCLUDE You can apply filters to a single linter by defining variable <LINTER_KEY>_FILTER_REGEX_INCLUDE and <LINTER_KEY>_FILTER_REGEX_EXCLUDE

Examples:

  • Lint only src folder: FILTER_REGEX_INCLUDE: (src/)
  • Don't lint files inside test and example folders: FILTER_REGEX_EXCLUDE: (test/|examples/)
  • Don't lint javascript files inside test folder: FILTER_REGEX_EXCLUDE: (test/.*\.js)

Warning: not applicable with linters using CLI lint mode project (see details)

Apply fixes

Mega-linter is able to apply fixes provided by linters. To use this capability, you need 3 env variables defined at top level

  • APPLY_FIXES: all to apply fixes of all linters, or a list of linter keys (ex: JAVASCRIPT_ES,MARKDOWN_MARKDOWNLINT)

Only for GitHub Action Workflow file if you use it:

  • APPLY_FIXES_EVENT: all, push, pull_request, none (use none in case of use of Updated sources reporter)
  • APPLY_FIXES_MODE: commit to create a new commit and push it on the same branch, or pull_request to create a new PR targeting the branch.

Apply fixes issues

You may see github permission errors, or workflows not run on the new commit.

To solve these issues, you can apply one of the following solutions.

Notes

  • You can use Updated sources reporter if you don't want fixes to be automatically applied on git branch, but download them in a zipped file and manually extract them in your project
  • If used, APPLY_FIXES_EVENT and APPLY_FIXES_MODE can not be defined in .mega-linter.ymlconfig file, they must be set as environment variables
  • If you use APPLY_FIXES, add the following line in your .gitignore file
megalinter-reports/

Linter specific variables

See variables related to a single linter behavior in linters documentations

Pre-commands

MegaLinter can run custom commands before running linters (for example, installing an plugin required by one of the linters you use)

Example in .mega-linter.yml config file

PRE_COMMANDS:
  - command: npm install eslint-plugin-whatever
    cwd: root        # Will be run at the root of MegaLinter docker image
    secured_env: true  # True by default, but if defined to false, no global variable will be hidden (for example if you need GITHUB_TOKEN)
  - command: echo "pre-test command has been called"
    cwd: workspace   # Will be run at the root of the workspace (usually your repository root)
    continue_if_failed: False  # Will stop the process if command is failed (return code > 0)
  - command: pip install flake8-cognitive-complexity
    venv: flake8 # Will be run within flake8 python virtualenv. There is one virtualenv per python-based linter, with the same name
  - command: export MY_OUTPUT_VAR="my output var" && export MY_OUTPUT_VAR2="my output var2"
    output_variables: ["MY_OUTPUT_VAR","MY_OUTPUT_VAR2"] # Will collect the values of output variables and update MegaLinter own ENV context
  - command: echo "Some command called before loading MegaLinter plugins"
    cwd: workspace   # Will be run at the root of the workspace (usually your repository root)
    continue_if_failed: False  # Will stop the process if command is failed (return code > 0)
    tag: before_plugins # Tag indicating that the command will be run before loading plugins
PropertyDescriptionDefault value
commandCommand line to runMandatory
cwdDirectory where to run the command (workspace or root)workspace
secured_envApply filtering of secured env variables before calling the command (default true)
Be careful if you disable it !
true
continue_if_failedIf set to false, stop MegaLinter process in case of command failuretrue
venvIf set, runs the command into the related python venv
output_variablesENV variables to get from output after running the commands, and store in MegaLinter ENV context, so they can be reused in next commands[]
tagTag defining at which commands entry point the command will be run (available tags: before_plugins)

Post-commands

MegaLinter can run custom commands after running linters (for example, running additional tests)

Example in .mega-linter.yml config file

POST_COMMANDS:
  - command: npm run test
    cwd: "workspace"   # Will be run at the root of the workspace (usually your repository root)
    continue_if_failed: False  # Will stop the process if command is failed (return code > 0)

Environment variables security

Secured env variables

MegaLinter runs on a docker image and calls the linters via command line to gather their results.

If you run it from your CI/CD pipelines, the docker image may have access to your environment variables, that can contain secrets defined in CI/CD variables.

As it can be complicated to trust the authors of all the open-source linters, MegaLinter removes variables from the environment used to call linters.

Thanks to this feature, you only need to trust MegaLinter and its internal python dependencies, but there is no need to trust all the linters that are used !

You can add secured variables to the default list using configuration property SECURED_ENV_VARIABLES in .mega-linter.yml or in an environment variable (priority is given to ENV variables above .mega-linter.yml property).

Values can be:

  • String (ex: MY_SECRET_VAR)
  • Regular Expression (ex: (MY.*VAR))

Environment variables are secured for each command line called (linters, plugins, sarif formatter...) except for PRE_COMMANDS , ONLY if you define secured_env: false in the command.

Secured configuration examples

  • Example of adding extra secured variables .mega-linter.yml:
SECURED_ENV_VARIABLES:
  - MY_SECRET_TOKEN
  - ANOTHER_VAR_CONTAINING_SENSITIVE_DATA
  - OX_API_KEY
  - (MY.*VAR)  # Regex format
  • Example of adding extra secured variables in CI variables, so they can not be overridden in .mega-linter.yml:
SECURED_ENV_VARIABLES=MY_SECRET_TOKEN,ANOTHER_VAR_CONTAINING_SENSITIVE_DATA,OX_API_KEY

Default secured variables

If you override SECURED_ENV_VARIABLES_DEFAULT, it replaces the default list, so it's better to only define SECURED_ENV_VARIABLES to add them to the default list !

SECURED_ENV_VARIABLES_DEFAULT contains:

  • GITHUB_TOKEN
  • PAT
  • SYSTEM_ACCESSTOKEN
  • GIT_AUTHORIZATION_BEARER
  • CI_JOB_TOKEN
  • GITLAB_ACCESS_TOKEN_MEGALINTER
  • GITLAB_CUSTOM_CERTIFICATE
  • WEBHOOK_REPORTER_BEARER_TOKEN
  • NODE_TOKEN
  • NPM_TOKEN
  • DOCKER_USERNAME
  • DOCKER_PASSWORD
  • CODECOV_TOKEN
  • GCR_USERNAME
  • GCR_PASSWORD
  • SMTP_PASSWORD
  • CI_SFDX_HARDIS_GITLAB_TOKEN
  • (SFDX_CLIENT_ID_.*)
  • (SFDX_CLIENT_KEY_.*)

Unhide variables for linters

You can configure exceptions for a specific linter by defining (linter-key)_UNSECURED_ENV_VARIABLES.

Variable names in this list won't be hidden to the linter commands.

TERRAFORM_TFLINT_UNSECURED_ENV_VARIABLES:
  - GITHUB_TOKEN # Can contain string only, not regex

CLI lint mode

Each linter is pre-configured to use a default lint mode, which are visible in the MegaLinter documentation (example). The possible values are:

  • list_of_files: The linter is called only once, and passed a list of all the files to be processed
  • project: The linter is called only once, from the root folder of the repository, and it scans for the files to process, as no file names are provided it
  • file: The linter is called once per file, which hurts performance

You can override the CLI_LINT_MODE by using a configuration variable for each linter (see linters documentation).

  • Linters that default to the file lint mode cannot be overridden to use the list_of_files lint mode
  • Linters that default to the project lint mode cannot be overridden to use either the list_of_files or file lint modes.

Allowing file or list_of_files to be overridden to project is mostly for workarounds. For example, some linters have a problem finding their config file when the current folder isn't the repository's root folder.

Special considerations:

  • Linters that are configured to use the project lint mode ignore variables like FILTER_REGEX_INCLUDE and FILTER_REGEX_EXCLUDE, as they are not passed a list of files to lint. For those linters, you must check their documentation to see if a linter can be configured to ignore specific files. For example, the Secretlint linter ignore files listed in ~/.secretlintignore by default, or it can be configured to instead ignore files listed in ~/.gitignore by setting REPOSITORY_SECRETLINT_ARGUMENTS to --secretlintignore .gitignore..

Reporters

MegaLinter can generate various reports that you can activate / deactivate and customize

ReporterDescriptionDefault
Text filesGenerates One log file by linter + suggestions for fixes that can not be automatedActive
SARIF (beta)Generates an aggregated SARIF output fileInactive
GitHub Pull Request commentsMegaLinter posts a comment on the PR with a summary of lint results, and links to detailed logsActive if GitHub Action
Gitlab Merge Request commentsMega-Linter posts a comment on the MR with a summary of lint results, and links to detailed logsActive if in Gitlab CI
Azure Pipelines Pull Request commentsMega-Linter posts a comment on the PR with a summary of lint results, and links to detailed logsActive if in Azure Pipelines
Bitbucket Pull Request commentsMega-Linter posts a comment on the PR with a summary of lint results, and links to detailed logsActive if in Bitbucket CI
API (Grafana)Sends logs and metrics to Grafana endpoint (Loki / Prometheus)Inactive
Updated sourcesZip containing all formatted and autofixed sources so you can extract them in your repositoryActive
IDE ConfigurationApply MegaLinter configuration in your local IDE with linter config files and IDE extensionsActive
GitHub StatusOne GitHub status by linter on the PR, with links to detailed logsActive if GitHub Action
File.ioSend reports on file.io so you can access them with a simple hyperlink provided at the end of console logInactive
JSONGenerates a JSON output report fileInactive
EmailReceive all reports on your e-mail, if you can not use artifactsActive
TAP filesOne file by linter following Test Anything Protocol formatActive
ConsoleExecution logs visible in console with summary table and links to other reports at the endActive
Markdown SummaryGenerates a Markdown summary report fileInactive

Flavors

To improve run performances, we generate Flavored MegaLinter images containing only the list of linters related to a project type

  • When using default MegaLinter, if a MegaLinter Flavor would cover all your project requirements, a message is added in the logs
  • If your project uses a MegaLinter Flavor not covering linter requirements, an error message will be thrown with instructions about how to solve the issue

The following table doesn't display docker pulls from MegaLinter v4 & v5 images.

FlavorDescriptionEmbedded lintersInfo
allDefault MegaLinter Flavor124Docker Image Size (tag) Docker Pulls
c_cppOptimized for pure C/C++ projects54Docker Image Size (tag) Docker Pulls
ci_lightOptimized for CI items (Dockerfile, Jenkinsfile, JSON/YAML schemas,XML21Docker Image Size (tag) Docker Pulls
cupcakeMegaLinter for the most commonly used languages83Docker Image Size (tag) Docker Pulls
documentationMegaLinter for documentation projects49Docker Image Size (tag) Docker Pulls
dotnetOptimized for C, C++, C# or VB based projects61Docker Image Size (tag) Docker Pulls
dotnetwebOptimized for C, C++, C# or VB based projects with JS/TS70Docker Image Size (tag) Docker Pulls
formattersContains only formatters17Docker Image Size (tag) Docker Pulls
goOptimized for GO based projects51Docker Image Size (tag) Docker Pulls
javaOptimized for JAVA based projects52Docker Image Size (tag) Docker Pulls
javascriptOptimized for JAVASCRIPT or TYPESCRIPT based projects59Docker Image Size (tag) Docker Pulls
phpOptimized for PHP based projects54Docker Image Size (tag) Docker Pulls
pythonOptimized for PYTHON based projects62Docker Image Size (tag) Docker Pulls
rubyOptimized for RUBY based projects50Docker Image Size (tag) Docker Pulls
rustOptimized for RUST based projects50Docker Image Size (tag) Docker Pulls
salesforceOptimized for Salesforce based projects54Docker Image Size (tag) Docker Pulls
securityOptimized for security24Docker Image Size (tag) Docker Pulls
swiftOptimized for SWIFT based projects50Docker Image Size (tag) Docker Pulls
terraformOptimized for TERRAFORM based projects54Docker Image Size (tag) Docker Pulls

If you need a new flavor, post an issue :wink:

Badge

You can show MegaLinter status with a badge in your repository README

MegaLinter

If your main branch is master , replace main by master in URLs

Markdown

  • Format
[![MegaLinter](https://github.com/<OWNER>/<REPOSITORY>/workflows/MegaLinter/badge.svg?branch=main)](https://github.com/<OWNER>/<REPOSITORY>/actions?query=workflow%3AMegaLinter+branch%3Amain)
  • Example
[![MegaLinter](https://github.com/nvuillam/npm-groovy-lint/workflows/MegaLinter/badge.svg?branch=main)](https://github.com/nvuillam/npm-groovy-lint/actions?query=workflow%3AMegaLinter+branch%3Amain)

reStructuredText

  • Format
.. |MegaLinter yes| image:: https://github.com/<OWNER>/<REPOSITORY>/workflows/MegaLinter/badge.svg?branch=main
   :target: https://github.com/<OWNER>/<REPOSITORY>/actions?query=workflow%3AMegaLinter+branch%3Amain
  • Example
.. |MegaLinter yes| image:: https://github.com/nvuillam/npm-groovy-lint/workflows/MegaLinter/badge.svg?branch=main
   :target: https://github.com/nvuillam/npm-groovy-lint/actions?query=workflow%3AMegaLinter+branch%3Amain

Note: IF you did not use MegaLinter as GitHub Action name, please read GitHub Actions Badges documentation{target=_blank}

Plugins

For performances and security reasons, we can not embed all linters of the world within MegaLinter.

But our core architecture allows to build and publish MegaLinter Plugins !

External Plugins Catalog

NameDescriptionAuthorRaw URL
jupyfmtThe uncompromising Jupyter notebook formatterKim Philipp JablonskiDescriptor
linkcheckPlugin to check and validate markdown links exist and workingShiran RubinDescriptor
nitpickCommand-line tool and flake8 plugin to enforce the same settings across multiple language-independent projectsW. Augusto AndreoliDescriptor
mustachePlugin to validate Logstash pipeline definition files using mustacheYann JouaniqueDescriptor
salt-lintChecks Salt State files (SLS) for best practices and behavior that could potentially be improved.Joachim GrimmDescriptor

Note: Using an external plugin means you trust its author

Submit a Pull Request if you want your plugin to appear here :)

Use external plugins

Add plugin URLs in PLUGINS property of .mega-linter.yml. URLs must either begin with "https://" or take the form of "file://<path>", where <path> points to a valid plugin descriptor file.

Note: Both <path> and the default mount directory (/tmp/lint/<path>) will be checked for a valid descriptor.

Example

PLUGINS:
  - https://raw.githubusercontent.com/kpj/jupyfmt/master/mega-linter-plugin-jupyfmt/jupyfmt.megalinter-descriptor.yml
  - file://.automation/test/mega-linter-plugin-test/test.megalinter-descriptor.yml

Create your own plugin

You can implement your own descriptors and load them as plugins during MegaLinter runtime

Limitations

  • For now, the only install attributes managed are dockerfile instructions starting by RUN

They talk about MegaLinter

English articles

ArticleAuthor
30 Seconds to Setup MegaLinter: Your Go-To Tool for Automated Code Quality{target=_blank}Peng Cao
Introducing MegaLinter: Streamlining Code Quality Checks Across Multiple Languages{target=_blank}Cloud Tuned{target=_blank}
Infrastructure as Code GitHub Codespace Template{target=_blank}Luke Murray{target=_blank}
5 ways MegaLinter upped our DevSecOps game{target=_blank}Wes Dean{target=_blank}
Achieve Code Consistency: MegaLinter Integration in Azure DevOps{target=_blank}Don Koning{target=_blank} on Microsoft Tech Community{target=_blank}
MegaLinter in Azure DevOps{target=_blank}James Cook{target=_blank}
Maximize your code consistency with Megalinter{target=_blank}Tor Ivar Asbølmo{target=_blank} on codewithme.cloud{target=_blank}
8 Tools to Scan Node.js Applications for Security Vulnerability{target=_blank}Chandan Kumar{target=_blank} on GeekFlare.com{target=_blank}
Use the Workflows JSON schema in your IDE{target=_blank}Google Cloud{target=_blank}
Level up your Unity Packages with CI/CD{target=_blank}RunningMattress{target=_blank}
Writing documentation as a champ in engineering teams{target=_blank}Gijs Reijn{target=_blank}
GitHub Actions: sharing your secrets with third-party actions{target=_blank}Constantin Bosse{target=_blank} and Stephen Hosom{target=_blank}
GitOps security topics you must address{target=_blank}Wiebe de Roos{target=_blank}
Talk about the Kotlin plugins Kover, Ktlint and Detekt. Made for the AmsterdamJUG meetup.{target=_blank}Simone de Gijt{target=_blank}
Linting - What is all the fluff about?{target=_blank}Neil Shepard{target=_blank}, University Of Sheffield
How to apply security at the source using GitOps{target=_blank}Edu Minguez{target=_blank}
How to linter basic things like trailing whitespaces and newlines{target=_blank}Nicolai Antiferov{target=_blank}
Open-source linters landscape in 2021{target=_blank}Cédric Teyton{target=_blank}
Node.js Coding Standard Tools with MegaLinter on Gitlab CI{target=_blank}Albion Bame{target=_blank}
Linting a Jekyll blog with MegaLinter{target=_blank}Alec Johnson{target=_blank}
MegaLinter sells his soul and joins OX Security{target=_blank}Nicolas Vuillamy{target=_blank}
Limit your technical debt and secure your code base using MegaLinter{target=_blank}Nicolas Vuillamy{target=_blank}

French articles

ArticleAuthor
MegaLinter{target=_blank}Stéphane Robert, 3DS OutScale{target=_blank}
MegaLinter: un linter pour les gouverner tous{target=_blank}Guillaume Arnaud, WeScale{target=_blank}
MegaLinter, votre meilleur ami pour un code de qualité{target=_blank}Thomas Sanson{target=_blank}

Japanese articles

ArticleAuthor
Try using MegaLinter{target=_blank}Takashi Minayaga{target=_blank}

Videos

  • Code quality - Ep01 - MegaLinter, one linter to rule them all, by Bertrand Thomas
  • Ortelius Architecture Meeting, with a review of MegaLinter, by Steve Taylor{target=_blank} from Ortelius

Web Sites

Linters

Frequently Asked Questions

My repo CI already have linters and they're perfectly working, so why do I need MegaLinter ?

You can perfectly continue using your installed linters and deactivate them in .mega-linter.yml. For example, in a javascript project using eslint, you can configure MegaLinter with DISABLE: JAVASCRIPT. That way, you will benefit from both your installed linters but also from other MegaLinter linters checking JSON, YAML, Markdown, Dockerfile, Bash, spelling mistakes, dead URLs…

Ok but… how does it work ?

MegaLinter is based on Docker images containing either all linters, or just a selection of linters if you are using a MegaLinter flavor for a project using a specific language / format

The core architecture does the following:

  • Initialization
    • List all project files:
      • except files in ignored folders (node_modules, etc…)
      • except files not matching FILTER_REGEX_INCLUDE (if defined by user)
      • except files matching FILTER_REGEX_EXCLUDE (if defined by user)
    • Collect files for each activated linter, matching their own filtering criteria:
      • file extensions
      • file names
      • file content
      • <descriptor_or_linter_key>_FILTER_REGEX_INCLUDE (if defined by user)
      • <descriptor_or_linter_key>_FILTER_REGEX_EXCLUDE (if defined by user)
  • Linting
    • Parallelly, for each linter with matching files:
      • Call the linter on matching files (or the whole project for some linters like copy-paste detector)
      • Call activated linter-level reporters (GitHub Status Reporter…)
  • Finalization
    • Call activated global level reporters (GitHub Pull Request Comment Reporter, File.io Reporter, Email Reporter…)
    • Manage return code:
      • 0 if no error (or only non blocking errors if user defined DISABLE_ERRORS or <descriptor_or_linter_key>_DISABLE_ERRORS)
      • 1 if errors

How to contribute

Contributions to MegaLinter are very welcome, the more we're, the stronger MegaLinter is ! Please follow Contributing Guide

To help, you can also:

Special thanks

Maintainers

MegaLinter wouldn't be what it is without its great team of maintainers !

Contributors

Open-source teams

MegaLinter obviously would not exist without its linters and libraries, so many thanks to all the dedicated Open-Source teams maintaining all these awesome linters !

Super-Linter team

MegaLinter has been built on the ashes of a rejected Pull Request{target=_blank} on GitHub Super-Linter{target=_blank}.

Even if I disagree with their decision to remain in bash, the core team has always been nice and supporting during the time I was a Super-Linter contributor{target=_blank} :)

License

MegaLinter vs Super-Linter

The hard-fork of Super-Linter to be rewritten in Python isn't just a language switch: use of python flexibility and libraries allowed to define lots of additional functions described below

Security

MegaLinter hides many environment variables when calling the linters.

That way you need to trust only MegaLinter core code with your secrets, not the 100+ embedded linters !

Performances

  • MegaLinter Flavors allow to use smaller docker images, so the pull time is reduced
  • Thanks to python multiprocessing capabilities, linters are run in parallel, which is way faster than Super-Linter bash script who runs all linters in sequence
  • When the linter allows it, call it 1 time with N files, instead of calling N times with one file

More languages and formats linted

  • C, C++, Copy-Paste detection, Credentials, GraphQL, JSON & YAML with JSON schemas, Markdown tables formatting, Puppet, reStructuredText, Rust, Scala, Spell checker, Swift, Visual Basic .NET …

Automatically apply formatting and fixes

MegaLinter can automatically apply fixes performed by linters, and push them to the same branch, or create a Pull Request that you can validate

This is pretty handy, especially for linter errors related to formatting (in that case, you don't have any manual update to perform)

Run locally

MegaLinter can be run locally thanks to mega-linter-runner

Reports

Capabilities

  • Accuracy: Count the total number of errors and not only the number of files in error
  • Show linter version and applied filters for each linter processed
  • Reports stored as artefacts on GitHub Action run or other remote files
    • General log
    • One report file by linter

Additional Reporters

Screenshot

Screenshot

Screenshot

Screenshot

Screenshot

Screenshot

Enhanced Configuration

  • Assisted installation and configuration using a yeoman generator and JSON schemas for configuration file

Runner Install

Assisted configuration

  • Configure include and exclude regexes for a single language or linter: ex: JAVASCRIPT_FILTER_REGEX_INCLUDE (src)
  • Configure additional CLI arguments for a linter: ex: JAVASCRIPT_ES_ARGUMENTS "--debug --env-info"
  • Configure non blocking errors for a single language or linter: ex: JAVASCRIPT_DISABLE_ERRORS
  • Simplify languages and linters variables
    • ENABLE = list of languages and formats to apply lint on codebase (default: all)
    • ENABLE_LINTERS = list of linters to apply lint on codebase (default: all)
    • DISABLE = list of languages and formats to skip (default: none)
    • DISABLE_LINTERS = list of linters to skip (default: none)
    • Variables VALIDATE_XXX are still taken in account (but should not be used in association with ENABLE and DISABLE variables)

Enhanced Documentation

HTML doc home

  • One page per linter documentation :
    • All variables that can be used with this linter
    • List of file extensions, names and filters applied by the linter
    • Link to MegaLinter default linter configuration
    • Link to linter Web-Site
    • Link to official page explaining how to customize the linter rules
    • Link to official page explaining how to disable rules from source comments
    • Examples of linter command line calls behind the hood
    • Help command text
    • Installation commands

HTML doc linter

  • Installation links for related IDEs

HTML doc IDE

  • README
    • Separate languages, formats and tooling formats in the linters table
    • Add logos for each descriptor

Plugins management

For linters less commonly used, MegaLinters offers a plugins architecture so anyone can publish plugins

Simplify architecture and evolutive maintenance

  • Refactoring runtime in Python, for easier handling than bash thanks to classes and python modules
  • Everything related to each linter in a single descriptor YML file
    • easier evolutive maintenance
    • less conflicts to manage between PRs.
    • Few special cases require a python linter class)
  • Default behaviours for all linters, with possibility to override part of them for special cases
  • Hierarchical architecture: Apply fixes and new behaviours to all linters with a single code update
  • Documentation as code
    • Generate linters tables (ordered by type: language, format & tooling format) and include it in README. (see result)
    • Generate one markdown file per Linter, containing all configuration variables, infos and examples (See examples)
  • Automatic generation of Dockerfile using YML descriptors, always using the linter latest version
    • Dockerfile commands (FROM, ARG, ENV, COPY, RUN )
    • APK packages (linux)
    • NPM packages (node)
    • PIP packages (python)
    • GEM packages (ruby)
    • Phive packages (PHP)
  • Have a centralized exclude list (node_modules,.rbenv, etc…)

Improve robustness & stability

  • Test classes for each capability
  • Test classes for each linter: Automatic generation of test classes using .automation/build.py
  • Setup code coverage codecov
  • Development CD / CI
    • Validate multi-status on PR inside each PR (posted from step "Run against all code base")
    • Run test classes and code coverage with pytest during validation GitHub Action
    • Validate descriptor YML files with json schema during build
    • Automated job to upgrade linters to their latest stable version