Skip to content

Commit 8a30411

Browse files
Add code style check and fix commands (#210)
* Add code style check and fix commands * Fix code style
1 parent b39823e commit 8a30411

File tree

8 files changed

+166
-103
lines changed

8 files changed

+166
-103
lines changed

.github/workflows/tests.yml

+25-14
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,55 @@
11
name: Tests
22
on: push
33
jobs:
4+
code-style:
5+
name: Code style
6+
runs-on: ubuntu-latest
7+
steps:
8+
- uses: actions/checkout@v4
9+
- uses: actions/setup-python@v5
10+
with:
11+
python-version: 3.8
12+
cache: 'pip'
13+
- run: pip install -r requirements.txt
14+
- name: Check
15+
run: black . --check
16+
417
duplicates:
518
name: No duplicate domains in list
619
runs-on: ubuntu-latest
7-
continue-on-error: true
820
steps:
9-
- uses: actions/checkout@v2
10-
name: Python setup
11-
- uses: actions/setup-python@v2
21+
- uses: actions/checkout@v4
22+
- uses: actions/setup-python@v5
1223
with:
1324
python-version: 3.8
14-
- name: Install pytest
15-
run: pip install pytest
25+
cache: 'pip'
26+
- run: pip install -r requirements.txt
1627
- name: Check for duplicate lines
1728
run: |
1829
cd scripts
1930
python3 tests.py --type duplicates
31+
2032
regex:
2133
name: No regex domains in list
2234
runs-on: ubuntu-latest
23-
continue-on-error: true
2435
steps:
25-
- uses: actions/checkout@v2
26-
name: Python setup
27-
- uses: actions/setup-python@v2
36+
- uses: actions/checkout@v4
37+
- uses: actions/setup-python@v5
2838
with:
2939
python-version: 3.8
30-
- name: Install pytest
31-
run: pip install pytest
40+
cache: 'pip'
41+
- run: pip install -r requirements.txt
3242
- name: Check if list includes regex domains
3343
run: |
3444
cd scripts
3545
python3 tests.py --type regex
46+
3647
unbound:
3748
name: Check Unbound list
3849
runs-on: ubuntu-latest
3950
steps:
40-
- uses: actions/checkout@v2
51+
- uses: actions/checkout@v4
4152
- name: Install Unbound
4253
run: sudo apt-get update && sudo apt-get install -y unbound
4354
- name: Check unbound list
44-
run: unbound-checkconf unbound.conf
55+
run: unbound-checkconf unbound.conf

Makefile

+7-1
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,10 @@ whois: ## Check all domains with whois
1616
@. .venv/bin/activate; cd scripts && python domain-check-api.py
1717

1818
dnscheck: ## Check all domains if they have a response
19-
@. .venv/bin/activate; cd scripts && python dnscheck.py
19+
@. .venv/bin/activate; cd scripts && python dnscheck.py
20+
21+
codestyle-check: ## Check all Python scripts code style
22+
@. .venv/bin/activate; black . --check
23+
24+
codestyle-fix: ## Fix all Python scripts code style
25+
@. .venv/bin/activate; black .

convert.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,13 @@ def run(action: str):
177177
if __name__ == "__main__":
178178

179179
# Read subcommand from command line, with error handling.
180-
action_candidates = ["pihole", "unbound", "adguard", "adguard_important", "categories"]
180+
action_candidates = [
181+
"pihole",
182+
"unbound",
183+
"adguard",
184+
"adguard_important",
185+
"categories",
186+
]
181187
special_candidates = ["all", "duplicates", "json"]
182188
subcommand = None
183189
try:

install.py

+95-67
Original file line numberDiff line numberDiff line change
@@ -11,35 +11,39 @@ def fetch_url(url):
1111
if not url:
1212
return
1313

14-
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0'}
14+
headers = {
15+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0"
16+
}
1517

16-
print('[i] Fetching:', url)
18+
print("[i] Fetching:", url)
1719

1820
try:
1921
response = urlopen(Request(url, headers=headers))
2022
except HTTPError as e:
21-
print('[E] HTTP Error:', e.code, 'whilst fetching', url)
23+
print("[E] HTTP Error:", e.code, "whilst fetching", url)
2224
return
2325
except URLError as e:
24-
print('[E] URL Error:', e.reason, 'whilst fetching', url)
26+
print("[E] URL Error:", e.reason, "whilst fetching", url)
2527
return
2628

2729
# Read and decode
28-
response = response.read().decode('UTF-8').replace('\r\n', '\n')
30+
response = response.read().decode("UTF-8").replace("\r\n", "\n")
2931

3032
# If there is data
3133
if response:
3234
# Strip leading and trailing whitespace
33-
response = '\n'.join(x for x in map(str.strip, response.splitlines()))
35+
response = "\n".join(x for x in map(str.strip, response.splitlines()))
3436

3537
# Return the hosts
3638
return response
3739

3840

39-
url_regexps_remote = 'https://raw.githubusercontent.com/nickspaargaren/no-google/master/regex.list'
40-
install_comment = 'github.com/nickspaargaren/no-google'
41+
url_regexps_remote = (
42+
"https://raw.githubusercontent.com/nickspaargaren/no-google/master/regex.list"
43+
)
44+
install_comment = "github.com/nickspaargaren/no-google"
4145

42-
cmd_restart = ['pihole', 'restartdns', 'reload']
46+
cmd_restart = ["pihole", "restartdns", "reload"]
4347

4448
db_exists = False
4549
conn = None
@@ -61,73 +65,83 @@ def fetch_url(url):
6165

6266
# Check to see whether the default "pihole" docker container is active
6367
try:
64-
docker_id = subprocess.run(['docker', 'ps', '--filter', 'name=pihole', '-q'],
65-
stdout=subprocess.PIPE, universal_newlines=True).stdout.strip()
68+
docker_id = subprocess.run(
69+
["docker", "ps", "--filter", "name=pihole", "-q"],
70+
stdout=subprocess.PIPE,
71+
universal_newlines=True,
72+
).stdout.strip()
6673
# Exception for if docker is not installed
6774
except FileNotFoundError:
6875
pass
6976

7077
# If a pihole docker container was found, locate the first mount
7178
if docker_id:
72-
docker_mnt = subprocess.run(['docker', 'inspect', '--format', '{{ (json .Mounts) }}', docker_id],
73-
stdout=subprocess.PIPE, universal_newlines=True).stdout.strip()
79+
docker_mnt = subprocess.run(
80+
["docker", "inspect", "--format", "{{ (json .Mounts) }}", docker_id],
81+
stdout=subprocess.PIPE,
82+
universal_newlines=True,
83+
).stdout.strip()
7484
# Convert output to JSON and iterate through each dict
7585
for json_dict in json.loads(docker_mnt):
7686
# If this mount's destination is /etc/pihole
77-
if json_dict['Destination'] == r'/etc/pihole':
87+
if json_dict["Destination"] == r"/etc/pihole":
7888
# Use the source path as our target
79-
docker_mnt_src = json_dict['Source']
89+
docker_mnt_src = json_dict["Source"]
8090
break
8191

8292
# If we successfully found the mount
8393
if docker_mnt_src:
84-
print('[i] Running in docker installation mode')
94+
print("[i] Running in docker installation mode")
8595
# Prepend restart commands
86-
cmd_restart[0:0] = ['docker', 'exec', '-i', 'pihole']
96+
cmd_restart[0:0] = ["docker", "exec", "-i", "pihole"]
8797
else:
88-
print('[i] Running in physical installation mode ')
98+
print("[i] Running in physical installation mode ")
8999

90100
# Set paths
91-
path_pihole = docker_mnt_src if docker_mnt_src else r'/etc/pihole'
92-
path_legacy_regex = os.path.join(path_pihole, 'regex.list')
93-
path_legacy_mmotti_regex = os.path.join(path_pihole, 'mmotti-regex.list')
94-
path_pihole_db = os.path.join(path_pihole, 'gravity.db')
101+
path_pihole = docker_mnt_src if docker_mnt_src else r"/etc/pihole"
102+
path_legacy_regex = os.path.join(path_pihole, "regex.list")
103+
path_legacy_mmotti_regex = os.path.join(path_pihole, "mmotti-regex.list")
104+
path_pihole_db = os.path.join(path_pihole, "gravity.db")
95105

96106
# Check that pi-hole path exists
97107
if os.path.exists(path_pihole):
98-
print('[i] Pi-hole path exists')
108+
print("[i] Pi-hole path exists")
99109
else:
100-
print(f'[e] {path_pihole} was not found')
110+
print(f"[e] {path_pihole} was not found")
101111
exit(1)
102112

103113
# Check for write access to /etc/pihole
104114
if os.access(path_pihole, os.X_OK | os.W_OK):
105-
print(f'[i] Write access to {path_pihole} verified')
115+
print(f"[i] Write access to {path_pihole} verified")
106116
else:
107-
print(f'[e] Write access is not available for {path_pihole}. Please run as root or other privileged user')
117+
print(
118+
f"[e] Write access is not available for {path_pihole}. Please run as root or other privileged user"
119+
)
108120
exit(1)
109121

110122
# Determine whether we are using DB or not
111123
if os.path.isfile(path_pihole_db) and os.path.getsize(path_pihole_db) > 0:
112124
db_exists = True
113-
print('[i] DB detected')
125+
print("[i] DB detected")
114126
else:
115-
print('[i] Legacy regex.list detected')
127+
print("[i] Legacy regex.list detected")
116128

117129
# Fetch the remote regexps
118130
str_regexps_remote = fetch_url(url_regexps_remote)
119131

120132
# If regexps were fetched, remove any comments and add to set
121133
if str_regexps_remote:
122-
regexps_remote.update(x for x in map(str.strip, str_regexps_remote.splitlines()) if x and x[:1] != '#')
123-
print(f'[i] {len(regexps_remote)} regexps collected from {url_regexps_remote}')
134+
regexps_remote.update(
135+
x for x in map(str.strip, str_regexps_remote.splitlines()) if x and x[:1] != "#"
136+
)
137+
print(f"[i] {len(regexps_remote)} regexps collected from {url_regexps_remote}")
124138
else:
125-
print('[i] No remote regexps were found.')
139+
print("[i] No remote regexps were found.")
126140
exit(1)
127141

128142
if db_exists:
129143
# Create a DB connection
130-
print(f'[i] Connecting to {path_pihole_db}')
144+
print(f"[i] Connecting to {path_pihole_db}")
131145

132146
try:
133147
conn = sqlite3.connect(path_pihole_db)
@@ -139,93 +153,107 @@ def fetch_url(url):
139153
c = conn.cursor()
140154

141155
# Add / update remote regexps
142-
print('[i] Adding / updating regexps in the DB')
143-
144-
c.executemany('INSERT OR IGNORE INTO domainlist (type, domain, enabled, comment) '
145-
'VALUES (3, ?, 1, ?)',
146-
[(x, install_comment) for x in sorted(regexps_remote)])
147-
c.executemany('UPDATE domainlist '
148-
'SET comment = ? WHERE domain in (?) AND comment != ?',
149-
[(install_comment, x, install_comment) for x in sorted(regexps_remote)])
156+
print("[i] Adding / updating regexps in the DB")
157+
158+
c.executemany(
159+
"INSERT OR IGNORE INTO domainlist (type, domain, enabled, comment) "
160+
"VALUES (3, ?, 1, ?)",
161+
[(x, install_comment) for x in sorted(regexps_remote)],
162+
)
163+
c.executemany(
164+
"UPDATE domainlist " "SET comment = ? WHERE domain in (?) AND comment != ?",
165+
[(install_comment, x, install_comment) for x in sorted(regexps_remote)],
166+
)
150167

151168
conn.commit()
152169

153170
# Fetch all current mmotti regexps in the local db
154-
c.execute('SELECT domain FROM domainlist WHERE type = 3 AND comment = ?', (install_comment,))
171+
c.execute(
172+
"SELECT domain FROM domainlist WHERE type = 3 AND comment = ?",
173+
(install_comment,),
174+
)
155175
regexps_mmotti_local_results = c.fetchall()
156176
regexps_mmotti_local.update([x[0] for x in regexps_mmotti_local_results])
157177

158178
# Remove any local entries that do not exist in the remote list
159179
# (will only work for previous installs where we've set the comment field)
160-
print('[i] Identifying obsolete regexps')
180+
print("[i] Identifying obsolete regexps")
161181
regexps_remove = regexps_mmotti_local.difference(regexps_remote)
162182

163183
if regexps_remove:
164-
print('[i] Removing obsolete regexps')
165-
c.executemany('DELETE FROM domainlist WHERE type = 3 AND domain in (?)', [(x,) for x in regexps_remove])
184+
print("[i] Removing obsolete regexps")
185+
c.executemany(
186+
"DELETE FROM domainlist WHERE type = 3 AND domain in (?)",
187+
[(x,) for x in regexps_remove],
188+
)
166189
conn.commit()
167190

168191
# Delete mmotti-regex.list as if we've migrated to the db, it's no longer needed
169192
if os.path.exists(path_legacy_mmotti_regex):
170193
os.remove(path_legacy_mmotti_regex)
171194

172-
print('[i] Restarting Pi-hole')
195+
print("[i] Restarting Pi-hole")
173196
subprocess.run(cmd_restart, stdout=subprocess.DEVNULL)
174197

175198
# Prepare final result
176-
print('[i] Done - Please see your installed regexps below\n')
199+
print("[i] Done - Please see your installed regexps below\n")
177200

178-
c.execute('Select domain FROM domainlist WHERE type = 3')
201+
c.execute("Select domain FROM domainlist WHERE type = 3")
179202
final_results = c.fetchall()
180203
regexps_local.update(x[0] for x in final_results)
181204

182-
print(*sorted(regexps_local), sep='\n')
205+
print(*sorted(regexps_local), sep="\n")
183206

184207
conn.close()
185208

186209
else:
187210
# If regex.list exists and is not empty
188211
# Read it and add to a set
189212
if os.path.isfile(path_legacy_regex) and os.path.getsize(path_legacy_regex) > 0:
190-
print('[i] Collecting existing entries from regex.list')
191-
with open(path_legacy_regex, 'r') as fRead:
192-
regexps_local.update(x for x in map(str.strip, fRead) if x and x[:1] != '#')
213+
print("[i] Collecting existing entries from regex.list")
214+
with open(path_legacy_regex, "r") as fRead:
215+
regexps_local.update(x for x in map(str.strip, fRead) if x and x[:1] != "#")
193216

194217
# If the local regexp set is not empty
195218
if regexps_local:
196-
print(f'[i] {len(regexps_local)} existing regexps identified')
219+
print(f"[i] {len(regexps_local)} existing regexps identified")
197220
# If we have a record of a previous legacy install
198-
if os.path.isfile(path_legacy_mmotti_regex) and os.path.getsize(path_legacy_mmotti_regex) > 0:
199-
print('[i] Existing mmotti-regex install identified')
221+
if (
222+
os.path.isfile(path_legacy_mmotti_regex)
223+
and os.path.getsize(path_legacy_mmotti_regex) > 0
224+
):
225+
print("[i] Existing mmotti-regex install identified")
200226
# Read the previously installed regexps to a set
201-
with open(path_legacy_mmotti_regex, 'r') as fOpen:
202-
regexps_legacy_mmotti.update(x for x in map(str.strip, fOpen) if x and x[:1] != '#')
227+
with open(path_legacy_mmotti_regex, "r") as fOpen:
228+
regexps_legacy_mmotti.update(
229+
x for x in map(str.strip, fOpen) if x and x[:1] != "#"
230+
)
203231

204232
if regexps_legacy_mmotti:
205-
print('[i] Removing previously installed regexps')
233+
print("[i] Removing previously installed regexps")
206234
regexps_local.difference_update(regexps_legacy_mmotti)
207235

208236
# Add remote regexps to local regexps
209-
print(f'[i] Syncing with {url_regexps_remote}')
237+
print(f"[i] Syncing with {url_regexps_remote}")
210238
regexps_local.update(regexps_remote)
211239

212240
# Output to regex.list
213-
print(f'[i] Outputting {len(regexps_local)} regexps to {path_legacy_regex}')
214-
with open(path_legacy_regex, 'w') as fWrite:
241+
print(f"[i] Outputting {len(regexps_local)} regexps to {path_legacy_regex}")
242+
with open(path_legacy_regex, "w") as fWrite:
215243
for line in sorted(regexps_local):
216-
fWrite.write(f'{line}\n')
244+
fWrite.write(f"{line}\n")
217245

218246
# Output mmotti remote regexps to mmotti-regex.list
219247
# for future install / uninstall
220-
with open(path_legacy_mmotti_regex, 'w') as fWrite:
248+
with open(path_legacy_mmotti_regex, "w") as fWrite:
221249
for line in sorted(regexps_remote):
222-
fWrite.write(f'{line}\n')
250+
fWrite.write(f"{line}\n")
223251

224-
print('[i] Restarting Pi-hole')
252+
print("[i] Restarting Pi-hole")
225253
subprocess.run(cmd_restart, stdout=subprocess.DEVNULL)
226254

227255
# Prepare final result
228-
print('[i] Done - Please see your installed regexps below\n')
229-
with open(path_legacy_regex, 'r') as fOpen:
256+
print("[i] Done - Please see your installed regexps below\n")
257+
with open(path_legacy_regex, "r") as fOpen:
230258
for line in fOpen:
231-
print(line, end='')
259+
print(line, end="")

0 commit comments

Comments
 (0)