Skip to content

Commit 0ec5be9

Browse files
tarekbadrshafrittoli
authored andcommitted
Read from configuration
1 parent effd45d commit 0ec5be9

File tree

12 files changed

+318
-75
lines changed

12 files changed

+318
-75
lines changed

cli/cdevents/cli/artifact.py

Lines changed: 15 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,13 @@
55
from typing import List
66

77
import click
8-
import requests
9-
from cloudevents.http import CloudEvent, to_structured
108

119
from cdevents.cli.utils import add_disclaimer_text, print_function_args
12-
10+
from cdevents.cli.cdevents_command import CDeventsCommand
1311

1412
# pylint: disable=unused-argument
1513
def common_artifact_options(function):
1614
"""Decorator for common cli options for artifact."""
17-
function = click.option(
18-
"--cde_sink",
19-
"-c",
20-
required=False,
21-
type=str,
22-
default=lambda: os.environ.get("CDE_SINK", "http://localhost:8080"),
23-
help="CDE_SINK",
24-
)(function)
2515
function = click.option(
2616
"--id",
2717
"-i",
@@ -58,50 +48,36 @@ def common_artifact_options(function):
5848
@click.command(help=add_disclaimer_text("Artifact Packaged CloudEvent."))
5949
@common_artifact_options
6050
def packaged(
61-
cde_sink: str,
6251
id: str,
6352
name: str = None,
6453
version: str = None,
6554
data: List[str] = None,
6655
):
6756
print_function_args()
68-
attributes = {
69-
"type": "cd.artifact.packaged.v1",
70-
"source": "cde-cli",
71-
"extensions": {
72-
"artifactid": id,
73-
"artifactname": name,
74-
"artifactversion": version,
75-
},
57+
artifact_packaged_eventV1 = "cd.artifact.packaged.v1"
58+
extensions = {
59+
"artifactid": id,
60+
"artifactname": name,
61+
"artifactversion": version,
7662
}
77-
event = CloudEvent(attributes, dict(data))
78-
headers, body = to_structured(event)
79-
80-
# send and print event
81-
requests.post(cde_sink, headers=headers, data=body)
63+
cdevents_command = CDeventsCommand()
64+
cdevents_command.run(artifact_packaged_eventV1, extensions, data)
8265

8366

8467
@click.command(help=add_disclaimer_text("Artifact Published CloudEvent."))
8568
@common_artifact_options
8669
def published(
87-
cde_sink: str,
8870
id: str,
8971
name: str = None,
9072
version: str = None,
9173
data: List[str] = None,
9274
):
9375
print_function_args()
94-
attributes = {
95-
"type": "cd.artifact.published.v1",
96-
"source": "cde-cli",
97-
"extensions": {
98-
"artifactid": id,
99-
"artifactname": name,
100-
"artifactversion": version,
101-
},
76+
artifact_published_eventV1 = "cd.artifact.published.v1"
77+
extensions = {
78+
"artifactid": id,
79+
"artifactname": name,
80+
"artifactversion": version,
10281
}
103-
event = CloudEvent(attributes, dict(data))
104-
headers, body = to_structured(event)
105-
106-
# send and print event
107-
requests.post(cde_sink, headers=headers, data=body)
82+
cdevents_command = CDeventsCommand()
83+
cdevents_command.run(artifact_published_eventV1, extensions, data)

cli/cdevents/cli/branch.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Module for cli branch commands."""
22
from __future__ import annotations
33

4+
import logging
45
import os
56
from typing import List
67

@@ -10,6 +11,7 @@
1011

1112
from cdevents.cli.utils import add_disclaimer_text, print_function_args
1213

14+
_log = logging.getLogger(__name__)
1315

1416
# pylint: disable=unused-argument
1517
def common_branch_options(function):
@@ -78,8 +80,8 @@ def created(
7880
headers, body = to_structured(event)
7981

8082
# send and print event
81-
requests.post(cde_sink, headers=headers, data=body)
82-
83+
result = requests.post(cde_sink, headers=headers, data=body)
84+
_log.debug(f"Response with state code {result.status_code}")
8385

8486
@click.command(help=add_disclaimer_text("Branch Deleted CloudEvent."))
8587
@common_branch_options
@@ -104,4 +106,5 @@ def deleted(
104106
headers, body = to_structured(event)
105107

106108
# send and print event
107-
requests.post(cde_sink, headers=headers, data=body)
109+
result = requests.post(cde_sink, headers=headers, data=body)
110+
_log.debug(f"Response with state code {result.status_code}")

cli/cdevents/cli/build.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Module for cli build commands."""
22
from __future__ import annotations
33

4+
import logging
45
import os
56
from typing import List
67

@@ -10,6 +11,8 @@
1011

1112
from cdevents.cli.utils import add_disclaimer_text, print_function_args
1213

14+
_log = logging.getLogger(__name__)
15+
1316

1417
# pylint: disable=unused-argument
1518
def common_build_options(function):
@@ -79,7 +82,8 @@ def started(
7982
headers, body = to_structured(event)
8083

8184
# send and print event
82-
requests.post(cde_sink, headers=headers, data=body)
85+
result = requests.post(cde_sink, headers=headers, data=body)
86+
_log.debug(f"Response with state code {result.status_code}")
8387

8488

8589
@click.command(help=add_disclaimer_text("Build Finished CloudEvent."))
@@ -105,7 +109,8 @@ def finished(
105109
headers, body = to_structured(event)
106110

107111
# send and print event
108-
requests.post(cde_sink, headers=headers, data=body)
112+
result = requests.post(cde_sink, headers=headers, data=body)
113+
_log.debug(f"Response with state code {result.status_code}")
109114

110115

111116
@click.command(help=add_disclaimer_text("PipelineRun Queued CloudEvent."))
@@ -131,4 +136,5 @@ def queued(
131136
headers, body = to_structured(event)
132137

133138
# send and print event
134-
requests.post(cde_sink, headers=headers, data=body)
139+
result = requests.post(cde_sink, headers=headers, data=body)
140+
_log.debug(f"Response with state code {result.status_code}")
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""Module for cli common command code."""
2+
import logging
3+
from abc import ABC
4+
import requests
5+
6+
from cdevents.cli.configuration_handler import ConfigurationHandler
7+
from cloudevents.http import CloudEvent, to_structured
8+
from cdevents.cli.configuration_handler import new_default_configuration_handler
9+
10+
class CDeventsCommand(ABC):
11+
"""Abstract base class for all Hostlog commands."""
12+
13+
def __init__(self, config_handler: ConfigurationHandler = None):
14+
"""Initializes base class.
15+
16+
Args:
17+
config_handler (ConfigurationHandler): the configuration handler.
18+
"""
19+
self._log = logging.getLogger(__name__)
20+
self._config_handler = config_handler
21+
if config_handler is None:
22+
self._config_handler = new_default_configuration_handler()
23+
24+
def run(self, type, extensions, data):
25+
"""run command.
26+
"""
27+
attributes = {
28+
"type": type,
29+
"source": self.config_handler.source.name,
30+
"extensions": extensions,
31+
}
32+
event = CloudEvent(attributes, dict(data))
33+
headers, body = to_structured(event)
34+
cde_link = self.config_handler.client.host
35+
36+
# send and print event
37+
result = requests.post(cde_link, headers=headers, data=body)
38+
self._log.info(f"Response with state code {result.status_code}")
39+
40+
41+
@property
42+
def config_handler(self) -> ConfigurationHandler:
43+
"""Property for configuration handler."""
44+
return self._config_handler
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
"""Module for configuration provider."""
2+
from __future__ import annotations
3+
4+
import copy
5+
import os
6+
from dataclasses import dataclass
7+
from pathlib import Path
8+
from typing import Union
9+
10+
from cdevents.cli.configuration_reader import ConfigurationReader
11+
from cdevents.cli.constants import DEAFULT_CONFIGURATION_FILE
12+
from cdevents.cli.utils import DictUtils
13+
14+
15+
def get_default_configuration_file() -> str:
16+
"""Returns the default configuration file path."""
17+
return DEAFULT_CONFIGURATION_FILE
18+
19+
def new_default_configuration_handler() -> ConfigurationHandler:
20+
"""Returnes a configuration handler with the default configuration file"""
21+
config_handler: ConfigurationHandler = ConfigurationHandler.create_new(
22+
get_default_configuration_file()
23+
)
24+
25+
return config_handler
26+
27+
28+
def new_configuration_handler_with_override(
29+
client_host, source_name
30+
) -> ConfigurationHandler:
31+
"""Returnes a configuration handler where args override configuration file."""
32+
args_as_config = ConfigurationHandler.create_override_config(
33+
client_host=client_host,
34+
source_name=source_name
35+
)
36+
37+
config_handler: ConfigurationHandler = ConfigurationHandler.create_new(
38+
get_default_configuration_file(), args_as_config
39+
)
40+
41+
return config_handler
42+
43+
44+
class ConfigurationHandler:
45+
"""Class for providing configuration."""
46+
47+
def __init__(self, configuration: dict):
48+
"""Initializes the configuration.
49+
50+
Args:
51+
configuration (dict): The configuration.
52+
"""
53+
self.client = _ClientConfig(**configuration["client"])
54+
self.source = _SourceConfig(**configuration["source"])
55+
56+
@staticmethod
57+
def create_override_config(
58+
client_host: str = None,
59+
source_name: str = None,
60+
) -> dict:
61+
"""Create a dict that can be used for overriding the default configuration.
62+
63+
Args:
64+
host (str, optional): client host address. Defaults to None.
65+
name (str, optional): source name. Defaults to None.
66+
67+
Returns:
68+
dict: the dict to ovverride configuration with.
69+
"""
70+
override_dict: dict = {}
71+
if client_host:
72+
DictUtils.merge_dicts({"client": {"host": client_host}}, override_dict)
73+
if source_name:
74+
DictUtils.merge_dicts({"source": {"name": source_name}}, override_dict)
75+
76+
return override_dict
77+
78+
@staticmethod
79+
def create_new(
80+
configuration_files: Union[list[str], str] = None, override_config: dict = None
81+
) -> ConfigurationHandler:
82+
"""Reads default configurationfile plus any additional configuration files provided.
83+
84+
Additional configuration files will be merged with the default configfuration file.
85+
Ovveride configuration will ovverid any configuration from files.
86+
A configuration provider is returned.
87+
88+
Args:
89+
configuration_files (Union[list[str], str], optional): yaml or json configration file. \
90+
Defaults to None.
91+
override_config (dict):override configuration from cli args. Defaults to None.
92+
93+
Returns:
94+
ConfigurationHandler: the handler.
95+
"""
96+
file_list = []
97+
if isinstance(configuration_files, str) or isinstance(configuration_files, Path):
98+
file_list.append(configuration_files)
99+
elif isinstance(configuration_files, list):
100+
file_list.extend(configuration_files)
101+
102+
reader = ConfigurationReader()
103+
for _file in file_list:
104+
reader.read_configuration(_file)
105+
106+
# merge dicts
107+
if override_config:
108+
_config = copy.deepcopy(override_config)
109+
DictUtils.merge_dicts(reader.configuration["configuration"], _config)
110+
else:
111+
_config = reader.configuration["configuration"]
112+
113+
return ConfigurationHandler(_config)
114+
115+
116+
@dataclass
117+
class _ClientConfig:
118+
host: str
119+
120+
@dataclass
121+
class _SourceConfig:
122+
name: str

0 commit comments

Comments
 (0)