Skip to content

Commit

Permalink
[README] Expand no_trailing_whitespace example
Browse files Browse the repository at this point in the history
Expand the no_trailing_whitespace example to work with 'shac fmt'.

Change-Id: Ib029169cf5e01519e7bc7877d64e17d94f11c26f
Reviewed-on: https://fuchsia-review.googlesource.com/c/shac-project/shac/+/1051018
Commit-Queue: Auto-Submit <[email protected]>
Fuchsia-Auto-Submit: Rob Mohr <[email protected]>
Reviewed-by: Oliver Newman <[email protected]>
  • Loading branch information
mohrr authored and CQ Bot committed May 21, 2024
1 parent f2f79af commit 7e0cb4c
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,45 @@ $ shac check
- black (success in 540ms)
```

With a couple minor changes we can configure `no_trailing_whitespace` to work
with `shac fmt` too. We need to rename the function from
`no_trailing_whitespace` to `_no_trailing_whitespace`, add a `replacements`
argument to `ctx.emit.finding()`, and register the check as a formatter. The
`replacements` argument only applies to the characters between `col` and
`end_col`. Since we want to remove those characters, we replace them with an
empty string.

```python
def _no_trailing_whitespace(ctx):
"""Check that no source files contain lines with trailing whitespace."""
for f in ctx.scm.affected_files():
contents = str(ctx.io.read_file(f))
for i, line in enumerate(contents.splitlines()):
stripped = line.rstrip()
if stripped != line:
ctx.emit.finding(
level = "error",
filepath = f,
# Finding lines and columns are 1-indexed.
line = i + 1,
col = len(stripped) + 1,
# End column is exclusive.
end_col = len(line) + 1,
message = "Delete trailing whitespace.",
replacements = [""]
)

no_trailing_whitespace = shac.check(_no_trailing_whitespace, formatter = True)
shac.register_check(no_trailing_whitespace)
```

Now `no_trailing_whitespace` will run in `shac fmt`:

```shell
$ shac fmt
- no_trailing_whitespace (all good!)
```

## Road map

Planned features/changes, in descending order by priority:
Expand Down

0 comments on commit 7e0cb4c

Please sign in to comment.