SXXXXXXX_DependencyAnalyzer/README.md
2025-05-06 14:47:12 +02:00

180 lines
9.5 KiB
Markdown

# Dependency Analyzer
Un'applicazione GUI per analizzare le dipendenze di progetti Python, generare `requirements.txt`, scaricare pacchetti offline e confrontare ambienti.
---
[English Version Below](#english)
---
## Dependency Analyzer (Italiano)
### Introduzione
`Dependency Analyzer` è uno strumento desktop (con interfaccia grafica costruita usando Tkinter) che semplifica la gestione delle dipendenze per progetti Python. Analizza staticamente il codice sorgente per identificare i moduli importati, distinguendo tra librerie standard e pacchetti esterni.
L'obiettivo è fornire un modo semplice per:
1. Ottenere un elenco chiaro delle dipendenze esterne di un progetto.
2. Generare un file `requirements.txt` dettagliato e informativo.
3. Preparare i pacchetti per una distribuzione offline.
4. Confrontare le dipendenze richieste con l'ambiente di sviluppo corrente.
### Caratteristiche Principali
* **Interfaccia Grafica Semplice:** Basata su Tkinter per un utilizzo intuitivo.
* **Selezione Cartella Flessibile:** Analizza l'intera cartella selezionata o una sottocartella specifica se segue la convenzione `nomeprogetto_minuscolo/`.
* **Analisi Statica (AST):** Esamina i file `.py` per trovare le istruzioni `import` senza eseguire il codice.
* **Generazione `requirements.txt` Dettagliata:**
* Include la versione Python dell'ambiente di analisi.
* Elenca i moduli standard utilizzati con i file sorgente di riferimento.
* Elenca le dipendenze esterne con:
* Nome pacchetto PyPI corretto (es. `Pillow` da `import PIL`).
* Versione rilevata nell'ambiente di analisi (se disponibile).
* File sorgente in cui è stato trovato l'import.
* **Download Pacchetti Offline:** Scarica le dipendenze esterne e le loro dipendenze nella sottocartella `_req_packages`.
* **Script di Installazione:** Genera `install_packages.bat`/`.sh` in `_req_packages` per una facile installazione offline su altre macchine (con controllo `pip` integrato e percorsi relativi).
* **Confronto Ambiente:** Mostra una tabella che confronta le dipendenze richieste con i pacchetti attualmente installati.
* **Aggiornamento Ambiente (Opzionale):** Permette di installare/aggiornare pacchetti selezionati direttamente nell'ambiente corrente (**Usare con cautela, preferibilmente in ambienti virtuali!**).
* **Logging in Tempo Reale:** Visualizza i log delle operazioni direttamente nell'interfaccia grafica.
### Prerequisiti
* **Python 3:** Raccomandato Python 3.7+
* **Pip:** Deve essere installato e accessibile.
* **(Opzionale ma Consigliato):** `pip install packaging` (per un confronto delle versioni più accurato).
### Installazione / Setup
1. Clona o scarica questo repository.
2. Assicurati che la struttura sia:
```
<qualche_cartella>/
└── dependencyanalyzer/
├── __init__.py
├── __main__.py
├── core.py
└── gui.py
```
3. Non è richiesta un'installazione separata tramite `pip` per lo strumento stesso, viene eseguito come modulo.
### Utilizzo
1. Apri un terminale o prompt dei comandi.
2. Naviga (**`cd`**) nella cartella che **contiene** la directory `dependencyanalyzer`.
3. Esegui lo strumento usando il flag `-m` di Python:
```bash
python -m dependencyanalyzer
```
*(Se hai rinominato la cartella `dependencyanalyzer`, usa quel nome nel comando).*
4. L'interfaccia grafica apparirà. Segui i passaggi numerati:
* **1. Select Repository Folder:** Scegli la cartella del progetto Python da analizzare.
* **2. Analyze Project & Generate requirements.txt:** Avvia l'analisi e la creazione del file.
* **3. External Dependencies Found:** Visualizza le dipendenze esterne trovate.
* **4. Download / Create Installers:** Scarica i pacchetti o genera gli script per l'offline.
* **5. System Package Comparison:** Confronta con l'ambiente locale ed eventualmente aggiorna (con cautela).
* **Log Messages:** Monitora l'output e i progressi.
### Come Funziona (Breve Panoramica Tecnica)
* Utilizza il modulo `ast` per creare un Abstract Syntax Tree del codice Python e trovare nodi `Import` e `ImportFrom`.
* Usa `sysconfig`, `importlib.util.find_spec` e una lista predefinita per distinguere i moduli standard da quelli esterni.
* Applica una mappatura (es. `PIL` -> `Pillow`) per usare i nomi corretti dei pacchetti PyPI.
* Utilizza `importlib.metadata.version` per rilevare le versioni installate.
* Invoca `pip` tramite `subprocess` per le operazioni di download, elenco e aggiornamento.
* Usa `tkinter.ttk` per la GUI e `logging` per mostrare i messaggi nell'interfaccia.
### Limitazioni Note
* Non rileva import dinamici (`importlib.import_module`).
* Non gestisce dipendenze non-Python.
* L'identificazione dei moduli interni si basa su convenzioni di base e potrebbe non essere perfetta per strutture di progetto molto complesse.
* Le versioni nel `requirements.txt` riflettono l'ambiente di analisi; non risolve attivamente i vincoli da `setup.py` o `pyproject.toml` durante la generazione iniziale.
---
## Dependency Analyzer (English)
### Introduction
`Dependency Analyzer` is a desktop application (with a GUI built using Tkinter) that simplifies dependency management for Python projects. It statically analyzes source code to identify imported modules, distinguishing between standard libraries and external packages.
The goal is to provide an easy way to:
1. Get a clear list of a project's external dependencies.
2. Generate a detailed and informative `requirements.txt` file.
3. Prepare packages for offline distribution.
4. Compare required dependencies against the current development environment.
### Key Features
* **Simple Graphical Interface:** Based on Tkinter for intuitive use.
* **Flexible Folder Selection:** Analyzes the entire selected folder or a specific subfolder if it follows the `projectname_lowercase/` convention.
* **Static Analysis (AST):** Examines `.py` files to find `import` statements without executing code.
* **Detailed `requirements.txt` Generation:**
* Includes the Python version of the analysis environment.
* Lists used standard library modules with referencing source files.
* Lists external dependencies with:
* Correct PyPI package name (e.g., `Pillow` from `import PIL`).
* Detected version in the analysis environment (if available).
* Source files where the import was found.
* **Offline Package Download:** Downloads external dependencies and their dependencies into the `_req_packages` subfolder.
* **Installation Script Generation:** Creates `install_packages.bat`/`.sh` in `_req_packages` for easy offline installation on other machines (with built-in `pip` check and relative paths).
* **Environment Comparison:** Shows a table comparing required dependencies against currently installed packages.
* **Environment Update (Optional):** Allows installing/updating selected packages directly in the current environment (**Use with caution, preferably in virtual environments!**).
* **Real-time Logging:** Displays operation logs directly in the GUI.
### Prerequisites
* **Python 3:** Python 3.7+ recommended.
* **Pip:** Must be installed and accessible.
* **(Optional but Recommended):** `pip install packaging` (for more accurate version comparison).
### Installation / Setup
1. Clone or download this repository.
2. Ensure the structure is:
```
<some_folder>/
└── dependencyanalyzer/
├── __init__.py
├── __main__.py
├── core.py
└── gui.py
```
3. No separate `pip install` for the tool itself is required; it runs as a module.
### Usage
1. Open a terminal or command prompt.
2. Navigate (**`cd`**) to the directory **containing** the `dependencyanalyzer` directory.
3. Run the tool using Python's `-m` flag:
```bash
python -m dependencyanalyzer
```
*(If you renamed the `dependencyanalyzer` folder, use that name in the command).*
4. The GUI will appear. Follow the numbered steps:
* **1. Select Repository Folder:** Choose the Python project folder to analyze.
* **2. Analyze Project & Generate requirements.txt:** Start the analysis and file creation.
* **3. External Dependencies Found:** View the detected external dependencies.
* **4. Download / Create Installers:** Download packages or generate scripts for offline use.
* **5. System Package Comparison:** Compare with the local environment and optionally update (carefully).
* **Log Messages:** Monitor output and progress.
### How it Works (Brief Technical Overview)
* Uses the `ast` module to build an Abstract Syntax Tree of Python code and find `Import` and `ImportFrom` nodes.
* Uses `sysconfig`, `importlib.util.find_spec`, and a predefined list to distinguish standard modules from external ones.
* Applies mappings (e.g., `PIL` -> `Pillow`) to use correct PyPI package names.
* Uses `importlib.metadata.version` to detect installed versions.
* Invokes `pip` via `subprocess` for download, list, and update operations.
* Uses `tkinter.ttk` for the GUI and the `logging` module to display messages in the interface.
### Known Limitations
* Does not detect dynamic imports (`importlib.import_module`).
* Does not handle non-Python dependencies.
* Internal module identification relies on basic conventions and might not be perfect for highly complex project structures.
* Versions in `requirements.txt` reflect the analysis environment; it doesn't actively resolve constraints from `setup.py` or `pyproject.toml` during initial generation.