keep-sorted 是一个语言无关的格式化工具,它可以在较大文件中对两个标记之间的行进行排序。
keep-sorted is a language-agnostic formatter that sorts lines between two markers in a larger file.
Surround the lines to keep sorted with keep-sorted start and
keep-sorted end in comments. For example, in Java:
Before
@Component(
modules = {
UtilsModule.class,
GetRequestModule.class,
PostRequestModule.class,
AuthModule.class,
MonitoringModule.class,
LoggingModule.class,
})
interface FrontendComponent {
FrontendRequestHandler requestHandler();
}After
@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:
foo = [
'y',
'x',
'z',
]
bar = [
'1',
'3',
'2',
]
+# 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[!NOTE] keep-sorted currently requires at least go 1.23.
Install keep-sorted:
$ go install github.com/google/[email protected]Run keep-sorted:
$ keep-sorted [file1] [file2] ...If the file is -, the tool will read from stdin and write to stdout.
You can run keep-sorted automatically by adding this repository to your pre-commit.
- repo: https://github.com/google/keep-sorted
rev: v0.10.0
hooks:
- id: keep-sortedPre-sorting options tell keep-sorted what content in your file constitutes a single logical line that needs to be sorted.
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.
// keep-sorted start
private final Bar bar;
private final Baz baz =
new Baz()
private final Foo foo;
// keep-sorted end+// keep-sorted start group=no
new Baz()
private final Bar bar;
private final Baz baz =
private final Foo foo;
// keep-sorted endAlternatively, 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.
widgets := []widget{
{
Name: "def",
},
{
Name: "abc",
},
} 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.
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
+// keep-sorted start group_prefixes=and,with
hamburger
with lettuce
and tomatoes
peanut butter
and jelly
spaghetti
with meatballs
+// keep-sorted endTwo 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;
+// 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 endComments 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
+
Item | Cost
----- | -----
Apple | $1.09
Lemon | $1.50
Pear | $2.10
----- | -----
Total | $4.69
+Sorting options tell keep-sorted how the logical lines in your keep-sorted block should be sorted.
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:
# keep-sorted start
Bravo
Delta
Foxtrot
alpha
charlie
echo
# keep-sorted end+# keep-sorted start case=no
alpha
Bravo
charlie
Delta
echo
Foxtrot
# keep-sorted endBy 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:
progress = (
# keep-sorted start
'PROGRESS_100_PERCENT',
'PROGRESS_10_PERCENT',
'PROGRESS_1_PERCENT',
'PROGRESS_50_PERCENT',
'PROGRESS_5_PERCENT',
# keep-sorted end
)progress = (
+ # keep-sorted start numeric=yes
'PROGRESS_1_PERCENT',
'PROGRESS_5_PERCENT',
'PROGRESS_10_PERCENT',
'PROGRESS_50_PERCENT',
'PROGRESS_100_PERCENT',
# keep-sorted end
)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
sflag 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_regexoption.
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.
// keep-sorted start
List foo;
Object baz;
String bar;
// keep-sorted end// keep-sorted start
List foo;
Object baz;
String bar;
// keep-sorted end// 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 endkeep-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+// keep-sorted start by_regex=\w+;
String bar;
Object baz;
List foo;
// keep-sorted end+// keep-sorted start by_regex=\w+; prefix_order=foo
List foo;
String bar;
Object baz;
// keep-sorted end+// 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+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+// 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 endSometimes, 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.
// keep-sorted start
DO_SOMETHING_WITH_BAR,
DO_SOMETHING_WITH_FOO,
FINAL_BAR,
FINAL_FOO,
INIT_BAR,
INIT_FOO
// keep-sorted end // 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 endThis can also be combined with numeric sorting:
droid_components = [
+ # keep-sorted start numeric=yes prefix_order=R2,C3
R2D2_BOLTS_5_MM,
R2D2_BOLTS_10_MM,暂无开放 Issues,或尚未同步最近议题。