-
Notifications
You must be signed in to change notification settings - Fork 4
Add lint #56
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
swtwsk
wants to merge
6
commits into
develop
Choose a base branch
from
add-lint
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Add lint #56
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
476b310
Add dp lint command
swtwsk 47f4109
Update sqlfluff to 0.12.0
swtwsk 060d66d
Read an existing .sqlfluff config
swtwsk fbcfce1
Bump packaging
swtwsk ef05e0e
Update docs requirements.txt
swtwsk cf74371
Update sqlfluff expectations
swtwsk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,160 @@ | ||
| import pathlib | ||
| import tempfile | ||
| from configparser import ConfigParser | ||
| from typing import Any, List | ||
|
|
||
| import click | ||
| import yaml | ||
|
|
||
| from ..cli_constants import BUILD_DIR | ||
| from ..cli_utils import echo_info, echo_subinfo, echo_warning, subprocess_run | ||
| from ..config_generation import ( | ||
| generate_profiles_yml, | ||
| read_dictionary_from_config_directory, | ||
| ) | ||
| from ..dbt_utils import read_dbt_vars_from_configs | ||
| from ..errors import SQLLintError, SubprocessNonZeroExitError | ||
|
|
||
| SQLFLUFF_FIX_NOT_EVERYTHING_ERROR = 1 | ||
| SQLFLUFF_LINT_ERROR = 65 # according to `sqlfluff.core.linter.LintingResult.stats` | ||
| SQLFLUFF_DIALECT_LOADING_ERROR = 66 # according to `sqlfluff.cli.commands.get_config` | ||
|
|
||
|
|
||
| def _get_dialect_or_default() -> str: | ||
| """Read ``dbt.yml`` config file and return its ``target_type`` or just the ``ansi``.""" | ||
| env, dbt_filename = "base", "dbt.yml" | ||
| dbt_env_config = read_dictionary_from_config_directory( | ||
| BUILD_DIR.joinpath("dag"), env, dbt_filename | ||
| ) or read_dictionary_from_config_directory(pathlib.Path.cwd(), env, dbt_filename) | ||
| try: | ||
| dialect = dbt_env_config["target_type"] | ||
| echo_subinfo(f'Found target_type "{dialect}", attempting to use it as the SQL dialect.') | ||
| except KeyError: | ||
| dialect = "ansi" | ||
| echo_warning( | ||
| 'Could not find `target_type` in `dbt.yml`. Using the default SQL dialect ("ansi").' | ||
| ) | ||
| return dialect | ||
|
|
||
|
|
||
| def _get_source_tests_paths() -> List[pathlib.Path]: | ||
| with open(pathlib.Path.cwd().joinpath("dbt_project.yml"), "r") as f: | ||
| dbt_project_config = yaml.safe_load(f) | ||
| dir_names: List[str] = ( | ||
| dbt_project_config.get("source-paths", []) | ||
| + dbt_project_config.get("model-paths", []) | ||
| + dbt_project_config.get("test-paths", []) | ||
| ) | ||
| return list(map(lambda dir_name: pathlib.Path.cwd().joinpath(dir_name), dir_names)) | ||
|
|
||
|
|
||
| def _insert_into_config_section(config: ConfigParser, section: str, key: str, value: Any) -> None: | ||
| if section not in config: | ||
| config[section] = {} | ||
| config[section][key] = value | ||
|
|
||
|
|
||
| def _create_temporary_sqlfluff_config(env: str) -> ConfigParser: | ||
| sqlfluff_config_path = pathlib.Path.cwd().joinpath(".sqlfluff") | ||
| config = ConfigParser() | ||
| if sqlfluff_config_path.exists(): | ||
| config.read(sqlfluff_config_path) | ||
|
|
||
| _insert_into_config_section(config, "sqlfluff", "templater", "dbt") | ||
| _insert_into_config_section( | ||
| config, | ||
| "sqlfluff:templater:dbt", | ||
| "profiles_dir", | ||
| str(generate_profiles_yml(env, copy_config_dir=True).absolute()), | ||
| ) | ||
| config["sqlfluff:templater:dbt:context"] = read_dbt_vars_from_configs(env) | ||
|
|
||
| return config | ||
|
|
||
|
|
||
| def _run_sqlfluff(command: str, dialect: str, env: str, additional_args: List[str]) -> None: | ||
| with tempfile.TemporaryDirectory() as tmp_dir: | ||
| tmp_config_path = pathlib.Path(tmp_dir).joinpath("sqlfluff.config") | ||
| with open(tmp_config_path, "w") as tmp_config: | ||
| _create_temporary_sqlfluff_config(env).write(tmp_config) | ||
|
|
||
| def sqlfluff_args(sql_dialect: str) -> List[str]: | ||
| return [ | ||
| "sqlfluff", | ||
| command, | ||
| "--dialect", | ||
| sql_dialect, | ||
| "--config", | ||
| str(tmp_config_path), | ||
| *additional_args, | ||
| *map(str, _get_source_tests_paths()), | ||
| ] | ||
|
|
||
| try: | ||
| subprocess_run(sqlfluff_args(dialect)) | ||
| except SubprocessNonZeroExitError as err: | ||
| if err.exit_code == SQLFLUFF_DIALECT_LOADING_ERROR and dialect != "ansi": | ||
| subprocess_run(sqlfluff_args("ansi")) | ||
| else: | ||
| raise err | ||
|
|
||
|
|
||
| def _run_fix_sqlfluff(dialect: str, env: str) -> None: | ||
| try: | ||
| echo_subinfo("Attempting to fix SQLs. Not every error can be automatically fixed.") | ||
| _run_sqlfluff("fix", dialect, env, ["--force"]) | ||
| except SubprocessNonZeroExitError as err: | ||
| if err.exit_code != SQLFLUFF_FIX_NOT_EVERYTHING_ERROR: | ||
| raise err | ||
|
|
||
|
|
||
| def _run_lint_sqlfluff(dialect: str, env: str) -> None: | ||
| try: | ||
| echo_subinfo("Linting SQLs.") | ||
| _run_sqlfluff("lint", dialect, env, []) | ||
| except SubprocessNonZeroExitError as err: | ||
| if err.exit_code == SQLFLUFF_LINT_ERROR: | ||
| raise SQLLintError | ||
| else: | ||
| raise err | ||
|
|
||
|
|
||
| def lint(fix: bool, env: str) -> None: | ||
| """ | ||
| Lint and format SQL. | ||
|
|
||
| :param fix: Whether to lint and fix linting errors, or just lint. | ||
| :type fix: bool | ||
| :param env: Name of the environment | ||
| :type env: str | ||
| """ | ||
| echo_info("Linting SQLs:") | ||
| dialect = _get_dialect_or_default() | ||
| if fix: | ||
| _run_fix_sqlfluff(dialect, env) | ||
| _run_lint_sqlfluff(dialect, env) | ||
|
|
||
|
|
||
| @click.command( | ||
| name="lint", | ||
| short_help="Lint and format SQL", | ||
| help="Lint and format SQL using SQLFluff.\n\n" | ||
| "For more information on rules and the workings of SQLFluff, " | ||
| "refer to https://docs.sqlfluff.com/", | ||
| ) | ||
| @click.option( | ||
| "--no-fix", | ||
| is_flag=True, | ||
| default=False, | ||
| type=bool, | ||
| help="Whether to lint and fix linting errors, or just lint.", | ||
| ) | ||
| @click.option( | ||
| "--env", | ||
| default="local", | ||
| type=str, | ||
| show_default=True, | ||
| help="Name of the environment", | ||
| ) | ||
| def lint_command(no_fix: bool, env: str) -> None: | ||
| lint(not no_fix, env) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
To remove when
copieris updated