Skip to content

Commit 2e1f02d

Browse files
committed
refactor: simplify code formatting and improve readability in multiple files
1 parent 5203e9a commit 2e1f02d

12 files changed

+99
-314
lines changed

.pre-commit-config.yaml

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,19 @@ repos:
1313
- id: check-yaml
1414
- id: end-of-file-fixer
1515
- id: trailing-whitespace
16-
- repo: https://github.com/PyCQA/flake8
17-
rev: 6.0.0
16+
- repo: local
1817
hooks:
1918
- id: flake8
20-
args: [--max-line-length=160]
21-
exclude: venv|assets
22-
- repo: https://github.com/psf/black
23-
rev: 25.1.0
19+
name: flake8
20+
entry: pipenv run flake8 --max-line-length=160 --exclude venv,assets .
21+
language: system
22+
pass_filenames: false
23+
always_run: true
24+
- repo: local
2425
hooks:
2526
- id: black
26-
args: [--line-length=160, --diff]
27-
exclude: "/venv/|/assets/"
27+
name: black
28+
entry: pipenv run black --line-length=160 --exclude='/venv/|/assets/' .
29+
language: system
30+
pass_filenames: false
31+
always_run: true

sources/graphics_chart_drawer.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,7 @@ async def create_loc_graph(yearly_data: Dict, save_path: str):
4545
for lang in langs:
4646
if lang not in languages_all_loc:
4747
languages_all_loc[lang] = zeros((years, 4, 2), dtype=int)
48-
languages_all_loc[lang][i][q - 1] = array(
49-
[yearly_data[y][q][lang]["add"], yearly_data[y][q][lang]["del"]]
50-
)
48+
languages_all_loc[lang][i][q - 1] = array([yearly_data[y][q][lang]["add"], yearly_data[y][q][lang]["del"]])
5149

5250
fig = plt.figure()
5351
ax = fig.add_axes([0, 0, 1.5, 1])

sources/graphics_chart_drawer_test.py

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,7 @@ def sample_colors():
8585
async def test_create_loc_graph_success(sample_yearly_data, sample_colors, tmp_path):
8686
test_save_path = str(tmp_path / "test_graph.png")
8787

88-
with patch(
89-
"manager_download.DownloadManager.get_remote_yaml", new_callable=AsyncMock
90-
) as mock_get_yaml:
88+
with patch("manager_download.DownloadManager.get_remote_yaml", new_callable=AsyncMock) as mock_get_yaml:
9189
mock_get_yaml.return_value = sample_colors
9290

9391
await create_loc_graph(sample_yearly_data, test_save_path)
@@ -100,9 +98,7 @@ async def test_create_loc_graph_success(sample_yearly_data, sample_colors, tmp_p
10098
async def test_create_loc_graph_no_colors(sample_yearly_data, tmp_path):
10199
test_save_path = str(tmp_path / "test_graph_no_colors.png")
102100

103-
with patch(
104-
"manager_download.DownloadManager.get_remote_yaml", new_callable=AsyncMock
105-
) as mock_get_yaml:
101+
with patch("manager_download.DownloadManager.get_remote_yaml", new_callable=AsyncMock) as mock_get_yaml:
106102
mock_get_yaml.return_value = None
107103

108104
await create_loc_graph(sample_yearly_data, test_save_path)
@@ -116,9 +112,7 @@ async def test_create_loc_graph_empty_data(tmp_path):
116112
test_save_path = str(tmp_path / "test_graph_empty.png")
117113
empty_data = {}
118114

119-
with patch(
120-
"manager_download.DownloadManager.get_remote_yaml", new_callable=AsyncMock
121-
) as mock_get_yaml:
115+
with patch("manager_download.DownloadManager.get_remote_yaml", new_callable=AsyncMock) as mock_get_yaml:
122116
mock_get_yaml.return_value = {}
123117

124118
await create_loc_graph(empty_data, test_save_path)
@@ -139,9 +133,7 @@ async def test_create_loc_graph_single_language(tmp_path):
139133
}
140134
}
141135

142-
with patch(
143-
"manager_download.DownloadManager.get_remote_yaml", new_callable=AsyncMock
144-
) as mock_get_yaml:
136+
with patch("manager_download.DownloadManager.get_remote_yaml", new_callable=AsyncMock) as mock_get_yaml:
145137
mock_get_yaml.return_value = {"Python": {"color": "blue"}}
146138

147139
await create_loc_graph(single_lang_data, test_save_path)
@@ -151,9 +143,7 @@ async def test_create_loc_graph_single_language(tmp_path):
151143

152144

153145
@pytest.mark.asyncio
154-
async def test_create_loc_graph_max_languages(
155-
sample_yearly_data, sample_colors, tmp_path
156-
):
146+
async def test_create_loc_graph_max_languages(sample_yearly_data, sample_colors, tmp_path):
157147
test_save_path = str(tmp_path / "test_graph_max.png")
158148

159149
# Add more than MAX_LANGUAGES languages to test the limit
@@ -165,9 +155,7 @@ async def test_create_loc_graph_max_languages(
165155
}
166156
)
167157

168-
with patch(
169-
"manager_download.DownloadManager.get_remote_yaml", new_callable=AsyncMock
170-
) as mock_get_yaml:
158+
with patch("manager_download.DownloadManager.get_remote_yaml", new_callable=AsyncMock) as mock_get_yaml:
171159
mock_get_yaml.return_value = sample_colors
172160

173161
await create_loc_graph(sample_yearly_data, test_save_path)

sources/graphics_list_formatter.py

Lines changed: 19 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -90,38 +90,17 @@ def make_list(
9090
:returns: The string representation of the list.
9191
"""
9292
if data is not None:
93-
names = (
94-
[value for item in data for key, value in item.items() if key == "name"]
95-
if names is None
96-
else names
97-
)
98-
texts = (
99-
[value for item in data for key, value in item.items() if key == "text"]
100-
if texts is None
101-
else texts
102-
)
103-
percents = (
104-
[value for item in data for key, value in item.items() if key == "percent"]
105-
if percents is None
106-
else percents
107-
)
93+
names = [value for item in data for key, value in item.items() if key == "name"] if names is None else names
94+
texts = [value for item in data for key, value in item.items() if key == "text"] if texts is None else texts
95+
percents = [value for item in data for key, value in item.items() if key == "percent"] if percents is None else percents
10896

10997
data = list(zip(names, texts, percents))
110-
top_data = (
111-
sorted(data[:top_num], key=lambda record: record[2], reverse=True)
112-
if sort
113-
else data[:top_num]
114-
)
115-
data_list = [
116-
f"{n[:25]}{' ' * (25 - len(n))}{t}{' ' * (20 - len(t))}{make_graph(p)} {p:05.2f} % "
117-
for n, t, p in top_data
118-
]
98+
top_data = sorted(data[:top_num], key=lambda record: record[2], reverse=True) if sort else data[:top_num]
99+
data_list = [f"{n[:25]}{' ' * (25 - len(n))}{t}{' ' * (20 - len(t))}{make_graph(p)} {p:05.2f} % " for n, t, p in top_data]
119100
return "\n".join(data_list)
120101

121102

122-
async def make_commit_day_time_list(
123-
time_zone: str, repositories: Dict, commit_dates: Dict
124-
) -> str:
103+
async def make_commit_day_time_list(time_zone: str, repositories: Dict, commit_dates: Dict) -> str:
125104
"""
126105
Calculate commit-related info, how many commits were made, and at what time of day and day of week.
127106
@@ -132,19 +111,13 @@ async def make_commit_day_time_list(
132111
"""
133112
stats = str()
134113
day_times = [0] * 4 # 0 - 6, 6 - 12, 12 - 18, 18 - 24
135-
week_days = [
136-
0
137-
] * 7 # Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
114+
week_days = [0] * 7 # Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
138115

139116
for repository in repositories:
140117
if repository["name"] not in commit_dates.keys():
141118
continue
142119

143-
for committed_date in [
144-
commit_date
145-
for branch in commit_dates[repository["name"]].values()
146-
for commit_date in branch.values()
147-
]:
120+
for committed_date in [commit_date for branch in commit_dates[repository["name"]].values() for commit_date in branch.values()]:
148121
local_date = datetime.strptime(committed_date, "%Y-%m-%dT%H:%M:%SZ")
149122
date = local_date.replace(tzinfo=utc).astimezone(timezone(time_zone))
150123

@@ -156,33 +129,17 @@ async def make_commit_day_time_list(
156129
day_times = day_times[1:] + day_times[:1]
157130

158131
if EM.SHOW_COMMIT:
159-
dt_names = [
160-
f"{DAY_TIME_EMOJI[i]} {FM.t(DAY_TIME_NAMES[i])}"
161-
for i in range(len(day_times))
162-
]
132+
dt_names = [f"{DAY_TIME_EMOJI[i]} {FM.t(DAY_TIME_NAMES[i])}" for i in range(len(day_times))]
163133
dt_texts = [f"{day_time} commits" for day_time in day_times]
164-
dt_percents = [
165-
0 if sum_day == 0 else round((day_time / sum_day) * 100, 2)
166-
for day_time in day_times
167-
]
168-
title = (
169-
FM.t("I am an Early")
170-
if sum(day_times[0:2]) >= sum(day_times[2:4])
171-
else FM.t("I am a Night")
172-
)
134+
dt_percents = [0 if sum_day == 0 else round((day_time / sum_day) * 100, 2) for day_time in day_times]
135+
title = FM.t("I am an Early") if sum(day_times[0:2]) >= sum(day_times[2:4]) else FM.t("I am a Night")
173136
stats += f"**{title}** \n\n```text\n{make_list(names=dt_names, texts=dt_texts, percents=dt_percents, top_num=7, sort=False)}\n```\n"
174137

175138
if EM.SHOW_DAYS_OF_WEEK:
176139
wd_names = [FM.t(week_day) for week_day in WEEK_DAY_NAMES]
177140
wd_texts = [f"{week_day} commits" for week_day in week_days]
178-
wd_percents = [
179-
0 if sum_week == 0 else round((week_day / sum_week) * 100, 2)
180-
for week_day in week_days
181-
]
182-
title = (
183-
FM.t("I am Most Productive on")
184-
% wd_names[wd_percents.index(max(wd_percents))]
185-
)
141+
wd_percents = [0 if sum_week == 0 else round((week_day / sum_week) * 100, 2) for week_day in week_days]
142+
title = FM.t("I am Most Productive on") % wd_names[wd_percents.index(max(wd_percents))]
186143
stats += f"📅 **{title}** \n\n```text\n{make_list(names=wd_names, texts=wd_texts, percents=wd_percents, top_num=7, sort=False)}\n```\n"
187144

188145
return stats
@@ -196,30 +153,16 @@ def make_language_per_repo_list(repositories: Dict) -> str:
196153
:returns: string representation of statistics.
197154
"""
198155
language_count = dict()
199-
repos_with_language = [
200-
repo for repo in repositories if repo["primaryLanguage"] is not None
201-
]
156+
repos_with_language = [repo for repo in repositories if repo["primaryLanguage"] is not None]
202157
for repo in repos_with_language:
203158
language = repo["primaryLanguage"]["name"]
204159
language_count[language] = language_count.get(language, {"count": 0})
205160
language_count[language]["count"] += 1
206161

207162
names = list(language_count.keys())
208-
texts = [
209-
f"{language_count[lang]['count']} {'repo' if language_count[lang]['count'] == 1 else 'repos'}"
210-
for lang in names
211-
]
212-
percents = [
213-
round(language_count[lang]["count"] / len(repos_with_language) * 100, 2)
214-
for lang in names
215-
]
216-
217-
top_language = max(
218-
list(language_count.keys()), key=lambda x: language_count[x]["count"]
219-
)
220-
title = (
221-
f"**{FM.t('I Mostly Code in') % top_language}** \n\n"
222-
if len(repos_with_language) > 0
223-
else ""
224-
)
163+
texts = [f"{language_count[lang]['count']} {'repo' if language_count[lang]['count'] == 1 else 'repos'}" for lang in names]
164+
percents = [round(language_count[lang]["count"] / len(repos_with_language) * 100, 2) for lang in names]
165+
166+
top_language = max(list(language_count.keys()), key=lambda x: language_count[x]["count"])
167+
title = f"**{FM.t('I Mostly Code in') % top_language}** \n\n" if len(repos_with_language) > 0 else ""
225168
return f"{title}```text\n{make_list(names=names, texts=texts, percents=percents)}\n```\n\n"

sources/main.py

Lines changed: 14 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -42,19 +42,11 @@ async def get_waka_time_stats(repositories: Dict, commit_dates: Dict) -> str:
4242
if data is None:
4343
DBM.p("WakaTime data unavailable!")
4444
return stats
45-
if (
46-
EM.SHOW_COMMIT or EM.SHOW_DAYS_OF_WEEK
47-
): # if any on flag is turned on then we need to calculate the data and print accordingly
45+
if EM.SHOW_COMMIT or EM.SHOW_DAYS_OF_WEEK: # if any on flag is turned on then we need to calculate the data and print accordingly
4846
DBM.i("Adding user commit day time info...")
4947
stats += f"{await make_commit_day_time_list(data['data']['timezone'], repositories, commit_dates)}\n\n"
5048

51-
if (
52-
EM.SHOW_TIMEZONE
53-
or EM.SHOW_LANGUAGE
54-
or EM.SHOW_EDITORS
55-
or EM.SHOW_PROJECTS
56-
or EM.SHOW_OS
57-
):
49+
if EM.SHOW_TIMEZONE or EM.SHOW_LANGUAGE or EM.SHOW_EDITORS or EM.SHOW_PROJECTS or EM.SHOW_OS:
5850
no_activity = FM.t("No Activity Tracked This Week")
5951
stats += f"📊 **{FM.t('This Week I Spend My Time On')}** \n\n```text\n"
6052

@@ -65,38 +57,22 @@ async def get_waka_time_stats(repositories: Dict, commit_dates: Dict) -> str:
6557

6658
if EM.SHOW_LANGUAGE:
6759
DBM.i("Adding user top languages info...")
68-
lang_list = (
69-
no_activity
70-
if len(data["data"]["languages"]) == 0
71-
else make_list(data["data"]["languages"])
72-
)
60+
lang_list = no_activity if len(data["data"]["languages"]) == 0 else make_list(data["data"]["languages"])
7361
stats += f"💬 {FM.t('Languages')}: \n{lang_list}\n\n"
7462

7563
if EM.SHOW_EDITORS:
7664
DBM.i("Adding user editors info...")
77-
edit_list = (
78-
no_activity
79-
if len(data["data"]["editors"]) == 0
80-
else make_list(data["data"]["editors"])
81-
)
65+
edit_list = no_activity if len(data["data"]["editors"]) == 0 else make_list(data["data"]["editors"])
8266
stats += f"🔥 {FM.t('Editors')}: \n{edit_list}\n\n"
8367

8468
if EM.SHOW_PROJECTS:
8569
DBM.i("Adding user projects info...")
86-
project_list = (
87-
no_activity
88-
if len(data["data"]["projects"]) == 0
89-
else make_list(data["data"]["projects"])
90-
)
70+
project_list = no_activity if len(data["data"]["projects"]) == 0 else make_list(data["data"]["projects"])
9171
stats += f"🐱‍💻 {FM.t('Projects')}: \n{project_list}\n\n"
9272

9373
if EM.SHOW_OS:
9474
DBM.i("Adding user operating systems info...")
95-
os_list = (
96-
no_activity
97-
if len(data["data"]["operating_systems"]) == 0
98-
else make_list(data["data"]["operating_systems"])
99-
)
75+
os_list = no_activity if len(data["data"]["operating_systems"]) == 0 else make_list(data["data"]["operating_systems"])
10076
stats += f"💻 {FM.t('operating system')}: \n{os_list}\n\n"
10177

10278
stats = f"{stats[:-1]}```\n\n"
@@ -152,9 +128,7 @@ async def get_short_github_info() -> str:
152128
stats += f"> 📜 {FM.t('public repository') % public_repo} \n > \n"
153129

154130
DBM.i("Adding private repositories info...")
155-
private_repo = (
156-
GHM.USER.owned_private_repos if GHM.USER.owned_private_repos is not None else 0
157-
)
131+
private_repo = GHM.USER.owned_private_repos if GHM.USER.owned_private_repos is not None else 0
158132
if public_repo != 1:
159133
stats += f"> 🔑 {FM.t('private repositories') % private_repo} \n > \n"
160134
else:
@@ -171,21 +145,13 @@ async def collect_user_repositories() -> Dict:
171145
:returns: Complete list of user repositories.
172146
"""
173147
DBM.i("Getting user repositories list...")
174-
repositories = await DM.get_remote_graphql(
175-
"user_repository_list", username=GHM.USER.login, id=GHM.USER.node_id
176-
)
148+
repositories = await DM.get_remote_graphql("user_repository_list", username=GHM.USER.login, id=GHM.USER.node_id)
177149
repo_names = [repo["name"] for repo in repositories]
178150
DBM.g("\tUser repository list collected!")
179151

180-
contributed = await DM.get_remote_graphql(
181-
"repos_contributed_to", username=GHM.USER.login
182-
)
152+
contributed = await DM.get_remote_graphql("repos_contributed_to", username=GHM.USER.login)
183153

184-
contributed_nodes = [
185-
repo
186-
for repo in contributed
187-
if repo is not None and repo["name"] not in repo_names and not repo["isFork"]
188-
]
154+
contributed_nodes = [repo for repo in contributed if repo is not None and repo["name"] not in repo_names and not repo["isFork"]]
189155
DBM.g("\tUser contributed to repository list collected!")
190156

191157
return repositories + contributed_nodes
@@ -203,12 +169,7 @@ async def get_stats() -> str:
203169
stats = str()
204170
repositories = await collect_user_repositories()
205171

206-
if (
207-
EM.SHOW_LINES_OF_CODE
208-
or EM.SHOW_LOC_CHART
209-
or EM.SHOW_COMMIT
210-
or EM.SHOW_DAYS_OF_WEEK
211-
): # calculate commit data if any one of these is enabled
172+
if EM.SHOW_LINES_OF_CODE or EM.SHOW_LOC_CHART or EM.SHOW_COMMIT or EM.SHOW_DAYS_OF_WEEK: # calculate commit data if any one of these is enabled
212173
yearly_data, commit_data = await calculate_commit_data(repositories)
213174
else:
214175
yearly_data, commit_data = dict(), dict()
@@ -229,14 +190,7 @@ async def get_stats() -> str:
229190

230191
if EM.SHOW_LINES_OF_CODE:
231192
DBM.i("Adding lines of code info...")
232-
total_loc = sum(
233-
[
234-
yearly_data[y][q][d]["add"]
235-
for y in yearly_data.keys()
236-
for q in yearly_data[y].keys()
237-
for d in yearly_data[y][q].keys()
238-
]
239-
)
193+
total_loc = sum([yearly_data[y][q][d]["add"] for y in yearly_data.keys() for q in yearly_data[y].keys() for d in yearly_data[y][q].keys()])
240194
data = f"{intword(total_loc)} {FM.t('Lines of code')}"
241195
stats += f"![Lines of code](https://img.shields.io/badge/{quote(FM.t('From Hello World I have written'))}-{quote(data)}-blue)\n\n"
242196

@@ -251,15 +205,11 @@ async def get_stats() -> str:
251205

252206
if EM.SHOW_LOC_CHART:
253207
await create_loc_graph(yearly_data, GRAPH_PATH)
254-
stats += (
255-
f"**{FM.t('Timeline')}**\n\n{GHM.update_chart('Lines of Code', GRAPH_PATH)}"
256-
)
208+
stats += f"**{FM.t('Timeline')}**\n\n{GHM.update_chart('Lines of Code', GRAPH_PATH)}"
257209

258210
if EM.SHOW_UPDATED_DATE:
259211
DBM.i("Adding last updated time...")
260-
stats += (
261-
f"\n Last Updated on {datetime.now().strftime(EM.UPDATED_DATE_FORMAT)} UTC"
262-
)
212+
stats += f"\n Last Updated on {datetime.now().strftime(EM.UPDATED_DATE_FORMAT)} UTC"
263213

264214
DBM.g("Stats for README collected!")
265215
return stats

0 commit comments

Comments
 (0)