Skip to content

Commit

Permalink
Merge pull request #26 from ZedThree/modernise
Browse files Browse the repository at this point in the history
Fix various lint issues
  • Loading branch information
ZedThree authored Jul 5, 2023
2 parents fd665b3 + 606d86e commit 09770b0
Show file tree
Hide file tree
Showing 13 changed files with 116 additions and 133 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/black.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ jobs:
black:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Setup Python
uses: actions/setup-python@v2
uses: actions/setup-python@v4
with:
python-version: 3.x
- name: Install black
Expand All @@ -28,7 +28,7 @@ jobs:
black --version
- name: Run black
run: |
black fortdepend setup.py tests
black fortdepend tests
- uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: "Apply black changes"
6 changes: 3 additions & 3 deletions .github/workflows/python_publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
- uses: actions/checkout@v3
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.x'
- name: Install dependencies
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: [3.7, 3.8, 3.9]
python-version: ["3.8", "3.9", "3.10", "3.11"]

steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v1
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
Expand Down
4 changes: 2 additions & 2 deletions fortdepend/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
try:
from importlib.metadata import version, PackageNotFoundError
from importlib.metadata import PackageNotFoundError, version
except ModuleNotFoundError:
from importlib_metadata import version, PackageNotFoundError
from importlib_metadata import PackageNotFoundError, version
try:
__version__ = version(__name__)
except PackageNotFoundError:
Expand Down
9 changes: 4 additions & 5 deletions fortdepend/__main__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
#!/usr/bin/env python3
import argparse

import colorama
from fortdepend import FortranProject
from fortdepend import __version__

from fortdepend import FortranProject, __version__


def create_argument_parser():
Expand Down Expand Up @@ -63,9 +64,7 @@ def create_argument_parser():
help="Don't use the preprocessor",
)
parser.add_argument(
"--version",
action="version",
version="%(prog)s {version}".format(version=__version__),
"--version", action="version", version=f"%(prog)s {__version__}"
)

return parser
Expand Down
51 changes: 19 additions & 32 deletions fortdepend/fort_depend.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,13 @@
from __future__ import print_function

import os
import sys
from contextlib import suppress
from pathlib import Path

# Terminal colours
from colorama import Fore

from .graph import Graph
from .smartopen import smart_open
from .units import FortranFile, FortranModule
from .graph import Graph

# Python 2/3 compatibility
try:
input = raw_input
except NameError:
pass

DEPFILE_HEADER = "# This file is generated automatically. DO NOT EDIT!"
DEFAULT_IGNORED_MODULES = ["iso_c_binding", "iso_fortran_env"]
Expand Down Expand Up @@ -61,7 +54,7 @@ def __init__(
verbose=False,
):
if name is None:
self.name = os.path.basename(os.getcwd())
self.name = Path.cwd().name
else:
self.name = name

Expand Down Expand Up @@ -107,10 +100,9 @@ def get_source(self, extensions=None):
elif not isinstance(extensions, list):
extensions = [extensions]

tmp = os.listdir(".")
files = []
for ext in extensions:
files.extend([x for x in tmp if x.endswith(ext)])
files.extend([x.name for x in Path.cwd().iterdir() if x.suffix == ext])

return files

Expand Down Expand Up @@ -297,25 +289,23 @@ def write_depends(
skip_programs (bool): Don't write dependencies for programs
"""

build = Path(build)

def _format_dependencies(target, target_extension, dep_list):
_, filename = os.path.split(target)
target_name = os.path.splitext(filename)[0] + target_extension
listing = "\n{} : ".format(os.path.join(build, target_name))
target_name = Path(target).with_suffix(target_extension).name
listing = f"\n{build / target_name} : "
for dep in dep_list:
_, depfilename = os.path.split(dep)
depobjectname = os.path.splitext(depfilename)[0] + ".o"
listing += " \\\n\t{}".format(os.path.join(build, depobjectname))
depobjectname = Path(dep).with_suffix(".o").name
listing += f" \\\n\t{build / depobjectname}"
listing += "\n"
return listing

filename = Path(filename)

# Test file doesn't exist
if os.path.exists(filename):
if not (overwrite):
print(
Fore.RED
+ "Warning: file '{}' exists.".format(filename)
+ Fore.RESET
)
if filename.exists():
if not overwrite:
print(f"{Fore.RED}Warning: file '{filename}' exists.{Fore.RESET}")
opt = input("Overwrite? Y... for yes.")
if opt.lower().startswith("y"):
pass
Expand Down Expand Up @@ -374,13 +364,10 @@ def remove_ignored_modules(self, ignore_modules=None):
self.modules.pop(ignore_mod, None)
# Remove from 'used' modules
for module in self.modules.values():
try:
with suppress(ValueError):
module.uses.remove(ignore_mod)
except ValueError:
pass

# Remove from 'used' files
for source_file in self.files.values():
try:
with suppress(ValueError):
source_file.uses.remove(ignore_mod)
except ValueError:
pass
10 changes: 6 additions & 4 deletions fortdepend/graph.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
"""Utilities for making graphs of dependencies"""

import warnings

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

has_graphviz = True
HAS_GRAPHVIZ = True
except ImportError:
has_graphviz = False
HAS_GRAPHVIZ = False


class Graph:
Expand All @@ -20,7 +22,7 @@ class Graph:
"""

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

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

def draw(self):
"""Render the graph to an image"""
if not has_graphviz:
if not HAS_GRAPHVIZ:
warnings.warn("graphviz not installed: can't make graph", RuntimeWarning)
return

Expand Down
8 changes: 7 additions & 1 deletion fortdepend/preprocessor.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
"""Utilities for preprocessing Fortran"""

import io

import pcpp


class FortranPreprocessor(pcpp.Preprocessor):
"""Simple wrapper around `pcpp.Preprocessor` to write to string"""

def __init__(self):
super().__init__()
self.add_path(".")

def parse_to_string(self, text, source):
def parse_to_string(self, text: str, source: str) -> str:
"""Preprocess ``text`` straight to string"""
with io.StringIO() as f:
self.parse(text, source=source)
self.write(f)
Expand Down
2 changes: 1 addition & 1 deletion fortdepend/smartopen.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import sys
import contextlib
import sys


@contextlib.contextmanager
Expand Down
50 changes: 21 additions & 29 deletions fortdepend/units.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .preprocessor import FortranPreprocessor
import re

from .preprocessor import FortranPreprocessor
from .smartopen import smart_open

UNIT_REGEX = re.compile(
Expand Down Expand Up @@ -50,20 +50,20 @@ def __init__(
contents = f.read()

preprocessor = FortranPreprocessor()
macros = macros or {}

if macros:
if isinstance(macros, dict):
for k, v in macros.items():
preprocessor.define("{} {}".format(k, v))
else:
if not isinstance(macros, list):
macros = [macros]
for macro in macros:
if "=" in macro:
temp = macro.split("=")
preprocessor.define("{} {}".format(*temp))
else:
preprocessor.define(macro)
if isinstance(macros, dict):
for k, v in macros.items():
preprocessor.define(f"{k} {v}")
else:
if not isinstance(macros, list):
macros = [macros]
for macro in macros:
if "=" in macro:
key, value = macro.split("=")
preprocessor.define(f"{key} {value}")
else:
preprocessor.define(macro)

if cpp_includes:
if not isinstance(cpp_includes, list):
Expand All @@ -81,7 +81,7 @@ def __str__(self):
return self.filename

def __repr__(self):
return "FortranFile('{}')".format(self.filename)
return f"FortranFile('{self.filename}')"

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

for num, line in enumerate(contents):
unit = re.match(UNIT_REGEX, line)
end = re.match(END_REGEX, line)
if unit:
if unit := UNIT_REGEX.match(line):
found_units.append(unit)
starts.append(num)
if end:
if end := END_REGEX.match(line):
ends.append(num)

if found_units:
if (len(found_units) != len(starts)) or (len(starts) != len(ends)):
error_string = (
"Unmatched start/end of modules in {} ({} begins/{} ends)".format(
self.filename, len(starts), len(ends)
)
raise ValueError(
f"Unmatched start/end of modules in {self.filename} ({len(starts)} begins/{len(ends)} ends)"
)
raise ValueError(error_string)
for unit, start, end in zip(found_units, starts, ends):
name = unit.group("modname")
mod = FortranModule(
Expand Down Expand Up @@ -167,9 +162,7 @@ def __str__(self):
return self.name

def __repr__(self):
return "FortranModule({}, '{}', '{}')".format(
self.unit_type, self.name, self.source_file.filename
)
return f"FortranModule({self.unit_type}, '{self.name}', '{self.source_file.filename}')"

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

for line in contents[self.defined_at : self.end]:
found = re.match(USE_REGEX, line)
if found:
if found := USE_REGEX.match(line):
uses.append(found.group("moduse").strip().lower())

# Remove duplicates
Expand Down
Loading

0 comments on commit 09770b0

Please sign in to comment.