|
| 1 | +import asyncio |
| 2 | +import sys |
| 3 | +from concurrent.futures import ThreadPoolExecutor |
| 4 | +from functools import partial |
| 5 | +from os import cpu_count |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +from binaryornot.check import is_binary |
| 9 | +from plumbum import cli |
| 10 | + |
| 11 | +from .core import CombinedReplacerFactory |
| 12 | +from .core.InBufferReplacer import InBufferReplacer |
| 13 | +from .core.InFileReplacer import InFileReplacer |
| 14 | +from .replacers.HEReplacer import HEReplacer |
| 15 | +from .replacers.HSTSPreloadReplacer import HSTSPreloadReplacer |
| 16 | + |
| 17 | + |
| 18 | +class OurInBufferReplacer(InBufferReplacer): |
| 19 | + __slots__ = () |
| 20 | + FACS = CombinedReplacerFactory( |
| 21 | + { |
| 22 | + "preloads": HSTSPreloadReplacer, |
| 23 | + "heRulesets": HEReplacer, |
| 24 | + } |
| 25 | + ) |
| 26 | + |
| 27 | + def __init__(self, preloads=None, heRulesets=None): |
| 28 | + super().__init__(preloads=preloads, heRulesets=heRulesets) |
| 29 | + |
| 30 | + |
| 31 | +class OurInFileReplacer(InFileReplacer): |
| 32 | + def __init__(self, preloads=None, heRulesets=None): |
| 33 | + super().__init__(OurInBufferReplacer(preloads=preloads, heRulesets=heRulesets)) |
| 34 | + |
| 35 | + |
| 36 | +class CLI(cli.Application): |
| 37 | + """HTTPSEverywhere-like URI rewriter""" |
| 38 | + |
| 39 | + |
| 40 | +@CLI.subcommand("bulk") |
| 41 | +class FileRewriteCLI(cli.Application): |
| 42 | + """Rewrites URIs in files. Use - to consume list of files from stdin. Don't use `find`, it is a piece of shit which is impossible to configure to skip .git dirs.""" |
| 43 | + |
| 44 | + __slots__ = ("_repl",) |
| 45 | + |
| 46 | + @property |
| 47 | + def repl(self): |
| 48 | + if self._repl is None: |
| 49 | + self._repl = OurInFileReplacer() |
| 50 | + print( |
| 51 | + len(self._repl.inBufferReplacer.singleURIReplacer.children[0].preloads), |
| 52 | + "HSTS preloads", |
| 53 | + ) |
| 54 | + print( |
| 55 | + len(self._repl.inBufferReplacer.singleURIReplacer.children[1].rulesets), "HE rules" |
| 56 | + ) |
| 57 | + return self._repl |
| 58 | + |
| 59 | + def processEachFileName(self, l): |
| 60 | + l = l.strip() |
| 61 | + if l: |
| 62 | + l = l.decode("utf-8") |
| 63 | + return self.processEachFilePath(Path(l).resolve().absolute()) |
| 64 | + |
| 65 | + def processEachFilePath(self, p): |
| 66 | + for pa in p.parts: |
| 67 | + if not self.noSkipDot and pa[0] == ".": |
| 68 | + print("Skipping ", p, ": dotfile") |
| 69 | + return |
| 70 | + |
| 71 | + if not p.is_dir(): |
| 72 | + if self.noSkipBinary or not is_binary(p): |
| 73 | + self.repl(p) |
| 74 | + else: |
| 75 | + print("Skipping ", p, ": binary") |
| 76 | + |
| 77 | + @asyncio.coroutine |
| 78 | + def asyncMainPathsFromStdIn(self): |
| 79 | + conc = [] |
| 80 | + asyncStdin = asyncio.StreamReader(loop=self.loop) |
| 81 | + yield from self.loop.connect_read_pipe( |
| 82 | + lambda: asyncio.StreamReaderProtocol(asyncStdin, loop=self.loop), sys.stdin |
| 83 | + ) |
| 84 | + with ThreadPoolExecutor(max_workers=cpu_count()) as pool: |
| 85 | + while not asyncStdin.at_eof(): |
| 86 | + l = yield from asyncStdin.readline() |
| 87 | + yield from self.loop.run_in_executor(pool, partial(self.processEachFileName, l)) |
| 88 | + |
| 89 | + @asyncio.coroutine |
| 90 | + def asyncMainPathsFromCLI(self, filesOrDirs): |
| 91 | + try: |
| 92 | + from tqdm import tqdm |
| 93 | + except ImportError: |
| 94 | + |
| 95 | + def tqdm(x): |
| 96 | + return x |
| 97 | + |
| 98 | + for fileOrDir in tqdm(filesOrDirs): |
| 99 | + fileOrDir = Path(fileOrDir).resolve().absolute() |
| 100 | + if fileOrDir.is_dir(): |
| 101 | + files = [el for el in fileOrDir.glob("**/*") if not el.is_dir()] |
| 102 | + print(files) |
| 103 | + else: |
| 104 | + files = [fileOrDir] |
| 105 | + |
| 106 | + if files: |
| 107 | + with ThreadPoolExecutor(max_workers=cpu_count()) as pool: |
| 108 | + for f in files: |
| 109 | + yield from self.loop.run_in_executor(pool, partial(self.processEachFilePath, f)) |
| 110 | + |
| 111 | + noSkipBinary = cli.Flag( |
| 112 | + ["--no-skip-binary", "-n"], |
| 113 | + help="Don't skip binary files. Allows usage without `binaryornot`", |
| 114 | + default=False, |
| 115 | + ) |
| 116 | + noSkipDot = cli.Flag( |
| 117 | + ["--no-skip-dotfiles", "-d"], |
| 118 | + help="Don't skip files and dirs which name stem begins from dot.", |
| 119 | + default=False, |
| 120 | + ) |
| 121 | + |
| 122 | + def main(self, *filesOrDirs): |
| 123 | + self._repl = None |
| 124 | + self.loop = asyncio.get_event_loop() |
| 125 | + |
| 126 | + if len(filesOrDirs) == 1 and filesOrDirs[0] == "0": |
| 127 | + t = self.loop.create_task(self.asyncMainPathsFromStdIn()) |
| 128 | + else: |
| 129 | + t = self.loop.create_task(self.asyncMainPathsFromCLI(filesOrDirs)) |
| 130 | + self.loop.run_until_complete(t) |
| 131 | + |
| 132 | + |
| 133 | +if __name__ == "__main__": |
| 134 | + CLI.run() |
0 commit comments