cli.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import os
  2. import click
  3. from .main import get_key, dotenv_values, set_key, unset_key
  4. @click.group()
  5. @click.option('-f', '--file', default=os.path.join(os.getcwd(), '.env'),
  6. type=click.Path(exists=True),
  7. help="Location of the .env file, defaults to .env file in current working directory.")
  8. @click.option('-q', '--quote', default='always',
  9. type=click.Choice(['always', 'never', 'auto']),
  10. help="Whether to quote or not the variable values. Default mode is always. This does not affect parsing.")
  11. @click.pass_context
  12. def cli(ctx, file, quote):
  13. '''This script is used to set, get or unset values from a .env file.'''
  14. ctx.obj = {}
  15. ctx.obj['FILE'] = file
  16. ctx.obj['QUOTE'] = quote
  17. @cli.command()
  18. @click.pass_context
  19. def list(ctx):
  20. '''Display all the stored key/value.'''
  21. file = ctx.obj['FILE']
  22. dotenv_as_dict = dotenv_values(file)
  23. for k, v in dotenv_as_dict.items():
  24. click.echo('%s="%s"' % (k, v))
  25. @cli.command()
  26. @click.pass_context
  27. @click.argument('key', required=True)
  28. @click.argument('value', required=True)
  29. def set(ctx, key, value):
  30. '''Store the given key/value.'''
  31. file = ctx.obj['FILE']
  32. quote = ctx.obj['QUOTE']
  33. success, key, value = set_key(file, key, value, quote)
  34. if success:
  35. click.echo('%s="%s"' % (key, value))
  36. else:
  37. exit(1)
  38. @cli.command()
  39. @click.pass_context
  40. @click.argument('key', required=True)
  41. def get(ctx, key):
  42. '''Retrieve the value for the given key.'''
  43. file = ctx.obj['FILE']
  44. stored_value = get_key(file, key)
  45. if stored_value:
  46. click.echo('%s="%s"' % (key, stored_value))
  47. else:
  48. exit(1)
  49. @cli.command()
  50. @click.pass_context
  51. @click.argument('key', required=True)
  52. def unset(ctx, key):
  53. '''Removes the given key.'''
  54. file = ctx.obj['FILE']
  55. quote = ctx.obj['QUOTE']
  56. success, key = unset_key(file, key, quote)
  57. if success:
  58. click.echo("Successfully removed %s" % key)
  59. else:
  60. exit(1)
  61. def get_cli_string(path=None, action=None, key=None, value=None):
  62. """Returns a string suitable for running as a shell script.
  63. Useful for converting a arguments passed to a fabric task
  64. to be passed to a `local` or `run` command.
  65. """
  66. command = ['dotenv']
  67. if path:
  68. command.append('-f %s' % path)
  69. if action:
  70. command.append(action)
  71. if key:
  72. command.append(key)
  73. if value:
  74. if ' ' in value:
  75. command.append('"%s"' % value)
  76. else:
  77. command.append(value)
  78. return ' '.join(command).strip()
  79. if __name__ == "__main__":
  80. cli()