#!/usr/bin/env python3 """placeholder-check: fail the build when placeholder images would ship. Scans files and directories (typically your build output) for * references to placeholder-image hosts in text files (HTML, CSS, JS, JSON, ...) * image files that carry the via.placeholder.com detectability marker Zero dependencies, Python 3.8+, one file. Download: https://tools.placeholder.com/check/placeholder-check Usage: placeholder-check [options] [PATH ...] (default PATH: .) Exit codes: 0 nothing found (or --exit-zero) 1 placeholders found 2 usage error, or a PATH that doesn't exist / can't be read Inline opt-out: a line containing "placeholder-check: ignore" is skipped. """ import argparse import base64 import binascii import fnmatch import json import os import re import sys from urllib.parse import unquote __version__ = "1.0.0" DEFAULT_HOSTS = [ "via.placeholder.com", "placeholder.com", "data.placeholder.com", "placehold.co", "placehold.it", "placekitten.com", "picsum.photos", "dummyimage.com", "fakeimg.pl", "source.unsplash.com", "loremflickr.com", ] # Where this tool and its docs live: mentioning them is not shipping a placeholder. DEFAULT_ALLOW = ["tools.placeholder.com", "docs.placeholder.com"] TEXT_EXTS = set(""" html htm xhtml shtml css scss sass less styl js mjs cjs jsx ts mts cts tsx vue svelte astro md mdx markdown json jsonc json5 webmanifest xml rss atom yml yaml toml txt csv php erb hbs handlebars mustache njk liquid twig ejs pug jade haml jinja jinja2 j2 tpl tmpl cshtml razor jsp aspx rb py go java kt swift dart elm ini conf properties env """.split()) IMAGE_EXTS = {"png", "jpg", "jpeg", "jfif", "gif", "webp", "svg", "avif", "ico", "bmp", "tif", "tiff"} DEFAULT_IGNORES = ["node_modules", ".git", ".hg", ".svn", "*.map"] # The marker written by via.placeholder.com (renderer/marker.py) and, as a fallback, the host itself. MARKER = b"Placeholder image from via.placeholder.com" MARKER_ALT = (b"via.placeholder.com",) # The marker as it appears in SVG markup (also inline in HTML, or in url-encoded/utf8 data: URIs). SVG_MARKER_TEXT = re.compile( r'' r'|data-placeholder\s*=\s*[\'"]via\.placeholder\.com[\'"]' r'|Placeholder image from via\.placeholder\.com[^<"\']*') # Bundlers inline small images (Vite's default limit is 4 KB) as base64 data: URIs. DATA_B64 = re.compile(r"data:image/(?:png|jpe?g|gif|webp|svg\+xml|avif)[^,\"'\s]*;base64,([A-Za-z0-9+/=_-]{16,})", re.I) MARKER_ATTR = b'data-placeholder="via.placeholder.com"' IGNORE_LINE = "placeholder-check: ignore" MAX_SNIPPET = 160 def host_regex(hosts): alts = "|".join(re.escape(h.lower()) for h in sorted(set(hosts), key=len, reverse=True)) # optional scheme (also JSON-escaped https:\/\/), any subdomains, a host on a label boundary, then the path return re.compile( r"(?:(?:https?:)?(?:\\?/){2})?" r"(?()\[\]{}`\\,|^])*)?", re.I) def host_of(url): u = re.sub(r"^(?:https?:)?(?:\\?/){2}", "", url, flags=re.I) return re.split(r"[/?#:\\]", u, maxsplit=1)[0].lower() def base_host(host, hosts): """The configured host that host is (a subdomain of).""" for h in sorted(hosts, key=len, reverse=True): if host == h or host.endswith("." + h): return h return host class Checker: def __init__(self, hosts, allow, ignores, check_text=True, check_images=True, max_bytes=20 << 20, extra_exts=()): self.hosts = [h.lower() for h in hosts] self.rx = host_regex(self.hosts) if self.hosts and check_text else None self.allow = [a.lower() for a in allow] self.ignores = ignores self.check_text = check_text self.check_images = check_images self.max_bytes = max_bytes self.text_exts = TEXT_EXTS | {e.lower().lstrip(".") for e in extra_exts} self.findings = [] self.scanned = 0 self.errors = [] # -- selection def ignored(self, rel): rel = rel.replace(os.sep, "/") parts = rel.split("/") for pat in self.ignores: if fnmatch.fnmatch(rel, pat) or fnmatch.fnmatch(rel, pat.rstrip("/") + "/*"): return True if "/" not in pat.strip("/") and any(fnmatch.fnmatch(p, pat.strip("/")) for p in parts): return True return False def allowed(self, url): u = url.lower() bare = re.sub(r"^(?:https?:)?//", "", u) # globs match with or without the scheme h = host_of(u) for a in self.allow: if any(c in a for c in "*?["): if fnmatch.fnmatch(u, a) or fnmatch.fnmatch(bare, a) or fnmatch.fnmatch(h, a): return True elif a in u: return True return False def walk(self, root): if os.path.isfile(root): yield root return for dirpath, dirnames, filenames in os.walk(root): rel_dir = os.path.relpath(dirpath, root) rel_dir = "" if rel_dir == "." else rel_dir dirnames[:] = sorted(d for d in dirnames if not self.ignored(os.path.join(rel_dir, d))) for f in sorted(filenames): if not self.ignored(os.path.join(rel_dir, f)): yield os.path.join(dirpath, f) # -- scanning def scan_path(self, root): if not os.path.exists(root): self.errors.append(f"{root}: no such file or directory") return for path in self.walk(root): self.scan_file(path) def scan_file(self, path): ext = os.path.splitext(path)[1].lower().lstrip(".") is_text = ext in self.text_exts or ext == "svg" is_image = ext in IMAGE_EXTS if not ((is_text and (self.check_text or self.check_images)) or (is_image and self.check_images)): return try: if os.path.getsize(path) > self.max_bytes: return with open(path, "rb") as fh: data = fh.read() except OSError as e: self.errors.append(f"{path}: {e.strerror or e}") return self.scanned += 1 marked = False if is_image and self.check_images and (MARKER in data or (ext != "svg" and any(m in data for m in MARKER_ALT))): marked = True self.findings.append({"type": "marker", "file": path, "line": None, "column": None, "url": None, "host": "via.placeholder.com", "message": "image carries the via.placeholder.com placeholder marker"}) if is_text and (self.check_text or self.check_images): text = data.decode("utf-8", errors="replace") self.scan_text(path, text, inline_markers=ext != "svg") def marker_finding(self, path, lineno, col, what): self.findings.append({"type": "marker", "file": path, "line": lineno, "column": col, "url": None, "host": "via.placeholder.com", "message": f"{what} carries the via.placeholder.com placeholder marker"}) def scan_text(self, path, text, inline_markers=True): for lineno, line in enumerate(text.splitlines(), 1): if IGNORE_LINE in line: continue # JSON-escaped slashes and percent-encoding (next/image: /_next/image?url=https%3A%2F%2F...) work = line.replace("\\/", "/") if "%" in work: work = unquote(work) exact = work == line low = line.lower() seen = {} def col_of(pos, needle): if exact: return pos + 1 # decoded text has shifted offsets: point at the next occurrence of needle in the original line needle = needle.lower() i = low.find(needle, seen.get(needle, -1) + 1) if i >= 0: seen[needle] = i return (i if i >= 0 else 0) + 1 if self.check_images and inline_markers: m = SVG_MARKER_TEXT.search(work) if m: self.marker_finding(path, lineno, col_of(m.start(), "via.placeholder.com"), "inline SVG") for m in DATA_B64.finditer(work): data = m.group(1).replace("-", "+").replace("_", "/") try: raw = base64.b64decode(data + "=" * (-len(data) % 4)) except (binascii.Error, ValueError): continue if MARKER in raw or MARKER_ATTR in raw: self.marker_finding(path, lineno, col_of(m.start(), m.group()[:30]), "inlined data: image") if not self.rx: continue work = SVG_MARKER_TEXT.sub(lambda m: " " * len(m.group()), work) # the marker is not a URL reference for m in self.rx.finditer(work): url = m.group().rstrip(".;:") if m.start() and work[m.start() - 1] == "=": # a query-string value: ?url=https://...&w=640 url = url.split("&", 1)[0] if self.allowed(url): continue host = host_of(url) col = col_of(m.start(), host) start = max(0, col - 41) snippet = line[start:start + MAX_SNIPPET].strip() self.findings.append({"type": "url", "file": path, "line": lineno, "column": col, "url": url, "host": base_host(host, self.hosts), "snippet": snippet, "message": f"placeholder URL {url}"}) def gh_escape(s, prop=False): s = str(s).replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") if prop: s = s.replace(":", "%3A").replace(",", "%2C") return s def main(argv=None): p = argparse.ArgumentParser( prog="placeholder-check", description="Fail when placeholder images (via.placeholder.com, placehold.co, picsum.photos, ...) " "would ship. Scans text files for placeholder URLs and images for the " "via.placeholder.com marker.", epilog="Exit codes: 0 = clean, 1 = placeholders found, 2 = usage or read error.") p.add_argument("paths", nargs="*", default=["."], help="files or directories to scan (default: .)") p.add_argument("--hosts", help="comma-separated hosts to look for (replaces the default list)") p.add_argument("--add-host", action="append", default=[], metavar="HOST", help="extra host (repeatable)") p.add_argument("--allow", action="append", default=[], metavar="PATTERN", help="ignore URLs containing PATTERN, or matching it as a glob (repeatable; " "e.g. --allow 'picsum.photos/seed/*' --allow docs.example.com)") p.add_argument("--ignore", action="append", default=[], metavar="GLOB", help="skip paths matching GLOB, relative to each PATH (repeatable; e.g. 'docs/**', '*.md')") p.add_argument("--no-default-ignores", action="store_true", help="also scan " + ", ".join(DEFAULT_IGNORES)) p.add_argument("--ext", action="append", default=[], metavar="EXT", help="extra text extension to scan") p.add_argument("--no-images", action="store_true", help="don't look for the marker in image files") p.add_argument("--no-text", action="store_true", help="don't look for placeholder URLs in text files") p.add_argument("--max-size", type=int, default=20, metavar="MB", help="skip files larger than this (20)") p.add_argument("--json", action="store_true", help="print a JSON report on stdout") p.add_argument("--github", action="store_true", help="emit GitHub Actions annotations (default when GITHUB_ACTIONS=true)") p.add_argument("--exit-zero", action="store_true", help="report but always exit 0 (unless an error)") p.add_argument("-q", "--quiet", action="store_true", help="only print the summary") p.add_argument("--version", action="version", version="%(prog)s " + __version__) try: args = p.parse_args(argv) except SystemExit as e: return 2 if e.code not in (0, None) else 0 hosts = [h.strip() for h in args.hosts.split(",")] if args.hosts is not None else list(DEFAULT_HOSTS) hosts = [h for h in hosts + args.add_host if h] check_text = not args.no_text and bool(hosts) if not check_text and args.no_images: print("placeholder-check: error: nothing to look for (no hosts and --no-images)", file=sys.stderr) return 2 allow = DEFAULT_ALLOW + args.allow ignores = ([] if args.no_default_ignores else list(DEFAULT_IGNORES)) + args.ignore c = Checker(hosts, allow, ignores, check_text=check_text, check_images=not args.no_images, max_bytes=args.max_size << 20, extra_exts=args.ext) for path in args.paths: c.scan_path(path) files = sorted({f["file"] for f in c.findings}) code = 2 if c.errors else (1 if c.findings and not args.exit_zero else 0) if args.json: json.dump({"version": __version__, "ok": not c.findings, "exit_code": code, "scanned_files": c.scanned, "findings": c.findings, "errors": c.errors, "summary": {"findings": len(c.findings), "files": len(files), "by_host": _count(f["host"] for f in c.findings)}}, sys.stdout, indent=2) sys.stdout.write("\n") else: if not args.quiet: for f in c.findings: loc = f["file"] if f["line"] is None else f"{f['file']}:{f['line']}:{f['column']}" print(f"{loc}: {f['message']}") for e in c.errors: print(f"placeholder-check: error: {e}", file=sys.stderr) if c.findings: hosts_s = ", ".join(f"{h} ({n})" for h, n in sorted(_count(f["host"] for f in c.findings).items())) print(f"placeholder-check: {len(c.findings)} placeholder reference(s) in {len(files)} file(s) " f"[{hosts_s}]; scanned {c.scanned} file(s)") else: print(f"placeholder-check: no placeholders found; scanned {c.scanned} file(s)") if args.github or os.environ.get("GITHUB_ACTIONS") == "true": level = "warning" if args.exit_zero else "error" for f in c.findings: props = f"file={gh_escape(f['file'], True)}" if f["line"]: props += f",line={f['line']},col={f['column']}" print(f"::{level} {props},title=placeholder-check::{gh_escape(f['message'])}", file=sys.stderr if args.json else sys.stdout) return code def _count(items): out = {} for i in items: out[i] = out.get(i, 0) + 1 return out if __name__ == "__main__": sys.exit(main())