Repository: sqlfluff/sqlfluff

Issue:
Disable rule inline doesn't work for commented sections of code
## Expected Behaviour

Adding -- noqa: L016 to the end of a commented line should ignore the 'Line too long' rule

## Observed Behaviour

Rule still fails for commented line even with the --noqa addition

## Steps to Reproduce

-- kkajshdkjhndkndansdjkasndjks knasdkasdkjaskjdhkajhdjkadn kahdkahnsjkdhkajdiundueubebd dkldkkljdalsd -- noqa: L016

## Dialect

Snowflake

## Version

SQLFluff v 0.8.2, Python v 3.8.2

## Configuration

```
[sqlfluff]
verbose = 0
nocolor = False
dialect = snowflake
templater = jinja
rules = None
exclude_rules = None
recurse = 0
output_line_length = 80
runaway_limit = 10
ignore_templated_areas = True
sql_file_exts = .sql,.sql.j2,.dml,.ddl

[sqlfluff:indentation]
indented_joins = False
template_blocks_indent = True

[sqlfluff:templater]
unwrap_wrapped_queries = True

[sqlfluff:templater:jinja]
apply_dbt_builtins = True

[sqlfluff:templater:jinja:macros]
# Macros provided as builtins for dbt projects
dbt_ref = {% macro ref(model_ref) %}{{model_ref}}{% endmacro %}
dbt_source = {% macro source(source_name, table) %}{{source_name}}_{{table}}{% endmacro %}
dbt_config = {% macro config() %}{% for k in kwargs %}{% endfor %}{% endmacro %}
dbt_var = {% macro var(variable) %}item{% endmacro %}
dbt_is_incremental = {% macro is_incremental() %}True{% endmacro %}

[sqlfluff:rules]
tab_space_size = 4
max_line_length = 80
indent_unit = space
comma_style = trailing
allow_scalar = False
single_table_references = unqualified
unquoted_identifiers_policy = all

[sqlfluff:rules:L003]
lint_templated_tokens = True

[sqlfluff:rules:L010]
capitalisation_policy = upper

[sqlfluff:rules:L014]
extended_capitalisation_policy = lower

[sqlfluff:rules:L016]
ignore_comment_lines = False

[sqlfluff:rules:L029]
unquoted_identifiers_policy = aliases

[sqlfluff:rules:L030]
capitalisation_policy = lower

[sqlfluff:rules:L038]
select_clause_trailing_comma = forbid

[sqlfluff:rules:L040]
capitalisation_policy = upper

[sqlfluff:rules:L042]
forbid_subquery_in = both

[sqlfluff:rules:L047]
prefer_count_1 = False
```


Discussion:
jpy-git: Just looking up where to add inline ignore tests for this.
codecov[bot]: # [Codecov](https://codecov.io/gh/sqlfluff/sqlfluff/pull/1985?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=sqlfluff) Report
> Merging [#1985](https://codecov.io/gh/sqlfluff/sqlfluff/pull/1985?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=sqlfluff) (a76a4b7) into [main](https://codecov.io/gh/sqlfluff/sqlfluff/commit/3bca62f8d6b2b4f5e9603d8782f3473805a14543?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=sqlfluff) (3bca62f) will **not change** coverage.
> The diff coverage is `100.00%`.

[![Impacted file tree graph](https://codecov.io/gh/sqlfluff/sqlfluff/pull/1985/graphs/tree.svg?width=650&height=150&src=pr&token=maM8kLgCmn&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=sqlfluff)](https://codecov.io/gh/sqlfluff/sqlfluff/pull/1985?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=sqlfluff)

```diff
@@            Coverage Diff            @@
##              main     #1985   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          148       148           
  Lines        10290     10291    +1     
=========================================
+ Hits         10290     10291    +1     
```


| [Impacted Files](https://codecov.io/gh/sqlfluff/sqlfluff/pull/1985?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=sqlfluff) | Coverage Δ | |
|---|---|---|
| [src/sqlfluff/core/linter/linter.py](https://codecov.io/gh/sqlfluff/sqlfluff/pull/1985/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=sqlfluff#diff-c3JjL3NxbGZsdWZmL2NvcmUvbGludGVyL2xpbnRlci5weQ==) | `100.00% <100.00%> (ø)` | |

------

[Continue to review full report at Codecov](https://codecov.io/gh/sqlfluff/sqlfluff/pull/1985?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=sqlfluff).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=sqlfluff)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/sqlfluff/sqlfluff/pull/1985?src=pr&el=footer&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=sqlfluff). Last update [3bca62f...a76a4b7](https://codecov.io/gh/sqlfluff/sqlfluff/pull/1985?src=pr&el=lastupdated&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=sqlfluff). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=sqlfluff).

tunetheweb: Should we add a test case?
tunetheweb: Ah missed your comment!
jpy-git: @tunetheweb I've added the unit tests now 😄 


tunetheweb: Probably getting really picky here but I presume this handles other inline comments too (I think it does but not sure)?

```sql
this_is_not_so_big a # Hash inline comment --noqa: L012
this_is_not_so_big a /* Full inline comment */ --noqa: L012
```

Should we add test cases just to be sure?
jpy-git: @tunetheweb got those extra unit tests added now 👍 
jpy-git: LGTM 🚀 

Patch:
diff --git a/src/sqlfluff/core/linter/linter.py b/src/sqlfluff/core/linter/linter.py
index 2ca7dc670..5a3c1216d 100644
--- a/src/sqlfluff/core/linter/linter.py
+++ b/src/sqlfluff/core/linter/linter.py
@@ -228,6 +228,12 @@ class Linter:
     def parse_noqa(comment: str, line_no: int):
         """Extract ignore mask entries from a comment string."""
         # Also trim any whitespace afterward
+
+        # Comment lines can also have noqa e.g.
+        # --dafhsdkfwdiruweksdkjdaffldfsdlfjksd -- noqa: L016
+        # Therefore extract last possible inline ignore.
+        comment = [c.strip() for c in comment.split("--")][-1]
+
         if comment.startswith("noqa"):
             # This is an ignore identifier
             comment_remainder = comment[4:]


Test patch:
diff --git a/test/core/linter_test.py b/test/core/linter_test.py
index 8f9c6abce..3df15c0c8 100644
--- a/test/core/linter_test.py
+++ b/test/core/linter_test.py
@@ -383,6 +383,10 @@ def test__linter__encoding(fname, config_encoding, lexerror):
         ("noqa: disable=L010", NoQaDirective(0, ("L010",), "disable")),
         ("noqa: disable=all", NoQaDirective(0, None, "disable")),
         ("noqa: disable", SQLParseError),
+        (
+            "Inline comment before inline ignore -- noqa:L001,L002",
+            NoQaDirective(0, ("L001", "L002"), None),
+        ),
     ],
 )
 def test_parse_noqa(input, expected):
@@ -520,6 +524,33 @@ def test_parse_noqa(input, expected):
             ],
             [2],
         ],
+        [
+            [
+                dict(
+                    comment="Inline comment before inline ignore -- noqa: L002",
+                    line_no=1,
+                )
+            ],
+            [DummyLintError(1)],
+            [0],
+        ],
+        [
+            [
+                dict(
+                    comment="Inline comment before inline ignore -- noqa: L002",
+                    line_no=1,
+                ),
+                dict(
+                    comment="Inline comment before inline ignore -- noqa: L002",
+                    line_no=2,
+                ),
+            ],
+            [
+                DummyLintError(1),
+                DummyLintError(2),
+            ],
+            [0, 1],
+        ],
     ],
     ids=[
         "1_violation_no_ignore",
@@ -538,6 +569,8 @@ def test_parse_noqa(input, expected):
         "1_violation_line_4_ignore_disable_all_2_3",
         "4_violations_two_types_disable_specific_enable_all",
         "4_violations_two_types_disable_all_enable_specific",
+        "1_violations_comment_inline_ignore",
+        "2_violations_comment_inline_ignore",
     ],
 )
 def test_linted_file_ignore_masked_violations(
@@ -564,6 +597,7 @@ def test_linter_noqa():
     lntr = Linter(
         config=FluffConfig(
             overrides={
+                "dialect": "bigquery",  # Use bigquery to allow hash comments.
                 "rules": "L012",
             }
         )
@@ -585,7 +619,10 @@ def test_linter_noqa():
         col_m m,
         col_n n, --noqa: disable=all
         col_o o,
-        col_p p --noqa: enable=all
+        col_p p, --noqa: enable=all
+        col_q q, --Inline comment --noqa: L012
+        col_r r, /* Block comment */ --noqa: L012
+        col_s s # hash comment --noqa: L012
     FROM foo
         """
     result = lntr.lint_string(sql)
@@ -598,6 +635,7 @@ def test_linter_noqa_with_templating():
     lntr = Linter(
         config=FluffConfig(
             overrides={
+                "dialect": "bigquery",  # Use bigquery to allow hash comments.
                 "templater": "jinja",
                 "rules": "L016",
             }
@@ -607,7 +645,9 @@ def test_linter_noqa_with_templating():
     {%- set a_var = ["1", "2"] -%}
     SELECT
       this_is_just_a_very_long_line_for_demonstration_purposes_of_a_bug_involving_templated_sql_files, --noqa: L016
-      this_is_not_so_big
+      this_is_not_so_big a, --Inline comment --noqa: L012
+      this_is_not_so_big b, /* Block comment */ --noqa: L012
+      this_is_not_so_big c # hash comment --noqa: L012
     FROM
       a_table
         """