Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
K

keep-sorted

> 数据库
Open source

keep-sorted is a language-agnostic formatter that sorts lines between two markers in a larger file.

395 stars0 likes4 views
WebsiteGitHub

About

keep-sorted is a language-agnostic formatter that sorts lines between two markers in a larger file.

keep-sorted

keep-sorted is a language-agnostic formatter that sorts lines between two markers in a larger file.

Usage

Surround the lines to keep sorted with keep-sorted start and keep-sorted end in comments. For example, in Java:

Before

java
@Component(
    modules = {

      UtilsModule.class,
      GetRequestModule.class,
      PostRequestModule.class,
      AuthModule.class,
      MonitoringModule.class,
      LoggingModule.class,

    })
interface FrontendComponent {
  FrontendRequestHandler requestHandler();
}

After

diff
@Component(
    modules = {
+     // keep-sorted start
      AuthModule.class,
      GetRequestModule.class,
      LoggingModule.class,
      MonitoringModule.class,
      PostRequestModule.class,
      UtilsModule.class,
+     // keep-sorted end
    })
interface FrontendComponent {
  FrontendRequestHandler requestHandler();
}

You can also nest keep-sorted blocks:

python
                              
foo = [

  'y',
  'x',
  'z',

]
bar = [

  '1',
  '3',
  '2',

]
diff
+# keep-sorted start block=yes
 bar = [
+  # keep-sorted start
   '1',
   '2',
   '3',
+  # keep-sorted end
 ]
 foo = [
+  # keep-sorted start
   'x',
   'y',
   'z',
+  # keep-sorted end
 ]
+# keep-sorted end

Sorting your file

  1. Install go: https://go.dev/doc/install

[!NOTE] keep-sorted currently requires at least go 1.23.

  1. Install keep-sorted:

    bash
    $ go install github.com/google/[email protected]
  2. Run keep-sorted:

    bash
    $ keep-sorted [file1] [file2] ...

    If the file is -, the tool will read from stdin and write to stdout.

pre-commit

You can run keep-sorted automatically by adding this repository to your pre-commit.

yaml
- repo: https://github.com/google/keep-sorted
  rev: v0.10.0
  hooks:
    - id: keep-sorted

Options

Pre-sorting options

Pre-sorting options tell keep-sorted what content in your file constitutes a single logical line that needs to be sorted.

Line continuations

By default, keep-sorted will interpret increasing indentation as a line continuation and group indented lines with the lines above. If you don't want this behavior, line continuation can be disabled via group=no.

java
// keep-sorted start
private final Bar bar;
private final Baz baz =
    new Baz()
private final Foo foo;
// keep-sorted end
diff
+// keep-sorted start group=no
     new Baz()
 private final Bar bar;
 private final Baz baz =
 private final Foo foo;
 // keep-sorted end

Blocks

Alternatively, block=yes is an opt-in way to handle more complicated blocks of code, with some gotchas. It looks at characters that are typically expected to be closed in a single logical line of code (e.g., braces are balanced). Thus, what gets considered a group is the smallest set of lines that has all the typical symbols balanced (parentheses, braces, brackets, and quotes). This allows for sorting data such as Go structs and JSON objects.

go
  widgets := []widget{

    {
      Name: "def",
    },
    {
      Name: "abc",
    },

  }
diff
  widgets := []widget{
+   // keep-sorted start block=yes
    {
      Name: "abc",
    },
    {
      Name: "def",
    },
+   // keep-sorted end
  }

Warning: keep-sorted is not language aware, so the groups are still being sorted as basic strings. e.g., "{\n" comes before "{Name:", so mixing the line break and whitespace usage may cause unexpected sorting.

Note: Braces within things that look like string literals are not counted when pairing braces. A string literal begins an ends with a matching pair of quotes, where quotes can be any of the following:

'
'''
"
"""
`
```

Note: angle brackets (``) are not supported by block mode due to being used for mathematical expressions in an unbalanced format.

Prefix grouping

Another way to group lines together is with the group_prefixes option. This takes a comma-separated list of prefixes. Any line beginning with one of those prefixes will be treated as a continuation line.


spaghetti
with meatballs
peanut butter
and jelly
hamburger
with lettuce
and tomatoes
diff
+// keep-sorted start group_prefixes=and,with
 hamburger
 with lettuce
 and tomatoes
 peanut butter
 and jelly
 spaghetti
 with meatballs
+// keep-sorted end

Regex-delimited grouping

Two mutually-exclusive options exist for delimiting groups using regular expressions: group_start_regex and group_end_regex. If part of a line matches the specified regular expression, that line will end the previous group and start a new group. With group_start_regex, the matching line will be at the start of a new group (potentially preceded by sticky comments), whereas with group_end_regex, the line will end the group. Some matching lines may be ignored based on the other options that are enabled.


// Some comment for foo
define foo =
abc + def;

// Some other comment for bar
define bar =
ghi + jkl;
diff
+// keep-sorted start group_start_regex=["^define\\b"] newline_separated=yes
 // Some other comment for bar
 define bar =
 ghi + jkl;

 // Some comment for foo
 define foo =
 abc + def;
+// keep-sorted end

Comments

Comments embedded within the sorted block are made to stick with their successor. The comment lines must start with the same comment marker as the keep-sorted instruction itself (e.g. # in the case below). keep-sorted will recognize //, /*, #, --, ;, and `

Name Value
Alpha Foo
Bravo Bar
Charlie Baz
Delta Qux
+

This can be used to keep the footers of a table from being sorted as well:

```md

Item  | Cost
----- | -----
Lemon | $1.50
Pear  | $2.10
Apple | $1.09
----- | -----
Total | $4.69
diff
+
 Item  | Cost
 ----- | -----
 Apple | $1.09
 Lemon | $1.50
 Pear  | $2.10
 ----- | -----
 Total | $4.69
+

Sorting options

Sorting options tell keep-sorted how the logical lines in your keep-sorted block should be sorted.

Case sensitivity

By default, keep-sorted is case-sensitive. This means that uppercase letters will be ordered before lowercase ones. This behavior can be changed to sort case-insensitively using the case flag:

proto
# keep-sorted start
Bravo
Delta
Foxtrot
alpha
charlie
echo
# keep-sorted end
diff
+# keep-sorted start case=no
 alpha
 Bravo
 charlie
 Delta
 echo
 Foxtrot
 # keep-sorted end

Numeric sorting

By default, keep-sorted uses lexical sorting. Depending on your data, this is not what you might want. By specifying numeric=yes, sequences of digits embedded in the lines are interpreted by their numeric values and sorted accordingly:

python
progress = (
  # keep-sorted start
  'PROGRESS_100_PERCENT',
  'PROGRESS_10_PERCENT',
  'PROGRESS_1_PERCENT',
  'PROGRESS_50_PERCENT',
  'PROGRESS_5_PERCENT',
  # keep-sorted end
)
diff
progress = (
+ # keep-sorted start numeric=yes
  'PROGRESS_1_PERCENT',
  'PROGRESS_5_PERCENT',
  'PROGRESS_10_PERCENT',
  'PROGRESS_50_PERCENT',
  'PROGRESS_100_PERCENT',
  # keep-sorted end
)

Regular expressions

It can be useful to sort an entire group based on a non-prefix substring. The option by_regex=… takes a comma-separated list of RE2 regular expressions that will be applied to the group, and then sorting will take place on just the results of the regular expressions.

[!NOTE] By default, keep-sorted adds the s flag to all regular expressions that allows . to also match \n. If you do not want that behavior, add (?-s) to the start of your regular expression.

[!TIP] Regular expressions often need special characters. See Syntax below for how to include special characters in the by_regex option.

By default, all characters that the regular expression matches will be considered for sorting. If the regular expression contains any capturing groups, only the characters matched by the capturing groups will be considered for sorting. The result from each regular expression will be concatenated into a list of results, and that list of results will be sorted lexicographically.

Regular expressions are applied after pre-sorting options. group_prefixes will consider the content of the file before any regular expression has been applied to it.

Regular expressions are applied before other sorting options. case, numeric, and prefix_order will only apply to the characters matched by your regular expressions.

[!TIP] If you want your regular expression itself to be case insensitive, consider setting the case-insensitive flag (?i) at the start of your expression.

When using the YAML Sequence syntax as the argument, a regexp template can be supplied optionally as a single string-to-string mapping in the sequence. Refer to the Bernoulli example below for a demonstration of pattern group reordering. Note that a templated rewrite will be returned wholly as the sorting key.

java
// keep-sorted start
List foo;
Object baz;
String bar;
// keep-sorted end
java
// keep-sorted start
List foo;
Object baz;
String bar;
// keep-sorted end
java
// keep-sorted start block=yes newline_separated=yes case=no
bool func2() {
  return true;
}

int func1() {
  return 1;
}

List
  func0() {
    return List.of(whatever);
}
// keep-sorted end
keep-sorted start skip_lines=1

Daniel Bernoulli
Emmy Noether
Jacob Bernoulli
Johann Bernoulli
Max Noether
Nicolaus Bernoulli

keep-sorted end
// keep-sorted start numeric=yes
Data Size A 20M
Data Size A 50K
Data Size A 250M
Data Size B 1B
Data Size B 80M
Data Size B 250K
// keep-sorted end
diff
+// keep-sorted start by_regex=\w+;
 String bar;
 Object baz;
 List foo;
 // keep-sorted end
diff
+// keep-sorted start by_regex=\w+; prefix_order=foo
 List foo;
 String bar;
 Object baz;
 // keep-sorted end
diff
+// keep-sorted start block=yes newline_separated=yes case=no by_regex=(\w+)\(\)\s+{ numeric=yes
 List
     func0() {
   return List.of(whatever);
 }
 
 int func1() {
   return 1;
 }
 
 bool func2() {
   return true;
 }
 // keep-sorted end
diff
+keep-sorted start skip_lines=1 by_regex=['^(?\w+) (?\w+)$': '${last_name} ${first_name}']
 
 Daniel Bernoulli
 Jacob Bernoulli
 Johann Bernoulli
 Nicolaus Bernoulli
 Emmy Noether
 Max Noether
 
 keep-sorted end
diff
+// keep-sorted start numeric=yes by_regex=(?i)(.*?)(?:(\d+)b|(\d+)m|(\d+)k)
Data Size A 50K
Data Size A 20M
Data Size A 250M
Data Size B 250K
Data Size B 80M
Data Size B 1B
// keep-sorted end

Prefix sorting

Sometimes, it is useful to specify a custom ordering for some elements. The option prefix_order=… takes a comma-separated list of prefixes that is matched against the lines to be sorted: if the line starts with one of the specified values, it is put at the corresponding position. Lines that don't match any of the prefixes are put after any lines that have a matching prefix. You can use an empty prefix to put unmatching lines in between non-empty prefixes.

c

// keep-sorted start
DO_SOMETHING_WITH_BAR,
DO_SOMETHING_WITH_FOO,
FINAL_BAR,
FINAL_FOO,
INIT_BAR,
INIT_FOO
// keep-sorted end
diff
 // Keep this list sorted with
 //   - INIT_* first
 //   - FINAL_* last
 //   - Everything else in between
+// keep-sorted start prefix_order=INIT_,,FINAL_
 INIT_BAR,
 INIT_FOO,
 DO_SOMETHING_WITH_BAR,
 DO_SOMETHING_WITH_FOO,
 FINAL_BAR,
 FINAL_FOO
 // keep-sorted end

This can also be combined with numeric sorting:

diff
droid_components = [
+ # keep-sorted start numeric=yes prefix_order=R2,C3
  R2D2_BOLTS_5_MM,
  R2D2_BOLTS_10_MM,

Issues· 13 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Godeveloper-toolsformatterlanguage-agnostic

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库