google / keep-sorted

keep-sorted is a language-agnostic formatter that sorts lines between two markers in a larger file.
Apache License 2.0
132 stars 15 forks source link

Sticky comments don't appear to be working? #9

Closed dougthor42 closed 1 year ago

dougthor42 commented 1 year ago

It appears that Sticky Comments are not working? Or do I just have some config wrong?

Steps to Reproduce

Input file keep-sorted2.py:

# go/keep-sorted start
d = 1
c = 2
# sticky comment
b = 3
# sticky multi-
# line comment
a = 1
# go/keep-sorted end

Pre-commit config:

---
repos:
  - repo: https://github.com/google/keep-sorted
    rev: v0.1.1
    hooks:
      - id: keep-sorted

Run:

$ pre-commit run keep-sorted --file keep-sorted2.py
keep-sorted..............................................................Passed

Actual result:

# go/keep-sorted start
# line comment
# sticky comment
# sticky multi-
a = 1
b = 3
c = 2
d = 1
# go/keep-sorted end

Expected Result:

# go/keep-sorted start
# sticky multi-
# line comment
a = 1
# sticky comment
b = 3
c = 2
d = 1
# go/keep-sorted end

Other info:

JeffFaer commented 1 year ago

keep-sorted has some pretty naive logic to guess the comment marker being used: https://github.com/google/keep-sorted/blob/main/keepsorted/options.go#L182

It assumes that folks are doing # keep-sorted instead of # go/keep-sorted. So as it stands, it's saying the comment marker is # go/ instead of #.

  1. If you remove those go/ prefixes the sticky comments will work as expected

    $ /tmp/keep-sorted-7bcbaf089973232082a8bd6af9f906080d6adc9be65b58e8ee438a0185985dd8 --mode=fix - <<EOF
    # keep-sorted start
    d = 1
    c = 2
    # sticky comment
    b = 3
    # sticky multi-
    # line comment
    a = 1
    # keep-sorted end
    EOF
    # keep-sorted start
    # sticky multi-
    # line comment
    a = 1
    # sticky comment
    b = 3
    c = 2
    d = 1
    # keep-sorted end
  2. You could add your comment leader explicitly with sticky_prefixes=#

$ /tmp/keep-sorted-7bcbaf089973232082a8bd6af9f906080d6adc9be65b58e8ee438a0185985dd8 --mode=fix - <<EOF
# go/keep-sorted start sticky_prefixes=#
d = 1
c = 2
# sticky comment
b = 3
# sticky multi-
# line comment
a = 1
# go/keep-sorted end
EOF
# go/keep-sorted start sticky_prefixes=#
# sticky multi-
# line comment
a = 1
# sticky comment
b = 3
c = 2
d = 1
# go/keep-sorted end
  1. That comment guessing logic could be smarter by taking into account various well-known comment leaders (#, //, maybe even -- for SQL). I'd be willing to accept a PR for that
dougthor42 commented 1 year ago

Ah ok, so there's a minor difference between the internal go/keep-sorted on g3doc and the public one. Got it! I didn't notice the difference when comparing the two.

As expected, its a PEBKAC problem :upside_down_face:

dougthor42 commented 1 year ago

This was changed/fixed in #11 (using option 3 from comment 9) and now things act as expected. Thanks!