Skip to content

Commit

Permalink
Add format command to force unconditional formatting (#1186)
Browse files Browse the repository at this point in the history
This allows users of buildozer to format files without also having
buildifier installed. This was possible previously by making a trivial
edit and reverting it, but a dedicated command is cleaner.

Will be used as part of the upcoming `bazel mod tidy` command.
  • Loading branch information
fmeum committed Aug 25, 2023
1 parent 5662808 commit b163fcf
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
2 changes: 2 additions & 0 deletions buildozer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ Buildozer supports the following commands(`'command args'`):
* `dict_remove <attr> <key(s)>`: Deletes the key for the dict attribute `attr`.
* `dict_list_add <attr> <key> <value(s)>`: Adds value(s) to the list in the
dict attribute `attr`.
* `format`: Force formatting of all files, even if they were not changed by
other commands.

Here, `<attr>` represents an attribute (being `add`ed/`rename`d/`delete`d etc.),
e.g.: `srcs`, `<value(s)>` represents values of the attribute and so on.
Expand Down
18 changes: 18 additions & 0 deletions buildozer/buildozer_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2299,4 +2299,22 @@ EOF
diff -u MODULE.bazel.expected MODULE.bazel || fail "Output didn't match"
}

function test_format() {
cat > MODULE.bazel <<EOF
module(
name = "foo", version = "0.27.0",
)
EOF

cat > MODULE.bazel.expected <<EOF
module(
name = "foo",
version = "0.27.0",
)
EOF

$buildozer 'format' //MODULE.bazel:all
diff -u MODULE.bazel.expected MODULE.bazel || fail "Output didn't match"
}

run_suite "buildozer tests"
6 changes: 6 additions & 0 deletions edit/buildozer.go
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,11 @@ func cmdImplUseRepo(env CmdEnvironment, mode string) (*build.File, error) {
return env.File, nil
}

func cmdFormat(opts *Options, env CmdEnvironment) (*build.File, error) {
// Force formatting by not returning a nil *build.File.
return env.File, nil
}

func isExtensionLabel(arg string) bool {
// Labels referencing extensions are either absolute or repo-absolute. Repository names are not
// allowed to contain "@" or "/".
Expand Down Expand Up @@ -868,6 +873,7 @@ var AllCommands = map[string]CommandInfo{
"dict_list_add": {cmdDictListAdd, true, 3, -1, "<attr> <key> <value(s)>"},
"use_repo_add": {cmdUseRepoAdd, false, 2, -1, "([dev] <extension .bzl file> <extension name>|<use_extension variable name>) <repo(s)>"},
"use_repo_remove": {cmdUseRepoRemove, false, 2, -1, "([dev] <extension .bzl file> <extension name>|<use_extension variable name>) <repo(s)>"},
"format": {cmdFormat, false, 0, 0, ""},
}

var readonlyCommands = map[string]bool{
Expand Down

0 comments on commit b163fcf

Please sign in to comment.