Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[REVISION] 25.1 #11

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 0 additions & 14 deletions docker/Dockerfile

This file was deleted.

66 changes: 0 additions & 66 deletions docker/build.py

This file was deleted.

15 changes: 15 additions & 0 deletions linpgtoolbox/__docker/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
FROM python:3.PYTHON_VERSION_MINOR

# Create a working directory
WORKDIR /app

# Copy the contents to the container
COPY PROJECT_NAME /app/PROJECT_NAME

# Set the working directory to the target folder
WORKDIR /app/PROJECT_NAME

# compile and pack project
RUN python3 -m pip install linpgtoolbox
RUN linpgtb -c .
RUN linpgtb -p
44 changes: 6 additions & 38 deletions linpgtoolbox/_compiler.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,19 @@
import os
from typing import Any

import mypy.stubgen

# setuptools.setup import不可以在Cython.Build之后
from setuptools import Extension, setup # type: ignore
from setuptools import setup # type: ignore
from Cython.Build import cythonize # type: ignore


# 编译方法
def _compile_file(
_source_folder: str,
_path: str,
_keep_c: bool,
_debug_mode: bool,
extra_compile_args: dict[str, list[str]],
_source_folder: str, _path: str, _keep_c: bool, _debug_mode: bool
) -> None:
setup(
ext_modules=cythonize(
(
_path
if _path.endswith(".py")
else [
Extension(
os.path.splitext(os.path.basename(_path))[0],
[_path],
extra_compile_args=extra_compile_args.get(
os.path.basename(_path), []
),
)
]
),
_path,
show_all_warnings=_debug_mode,
annotate=_debug_mode,
language_level="3",
Expand Down Expand Up @@ -65,6 +48,7 @@ def _compile_file(
from glob import glob
from multiprocessing import Process
from tempfile import gettempdir
from typing import Any

# 加载全局参数
_data_path: str = os.path.join(
Expand All @@ -82,10 +66,6 @@ def _compile_file(
_source_folder: str = str(_data["source_folder"])
# 需要忽略的文件的关键词
_ignores: tuple[str, ...] = tuple(_data["ignores"])
# 额外args
extra_compile_args: dict[str, list[str]] = dict(
_data.get("extra_compile_args", {})
)

# 移除参数文件
os.remove(_data_path)
Expand All @@ -112,24 +92,12 @@ def __generate_process(cls, _path: str) -> None:
cls.__processes.append(
Process(
target=_compile_file,
args=(
_source_folder,
_path,
_keep_c,
_debug_mode,
extra_compile_args,
),
args=(_source_folder, _path, _keep_c, _debug_mode),
)
)
# 如果不使用多线程
else:
_compile_file(
_source_folder,
_path,
_keep_c,
_debug_mode,
extra_compile_args,
)
_compile_file(_source_folder, _path, _keep_c, _debug_mode)
elif "pyinstaller" not in _path and "pycache" not in _path:
if not cls.__if_ignore(_path):
for file_in_dir in glob(os.path.join(_path, "*")):
Expand Down
35 changes: 31 additions & 4 deletions linpgtoolbox/_execute.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,36 @@
import sys
from subprocess import check_call

# the python version of current environment
_DEFAULT_PYTHON_VERSION: str = f"{sys.version_info.major}.{sys.version_info.minor}"

# the version that currently selected for commands
_SELECTED_PYTHON_VERSION: str = _DEFAULT_PYTHON_VERSION


# if the current platform is windows
def is_using_windows() -> bool:
return sys.platform.startswith("win")


# execute a python commend
def execute_python(*cmd: str, cwd: str | None = None) -> None:
if sys.platform.startswith("win"):
check_call(["py", f"-3.{sys.version_info.minor}", *cmd], cwd=cwd)
else:
check_call([f"python3.{sys.version_info.minor}", *cmd], cwd=cwd)
check_call(
(
["py", f"-{_SELECTED_PYTHON_VERSION}", *cmd]
if is_using_windows()
else [f"python{_SELECTED_PYTHON_VERSION}", *cmd]
),
cwd=cwd,
)


# set the python version used for commands
def set_python_version(v: str = _DEFAULT_PYTHON_VERSION) -> None:
global _SELECTED_PYTHON_VERSION
_SELECTED_PYTHON_VERSION = v


# get the version of current python selected
def get_current_python_version() -> list[str]:
return _SELECTED_PYTHON_VERSION.split(".")
86 changes: 86 additions & 0 deletions linpgtoolbox/_fixer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import os
import re
from pathlib import Path


class Fixer:

@classmethod
def match_case_to_if_else(cls, path: str) -> None:
if os.path.isdir(path):
for p in list(Path(path).rglob("*.py")):
cls.__match_case_to_if_else(str(p))
else:
cls.__match_case_to_if_else(path)

@staticmethod
def __match_case_to_if_else(input_file: str) -> None:
# read python script content
with open(input_file, "r", encoding="utf-8") as f:
script_content: str = f.read()

# if not match/case are found, then there is no reason to continue
if not "match" in script_content or not "case" in script_content:
return

# output lines
converted_lines: list[str] = []
# indents stack
indents: list[str] = []
# match var stack
match_vars: list[str] = []
# if hit if and start elif
hit_if: bool = False

for line in script_content.splitlines():
# remove indents in front for better matching
line_stripped: str = line.strip()
# get the indents
line_indent: str = re.match(r"^(\s*)", line).group(1) # type: ignore

# if we hit a match
if line_stripped.startswith("match"):
# flip the flag to start with if
hit_if = False
# capture indentation
indents.append(line_indent)
# extract the match variable
match_vars.append(line_stripped.split(" ")[1].rstrip(":"))
continue

# a smaller indent indicates the end of current match block
if len(indents) > 0 and 0 < len(line_indent) <= len(indents[-1]):
indents.pop()
match_vars.pop()

# if the line is not a case statement, then add the line and continue
if len(indents) <= 0 or not line_stripped.startswith("case"):
# Copy other lines unchanged
converted_lines.append(line)
continue

# extract the case condition
condition: str = line_stripped.split("case")[1].strip().rstrip(":")
# if condition is _, that indicates a else
if condition == "_":
converted_lines.append(f"{indents[-1]}else:")
else:
condition = (
f"in ({','.join(condition.split('|'))})"
if "|" in condition
else f"== {condition}"
)
# First case becomes 'if', others become 'elif'
if not hit_if:
converted_lines.append(
f"{indents[-1]}if {match_vars[-1]} {condition}:"
)
hit_if = True
else:
converted_lines.append(
f"{indents[-1]}elif {match_vars[-1]} {condition}:"
)

# write the modified python script content back
with open(input_file, "w", encoding="utf-8") as f:
f.write("\n".join(converted_lines))
Loading