Skip to content

Commit

Permalink
icm info: refactorization
Browse files Browse the repository at this point in the history
  • Loading branch information
Obijuan committed Jun 17, 2024
1 parent 4fb18f6 commit cf6dcb1
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 66 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

deps: ## Install dependencies
python -m pip install --upgrade pip
python -m pip install black flake8 flit pylint pytest tox tox-gh-actions semantic_version polib tqdm
python -m pip install black flake8 flit pylint pytest tox tox-gh-actions semantic_version polib tqdm requests tqdm

cenv: ## Create the virtual-environment
python3 -m venv env
Expand Down
157 changes: 94 additions & 63 deletions icm/commands/cmd_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,37 +8,55 @@
# -- Author Juan Gonzalez (Obijuan)
# -- Licence GPLv2

from pathlib import Path
from tqdm import tqdm
import platform
import shutil
import requests
import zipfile
import os
from pathlib import Path
from typing import NamedTuple

import requests
import click
from tqdm import tqdm


# -- Terminal width
TERMINAL_WIDTH = shutil.get_terminal_size().columns
# -- Context information
class Context(NamedTuple):
"""general Context information"""

# -- Horizontal line
HLINE = "─" * TERMINAL_WIDTH
@property
def terminal_width(self) -> int:
"""Get the terminal with in columns"""
return shutil.get_terminal_size().columns

# -- Home user folder
HOME = Path.home()
@property
def line(self) -> str:
"""Return a line as long as the terminal width"""
return "─" * self.terminal_width

# -- Icestudio HOME dir
ICESTUDIO_HOME = HOME / ".icestudio"

# -- Icestudio root for collections
COLLECTIONS = ICESTUDIO_HOME / "collections"
# -- Folder information
class Folders(NamedTuple):
"""Icestudio related folders"""

@property
def home(self) -> Path:
"""Return the home user folder"""
return Path.home()

@property
def icestudio(self) -> Path:
"""Return the icestudio data folder"""
return self.home / ".icestudio"

@property
def collections(self) -> Path:
"""Return the icestudio collections folder"""
return self.icestudio / "collections"


# -- Information about collections
icek = {
"name": "iceK",
"version": "0.1.4"
}
icek = {"name": "iceK", "version": "0.1.4"}

# -- Collection file
COLLECTION_FILE = "v"
Expand All @@ -49,25 +67,14 @@
TEMPLATE_URL_SUFFIX = "/archive/refs/tags/"


# Función para dibujar la barra de progreso
def print_progress_bar(iteration, total, length=50):
percent = f"{100 * (iteration / float(total)):.1f}"
filled_length = int(length * iteration // total)
bar = '#' * filled_length + '-' * (length - filled_length)
print(f"\r|{bar}| {percent}%", end='')

def print_system_info(ctx: Context) -> None:
"""Print System information"""

def main():
"""ENTRY POINT: Show system information"""

# --------------------------------
# -- Print System information
# --------------------------------
# -- Header
print()
click.secho(HLINE, fg="green")
click.secho(ctx.line, fg="green")
click.secho("SYSTEM INFORMATION", fg="green")
click.secho(HLINE, fg="green")
click.secho(ctx.line, fg="green")

# -- Read system information
plat = platform.uname()
Expand All @@ -78,67 +85,92 @@ def main():
click.echo(click.style("• Release: ", fg="green") + f"{plat.release}")
click.echo(click.style("• Version: ", fg="green") + f"{plat.version}")

# ----------------------------
# -- System folders
# ----------------------------

def print_folders_info(ctx: Context, folders: Folders) -> None:
"""Print Sytem folders info"""

# -- Header
print()
click.secho(HLINE, fg="yellow")
click.secho(ctx.line, fg="yellow")
click.secho("FOLDERS", fg="yellow")
click.secho(HLINE, fg="yellow")
click.secho(ctx.line, fg="yellow")

# -- Check if all the folders exist or not
ok_home = HOME.exists()
ok_icestudio = ICESTUDIO_HOME.exists()
ok_collections = COLLECTIONS.exists()
ok_home = folders.home.exists()
ok_icestudio = folders.icestudio.exists()
ok_collections = folders.collections.exists()

# -- Choose the correct bullet for the folder
home_check = "✅ " if ok_home else "❌ "
icestudio_check = "✅ " if ok_icestudio else "❌ "
collections_check = "✅ " if ok_collections else "❌ "

# -- Print the information
click.echo(home_check + click.style("HOME: ", fg="yellow") + f"{HOME}")
click.echo(
home_check + click.style("HOME: ", fg="yellow") + f"{folders.home}"
)
click.echo(
icestudio_check
+ click.style("Icestudio: ", fg="yellow")
+ f"{ICESTUDIO_HOME}"
+ f"{folders.icestudio}"
)
click.echo(
collections_check
+ click.style("Collections: ", fg="yellow")
+ f"{COLLECTIONS}"
+ f"{folders.collections}"
)

print()


def main():
"""ENTRY POINT: Show system information"""

# -- Get context information
ctx = Context()
folders = Folders()

# --------------------------------
# -- Print System information
# --------------------------------
print_system_info(ctx)

# ----------------------------
# -- System folders
# ----------------------------
print_folders_info(ctx, folders)

# --- Scafold for the installation of collections
# -- Download url: https://github.com/FPGAwars/iceK/archive/refs/tags/v0.1.4.zip
# -- Download url:
# https://github.com/FPGAwars/iceK/archive/refs/tags/v0.1.4.zip
# -- Build the collection filename
filename = f"v{icek['version']}.zip"
print(f"Colection file: {filename}")

absolut_filename = f"{COLLECTIONS}/{filename}"
absolut_filename = f"{folders.collections}/{filename}"
print(f"Absolut filename: {absolut_filename}")

url = f"{TEMPLATE_URL_PREFIX}{icek['name']}{TEMPLATE_URL_SUFFIX}{filename}"
print(f"Url: {url}")

# -- Download the collection
# Realizar la solicitud HTTP para obtener el contenido del archivo
response = requests.get(url, stream=True)
response = requests.get(url, stream=True, timeout=10)

# Verificar que la solicitud se completó correctamente
if response.status_code == 200:

# Obtener el tamaño total del archivo desde los headers
total_size = int(response.headers.get('content-length', 0))
total_size = int(response.headers.get("content-length", 0))

# Abrir un archivo local con el nombre especificado en modo escritura binaria
with open(absolut_filename, 'wb') as file:
# Abrir un archivo local con el nombre especificado en
# modo escritura binaria
with open(absolut_filename, "wb") as file:

# Crear una barra de progreso con tqdm
with tqdm(total=total_size, unit='B', unit_scale=True, desc=filename) as pbar:
with tqdm(
total=total_size, unit="B", unit_scale=True, desc=filename
) as pbar:
# Iterar sobre el contenido en bloques
for chunk in response.iter_content(chunk_size=1024):
# Filtrar bloques vacíos
Expand All @@ -148,27 +180,31 @@ def main():
# Actualizar la barra de progreso
pbar.update(len(chunk))

# Utilizar shutil.copyfileobj para copiar el contenido del archivo descargado al archivo local
#shutil.copyfileobj(response.raw, file)
# shutil.copyfileobj(response.raw, file)
print(f"Archivo descargado y guardado como {filename}")
else:
print(f"Error al descargar el archivo. Código de estado: {response.status_code}")
print(
f"Error al descargar el archivo. "
f"Código de estado: {response.status_code}"
)

# -- Uncompress the collection

# Nombre del archivo ZIP
zip_filename = absolut_filename

# Directorio de destino para descomprimir los archivos
extract_to = COLLECTIONS
extract_to = folders.collections

# Abrir el archivo ZIP y extraer su contenido con barra de progreso
with zipfile.ZipFile(zip_filename, 'r') as zip_ref:
with zipfile.ZipFile(zip_filename, "r") as zip_ref:
# Obtener la lista de archivos en el archivo ZIP
file_list = zip_ref.namelist()

# Crear una barra de progreso
with tqdm(total=len(file_list), desc='Descomprimiendo', unit='file') as pbar:
with tqdm(
total=len(file_list), desc="Descomprimiendo", unit="file"
) as pbar:
# Iterar sobre cada archivo en el archivo ZIP
for file in file_list:
# Extraer cada archivo
Expand All @@ -178,8 +214,3 @@ def main():

# -- Borrar el archivo zip
os.remove(zip_filename)





2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ classifiers=[
'License :: OSI Approved :: GNU General Public License v2 (GPLv2)',
'Programming Language :: Python']
description-file = "README.md"
requires-python = ">=3.7"
requires-python = ">=3.9"

[tool.flit.scripts]
icm = "icm.__main__:cli"
Expand Down
4 changes: 3 additions & 1 deletion tox.ini
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tox]
isolated_build = True
envlist = py10
envlist = py3.9

[testenv]
deps =
Expand All @@ -11,6 +11,8 @@ deps =
pylint
semantic_version
polib
requests
tqdm
commands = black icm #-- Python formating
flake8 icm #-- python lint
pylint icm #-- python lint
Expand Down

0 comments on commit cf6dcb1

Please sign in to comment.