We are designing a polyglot repo toolchain. The goal is to have a single repository that contains code in multiple programming languages, and we want to enforce consistency, run linters, and have CI that works across all languages.
Steps:
-
Directory Structure:
We can organize by language or by component. Since it's polyglot, we might have multiple languages in the same component (e.g., a backend in Go and a frontend in TypeScript). However, for simplicity in tooling, we might structure by language for the tooling configurations, but the actual code might be in a different structure.
Let's assume we have:
src/ for source code, with subdirectories for each project/component (which might contain multiple languages).
.github/ for GitHub Actions (CI).
linters/ or .linters/ for linter configurations (or we can put them in each component's directory?).
scripts/ for common scripts.
However, note that linter configurations are often language-specific and might live in the component's directory (like pyproject.toml for Python, package.json for JavaScript, .golangci.yml for Go, etc.). But we want a central way to run them.
-
Shared Config:
We can have a central configuration for the polyglot setup. For example, we might have a polyglot.yaml that lists the languages and their versions, and maybe the linters to run.
Alternatively, we can use a tool that supports multiple languages, like pre-commit (https://pre-commit.com/) which can run hooks for multiple languages. We can have a .pre-commit-config.yaml at the root that defines hooks for each language.
Also, we might want a central place for dependency versions (like a Dockerfile that has all the language runtimes? or just use the CI's environment?).
-
Linters:
We can use pre-commit to run linters for each language. For example:
- For Python:
black, flake8, mypy
- For JavaScript/TypeScript:
eslint, prettier
- For Go:
gofmt, govet, golangci-lint
- For Rust:
cargo fmt, cargo clippy
- etc.
We can set up a .pre-commit-config.yaml that includes all these hooks, and then each component can have its own configuration (like .eslintrc.js for JS) but the pre-commit config at the root will run the appropriate linter in the appropriate directory.
Example of .pre-commit-config.yaml:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- repo: https://github.com/psf/black
rev: 23.7.0
hooks:
- id: black
language_version: python3
- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8
- repo: https://github.com/pre-commit/mirrors-eslint
rev: v8.43.0
hooks:
- id: eslint
additional_dependencies:
- eslint-config-react-app@7.0.1
# ... and so on for other languages
But note: some linters require a configuration file in the project. We must ensure that each component has the necessary config. Alternatively, we can have a central config and copy it? But that might be messy.
Alternatively, we can have a script that runs the linters for each language in the appropriate directories, and then use pre-commit to run that script? But pre-commit is designed to run in the context of a repository and can handle multiple languages.
Another idea: use a monorepo tool like nx (https://nx.dev/) or turborepo (https://turbo.build/repo) but they are more for JavaScript/TypeScript. For polyglot, we might need something else.
-
Consistency Checks:
We might want to check for:
- Consistent formatting (handled by linters like black, prettier, etc.)
- Dependency management (e.g., no outdated dependencies? but that's language-specific)
- License headers? (can use a pre-commit hook for that)
- Security vulnerabilities (e.g.,
snyk, trivy, or language-specific tools)
We can use pre-commit for some of these, and then in CI we can run additional checks.
-
CI:
We can set up GitHub Actions (or GitLab CI, etc.) to run on every push and pull request.
Steps in CI:
- Checkout code.
- Set up the environment for all languages (e.g., install Python, Node.js, Go, Rust, etc.). We can use a matrix strategy? But if we have multiple languages in one commit, we might want to run all linters for all languages in one job? Or separate jobs per language?
Since we are polyglot, we might have a job that sets up all languages and then runs the linters for each language in the appropriate directories.
Alternatively, we can have a job that runs pre-commit run --all-files which will run all the hooks on all files. But note that some hooks are language-specific and might fail on files of other languages. However, pre-commit is designed to skip files it doesn't understand? Actually, it runs on all files by default, but we can specify files in the hook to limit to certain extensions.
Example:
jobs:
linters:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: '3.11'
- uses: actions/setup-node@v3
with:
node-version: '18'
- uses: actions/setup-go@v4
with:
go-version: '1.20'
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
- name: Run pre-commit
uses: pre-commit/action@v3.0.0
with:
extra_args: --all-files
But note: the pre-commit/action will run the hooks defined in .pre-commit-config.yaml. It will automatically use the installed languages? Actually, pre-commit will set up the environment for each hook, so we don't need to set up the languages globally? But for hooks that require a language (like black for Python) we do need the language? Actually, pre-commit will set up a virtual environment for each hook, but for black it will use the Python from the system? It might use the Python we set up in the step? We set up Python, Node, etc., and then pre-commit will use those.
Alternatively, we can let pre-commit set up everything by itself? But then we might have multiple versions of the same language? It's better to set up the languages we want in the CI and then pre-commit will use those.
However, note that the pre-commit action will run pre-commit run and it will use the hooks we defined. Each hook might have its own language version. For example, the black hook will use the Python version that is set in the hook's language_version (if specified) or the system Python? Actually, pre-commit sets up an isolated environment for each hook, but it uses the system's Python to run the hook? It's a bit complex.
To avoid confusion, we can set up the languages in the CI and then run without the action, just by running:
-
Additional consistency checks:
We might want to run:
git diff --check to check for whitespace errors? (but pre-commit has trailing-whitespace and end-of-file-fixer)
- Check for large files? (pre-commit hook)
- Check for secrets? (like
truffleHog or git-secrets)
We can add these as pre-commit hooks or as separate CI steps.
-
Central configuration for versions:
We might want to pin the versions of the linters and the languages. We can do:
- In
.pre-commit-config.yaml, we pin the hook versions (as shown above).
- In CI, we set up specific versions of the languages.
But note: the pre-commit hooks might require a minimum version of the language. We have to be careful.
-
How to handle multiple components with different configurations?
For example, one component might use Python 3.9 and another 3.11. We can set up multiple Python versions? But in one job we can only have one Python version? We can set up multiple Python versions in the same job? It's possible but messy.
Alternatively, we can have a matrix of jobs for each language? But then we have to run the linters in the appropriate directories.
Example:
jobs:
lint-python:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: '3.11'
- run: pip install pre-commit
- run: pre-commit run --all-files --hook-stage manual --hook-id black
# But we want to run only on Python files? Actually, pre-commit will run only on files that match the hook's `files` regex.
lint-js:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- run: npm install -g pre-commit
- run: pre-commit run --all-files --hook-stage manual --hook-id eslint
But then we are running pre-commit multiple times, and we might have to install pre-commit multiple times? We can do:
Alternatively, we can have one job that sets up all languages and then runs pre-commit for all hooks. But then we need to set up all languages in one job, which might be heavy.
We can use a matrix strategy to run each language in a separate job, and then have a job that aggregates the results? But if one job fails, the PR will fail.
Actually, we want the CI to fail if any linter fails, so we can have multiple jobs and if any fails, the CI fails.
But note: we might have a lot of languages and the CI might take a long time if we run them sequentially? We can run them in parallel with a matrix.
Let's design:
We have a matrix of languages. For each language, we set up the environment and run the linters for that language.
But how do we know which linters to run for which language? We can define in the root a mapping of languages to the directories they are in? Or we can have a polyglot.yaml that defines:
languages:
python:
version: "3.11"
directories: ["backend", "scripts"]
linters: ["black", "flake8"]
javascript:
version: "18"
directories: ["frontend"]
linters: ["eslint"]
Then, in the CI, we can generate a matrix from this config.
But then we have to write a script to parse polyglot.yaml and generate the matrix. Alternatively, we can hardcode the matrix in the CI YAML.
Since we are designing, let's assume we have a fixed set of languages and we can hardcode.
Alternatively, we can use the configuration to drive the CI? We can have a job that runs and it will run all hooks for all languages, but then we need to set up all languages in that job.
-
Additional CI steps:
We might want to run tests for each language? But that's beyond the scope of linters and consistency.
We can have separate jobs for building and testing each language, but that's a different concern.
-
Summary:
Proposed structure:
```
.
├── .pre-commit-config.yaml # central pre-commit config with hooks for all languages
├── .github/
│ └── workflows/
│ └── lint.yml # CI for linters
├── polyglot.yaml # optional: central config for language versions and directories?
├── backend/
│ ├── Python项目...
│ └── ...
├── frontend/
│ ├── JavaScript项目...
│ └── ...
└── ...
```
Steps:
a. Create `.pre-commit-config.yaml` with hooks for all languages we use, and make sure each hook has the correct `files` regex to run only on the files of that language.
b. In the CI, set up all the languages we use (with the versions we want) and then run `pre-commit run --all-files`.
c. We can also add other CI steps for security scanning, etc.
But note: if we have a lot of languages, the CI job might become too slow. We can split into multiple jobs by language? Then we have to set up the environment for each language and run pre-commit with only the hooks for that language? But pre-commit doesn't have a built-in way to run only hooks for a language.
We can define multiple pre-commit configs? Or we can have a script that runs only the hooks for a specific language by specifying the hook ids.
For example, for Python, we can run:
pre-commit run --all-files --hook-id black --hook-id flake8
But then we have to maintain a list of hook ids for each language.
Alternatively, we can have a separate pre-commit config for each language and then run:
pre-commit run --config .pre-commit-config.python.yaml --all-files
But then we have multiple configs and we have to keep them in sync? Actually, we can have one config and then in CI we run with `--config` for each language? But then we are running the same hooks multiple times? Not exactly.
Let me think: we have one config that includes hooks for all languages. We can run:
pre-commit run --all-files
and it will run every hook on every file, but each hook will skip files that don't match its `files` regex. So it's safe.
But then why split into multiple jobs? Because setting up all languages in one job might be heavy and we might want to run in parallel? But the job is already sequential.
If we split by language, we can set up only one language per job and run the hooks for that language. But then we are running the same hook (like `trailing-whitespace`) multiple times? Actually, the `trailing-whitespace` hook doesn't have a `files` regex? It runs on all files. So we would run it in every job? That's inefficient.
So maybe one job is better.
However, if we have a very large codebase and many languages, the one job might take too long. Then we can split by language, but we have to be careful with hooks that run on all files.
We can define the hooks that run on all files (like `trailing-whitespace`) to run only in one job? But then we have to know which job.
Alternatively, we can have:
Job 1: Run all hooks that are language-agnostic (like `trailing-whitespace`, `end-of-file-fixer`, etc.) on all files.
Job 2, 3, ...: Run language-specific hooks only on the files of that language.
But then we have to split the hooks in the pre-commit config? We can have two configs: one for language-agnostic and one per language? And then run:
pre-commit run --config .pre-commit-config.agnostic.yaml --all-files
pre-commit run --config .pre-commit-config.python.yaml --all-files
...
This is getting complicated.
Given the time, I think we start with one job that sets up all languages and runs all hooks on all files. Then, if it becomes too slow, we can optimize.
11. Implementation:
a. Create `.pre-commit-config.yaml` at the root with all the hooks we need for all languages.
b. Create a CI workflow (`.github/workflows/lint.yml`) that:
- Checks out the code.
- Sets up all the languages (with the versions we want).
- Installs pre-commit (if not already installed by the setup actions?).
- Runs `pre-commit run --all-files`.
c. We can also add a step to cache the pre-commit environments to speed up.
Example of `lint.yml`:
```yaml
name: Lint
on:
push:
branches: [ main, develop ]
pull_request:
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.20'
- name: Set up Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
- name: Install pre-commit
run: pip install pre-commit
- name: Cache pre-commit
uses: actions/cache@v3
with:
path: ~/.cache/pre-commit
key: pre-commit-${{ hashFiles('.pre-commit-config.yaml') }}
- name: Run pre-commit
run: pre-commit run --all-files
```
This should work.
12. What about other consistency checks?
We can add more steps in the CI job, or add more hooks in pre-commit.
For example, we can add a hook for license headers, or for checking for secrets.
We can also add a step to check for dependency updates (like `npm audit`, `pip list --outdated`, etc.) but that might be noisy and we don't want to fail the CI for outdated dependencies? Maybe we want to be notified but not block.
We can have a separate job for security scanning and dependency updates.
13. Conclusion:
We have:
- A central `.pre-commit-config.yaml` that defines linters for all languages.
- A CI job that sets up all languages and runs pre-commit on all files.
This is a simple and effective polyglot toolchain.
However, note that if we have many languages, the CI job will set up many language runtimes and run many linters, which might be slow. We can consider:
- Caching the language runtimes? (The setup actions already cache for us, e.g., `actions/setup-python` caches pip packages, `actions/setup-node` caches node modules, etc.)
- Caching pre-commit environments (as we did).
- Running only on changed files in PRs? (But then we might miss issues in other files? We can run on all files on main branch and on changed files on PRs? That's a common practice.)
Let's adjust the CI to run on changed files for PRs:
```yaml
- name: Run pre-commit
run: |
if [ ${{ github.event_name }} = 'pull_request' ]; then
pre-commit run --from-ref origin/${{ github.base_ref }} --to-ref HEAD
else
pre-commit run --all-files
fi
```
But note: `--from-ref` and `--to-ref` require the git history to be present. In a PR, we have the base branch and the head. We are using `github.base_ref` for the base branch.
However, in a pull request, the `github.base_ref` is the base branch name, but we need the full ref? Actually, `origin/${{ github.base_ref }}` should work because we fetched the entire repository? By default, `actions/checkout` fetches only the current branch? We might need to fetch the base branch.
We can change the checkout step to fetch the entire history:
- uses: actions/checkout@v3
with:
fetch-depth: 0
Then we can use `--from-ref` and `--to-ref`.
Alternatively, we can use the `pre-commit/action` which has `from_ref` and `to_ref` options and handles the checkout appropriately? Let's use the action:
```yaml
- name: Run pre-commit
uses: pre-commit/action@v3.0.0
with:
extra_args: --from-ref origin/${{ github.base_ref }} --to-ref HEAD
```
But only for PRs.
We can do:
```yaml
- name: Run pre-commit
if: github.event_name == 'pull_request'
uses: pre-commit/action@v3.0.0
with:
extra_args: --from-ref origin/${{ github.base_ref }} --to-ref HEAD
- name: Run pre-commit on all files
if: github.event_name != 'pull_request'
uses: pre-commit/action@v3.0.0
with:
extra_args: --all-files
```
But then we are running two steps? We can combine:
```yaml
- name: Run pre-commit
uses: pre-commit/action@v3.0.0
with:
extra_args: ${{ github.event_name == 'pull_request' && format('--from-ref origin/{0} --to-ref HEAD', github.base_ref) || '--all-files' }}
```
But that might not work because the action expects a string? We can do:
```yaml
- name: Run pre-commit
uses: pre-commit/action@v3.0.0
with:
extra_args: ${{ github.event_name == 'pull_request' && '--from-ref origin/' || '' }}${{ github.event_name == 'pull_request' && github.base_ref || '' }}${{ github.event_name == 'pull_request' && ' --to-ref HEAD' || ' --all-files' }}
```
That's messy. Let's do two steps.
Alternatively, we can write a script:
```yaml
- name: Run pre-commit
run: |
if [ "${{ github.event_name }}" = "pull_request" ]; then
pre-commit run --from-ref origin/${{ github.base_ref }} --to-ref HEAD
else
pre-commit run --all-files
fi
```
And we must have fetched the base branch. So we change the checkout:
- uses: actions/checkout@v3
with:
fetch-depth: 0
This will fetch all branches and tags, and we can then reference the base branch.
But note: in a push event, we don't have `github.base_ref`. So we only run the if condition on pull_request.
Let's adjust:
```yaml
on:
push:
branches: [ main, develop ]
pull_request:
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
... set up languages ...
- name: Run pre-commit
run: |
if [ "${{ github.event_name }}" = "pull_request" ]; then
pre-commit run --from-ref origin/${{ github.base_ref }} --to-ref HEAD
else
pre-commit run --all-files
fi
```
This should work.
14. Final note:
We must ensure that each component (directory) has the necessary configuration files for the linters (like `.eslintrc.js`, `pyproject.toml`, etc.). We can have a central template and then copy? Or we can have a script that generates them? But that might be too rigid.
Alternatively, we can let each component have its own config, and then the pre-commit hooks will use that config. For example, `black` will look for `pyproject.toml` in the directory of the file or in parent directories. So we can have a `pyproject.toml` at the root of the Python project.
We must make sure that the pre-commit hooks are configured to look for the config in the right place? Actually, the hooks run in the directory of the file by default? Or in the root of the repo? The pre-commit hooks run in the root of the repo by default? Actually, they run in the directory where the file is? The documentation says: "Hooks are executed in the directory where the file is located." So if we have a `pyproject.toml` in the same directory as the Python file, it will be found.
So we can have per-component configs.
But for consistency, we might want to enforce the same config for all Python projects? We can have a central `pyproject.toml` at the root and then each component can inherit? Or we can have a script that copies the central config to each component? That might be cumbersome.
Alternatively, we can have a single config for the entire repo for each language? But then if we have multiple Python projects that require different settings, we are stuck.
So we allow per-component configs, and we enforce that they are consistent? We can have a linter that checks the configs? That's too meta.
I think we leave it to the developers to have consistent configs. We can have a template and document it.
Given the complexity, I think we have a good starting point.
15. Additional tools:
We might want to use a tool that aggregates the results of multiple linters? Like `reviewdog` for CI comments? But that's optional.
We can also use `codecov` for coverage, but that's for tests.
So we stick to the above.
16. Example for a specific language:
For Python, we might have:
- `black` for formatting.
- `flake8` for linting.
- `mypy` for type checking.
We add these to `.pre-commit-config.yaml`:
- repo: https://github.com/psf/black
rev: 23.7.0
hooks:
- id: black
language_version: python3
- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.4.1
hooks:
- id: mypy
additional_dependencies:
- types-requests
- types-PyYAML
And then in each Python project, we have a `pyproject.toml` for black and flake8, and maybe a `mypy.ini` for mypy.
We can have a central `pyproject.toml` at the root and then each project can have its own? Or we can have one at the root and then the hooks will use that? Actually, black and flake8 look for config files in the current directory and then parent directories. So if we have a root `pyproject.toml`, it will be used for all Python files in the repo? But if a project wants a different config, it can have its own in its directory.
So we can have a central config and then override in subdirectories.
This is acceptable.
17. Conclusion:
We have:
- Central `.pre-commit-config.yaml` with hooks for all languages, using the appropriate `files` regex for each hook (or rely on the hook's default?).
- CI that sets up all languages and runs pre-commit on all files (or on changed files for PRs).
This should work for a polyglot repo.
Let me write the final files:
`.pre-commit-config.yaml`:
```yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
# Python
- repo: https://github.com/psf/black
rev: 23.7.0
hooks:
- id: black
language_version: python3
- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.4.1
hooks:
- id: mypy
# additional_dependencies if needed
# JavaScript/TypeScript
- repo: https://github.com/pre-commit/mirrors-eslint
rev: v8.43.0
hooks:
- id: eslint
additional_dependencies:
- eslint-config-react-app@7.0.1
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v3.0.3
hooks:
- id: prettier
# Go
- repo: https://github.com/golangci/golangci-lint-action
rev: v3.5.0
hooks:
- id: golangci-lint
# Rust
- repo: https://github.com/doublen/talossar-pre-commit-rust
rev: v0.1.0
hooks:
- id: cargo-fmt
- id: cargo-clippy
# ... add more for other languages
```
Note: for Go, we are using the `golangci-lint-action` hook? Actually, there is a hook for golangci-lint: https://github.com/golangci/golangci-lint/blob/master/.pre-commit-hooks.yaml. We can use:
- repo: https://github.com/golangci/golangci-lint
rev: v1.53.3
hooks:
- id: golangci-lint
Similarly for Rust, we can use:
- repo: https://github.com/rust-lang/rustfmt
rev: 1.5.1
hooks:
- id: rustfmt
- repo: https://github.com/rust-lang/rust-clippy
rev: v0.1.61
hooks:
- id: clippy
But note: the rustfmt and clippy hooks are not in the same repo? Actually, rustfmt is at https://github.com/rust-lang/rustfmt and clippy at https://github.com/rust-lang/rust-clippy. They have pre-commit hooks.
We can use:
- repo: https://github.com/rust-lang/rustfmt
rev: 1.5.1
hooks:
- id: rustfmt
- repo: https://github.com/rust-lang/rust-clippy
rev: v0.1.61
hooks:
- id: clippy
But then we have to set up Rust for these hooks? They are Rust tools, so they require Rust to be installed? Actually, the hooks will set up Rust themselves? They are `language: rust` hooks, so pre-commit will install Rust for them? We might not need to set up Rust in the CI? Let's check:
The rustfmt hook: https://github.com/rust-lang/rustfmt/blob/master/.pre-commit-hooks.yaml
It uses `language: rust` and `require_serial: true`. It will set up Rust by running `rustup`? It might use the system's Rust? The documentation says: "For rust hooks, the rust environment will be set up by pre-commit. The rust version will be the one that is installed on the system." So we need to have Rust installed in the system.
So we do need to set up Rust in the CI.
Similarly for Go, the golangci-lint hook uses `language: golang` and it will use the system's Go.
So we must set up all languages in the CI.
Therefore, our CI job must set up all languages we use.
Final CI:
```yaml
name: Lint
on:
push:
branches: [ main, develop ]
pull_request:
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.20'
- name: Set up Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
- name: Install pre-commit
run: pip install pre-commit
- name: Cache pre-commit
uses: actions/cache@v3
with:
path: ~/.cache/pre-commit
key: pre-commit-${{ hashFiles('.pre-commit-config.yaml') }}
- name: Run pre-commit
run: |
if [ "${{ github.event_name }}" = "pull_request" ]; then
pre-commit run --from-ref origin/${{ github.base_ref }} --to-ref HEAD
else
pre-commit run --all-files
fi
```
This should work.
18. What about other languages?
We can add more `setup-*` steps and more hooks in `.pre-commit-config.yaml`.
19. What about non-code files?
We have `check-yaml` and `check-added-large-files` from pre-commit-hooks.
We can add more hooks for markdown, etc.
20. What about formatting of non-code files? Like markdown? We can add markdownlint or prettier for markdown.
We can add:
- repo: https://github.com/markdownlint/markdownlint
rev: v0.11.0
hooks:
- id: markdownlint
And then set up the config for markdownlint? We can have a `.markdownlint.json` at the root.
21. What about shell scripts?
We can add `shellcheck`:
- repo: https://github.com/shellcheck-py/shellcheck-py
rev: v0.9.0.2
hooks:
- id: shellcheck
And then we need to have `shellcheck` installed? The hook uses the system's `shellcheck`? Actually, the hook is written in Python and it calls the `shellcheck` binary. So we need to install `shellcheck` in the CI.
We can install it with:
- name: Install shellcheck
run: sudo apt-get install -y shellcheck
Or we can use a hook that sets it up? There is a hook: https://github.com/koalaman/shellcheck-precommit, but it's not official.
Alternatively, we can use the `shellcheck-py` hook and then install shellcheck in the CI.
We can do:
- name: Install shellcheck
run: sudo apt-get update && sudo apt-get install -y shellcheck
But then we are installing via apt. We can also download the binary.
Given the complexity, we might skip shellcheck for now.
22. Final note:
This is a basic polyglot toolchain. We can extend it as needed.
We must document the structure and how to add new languages.
Steps to add a new language:
a. Add the setup step for the language in the CI.
b. Add the hooks for that language in `.pre-commit-config.yaml`.
c. Make sure the necessary configuration files are present in the projects for that language.
We can also have a `polyglot.yaml` that lists the languages and their versions, and then generate the CI and pre-commit config from it? That would be more advanced.
But for now, we keep it simple.
Let me write the files:
File: `.pre-commit-config.yaml`
```yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- id: check-merge-conflict
- id: check-executables-have-shebangs
# Python
- repo: https://github.com/psf/black
rev: 23.7.0
hooks:
- id: black
language_version: python3
- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8
additional_dependencies:
- flake8-bugbear
- flake8-comprehensions
- flake8-simplify
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.4.1
hooks:
- id: mypy
additional_dependencies:
- types-requests
- types-PyYAML
# JavaScript/TypeScript
- repo: https://github.com/pre-commit/mirrors-eslint
rev: v8.43.0
hooks:
- id: eslint
additional_dependencies:
- eslint-config-react-app@7.0.1
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v3.0.3
hooks:
- id: prettier
# Go
- repo: https://github.com/golangci/golangci-lint
rev: v1.53.3
hooks:
- id: golangci-lint
args: [--timeout=5m]
# Rust
- repo: https://github.com/rust-lang/rustfmt
rev: 1.5.1
hooks:
- id: rustfmt
- repo: https://github.com/rust-lang/rust-clippy
rev: v0.1.61
hooks:
- id: clippy
# Markdown
- repo: https://github.com/markdownlint/markdownlint
rev: v0.11.0
hooks:
- id: markdownlint
```
And then the CI as above, but we need to add the installation of `shellcheck` if we want to use it? We don't have it yet.
We also need to install `markdownlint`? It's a Ruby gem? The hook for markdownlint uses Ruby? Actually, the hook is written in Ruby and it requires the `markdownlint` gem. So we need to have Ruby and the gem installed? The hook doesn't set up Ruby? It uses the system's Ruby? We need to install Ruby and then `gem install markdownlint`? Or we can use a different hook?
Alternatively, we can use `markdownlint-cli` which is a Node.js tool? There is a pre-commit hook for that: https://github.com/igorshubovych/markdownlint-cli. We can use:
- repo: https://github.com/igorshubovych/markdownlint-cli
rev: v0.33.0
hooks:
- id: markdownlint
Then we need Node.js? We already have Node.js for JavaScript, so that's fine.
Let's change the markdown hook to use `markdownlint-cli`.
So we remove the Ruby-based one and add:
- repo: https://github.com/igorshubovych/markdownlint-cli
rev: v0.33.0
hooks:
- id: markdownlint
Then we don't need Ruby.
We must have a `.markdownlint.json` or `.markdownlint.yaml` at the root.
Now, the CI sets up Node.js, so the markdownlint hook will work.
We must adjust the CI to install `markdownlint-cli`? Actually, the hook will install it in its own environment? It's a Node.js hook, so it will set up Node.js? But we already have Node.js set up. It will use the system's Node.js? The hook's language is `node`, so it will use the system's Node.js? We set up Node.js in the CI, so it should work.
But note: the hook might install `markdownlint-cli` in its own environment? Actually, for `node` hooks, pre-commit uses the system's node and npm? It says: "For node hooks, the node environment will be set up by pre-commit. The node version will be the one that is installed on the system." So we need to have Node.js and npm installed.
We set up Node.js with `actions/setup-node`, which installs node and npm.
So we are good.
Final note: we might have to adjust the versions of the hooks and the languages to match our project's requirements.
This is a starting point.</think>
Here's a comprehensive polyglot repository toolchain design that works across multiple languages while maintaining consistency:
Directory Structure
repo/
├── .github/
│ └── workflows/ # CI/CD pipelines
├── .clang-format # C/C++/Java formatting
├── .editorconfig # Editor consistency
├── .gitattributes # Line endings, diff settings
├── .pre-commit-config.yaml # Universal pre-commit hooks
├── .dockerignore
├── Dockerfile # Polyglot build environment
├── Makefile # Common commands
├── LICENSE
├── README.md
├── polyglot.yaml # Central configuration
├── configs/
│ ├── eslint/ # JS/TS shared configs
│ ├── stylelint/ # CSS shared configs
│ ├── black/ # Python shared configs
│ ├── typos/ # Spell checking dictionary
│ └── markdownlint/ # Markdown rules
├── scripts/
│ ├── common.sh # Shared bash functions
│ ├── lint-all.sh # Master lint script
│ ├── format-all.sh # Master format script
│ └── check-deps.sh # Dependency consistency checker
├── tools/
│ ├── deptrack/ # Dependency version tracking
│ └── polyglot-lint/ # Custom polyglot linters
├── services/
│ ├── api/ # Go backend
│ │ ├── go.mod
│ │ ├── .golangci.yml
│ │ └── ...
│ ├── web/ # TypeScript/React frontend
│ │ ├── package.json
│ │ ├── tsconfig.json
│ │ ├── .eslintrc.js
│ │ └── ...
│ ├── ml/ # Python ML service
│ │ ├── pyproject.toml
│ │ ├── requirements.txt
│ │ └── ...
│ └── embedded/ # C++ firmware
│ ├── CMakeLists.txt
│ ├── .clang-tidy
│ └── ...
└── shared/
├── proto/ # Shared protobuf definitions
├── schemas/ # Shared JSON schemas
└── docs/ # Shared documentation
1. Central Configuration (polyglot.yaml)
languages:
enabled:
- python
- typescript
- go
- cpp
- markdown
- yaml
- json
- dockerfile
- shell
version_constraints:
python: ">=3.9,<3.13"
node: ">=18,<20"
go: ">=1.21"
rust: ">=1.70"
linting:
max_line_length: 100
tab_width: 4
trailing_whitespace: true
exclude_paths:
- "**/node_modules/**"
- "**/dist/**"
- "**/build/**"
- "**/.pytest_cache/**"
- "**/__pycache__/**"
- "**/.git/**"
dependency_check:
enabled: true
allow_unused: false
update_frequency: "weekly"
ci:
cache:
- key: "deps-{{ os }}-{{ hashFiles('**/package-lock.json', '**/requirements.txt', '**/go.sum') }}"
path:
- ~/.npm
- ~/.cargo/registry
- ~/.cache/pip
- key: "pre-commit-{{ hashFiles('.pre-commit-config.yaml') }}"
path: ~/.cache/pre-commit
2. Pre-commit Configuration (.pre-commit-config.yaml)
repos:
# Universal hooks
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- id: check-merge-conflict
- id: check-executables-have-shebangs
- id: check-shebang-scripts-are-executable
- id: check-case-conflict
- id: check-json
- id: check-toml
- id: check-xml
- id: check-yaml
- id: debug-statements
- id: forbid-new-submodules
- id: mixed-line-ending
args: ['--fix=lf']
- id: name-tests-test
args: ['--django']
# General formatting
- repo: https://github.com/editorconfig-checker/editorconfig-checker.python
rev: 2.7.3
hooks:
- id: editorconfig-checker
# Language-specific hooks
- repo: https://github.com/psf/black
rev: 23.11.0
hooks:
- id: black
language_version: python3.11
additional_dependencies: ['click==8.1.7']
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
args: ["--profile", "black"]
- repo: https://github.com/pycqa/flake8
rev: 6.1.0
hooks:
- id: flake8
additional_dependencies:
- flake8-bugbear
- flake8-comprehensions
- flake8-simplify
- flake8-pytest-style
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.7.0
hooks:
- id: mypy
additional_dependencies:
- types-requests
- types-PyYAML
- types-pyyaml
- repo: https://github.com/pre-commit/mirrors-eslint
rev: v8.55.0
hooks:
- id: eslint
files: \.[jt]sx?$
additional_dependencies:
- eslint@8.55.0
- '@typescript-eslint/parser@6.18.0'
- '@typescript-eslint/eslint-plugin@6.18.0'
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v3.1.1
hooks:
- id: prettier
types_or: [javascript, jsx, ts, tsx, json, css, scss, md, yaml, html]
- repo: https://github.com/golangci/golangci-lint-action
rev: v3.5.0
hooks:
- id: golangci-lint
args: [--timeout=5m]
- repo: https://github.com/doublen/talossar-pre-commit-rust
rev: v0.1.0
hooks:
- id: cargo-fmt
- id: cargo-clippy
args: [--all-targets, --all-features, --]
additional_dependencies: []
- repo: https://github.com/llvm-org/clang-tools-extra
rev: llvmorg-17.0.6
hooks:
- id: clang-format
files: \.(c|cc|cxx|cpp|h|hpp|hxx|h|hh)$
- id: clang-tidy
files: \.(c|cc|cxx|cpp|h|hpp|hxx|h|hh)$
args: [-p=build]
- repo: https://github.com/shellcheck-py/shellcheck-py
rev: v0.10.0.1
hooks:
- id: shellcheck
- repo: https://github.com/markdownlint/markdownlint
rev: v0.11.0
hooks:
- id: markdownlint
args: [--disable=MD013, --threshold=ERROR]
- repo: https://github.com/zricethezav/gitleaks
rev: v8.18.0
hooks:
- id: gitleaks
- repo: https://github.com/trufflesecurity/trufflehog
rev: v3.63.0
hooks:
- id: trufflehog
args: [--only-verified]
3. CI/CD Pipeline (.github/workflows/ci.yml)
name: Polyglot CI
on:
push:
branches: [main, develop]
pull_request:
branches: [main, develop]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
# Lint job runs for all languages
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: recursive
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
cache: 'pip'
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
- name: Setup Go
uses: actions/setup-go@v4
with:
go-version: '1.21'
cache: true
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- name: Install system dependencies
run: |
sudo apt-get update
sudo apt-get install -y shellcheck clang-tidy clang-format markdownlint
- name: Install pre-commit
run: pip install pre-commit pre-commit-hooks
- name: Cache pre-commit environments
uses: actions/cache@v3
with:
path: ~/.cache/pre-commit
key: pre-commit-${{ hashFiles('.pre-commit-config.yaml') }}
restore-keys: pre-commit-
- name: Run pre-commit on all files
run: pre-commit run --all-files --show-diff-on-failure
- name: Verify dependency consistency
run: ./scripts/check-deps.sh
# Language-specific test jobs
test-python:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install -r requirements-dev.txt
- name: Run tests
run: pytest --cov=./ --cov-report=xml --junitxml=junit.xml
- name: Upload coverage
uses: codecov/codecov-action@v3
with:
file: ./coverage.xml
test-typescript:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test -- --coverage --watchAll=false
- name: Upload coverage
uses: codecov/codecov-action@v3
with:
file: ./coverage/coverage-final.json
test-go:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v4
with:
go-version: '1.21'
- name: Run tests
run: go test -v ./... -coverprofile=coverage.out
- name: Upload coverage
uses: codecov/codecov-action@v3
with:
file: ./coverage.out
# Dependency vulnerability scan
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run Trivy vulnerability scanner
uses: aquasecurity/trivy-action@0.19.0
with:
scan-type: 'fs'
format: 'sarif'
output: 'trivy-results.sarif'
- name: Upload Trivy scan results
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: 'trivy-results.sarif'
# Build all services
build:
needs: [lint, test-python, test-typescript, test-go]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Build and push
run: |
docker buildx build \
--platform linux/amd64,linux/arm64 \
-t yourorg/yourrepo:${GITHUB_SHA} \
-t yourorg/yourrepo:latest \
--push \
.
4. Shared Scripts (scripts/lint-all.sh)
#!/bin/bash
set -euo pipefail
echo "🚀 Running polyglot linting..."
# Get changed files since main branch
CHANGED_FILES=$(git diff --name-only origin/main...HEAD || true)
# Filter by language
PYTHON_FILES=$(echo "$CHANGED_FILES" | grep -E '\.(py|pyx)$' || true)
TS_FILES=$(echo "$CHANGED_FILES" | grep -E '\.(ts|tsx)$' || true)
GO_FILES=$(echo "$CHANGED_FILES" | grep -E '\.(go)$' || true)
MD_FILES=$(echo "$CHANGED_FILES" | grep -E '\.(md|markdown)$' || true)
SH_FILES=$(echo "$CHANGED_FILES" | grep -E '\.(sh|bash|zsh)$' || true)
# Run language-specific linters
if [ -n "$PYTHON_FILES" ]; then
echo "🐍 Linting Python files..."
black --check $PYTHON_FILES
isort --check-only $PYTHON_FILES
flake8 $PYTHON_FILES
mypy $PYTHON_FILES
fi
if [ -n "$TS_FILES" ]; then
echo "📘 Linting TypeScript files..."
eslint $TS_FILES
prettier --check $TS_FILES
fi
if [ -n "$GO_FILES" ]; then
echo "🐹 Linting Go files..."
gofmt -l $GO_FILES | xargs -r gofmt -d
go vet ./...
staticcheck ./...
fi
if [ -n "$MD_FILES" ]; then
echo "📝 Linting Markdown files..."
markdownlint $MD_FILES
fi
if [ -n "$SH_FILES" ]; then
echo "🐚 Linting shell scripts..."
shellcheck $SH_FILES
fi
echo "✅ Linting complete!"
5. Dependency Consistency Checker (scripts/check-deps.sh)
#!/bin/bash
set -euo pipefail
echo "🔍 Checking dependency consistency..."
# Check for locked dependency versions
if [ -f "requirements.txt" ]; then
echo "Python requirements.txt present"
pip install pip-tools
pip-compile --output-file=requirements.txt requirements.in 2>/dev/null || true
fi
if [ -f "package.json" ]; then
echo "Node package-lock.json present"
if [ ! -f "package-lock.json" ]; then
echo "❌ Missing package-lock.json! Run 'npm ci' to generate."
exit 1
fi
npm ci --dry-run > /dev/null
fi
if [ -f "go.mod" ]; then
echo "Go go.sum present"
go mod tidy -v | grep -v "go: downloading" || true
fi
# Check for dependency conflicts across services
echo "Checking for version conflicts..."
python scripts/tools/deptrack/check_conflicts.py \
--python requirements.txt \
--node package.json \
--go go.mod
# Verify all services use approved versions
python scripts/tools/deptrack/verify_versions.py \
--config polyglot.yaml
echo "✅ Dependency check complete!"
6. Makefile (Common Commands)
.PHONY: all install lint format test clean
all: install lint test
install:
@echo "Installing all dependencies..."
@./scripts/install-all.sh
lint:
@echo "Running all linters..."
@pre-commit run --all-files
@./scripts/lint-all.sh
format:
@echo "Formatting all code..."
@pre-commit run --all-files --hook-stage manual
@./scripts/format-all.sh
test:
@echo "Running all tests..."
@docker compose -f docker-compose.test.yml up --build --abort-on-container-exit
clean:
@echo "Cleaning build artifacts..."
@find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
@find . -type f -name "*.pyc" -delete 2>/dev/null || true
@find . -type d -name "node_modules" -exec rm -rf {} + 2>/dev/null || true
@find . -type d -name "dist" -exec rm -rf {} + 2>/dev/null || true
@find . -type d -name "build" -exec rm -rf {} + 2>/dev/null || true
@docker system prune -f
# Polyglot-specific
verify: lint test
@./scripts/check-deps.sh
ci-setup:
@echo "Setting up CI environment..."
@docker build -t polyglot-builder:latest -f Dockerfile .
7. Dockerfile (Polyglot Builder)
# Multi-stage build for polyglot development environment
FROM python:3.11-slim as python-base
FROM node:18-bullseye-slim as node-base
FROM golang:1.21-bullseye as go-base
FROM rust:1.74-bullseye as rust-base
FROM ubuntu:22.04 as builder
# Install system dependencies
RUN apt-get update && apt-get install -y \
build-essential \
cmake \
clang \
clang-tidy \
clang-format \
shellcheck \
ruby-full \
git \
curl \
wget \
zip \
unzip \
protobuf-compiler \
&& rm -rf /var/lib/apt/lists/*
# Copy language-specific tools
COPY --from=python-base /usr/local/bin/python /usr/local/bin/
COPY --from=python-base /usr/local/lib/python3.11 /usr/local/lib/python3.11
COPY --from=node-base /usr/local/bin/node /usr/local/bin/
COPY --from=node-base /usr/local/lib/node_modules /usr/local/lib/node_modules
COPY --from=go-base /usr/local/go /usr/local/go
COPY --from=rust-base /usr/local/rustup /usr/local/rustup
COPY --from=rust-base /usr/local/cargo /usr/local/cargo
COPY --from=rust-base /usr/local/rustc /usr/local/rustc
# Install language tools
RUN pip install --no-cache-dir \
pre-commit \
black \
isort \
flake8 \
mypy \
bandit \
safety
RUN npm install -g \
npm \
eslint \
prettier \
@typescript-eslint/parser \
@typescript-eslint/eslint-plugin
RUN go install \
github.com/golangci/golangci-lint/cmd/golangci-lint@latest \
github.com/securecodewarrior/gosec/v2/cmd/gosec@latest \
honnef.co/go/tools/cmd/staticcheck@latest
RUN rustup component add rustfmt clippy
# Configure environment
ENV PATH="/usr/local/go/bin:/usr/local/cargo/bin:${PATH}"
ENV PYTHONPATH="/usr/local/lib/python3.11/site-packages:${PYTHONPATH}"
WORKDIR /workspace
8. Key Features & Best Practices
A. Consistency Enforcement
- EditorConfig: Ensure consistent indentation, line endings
- Pre-commit hooks: Run on all commits
- CI gates: Block merges on lint failures
- Centralized configs: Shared ESLint/Black configs in
configs/
B. Polyglot-Specific Optimizations
- Selective linting: Only run relevant linters on changed files
- Parallel execution: Matrix builds in CI for different languages
- Caching: Dependency and pre-commit cache across jobs
- Unified reporting: Aggregate results in CI dashboard
C. Dependency Management
- Version pinning: All languages have locked files
- Conflict detection: Script to check cross-language conflicts
- Security scanning: Trivy, Gitleaks, TruffleHog
- Update automation: Dependabot for all package managers
D. Onboarding & Maintenance
# One-command setup
make ci-setup
# Developer workflow
git commit -m "feature" # Runs pre-commit hooks
make lint # CI-local linting
make verify # Full pre-merge check
9. Migration Strategy
- Phase 1: Implement
.pre-commit-config.yaml and basic CI
- Phase 2: Add language-specific configs to
configs/
- Phase 3: Implement dependency consistency checks
- Phase 4: Add security scanning and advanced reporting
- Phase 5: Optimize caching and parallelization
10. Monitoring & Alerts
- Weekly: Dependency update reports
- Daily: Lint trend analysis
- Per PR: Complete lint report with file-specific results
- Security: Immediate alerts for vulnerability detection
This toolchain provides:
- ✅ Consistent formatting across all languages
- ✅ Fast incremental linting (only changed files)
- ✅ ** Unified** configuration management
- ✅ Comprehensive security scanning
- ✅ Developer-friendly local commands
- ✅ CI/CD integration with caching
- ✅ Scalable to new languages
Tip: Start with pre-commit + basic CI, then gradually add language-specific rules and consistency checks based on team needs.