Add time range as a parameter (#75)

* Add time range as a parameter

* Update the format of time range title; validate the json from wakatime API

* Update README to introduce TIME_RANGE parameter

Authored by: @jameshwc
This commit is contained in:
jameshwc 2022-02-21 09:58:47 +08:00 committed by GitHub
parent 645f70e0c2
commit 1b31f85a36
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 45 additions and 19 deletions

View File

@ -135,7 +135,17 @@ Since this project is contained all within one file, `main.py`. You can simply a
## Extras ## Extras
1. If you want to add the week in the Header of your stats, you can add `SHOW_TITLE: true` (by default it will be `false`) in your workflow file like this 1. You can specify the time range in the parameter (default `last_7_days`):
```yml
- uses: athul/waka-readme@master
with:
WAKATIME_API_KEY: ${{ secrets.WAKATIME_API_KEY }}
TIME_RANGE: last_30_days
```
See [Wakatime API docs](https://wakatime.com/developers#stats) for more possible values.
2. If you want to add the week in the Header of your stats, you can add `SHOW_TITLE: true` (by default it will be `false`) in your workflow file like this
```yml ```yml
- uses: athul/waka-readme@master - uses: athul/waka-readme@master
@ -148,7 +158,7 @@ Since this project is contained all within one file, `main.py`. You can simply a
Here is an example output with `SHOW_TITLE` set to `true`. Here is an example output with `SHOW_TITLE` set to `true`.
```text ```text
Week: 11 July, 2020 - 17 July, 2020 From: 12 February, 2022 - To: 19 February, 2022
Python 8 hrs 52 mins ███████████████████░░░░░░ 75.87 % Python 8 hrs 52 mins ███████████████████░░░░░░ 75.87 %
Go 1 hr 15 mins ██░░░░░░░░░░░░░░░░░░░░░░░ 10.79 % Go 1 hr 15 mins ██░░░░░░░░░░░░░░░░░░░░░░░ 10.79 %
@ -157,7 +167,7 @@ Since this project is contained all within one file, `main.py`. You can simply a
YAML 7 mins ░░░░░░░░░░░░░░░░░░░░░░░░░ 01.07 % YAML 7 mins ░░░░░░░░░░░░░░░░░░░░░░░░░ 01.07 %
``` ```
2. You can specify a commit message to override the default _"Updated the Graph with new Metrics"_. Here is how you do it 3. You can specify a commit message to override the default _"Updated the Graph with new Metrics"_. Here is how you do it
```yml ```yml
- uses: athul/waka-readme@master - uses: athul/waka-readme@master
@ -169,7 +179,7 @@ Since this project is contained all within one file, `main.py`. You can simply a
If no commit message is specified in the `yml` file, it defaults to _"Updated the Graph with new Metrics"_ If no commit message is specified in the `yml` file, it defaults to _"Updated the Graph with new Metrics"_
3. You can change the block characters to match with the style of your readme. By default the one show in the graphs before is used. Here is how you do it 4. You can change the block characters to match with the style of your readme. By default the one show in the graphs before is used. Here is how you do it
```yml ```yml
- uses: athul/waka-readme@master - uses: athul/waka-readme@master
@ -188,7 +198,7 @@ Since this project is contained all within one file, `main.py`. You can simply a
YAML 7 mins ⣄⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀ 01.07 % YAML 7 mins ⣄⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀ 01.07 %
``` ```
4. As an alternative to official WakaTime, _waka-readme_ also integrates with WakaTime-compatible services like [Wakapi](https://wakapi.dev) and [Hakatime](https://github.com/mujx/hakatime). To use one of these, **adapt the API URL accordingly and use the respective service's API key** instead: 5. As an alternative to official WakaTime, _waka-readme_ also integrates with WakaTime-compatible services like [Wakapi](https://wakapi.dev) and [Hakatime](https://github.com/mujx/hakatime). To use one of these, **adapt the API URL accordingly and use the respective service's API key** instead:
```yml ```yml
- uses: athul/waka-readme@master - uses: athul/waka-readme@master
@ -197,7 +207,7 @@ Since this project is contained all within one file, `main.py`. You can simply a
API_BASE_URL: https://wakapi.dev/api API_BASE_URL: https://wakapi.dev/api
``` ```
5. If you do not like to share how much time you spent on each language, you can add `SHOW_TIME: false` (by default it will be `true`) in your workflow file like so: 6. If you do not like to share how much time you spent on each language, you can add `SHOW_TIME: false` (by default it will be `true`) in your workflow file like so:
```yml ```yml
- uses: athul/waka-readme@master - uses: athul/waka-readme@master
@ -209,7 +219,7 @@ Since this project is contained all within one file, `main.py`. You can simply a
Here is an example output with `SHOW_TIME` set to `false`. Here is an example output with `SHOW_TIME` set to `false`.
```text ```text
Week: 11 July, 2020 - 17 July, 2020 From: 12 February, 2022 - To: 19 February, 2022
PHP ████████████████████▒░░░░░░░░░░░░░░░░░░░░ 49.98 % PHP ████████████████████▒░░░░░░░░░░░░░░░░░░░░ 49.98 %
Twig ████▓░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 11.07 % Twig ████▓░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 11.07 %

View File

@ -42,6 +42,10 @@ inputs:
default: true default: true
required: false required: false
TIME_RANGE:
description: "Time range of the queried statistics"
default: "last_7_days"
SHOW_TOTAL: SHOW_TOTAL:
description: "Displays weekly [total] coding time" description: "Displays weekly [total] coding time"
default: false default: false

36
main.py
View File

@ -25,14 +25,15 @@ show_total = os.getenv("INPUT_SHOW_TOTAL")
commit_message = os.getenv("INPUT_COMMIT_MESSAGE") commit_message = os.getenv("INPUT_COMMIT_MESSAGE")
blocks = os.getenv("INPUT_BLOCKS") blocks = os.getenv("INPUT_BLOCKS")
show_time = os.getenv("INPUT_SHOW_TIME") show_time = os.getenv("INPUT_SHOW_TIME")
time_range = os.getenv("INPUT_TIME_RANGE")
def this_week() -> str: def title(start: str, end: str) -> str:
'''Returns a week streak''' '''Returns a title of time range'''
week_end = datetime.datetime.today() - datetime.timedelta(days=1) start_date = datetime.datetime.strptime(start, '%Y-%m-%dT%H:%M:%SZ')
week_start = week_end - datetime.timedelta(days=6) end_date = datetime.datetime.strptime(end, '%Y-%m-%dT%H:%M:%SZ')
print("Week header created") print("Title created")
return f"Week: {week_start.strftime('%d %B, %Y')} - {week_end.strftime('%d %B, %Y')}" return f"From: {start_date.strftime('%d %B, %Y')} - To: {end_date.strftime('%d %B, %Y')}\n\n"
def make_graph(percent: float, ip_blocks: str, length: int = GRAPH_LENGTH) -> str: def make_graph(percent: float, ip_blocks: str, length: int = GRAPH_LENGTH) -> str:
@ -49,19 +50,29 @@ def make_graph(percent: float, ip_blocks: str, length: int = GRAPH_LENGTH) -> st
return graph return graph
def get_stats() -> str: def get_stats(range: str = 'last_7_days') -> str:
'''Gets API data and returns markdown progress''' '''Gets API data and returns markdown progress'''
encoded_key: str = str(base64.b64encode(waka_key.encode('utf-8')), 'utf-8') encoded_key: str = str(base64.b64encode(waka_key.encode('utf-8')), 'utf-8')
data = requests.get( data = requests.get(
f"{api_base_url.rstrip('/')}/v1/users/current/stats/last_7_days", f"{api_base_url.rstrip('/')}/v1/users/current/stats/{range}",
headers={ headers={
"Authorization": f"Basic {encoded_key}" "Authorization": f"Basic {encoded_key}"
}).json() }).json()
if 'errors' in data and 'Unauthorized.' in data['errors']:
print("Please Add your correct WakaTime API Key to the Repository Secrets")
sys.exit(1)
elif 'error' in data and data['error'] == 'Invalid time range':
print("Please Input the correct time range (e.g. last_7_days, last_30_days)")
sys.exit(1)
try: try:
start = data['data']['start']
end = data['data']['end']
lang_data = data['data']['languages'] lang_data = data['data']['languages']
total_data = data['data']['human_readable_total'] total_data = data['data']['human_readable_total']
except KeyError: except KeyError:
print("Please Add your WakaTime API Key to the Repository Secrets") print("Unknown KeyError")
sys.exit(1) sys.exit(1)
if show_time == 'true': if show_time == 'true':
@ -96,8 +107,9 @@ def get_stats() -> str:
return_text = '```text\n' return_text = '```text\n'
if show_title == 'true': if show_title == 'true':
print("Stats with Weeks in Title Generated") print("Stats with Time Range in Title Generated")
return_text += this_week()+'\n\n' range_title = title(start, end)
return_text += range_title
if show_total == 'true': if show_total == 'true':
print("add Total time") print("add Total time")
return_text += 'Total: ' + total_data+'\n\n' return_text += 'Total: ' + total_data+'\n\n'
@ -128,7 +140,7 @@ if __name__ == '__main__':
print("Invalid string blocks. Please provide string with 2 or more characters. Eg. '░▒▓█'") print("Invalid string blocks. Please provide string with 2 or more characters. Eg. '░▒▓█'")
sys.exit(1) sys.exit(1)
contents = repo.get_readme() contents = repo.get_readme()
waka_stats = get_stats() waka_stats = get_stats(time_range)
rdmd = decode_readme(contents.content) rdmd = decode_readme(contents.content)
new_readme = generate_new_readme(stats=waka_stats, readme=rdmd) new_readme = generate_new_readme(stats=waka_stats, readme=rdmd)
if new_readme != rdmd: if new_readme != rdmd: