codespell-project / codespell

check code for common misspellings
GNU General Public License v2.0
1.9k stars 466 forks source link

Handle CTRL+C by showing a better message #3511

Closed mwtoews closed 1 month ago

mwtoews commented 2 months ago

This tidies-up messages while using interactive codespell, if the user decides to cancel using CTRL+C.

For example, before this PR:

$ codespell -i1 file.txt
hte
    hte ==> the (Y/n) ^CTraceback (most recent call last):
  File "/tmp/py310/bin/codespell", line 8, in <module>
    sys.exit(_script_main())
  File "/home/mtoews/src/codespell/codespell_lib/_codespell.py", line 1102, in _script_main
    return main(*sys.argv[1:])
  File "/home/mtoews/src/codespell/codespell_lib/_codespell.py", line 1324, in main
    bad_count += parse_file(
  File "/home/mtoews/src/codespell/codespell_lib/_codespell.py", line 1007, in parse_file
    fix, fixword = ask_for_word_fix(
  File "/home/mtoews/src/codespell/codespell_lib/_codespell.py", line 775, in ask_for_word_fix
    r = sys.stdin.readline().strip().upper()
KeyboardInterrupt

$ echo $?
130

and after this PR:

$ codespell -i1 file.txt
hte
    hte ==> the (Y/n) ^C
Cancelling '/tmp/py310/bin/codespell'
$ echo $?
130

And the same behaviour if a user starts codespell with python -m codespell_lib ...


Currently there is no test for this. It's probably possible, but not easy for me to construct. If this is important to include, I'd appreciate some tips on how to enable testing SIGINT.

mwtoews commented 2 months ago

Another arbitrary decision that can be changed is the return code. I've set this as 1 for now. But it could also be restored to 130 (the default for KeyboardInterrupt) or 0 for "no error". Opinions welcome.

Update: after reading up on error codes, it seems that 130 is a better choice for CTRL+C.

mwtoews commented 2 months ago

See related xref #3217 #3218. This PR moves the try/catch to _script_main where is is more generically caught.

DimitriPapadopoulos commented 1 month ago

Thank you @mwtoews!