Skip to content
This repository has been archived by the owner on Oct 9, 2023. It is now read-only.

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
KOLANICH committed Oct 8, 2023
0 parents commit ee7c20a
Show file tree
Hide file tree
Showing 17 changed files with 311 additions and 0 deletions.
Empty file added .ci/aptPackagesToInstall.txt
Empty file.
Empty file.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
charset = utf-8
indent_style = tab
indent_size = 4
insert_final_newline = true
end_of_line = lf

[*.{yml,yaml}]
indent_style = space
indent_size = 2
1 change: 1 addition & 0 deletions .github/.templateMarker
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
KOLANICH/python_project_boilerplate.py
8 changes: 8 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
version: 2
updates:
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "daily"
allow:
- dependency-type: "all"
15 changes: 15 additions & 0 deletions .github/workflows/CI.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
name: CI
on:
push:
branches: [master]
pull_request:
branches: [master]

jobs:
build:
runs-on: ubuntu-22.04
steps:
- name: typical python workflow
uses: KOLANICH-GHActions/typical-python-workflow@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
__pycache__
*.py[co]
/*.egg-info
*.srctrlbm
*.srctrldb
build
dist
.eggs
monkeytype.sqlite3
/.ipynb_checkpoints
51 changes: 51 additions & 0 deletions .gitlab-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
image: registry.gitlab.com/kolanich-subgroups/docker-images/fixed_python:latest

variables:
DOCKER_DRIVER: overlay2
SAST_ANALYZER_IMAGE_TAG: latest
SAST_DISABLE_DIND: "true"
SAST_CONFIDENCE_LEVEL: 5
CODECLIMATE_VERSION: latest

include:
- template: SAST.gitlab-ci.yml
- template: Code-Quality.gitlab-ci.yml
- template: License-Management.gitlab-ci.yml

build:
tags:
- shared
- linux
stage: build
variables:
GIT_DEPTH: "1"
PYTHONUSERBASE: ${CI_PROJECT_DIR}/python_user_packages

before_script:
- export PATH="$PATH:$PYTHONUSERBASE/bin" # don't move into `variables`
- apt-get update
# todo:
#- apt-get -y install
#- pip3 install --upgrade
#- python3 ./fix_python_modules_paths.py

script:
- python3 -m build -nw bdist_wheel
- mv ./dist/*.whl ./dist/antiflash-0.CI-py3-none-any.whl
- pip3 install --upgrade ./dist/*.whl
- coverage run --source=antiflash -m --branch pytest --junitxml=./rspec.xml ./tests/test.py
- coverage report -m
- coverage xml

coverage: "/^TOTAL(?:\\s+\\d+){4}\\s+(\\d+%).+/"

cache:
paths:
- $PYTHONUSERBASE

artifacts:
paths:
- dist
reports:
junit: ./rspec.xml
cobertura: ./coverage.xml
1 change: 1 addition & 0 deletions Code_Of_Conduct.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
No codes of conduct!
4 changes: 4 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
include UNLICENSE
include *.md
include tests
include .editorconfig
17 changes: 17 additions & 0 deletions ReadMe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
antiflash.py [![Unlicensed work](https://raw.githubusercontent.com/unlicense/unlicense.org/master/static/favicon.png)](https://unlicense.org/)
============
~~[wheel (GitLab)](https://gitlab.com/KOLANICH-tools/antiflash.py/-/jobs/artifacts/master/raw/dist/antiflash-0.CI-py3-none-any.whl?job=build)~~
[wheel (GHA via `nightly.link`)](https://nightly.link/KOLANICH-tools/antiflash.py/workflows/CI/master/antiflash-0.CI-py3-none-any.whl)
~~![GitLab Build Status](https://gitlab.com/KOLANICH-tools/antiflash.py/badges/master/pipeline.svg)~~
~~![GitLab Coverage](https://gitlab.com/KOLANICH-tools/antiflash.py/badges/master/coverage.svg)~~
~~[![GitHub Actions](https://github.com/KOLANICH-tools/antiflash.py/workflows/CI/badge.svg)](https://github.com/KOLANICH-tools/antiflash.py/actions/)~~
[![Libraries.io Status](https://img.shields.io/librariesio/github/KOLANICH-tools/antiflash.py.svg)](https://libraries.io/github/KOLANICH-tools/antiflash.py)
[![Code style: antiflash](https://img.shields.io/badge/code%20style-antiflash-FFF.svg)](https://codeberg.org/KOLANICH-tools/antiflash.py)

A monkey-patch for `black` uncompromising Python source code reformatter, coercing it to use `tabs` for indentation instead of cargo cult `spaces`.

[`antiflash`](https://en.wikipedia.org/wiki/Anti-flash_white) is white coating applied to nuclear-carrying bombers to protect them from overheating from light emitted by nuclear explosion.

## Limitations
1. It monkey-patches `black` to use tabs. It doesn't create any branches in `black`. It just replaces hardcoded 4 spaces with a hardcoded `\t`. After the monkey-patch is applied, `black` itself will use tabs.
2. So, importing this package produces a side effect. So it is only useful in situations where only `antiflash` is needed, not `antiflash` and `black` simultaniously.
24 changes: 24 additions & 0 deletions UNLICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <https://unlicense.org/>
83 changes: 83 additions & 0 deletions antiflash/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import ast
import sys
import types
import typing
from pathlib import Path

from click.core import Command, Parameter


def patchSpacesBinOpAST(binOp: ast.BinOp) -> bool:
for sideName in ("left", "right"):
side = getattr(binOp, sideName)
if isinstance(side, ast.Constant) and side.value == " " * 4:
side.value = "\t"
return True

return False


def patchSpacesExprAST(e: ast.AST) -> bool:
if isinstance(e, ast.Assign):
if len(e.targets) == 1:
t0 = e.targets[0]
if isinstance(t0, ast.Name) and t0.id == "indent":
v = e.value
if isinstance(v, ast.BinOp) and isinstance(v.op, ast.Mult):
if patchSpacesBinOpAST(v):
return True
return False


def patchSpacesExprWithinFuncAST(f: ast.FunctionDef) -> typing.Optional[ast.FunctionDef]:
for el in f.body:
if patchSpacesExprAST(el):
return f
return None


def patchSpacesExprWithinFuncInClassAST(c: ast.ClassDef, funcToMonkeyPatch: str) -> typing.Optional[ast.FunctionDef]:
for el in c.body:
if isinstance(el, ast.FunctionDef) and el.name == funcToMonkeyPatch:
res = patchSpacesExprWithinFuncAST(el)
if res:
return res
return None


def patchSpacesExprWithinFuncInClassInModuleAST(m: ast.Module, classToMonkeyPatch: str, funcToMonkeyPatch: str) -> typing.Optional[ast.FunctionDef]:
for el in m.body:
if isinstance(el, ast.ClassDef) and el.name == classToMonkeyPatch:
res = patchSpacesExprWithinFuncInClassAST(el, funcToMonkeyPatch)
if res:
return res
return None


def patchSpacesExprWithinFuncInClassInModule(module: types.ModuleType, classToMonkeyPatch: str, funcToMonkeyPatch: str):
pathStr = module.__file__
if not pathStr:
raise ValueError("Module has no `__path__`", module)
path = Path(pathStr)
moduleAST = ast.parse(path.read_text("utf-8"))
modifiedFuncAST = patchSpacesExprWithinFuncInClassInModuleAST(moduleAST, classToMonkeyPatch, funcToMonkeyPatch)
clz = getattr(module, classToMonkeyPatch)

globalz = dict(module.__dict__) | dict(clz.__dict__)
monkeyPatchModule = ast.fix_missing_locations(ast.Module(body=[modifiedFuncAST], type_ignores=[]))
exec(compile(monkeyPatchModule, "<monkey-patch of " + classToMonkeyPatch + "." + funcToMonkeyPatch + ">", "exec"), globalz)
setattr(clz, funcToMonkeyPatch, globalz[funcToMonkeyPatch])


def applyPatch(black: types.ModuleType) -> None:
patchSpacesExprWithinFuncInClassInModule(black.lines, "Line", "__str__")


def indexClickParams(f: Command) -> typing.Dict[str, Parameter]:
return {el.name: el for el in f.params if el.name}


def patchDefaultParams(black: types.ModuleType, patchDict: typing.Dict[str, typing.Union[int, str]]) -> None:
paramsIndex = indexClickParams(black.main)
for k, v in patchDict.items():
paramsIndex[k].default = v
17 changes: 17 additions & 0 deletions antiflash/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from . import applyPatch, patchDefaultParams

defaultsPatch = {
"line_length": (1 << 64) - 1,
}


def main():
import black # pylint:disable=import-outside-toplevel

patchDefaultParams(black, defaultsPatch)
applyPatch(black)
black.patched_main()


if __name__ == "__main__":
main()
Empty file added antiflash/py.typed
Empty file.
44 changes: 44 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
[build-system]
requires = ["setuptools>=61.2.0", "setuptools_scm[toml]>=3.4.3"]
build-backend = "setuptools.build_meta"

[project]
name = "antiflash"
readme = "ReadMe.md"
description = "A monkey-patch for `black` uncompromising Python source code reformatter, coercing it to use tabs for indentation instead of cargo cult spaces."
authors = [{name = "KOLANICH"}]
classifiers = [
"Development Status :: 4 - Beta",
"Environment :: Other Environment",
"Intended Audience :: Developers",
"License :: Public Domain",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Topic :: Software Development :: Libraries :: Python Modules",
]
keywords = ["black", "white"]
license = {text = "Unlicense"}
requires-python = ">=3.4"
dynamic = ["version"]

[project.urls]
Homepage = "https://codeberg.org/KOLANICH-tools/antiflash.py"

[project.scripts]
antiflash = "antiflash.__main__:main"

[tool.setuptools]
zip-safe = true

[tool.setuptools.packages.find]
include = ["antiflash", "antiflash.*"]

[tool.setuptools_scm]

[tool.black]
line-length = 100500

[tool.isort]
profile = "black"
24 changes: 24 additions & 0 deletions tests/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
import unittest
import itertools, re

sys.path.insert(0, str(Path(__file__).parent.parent))

from collections import OrderedDict

dict = OrderedDict

import antiflash
from antiflash import *


class Tests(unittest.TestCase):

def testSimple(self):
raise NotImplementedError


if __name__ == "__main__":
unittest.main()

0 comments on commit ee7c20a

Please sign in to comment.