Skip to content
This repository has been archived by the owner on Jan 14, 2024. It is now read-only.

Commit

Permalink
Argument parsing: Add environment variables list to --help
Browse files Browse the repository at this point in the history
  • Loading branch information
blackandred committed May 13, 2020
1 parent cece64b commit 1540855
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 6 deletions.
23 changes: 20 additions & 3 deletions src/rkd/argparsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from typing import List
from argparse import ArgumentParser
from argparse import RawTextHelpFormatter
from .contract import TaskDeclarationInterface


Expand Down Expand Up @@ -66,15 +67,31 @@ def create_grouped_arguments(commandline: List[str]) -> List[TaskArguments]:

return tasks

@staticmethod
def get_parsed_vars_for_task(task: TaskDeclarationInterface, args: list):
argparse = ArgumentParser(task.to_full_name())
@classmethod
def get_parsed_vars_for_task(cls, task: TaskDeclarationInterface, args: list):
argparse = ArgumentParser(task.to_full_name(), formatter_class=RawTextHelpFormatter)

argparse.add_argument('--log-to-file', '-rf', help='Capture stdout and stderr to file')
argparse.add_argument('--log-level', '-rl', help='Log level: debug,info,warning,error,fatal')
argparse.add_argument('--keep-going', '-rk', help='Allow going to next task, even if this one fails',
action='store_true')
argparse.add_argument('--silent', '-rs', help='Do not print logs, just task output', action='store_true')

task.get_task_to_execute().configure_argparse(argparse)
cls.add_env_variables_to_argparse(argparse, task)

return vars(argparse.parse_args(args))

@classmethod
def add_env_variables_to_argparse(cls, argparse: ArgumentParser, task: TaskDeclarationInterface):
if argparse.description is None:
argparse.description = ""

# print all environment variables possible to use
argparse.description += "\nEnvironment variables for task \"%s\":\n" % task.to_full_name()

for env_name, default_value in task.get_task_to_execute().get_declared_envs().items():
argparse.description += " - %s (default: %s)\n" % (str(env_name), str(default_value))

if not task.get_task_to_execute().get_declared_envs():
argparse.description += ' -- No environment variables declared -- '
12 changes: 9 additions & 3 deletions src/rkd/test.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from typing import Dict
from argparse import ArgumentParser
from .syntax import TaskDeclaration
from .contract import TaskInterface, ExecutionContext
Expand All @@ -9,17 +10,22 @@ def __init__(self):
self._io = NullSystemIO()

def get_name(self) -> str:
pass
return ':test'

def get_group_name(self) -> str:
pass
return ':rkd'

def execute(self, context: ExecutionContext) -> bool:
pass
return True

def configure_argparse(self, parser: ArgumentParser):
pass

def get_declared_envs(self) -> Dict[str, str]:
return {
'Union': 'International Workers Association'
}


def get_test_declaration() -> TaskDeclaration:
return TaskDeclaration(TestTask(), {}, [])
20 changes: 20 additions & 0 deletions test/test_argparsing.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#!/usr/bin/env python3

import unittest
from argparse import ArgumentParser
from rkd.argparsing import CommandlineParsingHelper
from rkd.test import get_test_declaration


class ArgParsingTest(unittest.TestCase):
Expand Down Expand Up @@ -34,3 +36,21 @@ def test_creates_grouped_arguments_into_tasks__tasks_only(self):
])

self.assertEqual("[Task<:harbor:start ([])>, Task<:harbor:status ([])>, Task<:harbor:stop ([])>]", str(parsed))

def test_add_env_variables_to_argparse(self):
parser = ArgumentParser(':test')
task = get_test_declaration()

CommandlineParsingHelper.add_env_variables_to_argparse(parser, task)
self.assertIn('Union (default: International Workers Association)', parser.description)

def test_add_env_variables_to_argparse__no_envs(self):
parser = ArgumentParser(':test')
task = get_test_declaration()

# empty the values
task.get_task_to_execute().get_declared_envs = lambda: {}

CommandlineParsingHelper.add_env_variables_to_argparse(parser, task)
self.assertNotIn('Union (default: International Workers Association)', parser.description)
self.assertIn('-- No environment variables declared --', parser.description)
11 changes: 11 additions & 0 deletions test/test_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,14 @@ def test_logging_tasks_into_separate_files(self):
# clean up
os.unlink(first.name)
os.unlink(second.name)

def test_env_variables_listed_in_help(self):
full_output, exit_code = self._run_and_capture_output(['--help'])
self.assertIn('- RKD_DEPTH (default: 0)', full_output)

def test_env_variables_not_listed_in_tasks_task(self):
""" :tasks does not define any environment variables """

full_output, exit_code = self._run_and_capture_output([':tasks', '--help'])
self.assertNotIn('- RKD_DEPTH (default: 0)', full_output)
self.assertIn('-- No environment variables declared --', full_output)

0 comments on commit 1540855

Please sign in to comment.