Skip to content

Commit

Permalink
Merge pull request #25 from efabless/migrate_to_poetry
Browse files Browse the repository at this point in the history
Migrate to Poetry
  • Loading branch information
donn authored Jul 15, 2024
2 parents 0cd884c + 10a1588 commit 1af1f02
Show file tree
Hide file tree
Showing 12 changed files with 715 additions and 142 deletions.
11 changes: 3 additions & 8 deletions .github/workflows/publish-to-pypi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,11 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.x'

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel twine
python-version: '3.8'

- name: Build package
run: |
python setup.py sdist bdist_wheel
make dist
- name: Publish package to PyPI
env:
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ share/python-wheels/
.installed.cfg
*.egg
MANIFEST
requirements_tmp.txt

# PyInstaller
# Usually these files are written by a python script from a template
Expand Down Expand Up @@ -129,4 +130,4 @@ dmypy.json
.pyre/

# ipm
/ip
/ip
24 changes: 12 additions & 12 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
FILE=./requirements_dev.txt

all: dist

.PHONY: dist
dist: venv/created
./venv/bin/python3 setup.py sdist bdist_wheel
dist: venv/manifest.txt
./venv/bin/poetry build

.PHONY: lint
lint: venv/created
lint: venv/manifest.txt
./venv/bin/black --check .
./venv/bin/flake8 .

venv: venv/created
venv/created: $(FILE)
venv: venv/manifest.txt
venv/manifest.txt: ./pyproject.toml
rm -rf venv
python3 -m venv ./venv
./venv/bin/python3 -m pip install wheel
./venv/bin/python3 -m pip install -r $(FILE)
touch venv/created
PYTHONPATH= ./venv/bin/python3 -m pip install --upgrade pip
PYTHONPATH= ./venv/bin/python3 -m pip install --upgrade wheel poetry poetry-plugin-export
PYTHONPATH= ./venv/bin/poetry export --with dev --without-hashes --format=requirements.txt --output=requirements_tmp.txt
PYTHONPATH= ./venv/bin/python3 -m pip install --upgrade -r requirements_tmp.txt
PYTHONPATH= ./venv/bin/python3 -m pip freeze > $@
@echo ">> Venv prepared."

.PHONY: veryclean
veryclean: clean
Expand All @@ -29,4 +29,4 @@ clean:
rm -rf build/
rm -rf logs/
rm -rf dist/
rm -rf *.egg-info
rm -rf *.egg-info
28 changes: 26 additions & 2 deletions ipm/__version__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright 2023 Efabless Corporation
# Copyright 2024 Efabless Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
Expand All @@ -11,7 +11,31 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__version__ = "1.0.2"
import os
import sys
import importlib.metadata


def __get_version():
try:
return importlib.metadata.version("ipmgr")
except importlib.metadata.PackageNotFoundError:
import re

rx = re.compile(r"version\s*=\s*\"([^\"]+)\"")
openlane_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
pyproject_path = os.path.join(openlane_directory, "pyproject.toml")
try:
match = rx.search(open(pyproject_path, encoding="utf8").read())
assert match is not None, "pyproject.toml found, but without a version"
return match[1]
except FileNotFoundError:
print("Warning: Failed to extract IPM version.", file=sys.stderr)
return "UNKNOWN"


__version__ = __get_version()


if __name__ == "__main__":
print(__version__, end="")
53 changes: 30 additions & 23 deletions ipm/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,11 +182,11 @@ def get_installed_ip_info(ipm_root):
config_path = yaml_file
else:
logger.print_err(
f"Can't find {json_file} or {yaml_file}. Please refer to the IPM directory structure (IP name {self.ip_name} might be wrong)."
f"Can't find {json_file} or {yaml_file}. Please refer to the IPM directory structure (IP name {ip_name} might be wrong)."
)
return False

if config_path.endswith('.json'):
if config_path.endswith(".json"):
with open(config_path) as config_file:
data = json.load(config_file)
else:
Expand All @@ -209,11 +209,11 @@ class IPRoot:

def __post_init__(self):
pathlib.Path(self.path).mkdir(parents=True, exist_ok=True)
gitignore_path = os.path.join(self.path, '.gitignore')
with open(gitignore_path, 'w') as gitignore_file:
gitignore_file.write('*\n')
gitignore_file.write('!dependencies.json\n')
gitignore_file.write('!.gitignore\n')
gitignore_path = os.path.join(self.path, ".gitignore")
with open(gitignore_path, "w") as gitignore_file:
gitignore_file.write("*\n")
gitignore_file.write("!dependencies.json\n")
gitignore_file.write("!.gitignore\n")

@property
def dependencies_path(self) -> str:
Expand Down Expand Up @@ -445,10 +445,11 @@ def _recursive(


def get_terminal_width():
try:
return os.get_terminal_size().columns
except OSError:
return 80 # Default width if terminal size can't be determined
try:
return os.get_terminal_size().columns
except OSError:
return 80 # Default width if terminal size can't be determined


@dataclass
class IP:
Expand Down Expand Up @@ -613,8 +614,12 @@ def create_table(ip_list, version=None, extended=False, local=False):
"License": value["license"],
"Width (um)": value["release"][versions]["width"],
"Height (um)": value["release"][versions]["height"],
"Voltage (v)": ",".join(value["release"][versions]["supply_voltage"]),
"Clk freq (MHz)": value["release"][versions]["clock_freq_mhz"]
"Voltage (v)": ",".join(
value["release"][versions]["supply_voltage"]
),
"Clk freq (MHz)": value["release"][versions][
"clock_freq_mhz"
],
}
if local:
data_dict = {
Expand All @@ -630,7 +635,7 @@ def create_table(ip_list, version=None, extended=False, local=False):
"Width (um)": value["info"]["width"],
"Height (um)": value["info"]["height"],
# "Voltage (v)": ",".join(value["info"]["supply_voltage"]),
"Clk freq (MHz)": value["info"]["clock_freq_mhz"]
"Clk freq (MHz)": value["info"]["clock_freq_mhz"],
}

for col_name, _, _ in included_columns:
Expand All @@ -644,7 +649,6 @@ def create_table(ip_list, version=None, extended=False, local=False):
else:
logger.print_err("No IPs found")


def download_tarball(self, dest_path, no_verify_hash=False):
"""downloads the release tarball
Expand Down Expand Up @@ -1070,11 +1074,11 @@ def list_verified_ips(category=None, technology=None):
# Check if the request was successful
if response.status_code == 200:
# Parse the HTML content of the webpage
soup = BeautifulSoup(response.content, 'html.parser')
soup = BeautifulSoup(response.content, "html.parser")
platform_ips = []
links = soup.find_all('a')
links = soup.find_all("a")
for link in links:
href = link.get('href')
href = link.get("href")
if "/design_catalog/ip_block/" in href:
text = link.text
if "View Details" not in text and "\n\n" not in text:
Expand All @@ -1086,11 +1090,15 @@ def list_verified_ips(category=None, technology=None):
if ip_data["category"] == category:
ip_list.append({ip_name: ip_data})
elif technology and not category:
if ip_data["technology"] == technology or ip_data["technology"] == "n/a":
if (
ip_data["technology"] == technology
or ip_data["technology"] == "n/a"
):
ip_list.append({ip_name: ip_data})
elif technology and category:
if ip_data["category"] == category and (
ip_data["technology"] == technology or ip_data["technology"] == "n/a"
ip_data["technology"] == technology
or ip_data["technology"] == "n/a"
):
ip_list.append({ip_name: ip_data})
else:
Expand Down Expand Up @@ -1124,6 +1132,7 @@ def list_installed_ips(ipm_root):
ip_data = IPInfo.get_installed_ip_info(ipm_root)
IP.create_table(ip_data, local=True, extended=True)


def update_ips(ipm_root, ip_root=None, ip_to_update=None):
"""checks if the ips installed have newer versions
Expand Down Expand Up @@ -1166,9 +1175,7 @@ def update_ips(ipm_root, ip_root=None, ip_to_update=None):
f"IP {ip_name} is the newest version [magenta]{version}[/magenta]."
)
else:
logger.print_warn(
f"No IPs in your project to be updated."
)
logger.print_warn("No IPs in your project to be updated.")


def check_ips(ipm_root, update=False, ip_root=None):
Expand Down
59 changes: 19 additions & 40 deletions ipm/version_check.py
Original file line number Diff line number Diff line change
@@ -1,68 +1,47 @@
import os
import json
from venv import logger
import requests
import pkg_resources
import subprocess
from datetime import datetime, timedelta

__dir__ = os.path.abspath(os.path.dirname(__file__))
version = subprocess.check_output(
[
"python3",
os.path.join(
__dir__,
"__version__.py",
),
],
encoding="utf8",
)
from .__version__ import __version__

def check_for_updates(logger):
package_name = 'ipmgr'
current_version = subprocess.check_output(
[
"python3",
os.path.join(
__dir__,
"__version__.py",
),
],
encoding="utf8",
)

config_file = os.path.join(os.path.expanduser('~'), '.ipm', 'ipm_package.json')
def check_for_updates(logger):
package_name = "ipmgr"
config_file = os.path.join(os.path.expanduser("~"), ".ipm", "ipm_package.json")

def load_last_check():
if os.path.exists(config_file):
with open(config_file, 'r') as f:
with open(config_file, "r") as f:
return json.load(f)
return {}

def save_last_check(data):
if not os.path.exists(os.path.join(os.path.expanduser('~'), '.ipm')):
os.mkdir(os.path.join(os.path.expanduser('~'), '.ipm'))
with open(config_file, 'w') as f:
if not os.path.exists(os.path.join(os.path.expanduser("~"), ".ipm")):
os.mkdir(os.path.join(os.path.expanduser("~"), ".ipm"))
with open(config_file, "w") as f:
json.dump(data, f)

config = load_last_check()
last_check = config.get('last_check')
last_check = config.get("last_check")

if last_check:
last_check_date = datetime.strptime(last_check, '%Y-%m-%d')
last_check_date = datetime.strptime(last_check, "%Y-%m-%d")
if datetime.now() - last_check_date < timedelta(days=1):
return

try:
response = requests.get(f'https://pypi.org/pypi/{package_name}/json')
response = requests.get(f"https://pypi.org/pypi/{package_name}/json")
response.raise_for_status()
latest_version = response.json()['info']['version']
latest_version = response.json()["info"]["version"]

if current_version < latest_version:
logger.print_warn(f"A new version ({latest_version}) of {package_name} is available. "
f"You're using version {current_version}. Please update using 'pip install --upgrade {package_name}'.")
if __version__ < latest_version:
logger.print_warn(
f"A new version ({latest_version}) of {package_name} is available. "
f"You're using version {__version__}. Please update using 'pip install --upgrade {package_name}'."
)

config['last_check'] = datetime.now().strftime('%Y-%m-%d')
config["last_check"] = datetime.now().strftime("%Y-%m-%d")
save_last_check(config)
except requests.exceptions.RequestException as e:
logger.print_err(f"Could not check for updates: {e}")
logger.print_err(f"Could not check for updates: {e}")
Loading

0 comments on commit 1af1f02

Please sign in to comment.