Skip to content

Commit 09770b0

Browse files
authored
Merge pull request #26 from ZedThree/modernise
Fix various lint issues
2 parents fd665b3 + 606d86e commit 09770b0

13 files changed

+116
-133
lines changed

.github/workflows/black.yml

+3-3
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ jobs:
1313
black:
1414
runs-on: ubuntu-latest
1515
steps:
16-
- uses: actions/checkout@v2
16+
- uses: actions/checkout@v3
1717
- name: Setup Python
18-
uses: actions/setup-python@v2
18+
uses: actions/setup-python@v4
1919
with:
2020
python-version: 3.x
2121
- name: Install black
@@ -28,7 +28,7 @@ jobs:
2828
black --version
2929
- name: Run black
3030
run: |
31-
black fortdepend setup.py tests
31+
black fortdepend tests
3232
- uses: stefanzweifel/git-auto-commit-action@v4
3333
with:
3434
commit_message: "Apply black changes"

.github/workflows/python_publish.yml

+3-3
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@ jobs:
88
deploy:
99
runs-on: ubuntu-latest
1010
steps:
11-
- uses: actions/checkout@v2
12-
- name: Set up Python
13-
uses: actions/setup-python@v2
11+
- uses: actions/checkout@v3
12+
- name: Setup Python
13+
uses: actions/setup-python@v4
1414
with:
1515
python-version: '3.x'
1616
- name: Install dependencies

.github/workflows/test.yml

+3-3
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,12 @@ jobs:
88
strategy:
99
fail-fast: false
1010
matrix:
11-
python-version: [3.7, 3.8, 3.9]
11+
python-version: ["3.8", "3.9", "3.10", "3.11"]
1212

1313
steps:
14-
- uses: actions/checkout@v2
14+
- uses: actions/checkout@v3
1515
- name: Set up Python ${{ matrix.python-version }}
16-
uses: actions/setup-python@v1
16+
uses: actions/setup-python@v4
1717
with:
1818
python-version: ${{ matrix.python-version }}
1919
- name: Install dependencies

fortdepend/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
try:
2-
from importlib.metadata import version, PackageNotFoundError
2+
from importlib.metadata import PackageNotFoundError, version
33
except ModuleNotFoundError:
4-
from importlib_metadata import version, PackageNotFoundError
4+
from importlib_metadata import PackageNotFoundError, version
55
try:
66
__version__ = version(__name__)
77
except PackageNotFoundError:

fortdepend/__main__.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
#!/usr/bin/env python3
22
import argparse
3+
34
import colorama
4-
from fortdepend import FortranProject
5-
from fortdepend import __version__
5+
6+
from fortdepend import FortranProject, __version__
67

78

89
def create_argument_parser():
@@ -63,9 +64,7 @@ def create_argument_parser():
6364
help="Don't use the preprocessor",
6465
)
6566
parser.add_argument(
66-
"--version",
67-
action="version",
68-
version="%(prog)s {version}".format(version=__version__),
67+
"--version", action="version", version=f"%(prog)s {__version__}"
6968
)
7069

7170
return parser

fortdepend/fort_depend.py

+19-32
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,13 @@
1-
from __future__ import print_function
2-
3-
import os
41
import sys
2+
from contextlib import suppress
3+
from pathlib import Path
54

65
# Terminal colours
76
from colorama import Fore
87

8+
from .graph import Graph
99
from .smartopen import smart_open
1010
from .units import FortranFile, FortranModule
11-
from .graph import Graph
12-
13-
# Python 2/3 compatibility
14-
try:
15-
input = raw_input
16-
except NameError:
17-
pass
1811

1912
DEPFILE_HEADER = "# This file is generated automatically. DO NOT EDIT!"
2013
DEFAULT_IGNORED_MODULES = ["iso_c_binding", "iso_fortran_env"]
@@ -61,7 +54,7 @@ def __init__(
6154
verbose=False,
6255
):
6356
if name is None:
64-
self.name = os.path.basename(os.getcwd())
57+
self.name = Path.cwd().name
6558
else:
6659
self.name = name
6760

@@ -107,10 +100,9 @@ def get_source(self, extensions=None):
107100
elif not isinstance(extensions, list):
108101
extensions = [extensions]
109102

110-
tmp = os.listdir(".")
111103
files = []
112104
for ext in extensions:
113-
files.extend([x for x in tmp if x.endswith(ext)])
105+
files.extend([x.name for x in Path.cwd().iterdir() if x.suffix == ext])
114106

115107
return files
116108

@@ -297,25 +289,23 @@ def write_depends(
297289
skip_programs (bool): Don't write dependencies for programs
298290
"""
299291

292+
build = Path(build)
293+
300294
def _format_dependencies(target, target_extension, dep_list):
301-
_, filename = os.path.split(target)
302-
target_name = os.path.splitext(filename)[0] + target_extension
303-
listing = "\n{} : ".format(os.path.join(build, target_name))
295+
target_name = Path(target).with_suffix(target_extension).name
296+
listing = f"\n{build / target_name} : "
304297
for dep in dep_list:
305-
_, depfilename = os.path.split(dep)
306-
depobjectname = os.path.splitext(depfilename)[0] + ".o"
307-
listing += " \\\n\t{}".format(os.path.join(build, depobjectname))
298+
depobjectname = Path(dep).with_suffix(".o").name
299+
listing += f" \\\n\t{build / depobjectname}"
308300
listing += "\n"
309301
return listing
310302

303+
filename = Path(filename)
304+
311305
# Test file doesn't exist
312-
if os.path.exists(filename):
313-
if not (overwrite):
314-
print(
315-
Fore.RED
316-
+ "Warning: file '{}' exists.".format(filename)
317-
+ Fore.RESET
318-
)
306+
if filename.exists():
307+
if not overwrite:
308+
print(f"{Fore.RED}Warning: file '{filename}' exists.{Fore.RESET}")
319309
opt = input("Overwrite? Y... for yes.")
320310
if opt.lower().startswith("y"):
321311
pass
@@ -374,13 +364,10 @@ def remove_ignored_modules(self, ignore_modules=None):
374364
self.modules.pop(ignore_mod, None)
375365
# Remove from 'used' modules
376366
for module in self.modules.values():
377-
try:
367+
with suppress(ValueError):
378368
module.uses.remove(ignore_mod)
379-
except ValueError:
380-
pass
369+
381370
# Remove from 'used' files
382371
for source_file in self.files.values():
383-
try:
372+
with suppress(ValueError):
384373
source_file.uses.remove(ignore_mod)
385-
except ValueError:
386-
pass

fortdepend/graph.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
1+
"""Utilities for making graphs of dependencies"""
2+
13
import warnings
24

35
# If graphviz is not installed, graphs can't be produced
46
try:
57
import graphviz as gv
68

7-
has_graphviz = True
9+
HAS_GRAPHVIZ = True
810
except ImportError:
9-
has_graphviz = False
11+
HAS_GRAPHVIZ = False
1012

1113

1214
class Graph:
@@ -20,7 +22,7 @@ class Graph:
2022
"""
2123

2224
def __init__(self, tree, filename=None, format="svg", view=True):
23-
if not has_graphviz:
25+
if not HAS_GRAPHVIZ:
2426
warnings.warn("graphviz not installed: can't make graph", RuntimeWarning)
2527
return
2628

@@ -36,7 +38,7 @@ def __init__(self, tree, filename=None, format="svg", view=True):
3638

3739
def draw(self):
3840
"""Render the graph to an image"""
39-
if not has_graphviz:
41+
if not HAS_GRAPHVIZ:
4042
warnings.warn("graphviz not installed: can't make graph", RuntimeWarning)
4143
return
4244

fortdepend/preprocessor.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
1+
"""Utilities for preprocessing Fortran"""
2+
13
import io
4+
25
import pcpp
36

47

58
class FortranPreprocessor(pcpp.Preprocessor):
9+
"""Simple wrapper around `pcpp.Preprocessor` to write to string"""
10+
611
def __init__(self):
712
super().__init__()
813
self.add_path(".")
914

10-
def parse_to_string(self, text, source):
15+
def parse_to_string(self, text: str, source: str) -> str:
16+
"""Preprocess ``text`` straight to string"""
1117
with io.StringIO() as f:
1218
self.parse(text, source=source)
1319
self.write(f)

fortdepend/smartopen.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import sys
21
import contextlib
2+
import sys
33

44

55
@contextlib.contextmanager

fortdepend/units.py

+21-29
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
from .preprocessor import FortranPreprocessor
21
import re
32

3+
from .preprocessor import FortranPreprocessor
44
from .smartopen import smart_open
55

66
UNIT_REGEX = re.compile(
@@ -50,20 +50,20 @@ def __init__(
5050
contents = f.read()
5151

5252
preprocessor = FortranPreprocessor()
53+
macros = macros or {}
5354

54-
if macros:
55-
if isinstance(macros, dict):
56-
for k, v in macros.items():
57-
preprocessor.define("{} {}".format(k, v))
58-
else:
59-
if not isinstance(macros, list):
60-
macros = [macros]
61-
for macro in macros:
62-
if "=" in macro:
63-
temp = macro.split("=")
64-
preprocessor.define("{} {}".format(*temp))
65-
else:
66-
preprocessor.define(macro)
55+
if isinstance(macros, dict):
56+
for k, v in macros.items():
57+
preprocessor.define(f"{k} {v}")
58+
else:
59+
if not isinstance(macros, list):
60+
macros = [macros]
61+
for macro in macros:
62+
if "=" in macro:
63+
key, value = macro.split("=")
64+
preprocessor.define(f"{key} {value}")
65+
else:
66+
preprocessor.define(macro)
6767

6868
if cpp_includes:
6969
if not isinstance(cpp_includes, list):
@@ -81,7 +81,7 @@ def __str__(self):
8181
return self.filename
8282

8383
def __repr__(self):
84-
return "FortranFile('{}')".format(self.filename)
84+
return f"FortranFile('{self.filename}')"
8585

8686
def get_modules(self, contents, macros=None):
8787
"""Return all the modules or programs that are in the file
@@ -96,22 +96,17 @@ def get_modules(self, contents, macros=None):
9696
ends = []
9797

9898
for num, line in enumerate(contents):
99-
unit = re.match(UNIT_REGEX, line)
100-
end = re.match(END_REGEX, line)
101-
if unit:
99+
if unit := UNIT_REGEX.match(line):
102100
found_units.append(unit)
103101
starts.append(num)
104-
if end:
102+
if end := END_REGEX.match(line):
105103
ends.append(num)
106104

107105
if found_units:
108106
if (len(found_units) != len(starts)) or (len(starts) != len(ends)):
109-
error_string = (
110-
"Unmatched start/end of modules in {} ({} begins/{} ends)".format(
111-
self.filename, len(starts), len(ends)
112-
)
107+
raise ValueError(
108+
f"Unmatched start/end of modules in {self.filename} ({len(starts)} begins/{len(ends)} ends)"
113109
)
114-
raise ValueError(error_string)
115110
for unit, start, end in zip(found_units, starts, ends):
116111
name = unit.group("modname")
117112
mod = FortranModule(
@@ -167,9 +162,7 @@ def __str__(self):
167162
return self.name
168163

169164
def __repr__(self):
170-
return "FortranModule({}, '{}', '{}')".format(
171-
self.unit_type, self.name, self.source_file.filename
172-
)
165+
return f"FortranModule({self.unit_type}, '{self.name}', '{self.source_file.filename}')"
173166

174167
def get_uses(self, contents, macros=None):
175168
"""Return which modules are used in the file after expanding macros
@@ -183,8 +176,7 @@ def get_uses(self, contents, macros=None):
183176
uses = []
184177

185178
for line in contents[self.defined_at : self.end]:
186-
found = re.match(USE_REGEX, line)
187-
if found:
179+
if found := USE_REGEX.match(line):
188180
uses.append(found.group("moduse").strip().lower())
189181

190182
# Remove duplicates

0 commit comments

Comments
 (0)