qmk 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/usr/bin/env python3
  2. """CLI wrapper for running QMK commands.
  3. """
  4. import os
  5. import subprocess
  6. import sys
  7. from glob import glob
  8. from time import strftime
  9. from importlib import import_module
  10. # Add the QMK python libs to our path
  11. script_dir = os.path.dirname(os.path.realpath(__file__))
  12. qmk_dir = os.path.abspath(os.path.join(script_dir, '..'))
  13. python_lib_dir = os.path.abspath(os.path.join(qmk_dir, 'lib', 'python'))
  14. sys.path.append(python_lib_dir)
  15. # Figure out our version
  16. command = ['git', 'describe', '--abbrev=6', '--dirty', '--always', '--tags']
  17. result = subprocess.run(command, text=True, capture_output=True)
  18. if result.returncode == 0:
  19. os.environ['QMK_VERSION'] = 'QMK ' + result.stdout.strip()
  20. else:
  21. os.environ['QMK_VERSION'] = 'QMK ' + strftime('%Y-%m-%d-%H:%M:%S')
  22. # Setup the CLI
  23. import milc
  24. milc.EMOJI_LOGLEVELS['INFO'] = '{fg_blue}ψ{style_reset_all}'
  25. # If we were invoked as `qmk <cmd>` massage sys.argv into `qmk-<cmd>`.
  26. # This means we can't accept arguments to the qmk script itself.
  27. script_name = os.path.basename(sys.argv[0])
  28. if script_name == 'qmk':
  29. if len(sys.argv) == 1:
  30. milc.cli.log.error('No subcommand specified!\n')
  31. if len(sys.argv) == 1 or sys.argv[1] in ['-h', '--help']:
  32. milc.cli.echo('usage: qmk <subcommand> [...]')
  33. milc.cli.echo('\nsubcommands:')
  34. subcommands = glob(os.path.join(qmk_dir, 'bin', 'qmk-*'))
  35. for subcommand in sorted(subcommands):
  36. subcommand = os.path.basename(subcommand).split('-', 1)[1]
  37. milc.cli.echo('\t%s', subcommand)
  38. milc.cli.echo('\nqmk <subcommand> --help for more information')
  39. exit(1)
  40. if sys.argv[1] in ['-V', '--version']:
  41. milc.cli.echo(os.environ['QMK_VERSION'])
  42. exit(0)
  43. sys.argv[0] = script_name = '-'.join((script_name, sys.argv[1]))
  44. del sys.argv[1]
  45. # Look for which module to import
  46. if script_name == 'qmk':
  47. milc.cli.print_help()
  48. exit(0)
  49. elif not script_name.startswith('qmk-'):
  50. milc.cli.log.error('Invalid symlink, must start with "qmk-": %s', script_name)
  51. else:
  52. subcommand = script_name.replace('-', '.').replace('_', '.').split('.')
  53. subcommand.insert(1, 'cli')
  54. subcommand = '.'.join(subcommand)
  55. try:
  56. import_module(subcommand)
  57. except ModuleNotFoundError:
  58. milc.cli.log.error('Invalid subcommand! Could not import %s.', subcommand)
  59. exit(1)
  60. # Change to the root of our checkout
  61. os.environ['ORIG_CWD'] = os.getcwd()
  62. os.chdir(qmk_dir)
  63. if __name__ == '__main__':
  64. milc.cli()