pytrim


Namepytrim JSON
Version 0.1.2 PyPI version JSON
download
home_pagehttps://github.com/TrimTeam/PyTrim
SummaryAuto-detect and trim unused Python imports and dependencies
upload_time2025-07-24 09:45:52
maintainerNone
docs_urlNone
authorKonstantinos Karakatsanis, George Alexopoulos, Giannis Karyotakis, Foivos Proestakis, Evangelos Talos
requires_python>=3.10
licenseMIT License Copyright (c) 2025 Konstantinos Karakatsanis, George Alexopoulos, Giannis Karyotakis, Foivos Proestakis, and Evangelos Talos Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords dependencies imports cleanup trim python packaging optimization auto-detection unused
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # PyTrim

A Python tool for trimming of unused imports and dependencies from Python projects.
PyTrim helps keep your codebase clean by automatically removing unused dependencies from both source code and configuration files.

## Features

- **Auto-Detection**: Automatically finds unused dependencies without manual specification
- **Multi-format Support**: Handles Python files, requirements.txt, pyproject.toml, setup.py, poetry.lock, Pipfile, YAML files, Docker files, and more
- **Intelligent Analysis**: Uses AST parsing to accurately identify unused imports and dependencies
- **Modular Architecture**: Clean, extensible design with separate extractors and removers for different file types
- **CLI Interface**: Easy-to-use command line interface with smart defaults
- **Report Generation**: Creates detailed Markdown reports of changes
- **Git Integration**: Automatic branch creation and PR generation
- **Professional Package**: Ready for PyPI distribution with proper setup and documentation

## Installation

### PyPI Installation
```bash
pip install pytrim
```

### Source Installation
```bash
git clone https://github.com/karyotakisg/PyTrim.git
cd PyTrim
pip install .
```

### Install PyCG (optional)
When pytrim is installed from Pypi or source code, to run unused packages detection with call graph you need to install pycg.

1. Install PyCG from source:
    ```bash
    git clone https://github.com/gdrosos/PyCG.git && \
    cd PyCG && \
    pip3 install .
    ```
2. Ensure the PyCG entrypoint is in PATH:
   ```bash
    PATH="$HOME/.local/bin:$PATH"
   ```

## Use PyTrim inside a Docker container

1. Install `docker` (https://docs.docker.com/engine/install/)

2. Clone this repository:
      ```bash
      git clone https://github.com/TrimTeam/PyTrim.git
      ```

3. Enter the source code directory:

      ```bash
      cd PyTrim
      ```

4.  Build docker image:
    ```bash
    docker build -t pytrim .
    ```

5. Run docker container:
    ```bash
    docker run --rm -it -v /path/to/project:/project pytrim
    ```

    The Dockerfile is configured to:
    - Set working directory to `/project`
    - Mount your project at `/project`
    - Open bash terminal by default (`CMD ["/bin/bash"]`)

6. Then, you are ready to run pytrim:
    ```bash
    pytrim .
    ```


## Usage

After installation, use the `pytrim` command:

```bash
pytrim [-h] [-f FILE | -d DIRECTORY] [-u UNUSED_IMPORTS [UNUSED_IMPORTS ...]] [-r] [-o] [-pr] [-dp | -fd | -cg] [-v] [-V]
              [--generate-mappings [GENERATE_MAPPINGS ...]] [--mappings-file MAPPINGS_FILE] [-e EXCLUDE [EXCLUDE ...]]
              [project]
```

### Options
- `-f FILE, --file FILE`: Process a single Python file
- `-d DIRECTORY, --directory DIRECTORY`: Process all `.py` files in a directory
- `-u UNUSED_IMPORTS [...], --unused-imports UNUSED_IMPORTS [...]`: List of unused imports/dependencies to remove (optional - will auto-detect if not specified)
- `-r, --report`: Generate reports about trimmed packages in the `reports` folder
- `-o, --output`: Create new debloated files in folder `output` instead of overwriting originals
- `-pr, --pull-request`: Create a Git branch and GitHub Pull Request with changes
- `-V, --version`: Show version information
- `-v, --verbose`: Show detailed information about the trimming process.
- `-dp, --deptry`: Use deptry to find unused imports (requires deptry installed).
- `-fd, --fawltydeps`: Use fawltydeps to find unused dependencies (requires fawltydeps installed).
- `-cg, --call-graph`: Use call graph analysis to find unused imports (requires PyCG installed).
- `--generate-mappings`: Generate import mappings JSON file for specified packages (or use discovered packages if none specified).
- `--mappings-file`: Use custom import mappings JSON file instead of built-in mappings.
- `-e, --exclude`: Exclude specific dependencies from the removal process.E.g. a transitive dependency that needs its version pinned.
- `PROJECT`: Project root directory (default: current directory)

### Examples

**Trim current project:**
```bash
pytrim
```

**Auto-detect unused dependencies and remove them from a project:**
```bash
pytrim path/to/project/
```

**Remove unused imports from a single file:**
```bash
pytrim -f src/main.py -u os sys pandas
```

**Process all Python files in a directory:**
```bash
pytrim -d src/ -u requests json numpy
```

**Trim current project with reporting:**
```bash
pytrim -r
```

**Auto-detect specific project with reporting:**
```bash
pytrim project/ -r
```

**Clean an entire project with specific packages:**
```bash
pytrim project/ -u pandas matplotlib seaborn -r
```

**Create a Pull Request for current project:**
```bash
pytrim -pr
```

## Output Modes

### Default Mode
Files are modified in place. Only files that need changes are updated.

### Report Mode (`-r`)
- **Trimmed files**: Saved to `output/` directory with `_trimmed` suffix
- **Reports**: Generated in `reports/` directory with detailed analysis

### Pull Request Mode (`-pr`)
- Files modified in place
- Creates Git branch with timestamp
- Generates `project_report.md` in project root
- Automatically creates GitHub Pull Request

## Development

For development setup, contributing guidelines, and architecture details, see [DEV.md](DEV.md).

## Requirements

- Python 3.10+
- `tomli` (for Python < 3.11, automatically installed)
- `tqdm`
- `fawltydeps`
- `pkginfo`
- `flask`
- `toml`
- `colorama`

## License

MIT License - see [LICENSE](LICENSE) file for details.

## Contributing

Contributions are welcome! Please see [DEV.md](DEV.md) for detailed development setup and contribution guidelines.

## Support

- **Issues**: [GitHub Issues](https://github.com/pytrim/pytrim/issues)
- **Documentation**:
- **Source Code**: [GitHub](https://github.com/pytrim/pytrim)

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/TrimTeam/PyTrim",
    "name": "pytrim",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": "dependencies, imports, cleanup, trim, python, packaging, optimization, auto-detection, unused",
    "author": "Konstantinos Karakatsanis, George Alexopoulos, Giannis Karyotakis, Foivos Proestakis, Evangelos Talos",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/29/a7/69ae022dd8f56ba7179382fece73896cd82b43117f98a0c8d0e21dca08d9/pytrim-0.1.2.tar.gz",
    "platform": null,
    "description": "# PyTrim\n\nA Python tool for trimming of unused imports and dependencies from Python projects.\nPyTrim helps keep your codebase clean by automatically removing unused dependencies from both source code and configuration files.\n\n## Features\n\n- **Auto-Detection**: Automatically finds unused dependencies without manual specification\n- **Multi-format Support**: Handles Python files, requirements.txt, pyproject.toml, setup.py, poetry.lock, Pipfile, YAML files, Docker files, and more\n- **Intelligent Analysis**: Uses AST parsing to accurately identify unused imports and dependencies\n- **Modular Architecture**: Clean, extensible design with separate extractors and removers for different file types\n- **CLI Interface**: Easy-to-use command line interface with smart defaults\n- **Report Generation**: Creates detailed Markdown reports of changes\n- **Git Integration**: Automatic branch creation and PR generation\n- **Professional Package**: Ready for PyPI distribution with proper setup and documentation\n\n## Installation\n\n### PyPI Installation\n```bash\npip install pytrim\n```\n\n### Source Installation\n```bash\ngit clone https://github.com/karyotakisg/PyTrim.git\ncd PyTrim\npip install .\n```\n\n### Install PyCG (optional)\nWhen pytrim is installed from Pypi or source code, to run unused packages detection with call graph you need to install pycg.\n\n1. Install PyCG from source:\n    ```bash\n    git clone https://github.com/gdrosos/PyCG.git && \\\n    cd PyCG && \\\n    pip3 install .\n    ```\n2. Ensure the PyCG entrypoint is in PATH:\n   ```bash\n    PATH=\"$HOME/.local/bin:$PATH\"\n   ```\n\n## Use PyTrim inside a Docker container\n\n1. Install `docker` (https://docs.docker.com/engine/install/)\n\n2. Clone this repository:\n      ```bash\n      git clone https://github.com/TrimTeam/PyTrim.git\n      ```\n\n3. Enter the source code directory:\n\n      ```bash\n      cd PyTrim\n      ```\n\n4.  Build docker image:\n    ```bash\n    docker build -t pytrim .\n    ```\n\n5. Run docker container:\n    ```bash\n    docker run --rm -it -v /path/to/project:/project pytrim\n    ```\n\n    The Dockerfile is configured to:\n    - Set working directory to `/project`\n    - Mount your project at `/project`\n    - Open bash terminal by default (`CMD [\"/bin/bash\"]`)\n\n6. Then, you are ready to run pytrim:\n    ```bash\n    pytrim .\n    ```\n\n\n## Usage\n\nAfter installation, use the `pytrim` command:\n\n```bash\npytrim [-h] [-f FILE | -d DIRECTORY] [-u UNUSED_IMPORTS [UNUSED_IMPORTS ...]] [-r] [-o] [-pr] [-dp | -fd | -cg] [-v] [-V]\n              [--generate-mappings [GENERATE_MAPPINGS ...]] [--mappings-file MAPPINGS_FILE] [-e EXCLUDE [EXCLUDE ...]]\n              [project]\n```\n\n### Options\n- `-f FILE, --file FILE`: Process a single Python file\n- `-d DIRECTORY, --directory DIRECTORY`: Process all `.py` files in a directory\n- `-u UNUSED_IMPORTS [...], --unused-imports UNUSED_IMPORTS [...]`: List of unused imports/dependencies to remove (optional - will auto-detect if not specified)\n- `-r, --report`: Generate reports about trimmed packages in the `reports` folder\n- `-o, --output`: Create new debloated files in folder `output` instead of overwriting originals\n- `-pr, --pull-request`: Create a Git branch and GitHub Pull Request with changes\n- `-V, --version`: Show version information\n- `-v, --verbose`: Show detailed information about the trimming process.\n- `-dp, --deptry`: Use deptry to find unused imports (requires deptry installed).\n- `-fd, --fawltydeps`: Use fawltydeps to find unused dependencies (requires fawltydeps installed).\n- `-cg, --call-graph`: Use call graph analysis to find unused imports (requires PyCG installed).\n- `--generate-mappings`: Generate import mappings JSON file for specified packages (or use discovered packages if none specified).\n- `--mappings-file`: Use custom import mappings JSON file instead of built-in mappings.\n- `-e, --exclude`: Exclude specific dependencies from the removal process.E.g. a transitive dependency that needs its version pinned.\n- `PROJECT`: Project root directory (default: current directory)\n\n### Examples\n\n**Trim current project:**\n```bash\npytrim\n```\n\n**Auto-detect unused dependencies and remove them from a project:**\n```bash\npytrim path/to/project/\n```\n\n**Remove unused imports from a single file:**\n```bash\npytrim -f src/main.py -u os sys pandas\n```\n\n**Process all Python files in a directory:**\n```bash\npytrim -d src/ -u requests json numpy\n```\n\n**Trim current project with reporting:**\n```bash\npytrim -r\n```\n\n**Auto-detect specific project with reporting:**\n```bash\npytrim project/ -r\n```\n\n**Clean an entire project with specific packages:**\n```bash\npytrim project/ -u pandas matplotlib seaborn -r\n```\n\n**Create a Pull Request for current project:**\n```bash\npytrim -pr\n```\n\n## Output Modes\n\n### Default Mode\nFiles are modified in place. Only files that need changes are updated.\n\n### Report Mode (`-r`)\n- **Trimmed files**: Saved to `output/` directory with `_trimmed` suffix\n- **Reports**: Generated in `reports/` directory with detailed analysis\n\n### Pull Request Mode (`-pr`)\n- Files modified in place\n- Creates Git branch with timestamp\n- Generates `project_report.md` in project root\n- Automatically creates GitHub Pull Request\n\n## Development\n\nFor development setup, contributing guidelines, and architecture details, see [DEV.md](DEV.md).\n\n## Requirements\n\n- Python 3.10+\n- `tomli` (for Python < 3.11, automatically installed)\n- `tqdm`\n- `fawltydeps`\n- `pkginfo`\n- `flask`\n- `toml`\n- `colorama`\n\n## License\n\nMIT License - see [LICENSE](LICENSE) file for details.\n\n## Contributing\n\nContributions are welcome! Please see [DEV.md](DEV.md) for detailed development setup and contribution guidelines.\n\n## Support\n\n- **Issues**: [GitHub Issues](https://github.com/pytrim/pytrim/issues)\n- **Documentation**:\n- **Source Code**: [GitHub](https://github.com/pytrim/pytrim)\n",
    "bugtrack_url": null,
    "license": "MIT License\n        \n        Copyright (c) 2025 Konstantinos Karakatsanis, George Alexopoulos,\n                           Giannis Karyotakis, Foivos Proestakis,\n                           and Evangelos Talos\n        \n        Permission is hereby granted, free of charge, to any person obtaining a copy\n        of this software and associated documentation files (the \"Software\"), to deal\n        in the Software without restriction, including without limitation the rights\n        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n        copies of the Software, and to permit persons to whom the Software is\n        furnished to do so, subject to the following conditions:\n        \n        The above copyright notice and this permission notice shall be included in all\n        copies or substantial portions of the Software.\n        \n        THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n        SOFTWARE.\n        ",
    "summary": "Auto-detect and trim unused Python imports and dependencies",
    "version": "0.1.2",
    "project_urls": {
        "Bug Reports": "https://github.com/TrimTeam/PyTrim/issues",
        "Homepage": "https://github.com/TrimTeam/PyTrim",
        "Repository": "https://github.com/TrimTeam/PyTrim.git"
    },
    "split_keywords": [
        "dependencies",
        " imports",
        " cleanup",
        " trim",
        " python",
        " packaging",
        " optimization",
        " auto-detection",
        " unused"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "9bc5e4f2ce754d87229dc83647f4cf100915c510949cf20350dc9a398e1edbd9",
                "md5": "820af1ca6d8ac7fc1dcf3e95f43244be",
                "sha256": "ec2b49809b7c2197e74bc926883534828a0c012d9f73880f0325ddc0b7fa59b3"
            },
            "downloads": -1,
            "filename": "pytrim-0.1.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "820af1ca6d8ac7fc1dcf3e95f43244be",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 158939,
            "upload_time": "2025-07-24T09:45:51",
            "upload_time_iso_8601": "2025-07-24T09:45:51.262565Z",
            "url": "https://files.pythonhosted.org/packages/9b/c5/e4f2ce754d87229dc83647f4cf100915c510949cf20350dc9a398e1edbd9/pytrim-0.1.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "29a769ae022dd8f56ba7179382fece73896cd82b43117f98a0c8d0e21dca08d9",
                "md5": "8eda2700ef8df9f8a20a106599f9f6d2",
                "sha256": "0d8e484e9a87f3e5932034e3d366f2c8f2e81e1c97578f16c216e6828f5992ac"
            },
            "downloads": -1,
            "filename": "pytrim-0.1.2.tar.gz",
            "has_sig": false,
            "md5_digest": "8eda2700ef8df9f8a20a106599f9f6d2",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 145528,
            "upload_time": "2025-07-24T09:45:52",
            "upload_time_iso_8601": "2025-07-24T09:45:52.368722Z",
            "url": "https://files.pythonhosted.org/packages/29/a7/69ae022dd8f56ba7179382fece73896cd82b43117f98a0c8d0e21dca08d9/pytrim-0.1.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-24 09:45:52",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "TrimTeam",
    "github_project": "PyTrim",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "pytrim"
}
        
Elapsed time: 1.33729s