options.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. """
  4. @Contact : liuyuqi.gov@msn.cn
  5. @Time : 2023/11/01 00:01:04
  6. @License : Copyright © 2017-2022 liuyuqi. All Rights Reserved.
  7. @Desc : 命令行参数,或配置文件
  8. """
  9. import argparse
  10. import os
  11. import shlex
  12. import dotenv
  13. from collections import OrderedDict
  14. from .utils.str_util import preferredencoding
  15. def parser_args(overrideArguments=None):
  16. """解析参数"""
  17. argparser = argparse.ArgumentParser()
  18. argparser.add_argument('-c', '--config', help='config file', default='config.ini')
  19. argparser.add_argument(
  20. 'command',
  21. help='command: ',
  22. choices=['create', 'clone', 'push', 'delete', 'pull'],
  23. )
  24. argparser.add_argument('-d', '--debug', help='debug mode', action='store_true')
  25. argparser.add_argument(
  26. '-p',
  27. '--platform',
  28. help='set a platform',
  29. choices=['github', 'gitee', 'gitlab', 'gogs', 'gitea', 'bitbucket', 'coding', 'gitcode'],
  30. default='github',
  31. )
  32. argparser.add_argument('-token', '--token', help='set a token')
  33. argparser.add_argument(
  34. '-repo_path', '--repo_path', help='set a repo'
  35. ) # , default=os.getcwd())
  36. args = argparser.parse_args()
  37. # remove None
  38. command_line_conf = OrderedDict(
  39. {k: v for k, v in args.__dict__.items() if v is not None}
  40. )
  41. system_conf = user_conf = custom_conf = OrderedDict()
  42. user_conf = _read_user_conf()
  43. if args.config:
  44. custom_conf = _read_custom_conf(args.config)
  45. system_conf.update(user_conf)
  46. system_conf.update(command_line_conf)
  47. if args.command == None and args.extractor == None:
  48. raise 'Error, please input cmd and extractor params11'
  49. return system_conf
  50. def _read_custom_conf(config_path: str) -> OrderedDict:
  51. """读取自定义配置文件 config.yaml"""
  52. def compat_shlex_split(s, comments=False, posix=True):
  53. if isinstance(s, str):
  54. s = s.encode('utf-8')
  55. return list(map(lambda s: s.decode('utf-8'), shlex.split(s, comments, posix)))
  56. try:
  57. with open(config_path, 'r', encoding=preferredencoding()) as f:
  58. contents = f.read()
  59. res = compat_shlex_split(contents, comments=True)
  60. except Exception as e:
  61. return []
  62. return res
  63. def _read_user_conf() -> OrderedDict:
  64. """读取用户配置文件: .env 文件"""
  65. user_conf = OrderedDict()
  66. dotenv_path = '.env'
  67. if os.path.exists(dotenv_path):
  68. user_conf = dotenv.dotenv_values(dotenv_path)
  69. return OrderedDict(user_conf)