Skip to content

Commit

Permalink
Merge pull request #116 from joe733/workshop
Browse files Browse the repository at this point in the history
fix: adds lang count option properly
  • Loading branch information
yozachar authored Feb 8, 2023
2 parents 6e66f34 + b2db3c3 commit 413150b
Show file tree
Hide file tree
Showing 6 changed files with 473 additions and 362 deletions.
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,14 @@

</center>

# Dev Metrics in Readme [![UnitTests](https://github.com/athul/waka-readme/actions/workflows/testing.yml/badge.svg)](https://github.com/athul/waka-readme/actions/workflows/testing.yml)

<center>
# Dev Metrics in Readme [![Unit Tests](https://github.com/athul/waka-readme/actions/workflows/testing.yml/badge.svg?branch=master)](https://github.com/athul/waka-readme/actions/workflows/testing.yml) ![Python Version](https://img.shields.io/badge/python-v3.11-blue)

[WakaTime](https://wakatime.com) weekly metrics on your profile readme.

![Project Preview](https://user-images.githubusercontent.com/8397274/87243943-e6b45c00-c457-11ea-94c9-2aa0bf241be8.png)

:speech_balloon: **Forum** | [GitHub discussions][gh_discuss]

</center>

## New to WakaTime?

> Nope? Skip to [prep work](#prep-work).
Expand All @@ -32,15 +28,17 @@ Alternatively, you can also fetch data from WakaTime compatible services like [W

## Prep Work

A GitHub repository and a README file is required. We'll be making use of readme in the [profile repository][profile_readme]\*.
A GitHub repository and a `README.md` file is required. We'll be making use of readme in the [profile repository][profile_readme]\*.

- Save the README file after copy-pasting the following special comments. Your dev-metics will show up in between. `waka` here can be replaced by any string as long as you set the `SECTION_NAME` environment variable [as per the Tweaks section](tweaks).
- Save the `README.md` file after copy-pasting the following special comments. Your dev-metics will show up in between.

```md
<!--START_SECTION:waka-->
<!--END_SECTION:waka-->
```

"`waka`" can be replaced by any alphanumeric string with the `SECTION_NAME` environment variable. See the [#tweaks](#tweaks) section for more.

- Navigate to your repo's `Settings > Secrets` and add a new secret _named_ `WAKATIME_API_KEY` with your API key as it's _value_.

> Or use the url <https://github.com/USERNAME/USERNAME/settings/secrets/actions/new> by replacing the `USERNAME` with your own username.
Expand Down Expand Up @@ -90,6 +88,7 @@ There are many flags that you can tweak to suit your taste!
| `SHOW_TIME` | `true` | `false`, `true` | Displays the amount of time spent for each language |
| `SHOW_TOTAL` | `false` | `false`, `true` | Show total coding time |
| `SHOW_MASKED_TIME` | `false` | `false`, `true` | Adds total coding time including unclassified languages (overrides: `SHOW_TOTAL`) |
| `LANG_COUNT` | `5` | Any reasonable number | Number of languages to be displayed |

# Example

Expand Down Expand Up @@ -117,6 +116,7 @@ jobs:
TIME_RANGE: all_time
SHOW_TIME: true
SHOW_MASKED_TIME: true
LANG_COUNT: 10
```
**`README.md`**
Expand Down
5 changes: 5 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ inputs:
default: "last_7_days"
required: false

LANG_COUNT:
description: "Maximum number of languages to be shown"
default: "5"
required: false

SHOW_TIME:
description: "Displays the amount of time spent for each language"
default: "true"
Expand Down
51 changes: 29 additions & 22 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ class WakaInput:
show_time: str | bool = os.getenv('INPUT_SHOW_TIME') or False
show_total_time: str | bool = os.getenv('INPUT_SHOW_TOTAL') or False
show_masked_time: str | bool = os.getenv('INPUT_SHOW_MASKED_TIME') or False
language_count: str | bool = os.getenv('INPUT_LANGUAGE_COUNT') or "5"
language_count: str | int = os.getenv('INPUT_LANG_COUNT') or 5

def validate_input(self) -> bool:
"""
Expand All @@ -178,7 +178,7 @@ def validate_input(self) -> bool:
self.show_time = strtobool(self.show_time)
self.show_total_time = strtobool(self.show_total_time)
self.show_masked_time = strtobool(self.show_masked_time)
except ValueError as err:
except (ValueError, AttributeError) as err:
logger.error(err)
return False

Expand All @@ -202,6 +202,11 @@ def validate_input(self) -> bool:
logger.debug('Using default time range: last_7_days')
self.time_range = 'last_7_days'

if not str(self.language_count).isnumeric():
logger.warning('Invalid language count')
logger.debug('Using default language count: 5')
self.language_count = 5

logger.debug('Input validation complete\n')
return True

Expand Down Expand Up @@ -249,26 +254,21 @@ def make_graph(block_style: str, percent: float, gr_len: int, lg_nm: str = '', /
graph_bar += block_style[remainder_block] if remainder_block > 0 else ''
graph_bar += block_style[0] * (gr_len - len(graph_bar))

logger.debug(f'{lg_nm or "..."} graph generated')
logger.debug(f'"{lg_nm or "..."}" graph generated')
return graph_bar


def prep_content(stats: dict[Any, Any], language_count: str = 5, /) -> str:
def prep_content(stats: dict[str, Any], language_count: int = 5, /) -> str:
"""
WakaReadme Prepare Markdown
---------------------------
Prepared markdown content from the fetched statistics
```
"""
logger.debug('Making contents')
contents = ''

# Check if any data exists
if not (lang_info := stats.get('languages')):
logger.debug('The data seems to be empty, please wait for a day')
contents += 'No activity tracked'
return contents

# make title
if wk_i.show_title:
contents += make_title(stats.get('start'), stats.get('end')) + '\n\n'
Expand All @@ -284,19 +284,26 @@ def prep_content(stats: dict[Any, Any], language_count: str = 5, /) -> str:
):
contents += f'Total Time: {total_time}\n\n'

# make content
logger.debug('Making contents')
lang_info: list[dict[str, int | float | str]] | None = []

# Check if any language data exists
if not (lang_info := stats.get('languages')):
logger.debug('The API data seems to be empty, please wait for a day')
contents += 'No activity tracked'
return contents

# make lang content
pad_len = len(
# comment if it feels way computationally expensive
max((l.get('name') for l in lang_info), key=len)
max((str(lng['name']) for lng in lang_info), key=len)
# and then don't for get to set pad_len to say 13 :)
)
for idx, lang in enumerate(lang_info):
lang_name = lang.get('name')
lang_name = str(lang['name'])
# >>> add languages to filter here <<<
# if lang_name in {...}: continue
lang_time = lang.get('text') if wk_i.show_time else ''
lang_ratio = lang.get('percent')
lang_time = str(lang['text']) if wk_i.show_time else ''
lang_ratio = float(lang['percent'])
lang_bar = make_graph(
wk_i.block_style, lang_ratio, wk_i.graph_length, lang_name
)
Expand All @@ -305,22 +312,22 @@ def prep_content(stats: dict[Any, Any], language_count: str = 5, /) -> str:
f'{lang_time: <16}{lang_bar} ' +
f'{lang_ratio:.2f}'.zfill(5) + ' %\n'
)
if idx >= int(language_count) or lang_name == 'Other':
if idx >= language_count or lang_name == 'Other':
break

logger.debug('Contents were made\n')
return contents.rstrip('\n')


def fetch_stats() -> dict[Any, Any] | None:
def fetch_stats() -> dict[str, Any] | None:
"""
WakaReadme Fetch Stats
----------------------
Returns statistics as JSON string
"""
attempts = 4
statistic: dict[str, dict[Any, Any]] = {}
statistic: dict[str, dict[str, Any]] = {}
encoded_key = str(
b64encode(bytes(str(wk_i.waka_key), 'utf-8')), 'utf-8'
)
Expand All @@ -341,7 +348,7 @@ def fetch_stats() -> dict[Any, Any] | None:
timeout=30 * (5 - attempts)
)).status_code != 200:
resp_message += f' • {conn_info}' if (
conn_info := resp.json().get("message")
conn_info := resp.json().get('message')
) else ''
logger.debug(
f'API response #{5 - attempts}: {resp.status_code}{resp.reason}{resp_message}'
Expand Down Expand Up @@ -374,8 +381,8 @@ def churn(old_readme: str, /) -> str | None:
sys.exit(1)
# processing content
try:
generated_content = prep_content(waka_stats, wk_i.language_count)
except AttributeError as err:
generated_content = prep_content(waka_stats, int(wk_i.language_count))
except (AttributeError, KeyError, ValueError) as err:
logger.error(f'Unable to read API data | {err}\n')
sys.exit(1)
print(generated_content, '\n', sep='')
Expand Down
Loading

0 comments on commit 413150b

Please sign in to comment.