Skip to content

buildifier sorts strings of lists inconsistently when a comment appears in the middle of the list #1449

@mattnworb

Description

@mattnworb

I noticed that a line with only a comment in it will break any sorting of AssignExprs when there is a comment before the assignment, but if the "keep sorted" comment is the first element in the list, then it will sort the list. Example:

list1 = [
    "foo",
    "bar",
    "buzz",
]

# buildifier: keep sorted
list2 = [
    "bar",
    "buzz",
    "foo",
]

# this will not be sorted:
# buildifier: keep sorted
list3 = [
    "foo",
    "bar",
    "buzz",
    # "blah",
    "abc123",
]

# this WILL be sorted:
list4 = [
    # buildifier: keep sorted
    "foo",
    "bar",
    "buzz",
    # "blah",
    "abc123",
]

buildifier will sort list4 but not list3:

❯ buildifier -mode=diff -lint=warn example.bzl
--- example.bzl	2026-02-05 16:06:51
+++ /var/folders/m1/5018nxw5655fd55ql3xqqpjm0000gn/T/buildifier-tmp-3189288486	2026-02-05 16:10:37
@@ -24,9 +24,9 @@
 # this WILL be sorted:
 list4 = [
     # buildifier: keep sorted
-    "foo",
     "bar",
     "buzz",
+    "foo",
     # "blah",
     "abc123",
 ]
exit status 1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions