Skip to content

Commit 9e00616

Browse files
authored
Merge pull request #3 from ReproNim/add-pre-commit
[MAINT] add pre-commit
2 parents 5ed5e33 + bc47260 commit 9e00616

33 files changed

+175
-85
lines changed

.pre-commit-config.yaml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# See https://pre-commit.com for more information
2+
# See https://pre-commit.com/hooks.html for more hooks
3+
repos:
4+
- repo: https://github.com/pre-commit/pre-commit-hooks
5+
rev: v4.6.0
6+
hooks:
7+
- id: trailing-whitespace
8+
- id: end-of-file-fixer
9+
- id: check-yaml
10+
- id: check-json
11+
- id: check-ast
12+
- id: check-added-large-files
13+
- repo: https://github.com/psf/black
14+
rev: 24.4.2
15+
hooks:
16+
- id: black
17+
- repo: https://github.com/codespell-project/codespell
18+
rev: v2.2.6
19+
hooks:
20+
- id: codespell

README.md

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,16 @@ You can find a demo protocol [here](https://github.com/ReproNim/reproschema-demo
1414
The following are required and recommended tools for using this cookiecutter and the ReproSchema protocol it generates. This is all a one-time setup, so if you have already done it, skip to the [next section](#creating-a-new-project)!
1515

1616
* **pipx**
17-
17+
1818
pipx is a tool for managing isolated Python-based applications. It is the recommended way to install Poetry and cruft. To install `pipx` follow the instructions here: https://pypa.github.io/pipx/installation/
19-
19+
2020
* **cruft**
2121

2222
cruft is a tool for generating projects based on a cookiecutter (like this one!) and keeping those projects updated if the original cookiecutter changes. Install it with `pipx` by running:
2323
```shell
2424
pipx install cruft
2525
```
26-
You may also choose to not have a persistent installation of cruft, in which case you would replace any calls to the `cruft` command below with `pipx run cruft`.
26+
You may also choose to not have a persistent installation of cruft, in which case you would replace any calls to the `cruft` command below with `pipx run cruft`.
2727

2828
## Creating a new protocol
2929

@@ -71,21 +71,21 @@ make setup
7171
git branch -M main
7272
git push -u origin main
7373
```
74-
3. Create the gh-pages branch
75-
- Fetch the latest changes from your repository (if any):
76-
```bash
77-
git fetch origin
78-
```
79-
- Create and switch to the new gh-pages branch:
80-
```bash
81-
git checkout -b gh-pages
82-
```
74+
3. Create the gh-pages branch
75+
- Fetch the latest changes from your repository (if any):
76+
```bash
77+
git fetch origin
78+
```
79+
- Create and switch to the new gh-pages branch:
80+
```bash
81+
git checkout -b gh-pages
82+
```
8383
- Push the gh-pages branch to remote:
8484
```bash
8585
git push --set-upstream origin gh-pages
8686
```
87-
This branch allows you to deploy your ReproSchema UI publicly.
88-
87+
This branch allows you to deploy your ReproSchema UI publicly.
88+
8989
## Keeping your project up to date
9090

9191
To be up-to-date with the template, first check if there is a mismatch

hooks/post_gen_project.py

Lines changed: 61 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,65 +2,88 @@
22
import os
33
import shutil
44
import requests
5+
import subprocess
6+
57

68
def get_pref_label(activity_path):
79
try:
8-
with open(activity_path, 'r') as file:
10+
with open(activity_path, "r") as file:
911
activity_schema = json.load(file)
1012
return activity_schema.get("prefLabel", "Unknown Activity")
1113
except (FileNotFoundError, json.JSONDecodeError):
1214
return "Unknown Activity"
1315

16+
1417
def update_json_schema(activities, base_path):
15-
schema_file = os.path.join(base_path, '{{ cookiecutter.__protocol_slug }}/{{ cookiecutter.__protocol_slug }}_schema')
16-
with open(schema_file, 'r') as file:
18+
schema_file = os.path.join(
19+
base_path,
20+
"{{ cookiecutter.__protocol_slug }}/{{ cookiecutter.__protocol_slug }}_schema",
21+
)
22+
with open(schema_file, "r") as file:
1723
schema = json.load(file)
1824

19-
schema['ui']['addProperties'] = []
20-
schema['ui']['order'] = []
25+
schema["ui"]["addProperties"] = []
26+
schema["ui"]["order"] = []
2127

2228
for activity in activities:
23-
activity_schema_path = os.path.join(base_path, f'activities/{activity}/{activity}_schema')
29+
activity_schema_path = os.path.join(
30+
base_path, f"activities/{activity}/{activity}_schema"
31+
)
2432
pref_label = get_pref_label(activity_schema_path)
2533
activity_path = f"../activities/{activity}/{activity}_schema"
2634

27-
schema['ui']['addProperties'].append({
28-
"isAbout": activity_path,
29-
"variableName": f"{activity}_schema",
30-
"prefLabel": pref_label
31-
})
32-
schema['ui']['order'].append(activity_path)
35+
schema["ui"]["addProperties"].append(
36+
{
37+
"isAbout": activity_path,
38+
"variableName": f"{activity}_schema",
39+
"prefLabel": pref_label,
40+
}
41+
)
42+
schema["ui"]["order"].append(activity_path)
3343

34-
with open(schema_file, 'w') as file:
44+
with open(schema_file, "w") as file:
3545
json.dump(schema, file, indent=4)
3646

47+
3748
def fetch_latest_checksum(base_path):
3849
try:
3950
# Using Python requests to fetch and parse JSON
40-
response = requests.get("https://api.github.com/repos/ReproNim/reproschema-ui/commits/master")
51+
response = requests.get(
52+
"https://api.github.com/repos/ReproNim/reproschema-ui/commits/master"
53+
)
4154
response.raise_for_status() # Raises an HTTPError if the HTTP request returned an unsuccessful status code
42-
latest_hash = response.json()['sha']
55+
latest_hash = response.json()["sha"]
4356

44-
config_path = os.path.join(base_path, 'config.env')
45-
with open(config_path, 'w') as file:
57+
config_path = os.path.join(base_path, "config.env")
58+
with open(config_path, "w") as file:
4659
file.write(f"REPROSCHEMA_UI_CHECKSUM={latest_hash}\n")
4760

4861
print("Latest checksum fetched and saved in config.env.")
4962

5063
except Exception as e:
5164
print(f"Error fetching checksum: {e}")
5265

66+
67+
def setup_pre_commit():
68+
try:
69+
subprocess.check_call([sys.executable, "-m", "pip", "install", "pre-commit"])
70+
subprocess.check_call(["pre-commit", "install"])
71+
print("Pre-commit hooks set up successfully.")
72+
except subprocess.CalledProcessError as e:
73+
print(f"Failed to set up pre-commit hooks: {e}")
74+
75+
5376
def main():
5477
base_path = os.getcwd()
55-
init_flag_path = os.path.join(base_path, '.initialized')
78+
init_flag_path = os.path.join(base_path, ".initialized")
5679

5780
# Check if the project has been initialized before
5881
if not os.path.exists(init_flag_path):
5982
# Project initialization logic
60-
activities_path = os.path.join(base_path, 'activities')
83+
activities_path = os.path.join(base_path, "activities")
6184

6285
try:
63-
with open('selected_activities.json') as f:
86+
with open("selected_activities.json") as f:
6487
selected_activities = json.load(f)
6588
except (FileNotFoundError, json.JSONDecodeError):
6689
print("Error reading selected activities.")
@@ -71,22 +94,35 @@ def main():
7194
if not os.path.exists(activity_dir):
7295
os.makedirs(activity_dir)
7396

74-
all_activities = ['Activity1', 'Activity2', 'Activity3', 'selectActivity', 'voiceActivity']
97+
all_activities = [
98+
"Activity1",
99+
"Activity2",
100+
"Activity3",
101+
"selectActivity",
102+
"voiceActivity",
103+
]
75104
for activity in all_activities:
76105
if activity not in selected_activities:
77106
activity_dir = os.path.join(activities_path, activity)
78107
if os.path.exists(activity_dir):
79108
shutil.rmtree(activity_dir)
80109

81-
activities = [activity for activity in selected_activities if os.path.exists(os.path.join(activities_path, activity))]
110+
activities = [
111+
activity
112+
for activity in selected_activities
113+
if os.path.exists(os.path.join(activities_path, activity))
114+
]
82115
update_json_schema(activities, base_path)
83116

84117
# Mark initialization as complete
85-
with open(init_flag_path, 'w') as f:
86-
f.write('initialized')
118+
with open(init_flag_path, "w") as f:
119+
f.write("initialized")
87120

88121
# Fetch and save the latest checksum
89122
fetch_latest_checksum(base_path)
90123

124+
setup_pre_commit()
125+
126+
91127
if __name__ == "__main__":
92-
main()
128+
main()

hooks/pre_gen_project.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,21 @@
33
import sys
44
import json
55

6+
67
def select_activities(n):
7-
all_activities = ['Activity1', 'Activity2', 'Activity3', 'selectActivity', 'voiceActivity']
8+
all_activities = [
9+
"Activity1",
10+
"Activity2",
11+
"Activity3",
12+
"selectActivity",
13+
"voiceActivity",
14+
]
815
return random.sample(all_activities, n)
916

17+
1018
def main():
1119
# Read the number of activities from the Cookiecutter context
12-
num_activities_str = '{{ cookiecutter.number_of_activities }}'
20+
num_activities_str = "{{ cookiecutter.number_of_activities }}"
1321

1422
try:
1523
num_activities = int(num_activities_str)
@@ -23,8 +31,9 @@ def main():
2331
print(f"Selected activities: {', '.join(selected_activities)}")
2432

2533
# Write the selected activities to a file
26-
with open('selected_activities.json', 'w') as f:
34+
with open("selected_activities.json", "w") as f:
2735
json.dump(selected_activities, f)
2836

37+
2938
if __name__ == "__main__":
30-
main()
39+
main()

update_schema_version.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,27 @@
11
import os
22
import re
33

4-
latest_release = os.environ['LATEST_RELEASE']
4+
latest_release = os.environ["LATEST_RELEASE"]
5+
56

67
def update_file(file_path, version):
7-
with open(file_path, 'r') as file:
8+
with open(file_path, "r") as file:
89
content = file.read()
910

10-
content = re.sub(r'"@context": "https://raw\.githubusercontent\.com/ReproNim/reproschema/.+?/contexts/generic"',
11-
f'"@context": "https://raw.githubusercontent.com/ReproNim/reproschema/{version}/contexts/generic"',
12-
content)
13-
content = re.sub(r'"schemaVersion": ".+?"', f'"schemaVersion": "{version}"', content)
11+
content = re.sub(
12+
r'"@context": "https://raw\.githubusercontent\.com/ReproNim/reproschema/.+?/contexts/generic"',
13+
f'"@context": "https://raw.githubusercontent.com/ReproNim/reproschema/{version}/contexts/generic"',
14+
content,
15+
)
16+
content = re.sub(
17+
r'"schemaVersion": ".+?"', f'"schemaVersion": "{version}"', content
18+
)
1419

15-
with open(file_path, 'w') as file:
20+
with open(file_path, "w") as file:
1621
file.write(content)
1722

18-
for root, dirs, files in os.walk('.'):
23+
24+
for root, dirs, files in os.walk("."):
1925
for file in files:
20-
if file.endswith('_schema') or file.endswith('_item') or '_item_' in file:
26+
if file.endswith("_schema") or file.endswith("_item") or "_item_" in file:
2127
update_file(os.path.join(root, file), latest_release)

{{cookiecutter.protocol_name}}/.github/workflows/build_deploy.yaml

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@ jobs:
1414
- name: Set Environment Variable
1515
run: |
1616
echo "PROTOCOL_SLUG={{cookiecutter.__protocol_slug}}" >> $GITHUB_ENV
17-
17+
1818
- name: Echo Environment Variable
1919
run: |
20-
echo "PROTOCOL_SLUG is set to $PROTOCOL_SLUG"
21-
20+
echo "PROTOCOL_SLUG is set to $PROTOCOL_SLUG"
21+
2222
- name: Check out repository
2323
uses: actions/checkout@v3
2424
with:
@@ -53,7 +53,7 @@ jobs:
5353
run: |
5454
python -m pip install --upgrade pip setuptools
5555
pip install reproschema requests_cache pre-commit
56-
56+
5757
- name: Test with pyshacl
5858
run: |
5959
reproschema -l DEBUG validate activities
@@ -76,6 +76,6 @@ jobs:
7676
if: github.ref == 'refs/heads/main'
7777
uses: JamesIves/github-pages-deploy-action@v4
7878
with:
79-
token: {% raw %}${{ secrets.GITHUB_TOKEN }}{% endraw %}
79+
token: "{% raw %}${{ secrets.GITHUB_TOKEN }}{% endraw %}"
8080
branch: gh-pages
8181
folder: ui/dist
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
*.DS_Store
1+
*.DS_Store
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# See https://pre-commit.com for more information
2+
# See https://pre-commit.com/hooks.html for more hooks
3+
repos:
4+
- repo: https://github.com/pre-commit/pre-commit-hooks
5+
rev: v4.6.0
6+
hooks:
7+
- id: trailing-whitespace
8+
- id: end-of-file-fixer
9+
- id: check-yaml
10+
- id: check-json
11+
- id: check-ast
12+
- id: check-added-large-files
13+
- repo: https://github.com/psf/black
14+
rev: 24.4.2
15+
hooks:
16+
- id: black
17+
- repo: https://github.com/codespell-project/codespell
18+
rev: v2.2.6
19+
hooks:
20+
- id: codespell

{{cookiecutter.protocol_name}}/Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,4 @@ cruft-check:
4949

5050
# Update the project from the Cookiecutter template
5151
cruft-update:
52-
cruft update
52+
cruft update

{{cookiecutter.protocol_name}}/activities/Activity1/activity1_schema

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,4 @@
2929
"reproschema:AllowExport"
3030
]
3131
}
32-
}
32+
}

0 commit comments

Comments
 (0)