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

Commit

Permalink
Merge pull request #21 from opengisch/time-to-get-logging-seriously
Browse files Browse the repository at this point in the history
Logging to stdout
  • Loading branch information
why-not-try-calmer authored Feb 21, 2023
2 parents ba4fe1c + 8034616 commit 2b4d173
Show file tree
Hide file tree
Showing 7 changed files with 45 additions and 34 deletions.
3 changes: 2 additions & 1 deletion pytransifex/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import logging
import sys

from pytransifex.api import Transifex

logging.basicConfig(level=logging.INFO)
logging.basicConfig(stream=sys.stdout, level=logging.INFO)

VERSION = "2.dev"
42 changes: 22 additions & 20 deletions pytransifex/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
from pytransifex.interfaces import Tx
from pytransifex.utils import concurrently, ensure_login

logger = logging.getLogger(__name__)


class Client(Tx):
"""
Expand Down Expand Up @@ -44,7 +46,7 @@ def login(self):
organization = tx_api.Organization.get(slug=self.organization_name)
self.projects = organization.fetch("projects")
self.organization = organization
logging.info(f"Logged in as organization: {self.organization_name}")
logger.info(f"Logged in as organization: {self.organization_name}")

@ensure_login
def create_project(
Expand All @@ -69,28 +71,28 @@ def create_project(
organization=self.organization,
**kwargs,
)
logging.info(f"Project created with name '{project_name}' !")
logger.info(f"Project created with name '{project_name}' !")
return proj

except JsonApiException as error:
if hasattr(error, "detail") and "already exists" in error.detail: # type: ignore
return self.get_project(project_slug=project_slug)
else:
logging.error(f"Unable to create project; API replied with {error}")
logger.error(f"Unable to create project; API replied with {error}")

@ensure_login
def delete_project(self, project_slug: str):
if project := self.get_project(project_slug=project_slug):
project.delete()
logging.info(f"Deleted project: {project_slug}")
logger.info(f"Deleted project: {project_slug}")

@ensure_login
def get_project(self, project_slug: str) -> None | Resource:
"""Fetches the project matching the given slug"""
if self.projects:
try:
res = self.projects.get(slug=project_slug)
logging.info("Got the project!")
logger.info("Got the project!")
return res
except DoesNotExist:
return None
Expand Down Expand Up @@ -135,11 +137,11 @@ def create_resource(
content = fh.read()

tx_api.ResourceStringsAsyncUpload.upload(content, resource=resource)
logging.info(f"Resource created: {resource_slug or resource_name}")
logger.info(f"Resource created: {resource_slug or resource_name}")

else:
raise ValueError(
f"Not project could be found wiht the slug '{project_slug}'. Please create a project first."
f"Not project could be found with the slug '{project_slug}'. Please create a project first."
)

@ensure_login
Expand All @@ -155,7 +157,7 @@ def update_source_translation(
"Unable to fetch resource for this organization; define an 'organization slug' first."
)

logging.info(
logger.info(
f"Updating source translation for resource {resource_slug} from file {path_to_file} (project: {project_slug})."
)

Expand All @@ -166,7 +168,7 @@ def update_source_translation(
content = fh.read()

tx_api.ResourceStringsAsyncUpload.upload(content, resource=resource)
logging.info(f"Source updated for resource: {resource_slug}")
logger.info(f"Source updated for resource: {resource_slug}")
return

raise ValueError(
Expand Down Expand Up @@ -208,7 +210,7 @@ def get_translation(
with open(path_to_output_file, "w") as fh:
fh.write(translated_content)

logging.info(
logger.info(
f"Translations downloaded and written to file (resource: {resource_slug})"
)
return str(path_to_output_file)
Expand Down Expand Up @@ -248,7 +250,7 @@ def list_languages(self, project_slug: str, resource_slug: str) -> list[str]:
code = str(tr).rsplit("_", 1)[-1][:-1]
language_codes.append(code)

logging.info(f"Obtained these languages: {language_codes}")
logger.info(f"Obtained these languages: {language_codes}")
return language_codes

raise ValueError(
Expand Down Expand Up @@ -276,7 +278,7 @@ def create_language(
if coordinators:
project.add("coordinators", coordinators)

logging.info(
logger.info(
f"Created language resource for {language_code} and added these coordinators: {coordinators}"
)

Expand All @@ -299,7 +301,7 @@ def ping(self) -> bool:
Exposing this just for the sake of satisfying qgis-plugin-cli's expectations
There is no need to ping the server on the current implementation, as connection is handled by the SDK
"""
logging.info("'ping' is deprecated!")
logger.info("'ping' is deprecated!")
return True

@ensure_login
Expand Down Expand Up @@ -331,7 +333,7 @@ def pull(
args=args,
)

logging.info(f"Pulled {args} for {len(res)} results).")
logger.info(f"Pulled {args} for {len(res)} results).")

@ensure_login
def push(
Expand All @@ -345,15 +347,15 @@ def push(

resource_zipped_with_path = list(zip(resource_slugs, path_to_files))
resources = self.list_resources(project_slug)
logging.info(
logger.info(
f"Found {len(resources)} resource(s) for {project_slug}. Checking for missing resources and creating where necessary."
)
created_when_missing_resource = []

for slug, path in resource_zipped_with_path:
logging.info(f"Slug: {slug}. Resources: {resources}.")
logger.info(f"Slug: {slug}. Resources: {resources}.")
if not slug in resources:
logging.info(
logger.info(
f"{project_slug} is missing {slug}. Creating it from {path}."
)
self.create_resource(
Expand All @@ -372,7 +374,7 @@ def push(
args=args,
)

logging.info(f"Pushed {args} for {len(res)} results.")
logger.info(f"Pushed {args} for {len(res)} results.")


class Transifex:
Expand All @@ -389,7 +391,7 @@ def __new__(cls, *, defer_login: bool = False, **kwargs) -> Optional["Client"]:
if kwargs:
config = ApiConfig(**kwargs)
else:
logging.info(
logger.info(
f"As you called 'Transifex' without argument, we'll try defining your project from environment variables."
)
config = ApiConfig.from_env()
Expand All @@ -399,4 +401,4 @@ def __new__(cls, *, defer_login: bool = False, **kwargs) -> Optional["Client"]:
except ValueError as error:
available = list(ApiConfig._fields)
msg = f"Unable to define a proper config. API initialization uses the following fields, with only 'project_slug' optional: {available}"
logging.error(f"{msg}:\n{error}")
logger.error(f"{msg}:\n{error}")
1 change: 1 addition & 0 deletions pytransifex/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from pytransifex.api import Transifex
from pytransifex.config import CliSettings

logger = logging.getLogger(__name__)
client = Transifex(defer_login=True)
assert client

Expand Down
3 changes: 2 additions & 1 deletion tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import logging
import sys
from pathlib import Path

import toml

logging.basicConfig(level=logging.INFO)
logging.basicConfig(stream=sys.stdout, level=logging.INFO)

private = Path.cwd().joinpath("./tests/data/test_config.toml")
test_config = toml.load(private)
Expand Down
14 changes: 8 additions & 6 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from pytransifex.interfaces import Tx
from tests import logging, test_config_public

logger = logging.getLogger(__name__)


class TestNewApi(unittest.TestCase):
@classmethod
Expand All @@ -29,10 +31,10 @@ def setUpClass(cls):
f"Unable to complete test with broken tests inputs. Found missing: {missing}"
)

logging.info("Deleting test project if it already exists")
logger.info("Deleting test project if it already exists")
cls.tx.delete_project(project_slug=cls.project_slug)

logging.info("Creating a brand new project")
logger.info("Creating a brand new project")
cls.tx.create_project(
project_name=cls.project_name, project_slug=cls.project_slug, private=True
)
Expand Down Expand Up @@ -60,7 +62,7 @@ def test3_create_resource(self):

def test4_list_resources(self):
resources = self.tx.list_resources(project_slug=self.project_slug)
logging.info(f"Resources found: {resources}")
logger.info(f"Resources found: {resources}")
assert resources

def test5_update_source_translation(self):
Expand All @@ -78,7 +80,7 @@ def test7_list_languages(self):
languages = self.tx.list_languages(
project_slug=self.project_slug, resource_slug=self.resource_slug
)
logging.info(f"Languages found: {languages}")
logger.info(f"Languages found: {languages}")
assert languages

def test8_get_translation(self):
Expand All @@ -101,7 +103,7 @@ def test8_get_translation(self):
with open(path_to_output_file, "r") as fh:
f2 = fh.readlines()
res = list(diff.compare(f1, f2))
logging.warning(f"Notice that the two files were found to differ:")
logger.warning(f"Notice that the two files were found to differ:")
stdout.writelines(res)

def test9_project_exists(self):
Expand All @@ -114,7 +116,7 @@ def test10_ping(self):

def test11_stats(self):
stats = self.tx.get_project_stats(project_slug=self.project_slug)
logging.info(str(stats))
logger.info(str(stats))
assert stats

def test12_stats(self):
Expand Down
10 changes: 6 additions & 4 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
from pytransifex.cli import cli
from tests import logging, test_config_public

logger = logging.getLogger(__name__)


class TestCli(unittest.TestCase):
@classmethod
Expand All @@ -34,10 +36,10 @@ def setUpClass(cls):
)

if project := cls.tx.get_project(project_slug=cls.project_slug):
logging.info("Found old project, removing.")
logger.info("Found old project, removing.")
project.delete()

logging.info("Creating a brand new project")
logger.info("Creating a brand new project")
cls.tx.create_project(
project_name=cls.project_name, project_slug=cls.project_slug, private=True
)
Expand All @@ -60,13 +62,13 @@ def test1_init(self):
def test2_push(self):
result = self.runner.invoke(cli, ["push", "-in", str(self.path_to_input_dir)])
passed = result.exit_code == 0
logging.info(result.output)
logger.info(result.output)
assert passed

def test3_pull(self):
result = self.runner.invoke(cli, ["pull", "-l", "fr_CH,en_GB"])
passed = result.exit_code == 0
logging.info(result.output)
logger.info(result.output)
assert passed


Expand Down
6 changes: 4 additions & 2 deletions tests/test_public_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from pytransifex.api import Transifex
from tests import logging, test_config_public

logger = logging.getLogger(__name__)


class TestCli(unittest.TestCase):
@classmethod
Expand Down Expand Up @@ -32,10 +34,10 @@ def setUpClass(cls):
)

if project := cls.tx.get_project(project_slug=cls.project_slug):
logging.info("Found old project, removing.")
logger.info("Found old project, removing.")
project.delete()

logging.info("Creating a brand new project")
logger.info("Creating a brand new project")
cls.tx.create_project(
project_name=cls.project_name,
project_slug=cls.project_slug,
Expand Down

0 comments on commit 2b4d173

Please sign in to comment.