Skip to content

Commit f3b7e8a

Browse files
author
root
committed
PEP8 and pylint improvements. Tested and working with Python 3.9, 3.11. Ongoing testing for others versions. Finally I have a dev pipeline and server to create tests. Enjoy!
1 parent 1d4400e commit f3b7e8a

13 files changed

+339
-196
lines changed

cli.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,25 @@
1-
# uglypy/cli.py
1+
"""
2+
uglypy - Command-line interface for running various scripts.
3+
"""
4+
25
import subprocess
36
import os
47
import argparse
5-
from logging_setup import setup_logging, get_logger
8+
from logging_setup import setup_logging
69

710
# Setup logging
811
logger = setup_logging()
912

1013
def run_command(command):
1114
"""Run a command with subprocess and log the outcome."""
12-
logger.info(f"Running command: {' '.join(command)}")
15+
logger.info("Running command: %s", ' '.join(command))
1316
try:
1417
subprocess.run(command, check=True)
15-
logger.info(f"Command {' '.join(command)} executed successfully.")
18+
logger.info("Command %s executed successfully.", ' '.join(command))
1619
except subprocess.CalledProcessError as e:
17-
logger.error(f"Command {' '.join(command)} failed: {e}")
18-
except Exception as e:
19-
logger.error(f"An unexpected error occurred: {e}")
20+
logger.error("Command %s failed: %s", ' '.join(command), e)
21+
except Exception as e: # pylint: disable=broad-except
22+
logger.error("An unexpected error occurred: %s", e)
2023

2124
def run_streamlit(extra_args):
2225
"""Run the Streamlit application."""
@@ -28,7 +31,7 @@ def run_script(script_name, extra_args):
2831
script_path = os.path.join(os.getcwd(), script_name)
2932

3033
if not os.path.isfile(script_path):
31-
logger.error(f"Error: {script_name} not found.")
34+
logger.error("Error: %s not found.", script_name)
3235
return
3336

3437
command = ["python", script_path] + extra_args

config.py

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,34 @@
1-
import yaml
1+
"""
2+
Configuration Management for UglyFeed
3+
"""
4+
25
from pathlib import Path
6+
import yaml
37

4-
config_path = Path("config.yaml")
5-
feeds_path = Path("input/feeds.txt")
8+
CONFIG_PATH = Path("config.yaml")
9+
FEEDS_PATH = Path("input/feeds.txt")
610

711
def tuple_constructor(loader, node):
812
"""Constructor for !!python/tuple tag."""
913
return tuple(loader.construct_sequence(node))
1014

11-
# Add the constructor to PyYAML with SafeLoader replaced by the FullLoader to handle tuples
15+
# Add the constructor to PyYAML with FullLoader to handle tuples
1216
yaml.add_constructor('tag:yaml.org,2002:python/tuple', tuple_constructor, Loader=yaml.FullLoader)
1317

14-
def load_config(config_file=config_path):
18+
def load_config(config_file=CONFIG_PATH):
1519
"""Load the configuration from the specified YAML file."""
1620
if isinstance(config_file, str):
1721
config_file = Path(config_file)
1822

1923
try:
2024
if config_file.exists():
21-
with open(config_file, "r") as f:
25+
with open(config_file, "r", encoding='utf-8') as f:
2226
return yaml.load(f, Loader=yaml.FullLoader) # Use yaml.FullLoader to support custom constructors
23-
else:
24-
return {}
27+
return {}
2528
except yaml.YAMLError as e:
26-
raise Exception(f"Error loading YAML configuration: {e}")
29+
raise Exception(f"Error loading YAML configuration: {e}") from e
2730
except Exception as e:
28-
raise Exception(f"Failed to load configuration from {config_file}: {e}")
31+
raise Exception(f"Failed to load configuration from {config_file}: {e}") from e
2932

3033
def ensure_default_config(config_data):
3134
"""Ensure all required keys are in the config_data with default values."""
@@ -123,12 +126,12 @@ def recursive_update(d, u):
123126
def save_configuration(config_data, feeds):
124127
"""Save configuration and feeds to file."""
125128
try:
126-
with open(config_path, "w") as f:
129+
with open(CONFIG_PATH, "w", encoding='utf-8') as f:
127130
yaml.dump(config_data, f)
128-
with open(feeds_path, "w") as f:
131+
with open(FEEDS_PATH, "w", encoding='utf-8') as f:
129132
f.write(feeds)
130133
except Exception as e:
131-
raise Exception(f"Failed to save configuration: {e}")
134+
raise Exception(f"Failed to save configuration: {e}") from e
132135

133136
# Usage example
134137
if __name__ == "__main__":

deploy_xml.py

Lines changed: 36 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,26 @@
1+
"""
2+
This script uploads XML files to GitHub and GitLab repositories.
3+
"""
4+
15
import os
2-
import yaml
3-
import requests
46
import base64
57
import logging
8+
import requests
9+
import yaml
610

711
# Set up logging
812
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
913

10-
# Function to load configuration from YAML or environment variables
1114
def load_config(config_path='config.yaml'):
12-
logging.info(f"Loading configuration from {config_path} or environment variables...")
15+
"""
16+
Load configuration from YAML or environment variables.
17+
"""
18+
logging.info("Loading configuration from %s or environment variables...", config_path)
1319
if os.path.exists(config_path):
14-
with open(config_path, 'r') as file:
20+
with open(config_path, 'r', encoding='utf-8') as file:
1521
config = yaml.safe_load(file)
1622
else:
17-
logging.warning(f"Configuration file {config_path} not found. Falling back to environment variables.")
23+
logging.warning("Configuration file %s not found. Falling back to environment variables.", config_path)
1824
config = {}
1925

2026
config['github_token'] = config.get('github_token', os.getenv('GITHUB_TOKEN'))
@@ -26,8 +32,10 @@ def load_config(config_path='config.yaml'):
2632

2733
return config
2834

29-
# Function to upload file to GitHub
3035
def upload_to_github(file_path, config):
36+
"""
37+
Upload file to GitHub.
38+
"""
3139
logging.info("Uploading to GitHub...")
3240
repo_name = config['github_repo']
3341
token = config['github_token']
@@ -43,7 +51,7 @@ def upload_to_github(file_path, config):
4351
content = base64.b64encode(file.read()).decode('utf-8')
4452

4553
# Check if the file exists in the repository
46-
response = requests.get(url, headers=headers)
54+
response = requests.get(url, headers=headers, timeout=10)
4755
if response.status_code == 200:
4856
# File exists, retrieve its SHA
4957
sha = response.json()['sha']
@@ -54,7 +62,7 @@ def upload_to_github(file_path, config):
5462
'branch': 'main'
5563
}
5664
method = requests.put
57-
logging.info(f"File {file_name} exists in GitHub repo, updating it.")
65+
logging.info("File %s exists in GitHub repo, updating it.", file_name)
5866
elif response.status_code == 404:
5967
# File does not exist, create it
6068
data = {
@@ -63,22 +71,24 @@ def upload_to_github(file_path, config):
6371
'branch': 'main'
6472
}
6573
method = requests.put
66-
logging.info(f"File {file_name} does not exist in GitHub repo, creating it.")
74+
logging.info("File %s does not exist in GitHub repo, creating it.", file_name)
6775
else:
68-
logging.error(f"GitHub file check failed: {response.text}")
76+
logging.error("GitHub file check failed: %s", response.text)
6977
raise Exception(f"GitHub file check failed: {response.text}")
7078

7179
# Upload or update the file
72-
response = method(url, json=data, headers=headers)
80+
response = method(url, json=data, headers=headers, timeout=10)
7381
if response.status_code in (200, 201):
7482
download_url = response.json()['content']['download_url']
7583
return download_url
7684
else:
77-
logging.error(f"GitHub upload failed: {response.text}")
85+
logging.error("GitHub upload failed: %s", response.text)
7886
raise Exception(f"GitHub upload failed: {response.text}")
7987

80-
# Function to upload file to GitLab
8188
def upload_to_gitlab(file_path, config):
89+
"""
90+
Upload file to GitLab.
91+
"""
8292
logging.info("Uploading to GitLab...")
8393
repo_name = config['gitlab_repo']
8494
token = config['gitlab_token']
@@ -88,7 +98,7 @@ def upload_to_gitlab(file_path, config):
8898
file_name = os.path.basename(file_path)
8999
url = f'https://gitlab.com/api/v4/projects/{repo_name}/repository/files/{file_name}'
90100

91-
with open(file_path, 'r') as file:
101+
with open(file_path, 'r', encoding='utf-8') as file:
92102
content = file.read()
93103

94104
data = {
@@ -97,41 +107,43 @@ def upload_to_gitlab(file_path, config):
97107
'commit_message': 'Add uglyfeed.xml'
98108
}
99109

100-
response = requests.post(url, json=data, headers=headers)
110+
response = requests.post(url, json=data, headers=headers, timeout=10)
101111
if response.status_code == 201:
102112
download_url = f'https://gitlab.com/{repo_name}/-/raw/main/{file_name}'
103113
return download_url
104114
elif response.status_code == 400 and 'already exists' in response.text:
105115
# Update file if it already exists
106116
logging.info("File already exists on GitLab, attempting to update...")
107-
response = requests.put(url, json=data, headers=headers)
117+
response = requests.put(url, json=data, headers=headers, timeout=10)
108118
if response.status_code == 200:
109119
download_url = f'https://gitlab.com/{repo_name}/-/raw/main/{file_name}'
110120
return download_url
111121
else:
112-
logging.error(f"GitLab update failed: {response.text}")
122+
logging.error("GitLab update failed: %s", response.text)
113123
raise Exception(f"GitLab update failed: {response.text}")
114124
else:
115-
logging.error(f"GitLab upload failed: {response.text}")
125+
logging.error("GitLab upload failed: %s", response.text)
116126
raise Exception(f"GitLab upload failed: {response.text}")
117127

118-
# Main function to deploy XML file
119128
def deploy_xml(file_path, config):
129+
"""
130+
Deploy XML file to GitHub and GitLab based on the configuration.
131+
"""
120132
urls = {}
121133

122134
if config.get('enable_github', False):
123135
try:
124136
github_url = upload_to_github(file_path, config)
125137
urls['github'] = github_url
126138
except Exception as e:
127-
logging.error(f"GitHub upload error: {e}")
139+
logging.error("GitHub upload error: %s", e)
128140

129141
if config.get('enable_gitlab', False):
130142
try:
131143
gitlab_url = upload_to_gitlab(file_path, config)
132144
urls['gitlab'] = gitlab_url
133145
except Exception as e:
134-
logging.error(f"GitLab upload error: {e}")
146+
logging.error("GitLab upload error: %s", e)
135147

136148
return urls
137149

@@ -140,10 +152,10 @@ def deploy_xml(file_path, config):
140152
config = load_config()
141153

142154
# File to deploy
143-
xml_file_path = 'uglyfeeds/uglyfeed.xml'
155+
XML_FILE_PATH = 'uglyfeeds/uglyfeed.xml'
144156

145157
# Deploy the XML file
146-
urls = deploy_xml(xml_file_path, config)
158+
urls = deploy_xml(XML_FILE_PATH, config)
147159

148160
# Print the URLs
149161
if urls:

0 commit comments

Comments
 (0)