Skip to content

Commit e19deee

Browse files
fix after review
1 parent 0afa91e commit e19deee

11 files changed

Lines changed: 32 additions & 34 deletions

src/pysonar_scanner/__main__.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1919
#
2020

21+
import logging
2122
from pysonar_scanner import app_logging
2223
from pysonar_scanner import cache
2324
from pysonar_scanner import exceptions
@@ -48,22 +49,21 @@ def scan():
4849

4950
def do_scan():
5051
app_logging.setup()
51-
app_logging.get_logger().info("Starting Pysonar, the Sonar scanner CLI for Python")
52+
logging.info("Starting Pysonar, the Sonar scanner CLI for Python")
5253
config = ConfigurationLoader.load()
5354
set_logging_options(config)
54-
app_logging.get_logger().debug(f"Loaded configuration: {config}")
5555

5656
ConfigurationLoader.check_configuration(config)
5757

5858
api = build_api(config)
5959
check_version(api)
6060
update_config_with_api_urls(config, api.base_urls)
61-
app_logging.get_logger().debug(f"Configuration after update from API URL: {config}")
61+
logging.debug(f"Final loaded configuration: {config}")
6262

6363
cache_manager = cache.get_cache(config)
6464
scanner = create_scanner_engine(api, cache_manager, config)
6565

66-
app_logging.get_logger().info("Starting the analysis...")
66+
logging.info("Starting the analysis...")
6767
return scanner.run(config)
6868

6969

@@ -78,12 +78,12 @@ def build_api(config: dict[str, any]) -> SonarQubeApi:
7878

7979

8080
def check_version(api: SonarQubeApi):
81-
app_logging.get_logger().info("Checking SonarQube version...")
8281
if api.is_sonar_qube_cloud():
83-
app_logging.get_logger().info("Analysis will be run on SonarQube Cloud")
82+
logging.debug(f"SonarQube Cloud url: {api.base_urls.base_url}")
8483
return
8584
version = api.get_analysis_version()
86-
app_logging.get_logger().info("Analysis will be run on SonarQube version %s", version)
85+
logging.debug(f"SonarQube url: {api.base_urls.base_url}")
86+
8787
if not version.does_support_bootstrapping():
8888
raise SQTooOldException(
8989
f"This scanner only supports SonarQube versions >= {MIN_SUPPORTED_SQ_VERSION}. \n"
@@ -101,10 +101,9 @@ def update_config_with_api_urls(config, base_urls: BaseUrls):
101101

102102

103103
def create_scanner_engine(api, cache_manager, config):
104-
app_logging.get_logger().info("Creating the scanner engine...")
105104
jre_path = create_jre(api, cache_manager, config)
106105
config[SONAR_SCANNER_JAVA_EXE_PATH] = str(jre_path.path)
107-
app_logging.get_logger().debug(f"JRE path: {jre_path.path}")
106+
logging.debug(f"JRE path: {jre_path.path}")
108107
scanner_engine_path = ScannerEngineProvisioner(api, cache_manager).provision()
109108
scanner = ScannerEngine(jre_path, scanner_engine_path)
110109
return scanner

src/pysonar_scanner/api.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,6 @@ def download_analysis_engine(self, handle: typing.BinaryIO) -> None:
232232
This method can raise a SonarQubeApiException if the server doesn't respond successfully.
233233
Alternative, if the file IO fails, an IOError or OSError can be raised.
234234
"""
235-
app_logging.get_logger().info("Download the analysis engine...")
236235
try:
237236
res = requests.get(
238237
f"{self.base_urls.api_base_url}/analysis/engine",

src/pysonar_scanner/app_logging.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,3 @@ def setup() -> None:
2626

2727
def configure_logging_level(verbose: bool) -> None:
2828
logging.getLogger().setLevel(logging.DEBUG if verbose else logging.INFO)
29-
30-
31-
def get_logger() -> logging.Logger:
32-
return logging.getLogger()

src/pysonar_scanner/configuration/configuration_loader.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
# along with this program; if not, write to the Free Software Foundation,
1818
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1919
#
20+
import logging
2021
from pathlib import Path
2122

2223
from pysonar_scanner import app_logging
@@ -36,7 +37,7 @@ def get_static_default_properties() -> dict[Key, any]:
3637
class ConfigurationLoader:
3738
@staticmethod
3839
def load() -> dict[Key, any]:
39-
app_logging.get_logger().info("Loading configuration properties...")
40+
logging.debug("Loading configuration properties...")
4041

4142
# each property loader is required to return NO default values.
4243
# E.g. if no property has been set, an empty dict must be returned.

src/pysonar_scanner/configuration/environment_variables.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
# along with this program; if not, write to the Free Software Foundation,
1818
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1919
#
20+
import logging
2021
import os
2122
import json
2223
from typing import Dict
@@ -50,11 +51,11 @@ def load_json_env_variables():
5051
json_properties = json.loads(json_params)
5152
properties.update(json_properties)
5253
except json.JSONDecodeError as e:
53-
app_logging.get_logger().warning(
54+
logging.warning(
5455
"The JSON in SONAR_SCANNER_JSON_PARAMS environment variable is invalid. The other environment variables will still be loaded.",
5556
e,
5657
)
57-
58+
logging.debug("Loaded environment properties: " + ", ".join(f"{key}={value}" for key, value in properties.items()))
5859
return properties
5960

6061

src/pysonar_scanner/configuration/pyproject_toml.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
# along with this program; if not, write to the Free Software Foundation,
1818
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1919
#
20+
import logging
2021
from pathlib import Path
2122
from typing import Dict
2223
import os
@@ -40,8 +41,9 @@ class TomlConfigurationLoader:
4041
def load(base_dir: Path) -> TomlProperties:
4142
filepath = base_dir / "pyproject.toml"
4243
if not os.path.isfile(filepath):
44+
logging.debug(f"No pyproject.toml at {filepath}")
4345
return TomlProperties({}, {})
44-
46+
logging.debug(f"pyproject.toml loaded from {filepath}")
4547
try:
4648
with open(filepath, "rb") as f:
4749
toml_dict = tomli.load(f)
@@ -51,7 +53,7 @@ def load(base_dir: Path) -> TomlProperties:
5153
project_properties = TomlConfigurationLoader.__read_project_properties(toml_dict)
5254
return TomlProperties(sonar_properties, project_properties)
5355
except Exception as e:
54-
app_logging.get_logger().warning(
56+
logging.warning(
5557
"There was an error reading the pyproject.toml file. No properties from the TOML file were extracted.",
5658
e,
5759
)

src/pysonar_scanner/configuration/sonar_project_properties.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
# along with this program; if not, write to the Free Software Foundation,
1818
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1919
#
20+
import logging
2021
from pathlib import Path
2122
from typing import Dict
2223
import os
@@ -26,8 +27,10 @@
2627
def load(base_dir: Path) -> Dict[str, str]:
2728
filepath = base_dir / "sonar-project.properties"
2829
if not os.path.isfile(filepath):
30+
logging.debug(f"no sonar-project.properties file found at {filepath}")
2931
return {}
3032

33+
logging.debug(f"sonar-project.properties loaded from {filepath}")
3134
props = Properties()
3235
with open(filepath, "rb") as f:
3336
props.load(f)

src/pysonar_scanner/jre.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
# along with this program; if not, write to the Free Software Foundation,
1818
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1919
#
20+
import logging
2021
import pathlib
2122
import shutil
2223
import tarfile
@@ -67,6 +68,7 @@ def provision(self) -> JREResolvedPath:
6768
def __attempt_provisioning_jre_with_retry(self) -> tuple[JRE, pathlib.Path]:
6869
jre_and_resolved_path = self.__attempt_provisioning_jre()
6970
if jre_and_resolved_path is None:
71+
logging.warning("Something went wrong while provisionning the JRE. Retrying...")
7072
jre_and_resolved_path = self.__attempt_provisioning_jre()
7173
if jre_and_resolved_path is None:
7274
raise ChecksumException.create("JRE")

src/pysonar_scanner/scannerengine.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -116,18 +116,18 @@ def provision(self) -> pathlib.Path:
116116
if scanner_file is not None:
117117
return scanner_file.filepath
118118
# Retry once in case the checksum failed due to the scanner engine being updated between getting the checksum and downloading the jar
119+
logging.warning("Something went wrong while downloading the scanner engine. Retrying...")
119120
scanner_file = self.__download_and_verify()
120121
if scanner_file is not None:
121122
return scanner_file.filepath
122123
else:
123124
raise ChecksumException.create("scanner engine JAR")
124125

125126
def __download_and_verify(self) -> Optional[CacheFile]:
126-
app_logging.get_logger().info("Get the analysis engine info ...")
127127
engine_info = self.api.get_analysis_engine()
128128
cache_file = self.cache.get_file(engine_info.filename, engine_info.sha256)
129129
if not cache_file.is_valid():
130-
app_logging.get_logger().info("Cached analysis engine is not valid.")
130+
logging.debug("No valid cached analysis engine jar was found")
131131
self.__download_scanner_engine(cache_file)
132132
return cache_file if cache_file.is_valid() else None
133133

@@ -143,9 +143,9 @@ def __init__(self, jre_path: JREResolvedPath, scanner_engine_path: pathlib.Path)
143143

144144
def run(self, config: dict[str, any]):
145145
cmd = self.__build_command(self.jre_path, self.scanner_engine_path)
146-
app_logging.get_logger().debug(f"Command: {cmd}")
146+
logging.debug(f"Command: {cmd}")
147147
properties_str = self.__config_to_json(config)
148-
app_logging.get_logger().debug(f"Properties: {properties_str}")
148+
logging.debug(f"Properties: {properties_str}")
149149
return CmdExecutor(cmd, properties_str).execute()
150150

151151
def __build_command(self, jre_path: JREResolvedPath, scanner_engine_path: pathlib.Path) -> list[str]:

tests/test_environment_variables.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -106,18 +106,16 @@ def test_environment_variables_from_json_params(self):
106106
self.assertEqual(len(properties), 2)
107107
self.assertDictEqual(properties, expected_properties)
108108

109-
@patch("pysonar_scanner.configuration.environment_variables.app_logging.get_logger")
110-
def test_invalid_json_params(self, mock_get_logger):
111-
mock_logger = MagicMock()
112-
mock_get_logger.return_value = mock_logger
109+
@patch("pysonar_scanner.configuration.environment_variables.logging")
110+
def test_invalid_json_params(self, mock_logging):
113111

114112
env = {"SONAR_SCANNER_JSON_PARAMS": '{"sonar.token": "json-token"'}
115113
with patch.dict("os.environ", env, clear=True):
116114
properties = environment_variables.load()
117115
self.assertEqual(len(properties), 0)
118116
self.assertDictEqual(properties, {})
119117

120-
mock_logger.warning.assert_called_once_with(
118+
mock_logging.warning.assert_called_once_with(
121119
"The JSON in SONAR_SCANNER_JSON_PARAMS environment variable is invalid. The other environment variables will still be loaded.",
122120
unittest.mock.ANY,
123121
)

0 commit comments

Comments
 (0)