text.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """Ensure text files have the proper line endings.
  2. """
  3. from subprocess import DEVNULL
  4. from milc import cli
  5. from qmk.path import normpath
  6. from qmk.commands import get_chunks
  7. def dos2unix_run(files):
  8. """Spawn multiple dos2unix subprocess avoiding too long commands on formatting everything
  9. """
  10. for chunk in get_chunks(files, 10):
  11. dos2unix = cli.run(['dos2unix', *chunk])
  12. if dos2unix.returncode:
  13. return False
  14. @cli.argument('-b', '--base-branch', default='origin/master', help='Branch to compare to diffs to.')
  15. @cli.argument('-a', '--all-files', arg_only=True, action='store_true', help='Format all files.')
  16. @cli.argument('files', nargs='*', arg_only=True, type=normpath, help='Filename(s) to format.')
  17. @cli.subcommand("Ensure text files have the proper line endings.", hidden=True)
  18. def format_text(cli):
  19. """Ensure text files have the proper line endings.
  20. """
  21. # Find the list of files to format
  22. if cli.args.files:
  23. files = list(cli.args.files)
  24. if cli.args.all_files:
  25. cli.log.warning('Filenames passed with -a, only formatting: %s', ','.join(map(str, files)))
  26. elif cli.args.all_files:
  27. git_ls_cmd = ['git', 'ls-files']
  28. git_ls = cli.run(git_ls_cmd, stdin=DEVNULL)
  29. files = list(filter(None, git_ls.stdout.split('\n')))
  30. else:
  31. git_diff_cmd = ['git', 'diff', '--name-only', cli.args.base_branch]
  32. git_diff = cli.run(git_diff_cmd, stdin=DEVNULL)
  33. files = list(filter(None, git_diff.stdout.split('\n')))
  34. # Sanity check
  35. if not files:
  36. cli.log.error('No changed files detected. Use "qmk format-text -a" to format all files')
  37. return False
  38. return dos2unix_run(files)