djLint/src/djlint/src.py

92 lines
2.8 KiB
Python
Raw Normal View History

2021-10-14 10:19:48 +00:00
"""Build src file list."""
import re
from pathlib import Path
from typing import List
from click import echo
from colorama import Fore
from .settings import Config
def get_src(src: List[Path], config: Config) -> List[Path]:
"""Get source files."""
paths = []
for item in src:
2021-10-28 11:39:38 +00:00
# normalize path
2021-10-29 08:42:39 +00:00
2021-11-26 13:01:54 +00:00
normalized_item = item.resolve()
2021-10-28 11:39:38 +00:00
2021-10-29 08:42:39 +00:00
if (
Path.is_file(normalized_item)
and no_pragma(config, normalized_item)
and (
(
config.use_gitignore
and not config.gitignore.match_file(normalized_item)
)
or not config.use_gitignore
)
):
2021-10-28 11:39:38 +00:00
paths.append(normalized_item)
2021-10-14 10:19:48 +00:00
continue
# remove leading . from extension
extension = str(config.extension)
extension = extension[1:] if extension.startswith(".") else extension
paths.extend(
filter(
2021-10-28 11:39:38 +00:00
lambda x: not re.search(config.exclude, x.as_posix(), re.VERBOSE)
2021-10-29 08:42:39 +00:00
and no_pragma(config, x)
and (
(config.use_gitignore and not config.gitignore.match_file(x))
or not config.use_gitignore
),
2021-10-28 11:39:38 +00:00
list(normalized_item.glob(f"**/*.{extension}")),
2021-10-14 10:19:48 +00:00
)
)
if len(paths) == 0:
echo(Fore.BLUE + "No files to check! 😢")
return paths
html_patterns = [re.compile(r"<!--\s*djlint\:on\s*-->")]
django_jinja_patterns = [
re.compile(r"\{#\s*djlint\:on\s*#\}"),
re.compile(r"\{%\s*comment\s*%\}\s*djlint\:on\s*\{%\s*endcomment\s*%\}"),
]
nunjucks_patterns = [re.compile(r"\{#\s*djlint\:on\s*#\}")]
handlebars_patterns = [re.compile(r"\{\{!--\s*djlint\:on\s*--\}\}")]
golang_patterns = [re.compile(r"\{\{-?\s*/\*\s*djlint\:on\s*\*/\s*-?\}\}")]
def no_pragma(config: Config, this_file: Path) -> bool:
"""Verify there is no pragma present."""
if config.require_pragma is False:
return True
with this_file.open(encoding="utf8") as open_file:
first_line = open_file.readline()
pragma_patterns = {
2021-12-11 12:26:09 +00:00
"html": html_patterns,
2021-10-14 10:19:48 +00:00
"django": django_jinja_patterns + html_patterns,
"jinja": django_jinja_patterns + html_patterns,
"nunjucks": nunjucks_patterns + html_patterns,
"handlebars": handlebars_patterns + html_patterns,
"golang": golang_patterns + html_patterns,
2021-12-11 13:26:19 +00:00
"angular": html_patterns,
2021-10-14 10:19:48 +00:00
"all": django_jinja_patterns
+ nunjucks_patterns
+ handlebars_patterns
+ golang_patterns
+ html_patterns,
}
return any(
re.match(pattern, first_line) for pattern in pragma_patterns[config.profile]
)