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

AARD-1710: Exporter auto formatter updates #985

Merged
merged 23 commits into from
Jun 27, 2024
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
33 changes: 31 additions & 2 deletions .github/workflows/BlackFormat.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,37 @@ jobs:
name: Black Formatter for Python Exporter
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: psf/black@stable
- name: Checkout Code
uses: actions/checkout@v2
- name: Python Setup
uses: actions/setup-python@v2
with:
python-version: '3.9'
- name: Setup Isort
run: python3 -m pip install isort
- name: Validate Isort Formatting
run: |
python - <<'EOF'
import os, subprocess, sys

EXPORTER_DIR = "exporter/SynthesisFusionAddin"
files = (lambda d: [os.path.abspath(os.path.join(root, filename)) for root, _, filenames in os.walk(d)
for filename in filenames if filename.endswith(".py")])(EXPORTER_DIR)
oldFileStates = [open(file, "r").readlines() for file in files]
subprocess.call(["isort", EXPORTER_DIR], bufsize=1, shell=False)
newFileStates = [open(file, "r").readlines() for file in files]
exitCode = 0
for i, (oldFileState, newFileState) in enumerate(zip(oldFileStates, newFileStates)):
for j, (previousLine, newLine) in enumerate(zip(oldFileState, newFileState)):
if previousLine != newLine:
print(f"File {files[i]} is not formatted correctly!\nLine: {j + 1}")
exitCode = 1

if not exitCode: print("All files are formatted correctly with isort!")
sys.exit(exitCode)
EOF
BrandonPacewic marked this conversation as resolved.
Show resolved Hide resolved
- name: Validate Black Formatting
uses: psf/black@stable
with:
options: "--check"
src: "./exporter/SynthesisFusionAddin/"
6 changes: 3 additions & 3 deletions exporter/SynthesisFusionAddin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ Contact us for information on how to use the packaging script to obfuscate all o

### How to Format

We format using a Python formatter called `black` [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
We format using a Python formatter called `black` [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) in conjunction with [`isort`](https://pycqa.github.io/isort/).

- install by `pip3 install black` or `pip install black`
- use `black ./src`, Formats all files in src directory
- install by `pip3 install black && pip3 install isort` or `pip install black && pip install isort`
- use `isort .` followed by `black .` to format all relevant exporter python files.

__Note: black will always ignore files in the proto/proto_out folder since google formats those__
35 changes: 14 additions & 21 deletions exporter/SynthesisFusionAddin/Synthesis.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
from .src.general_imports import root_logger, gm, INTERNAL_ID, APP_NAME, DESCRIPTION

from .src.UI import HUI, Handlers, Camera, Helper, ConfigCommand
from .src.UI.Toolbar import Toolbar
from .src.Types.OString import OString
from .src.configure import setAnalytics, unload_config

import importlib.util
import logging.handlers
import os
import traceback
from shutil import rmtree
import logging.handlers, traceback, importlib.util, os

from .src.UI import MarkingMenu
import adsk.core

from .src.configure import setAnalytics, unload_config
from .src.general_imports import APP_NAME, DESCRIPTION, INTERNAL_ID, gm, root_logger
from .src.Types.OString import OString
from .src.UI import HUI, Camera, ConfigCommand, Handlers, Helper, MarkingMenu
from .src.UI.Toolbar import Toolbar


def run(_):
"""## Entry point to application from Fusion 360.
Expand All @@ -32,9 +33,7 @@ def run(_):
MarkingMenu.setupMarkingMenu(ui)

except:
logging.getLogger(f"{INTERNAL_ID}").error(
"Failed:\n{}".format(traceback.format_exc())
)
logging.getLogger(f"{INTERNAL_ID}").error("Failed:\n{}".format(traceback.format_exc()))


def stop(_):
Expand Down Expand Up @@ -74,9 +73,7 @@ def stop(_):

path = os.path.abspath(os.path.dirname(__file__))

path_proto_files = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "proto", "proto_out")
)
path_proto_files = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "proto", "proto_out"))

if path in sys.path:
sys.path.remove(path)
Expand All @@ -85,9 +82,7 @@ def stop(_):
sys.path.remove(path_proto_files)

except:
logging.getLogger(f"{INTERNAL_ID}").error(
"Failed:\n{}".format(traceback.format_exc())
)
logging.getLogger(f"{INTERNAL_ID}").error("Failed:\n{}".format(traceback.format_exc()))


def unregister_all() -> None:
Expand All @@ -105,9 +100,7 @@ def unregister_all() -> None:
tab.deleteMe()

except:
logging.getLogger(f"{INTERNAL_ID}").error(
"Failed:\n{}".format(traceback.format_exc())
)
logging.getLogger(f"{INTERNAL_ID}").error("Failed:\n{}".format(traceback.format_exc()))


def register_ui() -> None:
Expand Down
36 changes: 16 additions & 20 deletions exporter/SynthesisFusionAddin/proto/deps.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import logging
import os
import platform
import logging
from pathlib import Path

from src.general_imports import INTERNAL_ID
import adsk.core
import adsk.fusion

import adsk.core, adsk.fusion
from src.general_imports import INTERNAL_ID

system = platform.system()

Expand All @@ -21,8 +22,8 @@ def getPythonFolder() -> str:
"""

# Thank you Kris Kaplan
import sys
import importlib.machinery
import sys

osPath = importlib.machinery.PathFinder.find_spec("os", sys.path).origin

Expand All @@ -32,9 +33,7 @@ def getPythonFolder() -> str:
elif system == "Darwin":
pythonFolder = f"{Path(osPath).parents[2]}/bin"
else:
raise ImportError(
"Unsupported platform! This add-in only supports windows and macos"
)
raise ImportError("Unsupported platform! This add-in only supports windows and macos")

logging.getLogger(f"{INTERNAL_ID}").debug(f"Python Folder -> {pythonFolder}")
return pythonFolder
Expand Down Expand Up @@ -89,9 +88,7 @@ def installCross(pipDeps: list) -> bool:
try:
pythonFolder = getPythonFolder()
except ImportError as e:
logging.getLogger(f"{INTERNAL_ID}").error(
f"Failed to download dependencies: {e.msg}"
)
logging.getLogger(f"{INTERNAL_ID}").error(f"Failed to download dependencies: {e.msg}")
return False

if system == "Darwin": # macos
Expand All @@ -108,9 +105,9 @@ def installCross(pipDeps: list) -> bool:

executeCommand([f'"{pythonFolder}/python"', f'"{pythonFolder}/get-pip.py"'])

pythonExecutable = 'python'
pythonExecutable = "python"
if system == "Windows":
pythonExecutable = 'python.exe'
pythonExecutable = "python.exe"

for depName in pipDeps:
progressBar.progressValue += 1
Expand All @@ -120,17 +117,15 @@ def installCross(pipDeps: list) -> bool:
# os.path.join needed for varying system path separators
installResult = executeCommand(
[
f"\"{os.path.join(pythonFolder, pythonExecutable)}\"",
f'"{os.path.join(pythonFolder, pythonExecutable)}"',
"-m",
"pip",
"install",
depName,
]
)
if installResult != 0:
logging.getLogger(f"{INTERNAL_ID}").warn(
f'Dep installation "{depName}" exited with code "{installResult}"'
)
logging.getLogger(f"{INTERNAL_ID}").warn(f'Dep installation "{depName}" exited with code "{installResult}"')

if system == "Darwin":
pipAntiDeps = ["dataclasses", "typing"]
Expand All @@ -142,7 +137,7 @@ def installCross(pipDeps: list) -> bool:
adsk.doEvents()
uninstallResult = executeCommand(
[
f"\"{os.path.join(pythonFolder, pythonExecutable)}\"",
f'"{os.path.join(pythonFolder, pythonExecutable)}"',
"-m",
"pip",
"uninstall",
Expand All @@ -165,7 +160,7 @@ def installCross(pipDeps: list) -> bool:

def _checkDeps() -> bool:
try:
from .proto_out import joint_pb2, assembly_pb2, types_pb2, material_pb2
from .proto_out import assembly_pb2, joint_pb2, material_pb2, types_pb2

return True
except ImportError:
Expand All @@ -174,10 +169,11 @@ def _checkDeps() -> bool:

try:
import logging.handlers

import google.protobuf
import pkg_resources

from .proto_out import joint_pb2, assembly_pb2, types_pb2, material_pb2
from .proto_out import assembly_pb2, joint_pb2, material_pb2, types_pb2
except ImportError or ModuleNotFoundError:
installCross(["protobuf==4.23.3"])
from .proto_out import joint_pb2, assembly_pb2, types_pb2, material_pb2
from .proto_out import assembly_pb2, joint_pb2, material_pb2, types_pb2
23 changes: 18 additions & 5 deletions exporter/SynthesisFusionAddin/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
[build-system]
requires = ["protobuf", "black", "pyminifier"]
requires = ["protobuf", "isort", "black", "pyminifier"]

[tool.isort]
py_version = 39
profile = "black"
skip = [
"*.git/",
"*.venv",
"/build/",
"/docs/",
"/logs/",
".vscode/",
"/dist/",
"proto/proto_out",
]

[tool.black]
line-length = 90
line-length = 120
target-version = ['py39']
include = '\.pyi?$'
exclude = '''
Expand All @@ -13,10 +27,9 @@ exclude = '''
| build
| docs
| logs
| proto
| .vscode
| dist
| src/proto_out
| proto_out
)/
)
'''
'''
2 changes: 1 addition & 1 deletion exporter/SynthesisFusionAddin/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
black
pyminifier
pyminifier
2 changes: 1 addition & 1 deletion exporter/SynthesisFusionAddin/src/Analytics/alert.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from ..general_imports import gm
from ..configure import setAnalytics
from ..general_imports import gm


def showAnalyticsAlert():
Expand Down
13 changes: 7 additions & 6 deletions exporter/SynthesisFusionAddin/src/Analytics/poster.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from ..general_imports import *
from ..configure import CID, ANALYTICS, DEBUG
import sys
import urllib

import adsk.core

import urllib, sys, adsk.core
from ..configure import ANALYTICS, CID, DEBUG
from ..general_imports import *

# Reference https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters

Expand Down Expand Up @@ -169,9 +172,7 @@ def __send(self, body) -> bool:
if DEBUG:
self.logger.debug(f"Sending request: \n {url}")

req = urllib.request.Request(
f"{self.url}/collect?{body}", data=b"", headers=headers
)
req = urllib.request.Request(f"{self.url}/collect?{body}", data=b"", headers=headers)
# makes the request
response = urllib.request.urlopen(req)

Expand Down
13 changes: 8 additions & 5 deletions exporter/SynthesisFusionAddin/src/Analyzer/sniff.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
""" Takes in a given function call and times and tests the memory allocations to get data
"""

from ..general_imports import *
import inspect
import linecache
import os
import time
import tracemalloc
from time import time
import tracemalloc, time, linecache, os, inspect

from ..general_imports import *


class Sniffer:
def __init__(self):
self.logger = logging.getLogger(f"{INTERNAL_ID}.Analyzer.Sniffer")

(self.filename, self.line_number, _, self.lines, _) = inspect.getframeinfo(
inspect.currentframe().f_back.f_back
)
(self.filename, self.line_number, _, self.lines, _) = inspect.getframeinfo(inspect.currentframe().f_back.f_back)

self.stopped = False

Expand Down
6 changes: 4 additions & 2 deletions exporter/SynthesisFusionAddin/src/Analyzer/timer.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
""" Takes in a given function call and times and tests the memory allocations to get data
"""

from ..general_imports import *
import inspect
import os
from time import time
import os, inspect

from ..general_imports import *


class Timer:
Expand Down
5 changes: 4 additions & 1 deletion exporter/SynthesisFusionAddin/src/GlobalManager.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
""" Initializes the global variables that are set in the run method to reduce hanging commands. """

import adsk.core, adsk.fusion, traceback
import inspect
import traceback

import adsk.core
import adsk.fusion

from .general_imports import *
from .strings import *
Expand Down
Loading
Loading