options.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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', 'gui'],
  23. nargs='?',
  24. default=''
  25. )
  26. argparser.add_argument('-d', '--debug', help='debug mode', action='store_true')
  27. argparser.add_argument(
  28. '-p',
  29. '--platform',
  30. help='set a platform',
  31. choices=['github', 'gitee', 'gitlab', 'gogs', 'gitea', 'bitbucket', 'coding', 'aliyun','gitcode','cnb'],
  32. default='github',
  33. )
  34. argparser.add_argument('-token', '--token', help='set a token')
  35. argparser.add_argument(
  36. '-repo_path', '--repo_path', help='set a repo'
  37. ) # , default=os.getcwd())
  38. args = argparser.parse_args()
  39. # remove None
  40. command_line_conf = OrderedDict(
  41. {k: v for k, v in args.__dict__.items() if v is not None}
  42. )
  43. system_conf = user_conf = custom_conf = OrderedDict()
  44. user_conf = _read_user_conf()
  45. if args.config:
  46. custom_conf = _read_custom_conf(args.config)
  47. system_conf.update(user_conf)
  48. system_conf.update(command_line_conf)
  49. if args.command == None and args.extractor == None:
  50. raise 'Error, please input cmd and extractor params11'
  51. return system_conf
  52. def _read_custom_conf(config_path: str) -> OrderedDict:
  53. """读取自定义配置文件 config.yaml"""
  54. def compat_shlex_split(s, comments=False, posix=True):
  55. if isinstance(s, str):
  56. s = s.encode('utf-8')
  57. return list(map(lambda s: s.decode('utf-8'), shlex.split(s, comments, posix)))
  58. try:
  59. with open(config_path, 'r', encoding=preferredencoding()) as f:
  60. contents = f.read()
  61. res = compat_shlex_split(contents, comments=True)
  62. except Exception as e:
  63. return []
  64. return res
  65. def _read_user_conf() -> OrderedDict:
  66. """读取用户配置文件: .env 文件"""
  67. user_conf = OrderedDict()
  68. dotenv_path = '.env'
  69. if os.path.exists(dotenv_path):
  70. user_conf = dotenv.dotenv_values(dotenv_path)
  71. return OrderedDict(user_conf)