├── .cargo └── config.toml ├── .devcontainer ├── Dockerfile └── devcontainer.json ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── config.yml │ └── feature_request.md ├── changelog.yml ├── dependabot.yml └── workflows │ ├── audit.yaml │ ├── cd.yaml │ ├── changelog.yaml │ ├── ci.yaml │ └── issue_handler.yml ├── .gitignore ├── .vscode └── launch.json ├── CHANGELOG.md ├── Cargo.lock ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src ├── cli.rs ├── env.rs ├── error.rs ├── host_triple.rs ├── lib.rs ├── main.rs ├── targets.rs └── toolchain │ ├── gcc.rs │ ├── llvm.rs │ ├── mod.rs │ └── rust.rs └── tests └── integration.rs /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [target.x86_64-pc-windows-msvc] 2 | rustflags = ["-C", "target-feature=+crt-static"] 3 | -------------------------------------------------------------------------------- /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | ARG VARIANT=latest 2 | # Choose between: debian, ubuntu, fedora, opensuse/tumbleweed, opensuse/leap 3 | FROM debian:${VARIANT} 4 | ENV DEBIAN_FRONTEND=noninteractive 5 | ENV LC_ALL=C.UTF-8 6 | ENV LANG=C.UTF-8 7 | ARG CONTAINER_USER=esp 8 | ARG CONTAINER_GROUP=esp 9 | 10 | # Ubuntu/Debian 11 | RUN apt-get update \ 12 | && apt-get install -y git gcc build-essential curl pkg-config cmake \ 13 | && apt-get clean -y && rm -rf /var/lib/apt/lists/* /tmp/library-scripts 14 | RUN adduser --disabled-password --gecos "" ${CONTAINER_USER} 15 | 16 | # Fedora 17 | # RUN dnf -y update \ 18 | # && dnf -y install git perl gcc \ 19 | # && dnf clean all 20 | # RUN adduser ${CONTAINER_USER} 21 | 22 | USER ${CONTAINER_USER} 23 | WORKDIR /home/${CONTAINER_USER} 24 | 25 | # openSUSE Tumbleweed/Leap 26 | # RUN zypper install -y git gcc ninja make \ 27 | # && zypper clean 28 | 29 | # Install Rust 30 | RUN curl https://sh.rustup.rs -sSf | bash -s -- -y 31 | ENV PATH=${PATH}:/home/${CONTAINER_USER}/.cargo/bin 32 | 33 | CMD [ "/bin/bash" ] 34 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "espup", 3 | "build": { 4 | "dockerfile": "Dockerfile", 5 | "args": { 6 | "CONTAINER_USER": "esp", 7 | "CONTAINER_GROUP": "esp" 8 | } 9 | }, 10 | "customizations": { 11 | "vscode": { 12 | "settings": { 13 | "editor.formatOnPaste": true, 14 | "editor.formatOnSave": true, 15 | "editor.formatOnSaveMode": "file", 16 | "editor.formatOnType": true, 17 | "files.watcherExclude": { 18 | "**/target/**": true 19 | }, 20 | "lldb.executable": "/usr/bin/lldb", 21 | "lldb.verboseLogging": true, 22 | "rust-analyzer.checkOnSave.command": "clippy", 23 | "rust-analyzer.checkOnSave.allTargets": false, 24 | "search.exclude": { 25 | "**/target": true 26 | } 27 | }, 28 | "extensions": [ 29 | "vadimcn.vscode-lldb", 30 | "mutantdino.resourcemonitor", 31 | "rust-lang.rust-analyzer", 32 | "tamasfe.even-better-toml", 33 | "serayuzgur.crates", 34 | "vivaxy.vscode-conventional-commits", 35 | "yzhang.markdown-all-in-one", 36 | "GitHub.copilot" 37 | ] 38 | } 39 | }, 40 | "workspaceMount": "source=${localWorkspaceFolder},target=/home/esp/espup,type=bind,consistency=cached", 41 | "workspaceFolder": "/home/esp/espup" 42 | } 43 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## Bug description 11 | 12 | 13 | 14 | - Would you like to work on a fix? [y/n] 15 | 16 | ## To Reproduce 17 | 18 | Steps to reproduce the behavior: 19 | 20 | 1. ... 21 | 2. ... 22 | 3. ... 23 | 4. ... 24 | 25 | 26 | 27 | ## Expected behavior 28 | 29 | 30 | 31 | ## Screenshots 32 | 33 | 34 | 35 | ## Environment 36 | 37 | 38 | 39 | - OS: [e.g. Ubuntu 20.04] 40 | - espup version: [e.g. 0.1.0] 41 | 42 | ## Additional context 43 | 44 | 45 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: true 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## Motivations 11 | 12 | 15 | 16 | - Would you like to implement this feature? [y/n] 17 | 18 | ## Solution 19 | 20 | 21 | 22 | ## Alternatives 23 | 24 | 25 | 26 | ## Additional context 27 | 28 | 29 | -------------------------------------------------------------------------------- /.github/changelog.yml: -------------------------------------------------------------------------------- 1 | name: Changelog check 2 | 3 | on: 4 | pull_request: 5 | # Run on labeled/unlabeled in addition to defaults to detect 6 | # adding/removing skip-changelog labels. 7 | types: [opened, reopened, labeled, unlabeled, synchronize] 8 | 9 | jobs: 10 | changelog: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: dangoslen/changelog-enforcer@v3 14 | with: 15 | changeLogPath: CHANGELOG.md 16 | skipLabels: "skip-changelog" 17 | missingUpdateErrorMessage: "Please add a changelog entry in the CHANGELOG.md file." 18 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | # Check for updates every Monday 6 | schedule: 7 | interval: "weekly" 8 | open-pull-requests-limit: 10 9 | -------------------------------------------------------------------------------- /.github/workflows/audit.yaml: -------------------------------------------------------------------------------- 1 | name: Security audit 2 | 3 | on: 4 | schedule: 5 | # Runs at 00:00 UTC everyday 6 | - cron: "0 0 * * *" 7 | push: 8 | paths: 9 | - "**/Cargo.toml" 10 | - "**/Cargo.lock" 11 | pull_request: 12 | paths: 13 | - "**/Cargo.toml" 14 | - "**/Cargo.lock" 15 | 16 | env: 17 | CARGO_TERM_COLOR: always 18 | 19 | jobs: 20 | audit: 21 | name: Security audit 22 | runs-on: ubuntu-latest 23 | steps: 24 | - name: Checkout repository 25 | uses: actions/checkout@v4 26 | - name: Install Rust 27 | uses: dtolnay/rust-toolchain@v1 28 | with: 29 | toolchain: stable 30 | - uses: Swatinem/rust-cache@v2 31 | - uses: rustsec/audit-check@v2 32 | with: 33 | token: ${{ secrets.GITHUB_TOKEN }} 34 | -------------------------------------------------------------------------------- /.github/workflows/cd.yaml: -------------------------------------------------------------------------------- 1 | name: Continuous Deployment 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | env: 8 | CARGO_TERM_COLOR: always 9 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 10 | 11 | jobs: 12 | publish-release: 13 | name: Generating artifacts for ${{ matrix.job.target }} 14 | runs-on: ${{ matrix.job.os }} 15 | strategy: 16 | fail-fast: false 17 | matrix: 18 | job: 19 | - os: macos-latest 20 | target: x86_64-apple-darwin 21 | - os: ubuntu-22.04 22 | target: x86_64-unknown-linux-gnu 23 | - os: windows-latest 24 | target: x86_64-pc-windows-msvc 25 | binary-postfix: ".exe" 26 | - os: ubuntu-22.04 27 | target: aarch64-unknown-linux-gnu 28 | - os: macos-latest 29 | target: aarch64-apple-darwin 30 | steps: 31 | - name: Checkout repository 32 | uses: actions/checkout@v4 33 | - name: Install Rust toolchain 34 | uses: dtolnay/rust-toolchain@v1 35 | with: 36 | toolchain: stable 37 | target: ${{ matrix.job.target }} 38 | - name: Enable caching 39 | uses: Swatinem/rust-cache@v2 40 | - name: Publish (dry-run) 41 | if: matrix.job.target == 'x86_64-unknown-linux-gnu' 42 | run: cargo publish --dry-run 43 | - name: Install cross and build 44 | if: matrix.job.target == 'aarch64-unknown-linux-gnu' 45 | run: | 46 | cargo install cross 47 | cross build --release --target ${{ matrix.job.target }} 48 | - name: Cargo build 49 | if: matrix.job.target != 'aarch64-unknown-linux-gnu' 50 | run: cargo build --release --target ${{ matrix.job.target }} 51 | - name: Compress (Unix) 52 | if: ${{ matrix.job.os != 'windows-latest' }} 53 | run: zip -j espup-${{ matrix.job.target }}.zip target/${{ matrix.job.target }}/release/espup${{ matrix.job.binary-postfix }} 54 | - name: Compress (Windows) 55 | if: ${{ matrix.job.os == 'windows-latest' }} 56 | run: Compress-Archive target/${{ matrix.job.target }}/release/espup${{ matrix.job.binary-postfix }} espup-${{ matrix.job.target }}.zip 57 | - name: Upload compressed artifact 58 | uses: svenstaro/upload-release-action@v2 59 | with: 60 | repo_token: ${{ secrets.GITHUB_TOKEN }} 61 | file: espup-${{ matrix.job.target }}.zip 62 | tag: ${{ github.ref }} 63 | - name: Upload binary artifact 64 | uses: svenstaro/upload-release-action@v2 65 | with: 66 | repo_token: ${{ secrets.GITHUB_TOKEN }} 67 | file: target/${{ matrix.job.target }}/release/espup${{ matrix.job.binary-postfix }} 68 | asset_name: espup-${{ matrix.job.target }}${{ matrix.job.binary-postfix }} 69 | tag: ${{ github.ref }} 70 | publish-cratesio: 71 | name: Publishing to Crates.io 72 | needs: publish-release 73 | runs-on: ubuntu-22.04 74 | steps: 75 | - name: Checkout repository 76 | uses: actions/checkout@v4 77 | - name: Install Rust toolchain 78 | uses: dtolnay/rust-toolchain@v1 79 | with: 80 | toolchain: stable 81 | - name: Enable caching 82 | uses: Swatinem/rust-cache@v2 83 | - name: Cargo publish 84 | run: cargo publish --token ${{ secrets.CARGO_API_KEY }} 85 | -------------------------------------------------------------------------------- /.github/workflows/changelog.yaml: -------------------------------------------------------------------------------- 1 | name: Changelog check 2 | 3 | on: 4 | pull_request: 5 | # Run on labeled/unlabeled in addition to defaults to detect 6 | # adding/removing skip-changelog labels. 7 | types: [opened, reopened, labeled, unlabeled, synchronize] 8 | 9 | jobs: 10 | changelog: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Checkout sources 15 | uses: actions/checkout@v4 16 | 17 | - uses: dangoslen/changelog-enforcer@v3 18 | with: 19 | changeLogPath: CHANGELOG.md 20 | skipLabels: "skip-changelog" 21 | missingUpdateErrorMessage: "Please add a changelog entry in the CHANGELOG.md file." 22 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Continuous Integration 3 | 4 | on: 5 | push: 6 | branches: 7 | - main 8 | paths-ignore: 9 | - "**/README.md" 10 | - "**/CHANGELOG.md" 11 | - "**/audit.yaml" 12 | - "**/cd.yaml" 13 | pull_request: 14 | paths-ignore: 15 | - "**/README.md" 16 | - "**/CHANGELOG.md" 17 | - "**/audit.yaml" 18 | - "**/cd.yaml" 19 | 20 | env: 21 | CARGO_TERM_COLOR: always 22 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 23 | 24 | jobs: 25 | cargo-checks: 26 | name: cargo ${{ matrix.action.command }} | ${{ matrix.job.os }} 27 | runs-on: ${{ matrix.job.os }} 28 | strategy: 29 | fail-fast: false 30 | matrix: 31 | job: 32 | - os: macos-latest 33 | os-name: macos 34 | - os: ubuntu-22.04 35 | os-name: linux 36 | - os: windows-latest 37 | os-name: windows 38 | action: 39 | - command: check 40 | - command: test 41 | args: --all-features --workspace 42 | - command: fmt 43 | args: --all -- --check 44 | - command: clippy 45 | args: --all-targets --all-features --workspace -- -D warnings 46 | - command: doc 47 | args: --no-deps --document-private-items --all-features --workspace --examples 48 | steps: 49 | - name: Install dependencies 50 | if: ${{ matrix.job.os == 'ubuntu-20.04' }} 51 | run: | 52 | sudo sed -i 's/azure.archive.ubuntu.com/archive.ubuntu.com/' /etc/apt/sources.list 53 | sudo apt-get update 54 | sudo apt-get install libudev-dev 55 | - name: Checkout repository 56 | uses: actions/checkout@v4 57 | - name: Setup Rust toolchain 58 | uses: dtolnay/rust-toolchain@stable 59 | - name: Enable caching 60 | uses: Swatinem/rust-cache@v2 61 | - name: Cargo command 62 | run: cargo ${{ matrix.action.command }} ${{ matrix.action.args }} 63 | msrv: 64 | name: MSRV check 65 | runs-on: ubuntu-latest 66 | steps: 67 | - name: Install dependencies 68 | run: | 69 | sudo sed -i 's/azure.archive.ubuntu.com/archive.ubuntu.com/' /etc/apt/sources.list 70 | sudo apt-get update 71 | sudo apt-get install musl-tools libudev-dev 72 | - name: Checkout repository 73 | uses: actions/checkout@v4 74 | - name: Setup Rust toolchain 75 | uses: dtolnay/rust-toolchain@stable 76 | with: 77 | toolchain: 1.85.0 78 | - name: Enable caching 79 | uses: Swatinem/rust-cache@v2 80 | - name: Cargo check 81 | run: cargo check 82 | -------------------------------------------------------------------------------- /.github/workflows/issue_handler.yml: -------------------------------------------------------------------------------- 1 | name: Add new issues to project 2 | 3 | on: 4 | issues: 5 | types: 6 | - opened 7 | 8 | jobs: 9 | add-to-project: 10 | name: Add issue to project 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/add-to-project@v1.0.2 14 | with: 15 | project-url: https://github.com/orgs/esp-rs/projects/2 16 | github-token: ${{ secrets.PAT }} 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /tests_projects 3 | Commands.sh 4 | /test_projects 5 | export-esp.* 6 | .DS_Store 7 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "type": "lldb", 6 | "request": "launch", 7 | "name": "Debug executable", 8 | "cargo": { 9 | "args": [ 10 | "build", 11 | "--bin=espup", 12 | "--package=espup", 13 | "--manifest-path=Cargo.toml" 14 | ], 15 | "filter": { 16 | "name": "espup", 17 | "kind": "bin" 18 | } 19 | }, 20 | "args": [ 21 | "install" 22 | ], 23 | "cwd": "${workspaceFolder}" 24 | } 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [Unreleased] 9 | 10 | ### Added 11 | - Added option to specify Crosstool-NG version, using `-c` or `--crosstools-toolchain-version` 12 | 13 | ### Fixed 14 | 15 | ### Changed 16 | - Updated default GCC / Crosstools version to latest, [`esp-14.2.0_20241119`](https://github.com/espressif/crosstool-NG/releases/tag/esp-14.2.0_20241119) (#508) 17 | 18 | ### Removed 19 | 20 | ## [0.15.1] - 2025-05-19 21 | 22 | ### Changed 23 | - Improved GitHub API error handling (#496) 24 | - Update `zip` dependency to 3.0.0 as 2.6.1 was yanked (#504) 25 | 26 | ## [0.15.0] - 2025-04-08 27 | 28 | ### Changed 29 | - Install `stable` Rust toolchain instead of `nightly` for RISC-V devices (#487) 30 | 31 | ## [0.14.1] - 2025-03-04 32 | 33 | ### Added 34 | - Add support for LLVM esp-19.1.2_20250225 (#477, #479) 35 | 36 | ### Fixed 37 | - Return an error if GET request fails (#471) 38 | - Fix RISC-V installation error (#480) 39 | 40 | ## [0.14.0] - 2024-12-17 41 | 42 | ### Added 43 | - Smoother large file download&proxy support (#463) 44 | - Add GitHub API errors to clarify what failed (#464) 45 | 46 | ### Fixed 47 | - When queriying GitHub for the list of releases, retrieve more items (#462) 48 | 49 | ### Changed 50 | - `espup` now prints why an install step failed (#461) 51 | 52 | ## [0.13.0] - 2024-10-30 53 | 54 | ### Changed 55 | - Update GCC version to 14.2.0 (#442) 56 | - Update LLVM version to esp-18.1.2_20240912 (#452) 57 | 58 | ## [0.12.2] - 2024-07-18 59 | 60 | ### Fixed 61 | - Fix extended LLVM mode regression for LLVM versions < 17 introduced by #432. (#437) 62 | 63 | ## [0.12.1] - 2024-07-15 64 | 65 | ### Fixed 66 | - Make both `libclang.so` available again when installing the extended LLVM for LLVM versions >= 17 (#432) 67 | 68 | ## [0.12.0] - 2024-06-12 69 | 70 | ### Added 71 | - Added support for SOCKS5 proxy (#423) 72 | 73 | ### Changed 74 | - Update LLVM version to `esp-17.0.1_20240419` (#427) 75 | - Update dependencies (#429) 76 | 77 | ## [0.11.0] - 2024-02-02 78 | 79 | ### Added 80 | - Added support for specifying the location of the export file via `ESPUP_EXPORT_FILE` (#403) 81 | - Added support for ESP32-P4 (#408) 82 | 83 | ### Fixed 84 | - [Windows]: Avoid duplicating system environment variables into user environment variables (#411) 85 | 86 | ## [0.10.0] 87 | 88 | ### Fixed 89 | - `skip-version-parse` argument should require `toolchain-version` (#396) 90 | - If there is a minified LLVM installation, `--extended-llvm` now installs the full LLVM (#400) 91 | 92 | ### Changed 93 | - Update LLVM version to `esp-16.0.4-20231113` (#398) 94 | 95 | ## [0.9.0] - 2023-11-10 96 | 97 | ### Added 98 | - Added new `--esp-riscv-gcc` flag to install esp-riscv-gcc toolchain instead of the system one (#391) 99 | 100 | ### Changed 101 | - New Default behavior: install esp-riscv-gcc only if the user explicitly uses the `--esp-riscv-gcc` flag (#391) 102 | 103 | ## [0.8.0] - 2023-11-02 104 | 105 | ### Added 106 | - Add symlink to LLVM in Unix systems (#380) 107 | 108 | ### Changed 109 | - Reduce logs verbosity, add docstrings, and use async methods (#384) 110 | - Change how Windows environment is configured (#389) 111 | 112 | ## [0.7.0] - 2023-10-18 113 | 114 | ### Changed 115 | - Update GCC version to 13.2 (#373) 116 | - Update logging format and log messages (#375, #376) 117 | 118 | ## [0.6.1] - 2023-10-04 119 | 120 | ### Changed 121 | - Remove unnecessary CI jobs (#369) 122 | 123 | ### Fixed 124 | - Create $RUSTUP_HOME/tmp if needed (#365) 125 | - Complete Xtensa Rust versions when provided one is incomplete (#366) 126 | 127 | ## [0.6.0] - 2023-10-02 128 | 129 | ### Added 130 | - Add a flag to skip Xtensa Rust version parsing (#352) 131 | - Add warn message when failed to detect Xtensa Rust (#357) 132 | 133 | ### Changed 134 | - Update dependencies 135 | - Use `RUSTUP_HOME` tmp folder (#348) 136 | - Improve `remove_dir_all` errors (#346) 137 | 138 | ### Fixed 139 | - Fix temorary folders/files cleanup (#344) 140 | - Fix Clippy lint (#335) 141 | 142 | ### Removed 143 | 144 | ## [0.5.0] - 2023-08-11 145 | 146 | ## [0.4.1] - 2023-05-18 147 | 148 | ## [0.4.0] - 2023-04-24 149 | 150 | ## [0.3.2] - 2023-03-13 151 | 152 | ## [0.3.1] - 2023-03-06 153 | 154 | ## [0.3.0] - 2023-02-21 155 | 156 | ## [0.2.9] - 2023-02-14 157 | 158 | ## [0.2.8] - 2023-02-03 159 | 160 | ## [0.2.7] - 2023-02-03 161 | 162 | ## [0.2.6] - 2023-01-13 163 | 164 | ## [0.2.5] - 2023-01-11 165 | 166 | ## [0.2.4] - 2022-12-14 167 | 168 | ## [0.2.3] - 2022-11-17 169 | 170 | ## [0.2.2] - 2022-11-17 171 | 172 | ## [0.2.1] - 2022-11-04 173 | 174 | ## [0.2.0] - 2022-11-03 175 | 176 | ## [0.1.0] - 2022-10-07 177 | 178 | [Unreleased]: https://github.com/esp-rs/espup/compare/v0.15.1...HEAD 179 | [0.15.1]: https://github.com/esp-rs/espup/compare/v0.15.0...v0.15.1 180 | [0.15.0]: https://github.com/esp-rs/espup/compare/v0.14.1...v0.15.0 181 | [0.14.1]: https://github.com/esp-rs/espup/compare/v0.14.0...v0.14.1 182 | [0.14.0]: https://github.com/esp-rs/espup/compare/v0.13.0...v0.14.0 183 | [0.13.0]: https://github.com/esp-rs/espup/compare/v0.12.2...v0.13.0 184 | [0.12.2]: https://github.com/esp-rs/espup/compare/v0.12.1...v0.12.2 185 | [0.12.1]: https://github.com/esp-rs/espup/compare/v0.12.0...v0.12.1 186 | [0.12.0]: https://github.com/esp-rs/espup/compare/v0.11.0...v0.12.0 187 | [0.11.0]: https://github.com/esp-rs/espup/compare/v0.10.0...v0.11.0 188 | [0.10.0]: https://github.com/esp-rs/espup/compare/v0.9.0...v0.10.0 189 | [0.9.0]: https://github.com/esp-rs/espup/compare/v0.8.0...v0.9.0 190 | [0.8.0]: https://github.com/esp-rs/espup/compare/v0.7.0...v0.8.0 191 | [0.7.0]: https://github.com/esp-rs/espup/compare/v0.6.1...v0.7.0 192 | [0.6.1]: https://github.com/esp-rs/espup/compare/v0.6.0...v0.6.1 193 | [0.6.0]: https://github.com/esp-rs/espup/compare/v0.5.0...v0.6.0 194 | [0.5.0]: https://github.com/esp-rs/espup/compare/v0.4.1...v0.5.0 195 | [0.4.1]: https://github.com/esp-rs/espup/compare/v0.4.0...v0.4.1 196 | [0.4.0]: https://github.com/esp-rs/espup/compare/v0.3.2...v0.4.0 197 | [0.3.2]: https://github.com/esp-rs/espup/compare/v0.3.1...v0.3.2 198 | [0.3.1]: https://github.com/esp-rs/espup/compare/v0.3.0...v0.3.1 199 | [0.3.0]: https://github.com/esp-rs/espup/compare/v0.2.9...v0.3.0 200 | [0.2.9]: https://github.com/esp-rs/espup/compare/v0.2.8...v0.2.9 201 | [0.2.8]: https://github.com/esp-rs/espup/compare/v0.2.7...v0.2.8 202 | [0.2.7]: https://github.com/esp-rs/espup/compare/v0.2.6...v0.2.7 203 | [0.2.6]: https://github.com/esp-rs/espup/compare/v0.2.5...v0.2.6 204 | [0.2.5]: https://github.com/esp-rs/espup/compare/v0.2.4...v0.2.5 205 | [0.2.4]: https://github.com/esp-rs/espup/compare/v0.2.3...v0.2.4 206 | [0.2.3]: https://github.com/esp-rs/espup/compare/v0.2.2...v0.2.3 207 | [0.2.2]: https://github.com/esp-rs/espup/compare/v0.2.1...v0.2.2 208 | [0.2.1]: https://github.com/esp-rs/espup/compare/v0.2.0...v0.2.1 209 | [0.2.0]: https://github.com/esp-rs/espup/compare/v0.1.0...v0.2.0 210 | [0.1.0]: https://github.com/esp-rs/espup/releases/tag/v0.1.0 211 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "espup" 3 | version = "0.15.1" 4 | authors = ["Sergio Gasquez Arcos "] 5 | edition = "2024" 6 | license = "MIT OR Apache-2.0" 7 | readme = "README.md" 8 | repository = "https://github.com/esp-rs/espup" 9 | description = """ 10 | Tool for installing and maintaining Espressif Rust ecosystem. 11 | """ 12 | keywords = ["cli", "embedded", "esp", "esp-rs", "xtensa"] 13 | categories = ["command-line-utilities", "development-tools", "embedded"] 14 | rust-version = "1.85.0" 15 | 16 | [dependencies] 17 | async-trait = "0.1.88" 18 | bytes = "1.10.1" 19 | clap = { version = "4.5.38", features = ["derive", "env"] } 20 | clap_complete = "4.5.50" 21 | directories = "6.0.0" 22 | env_logger = "0.11.8" 23 | flate2 = "1.1.1" 24 | guess_host_triple = "0.1.4" 25 | indicatif = "0.17.11" 26 | indicatif-log-bridge = "0.2.3" 27 | lazy_static = "1.5.0" 28 | log = "0.4.27" 29 | miette = { version = "7.6.0", features = ["fancy"] } 30 | regex = "1.11.1" 31 | reqwest = { version = "0.12.15", features = ["blocking", "socks", "stream"] } 32 | retry = "2.1.0" 33 | serde_json = "1.0.140" 34 | strum = { version = "0.27.1", features = ["derive"] } 35 | tar = "0.4.44" 36 | tempfile = "3.20.0" 37 | thiserror = "2.0.12" 38 | tokio = { version = "1.45.0", features = ["full"] } 39 | tokio-retry = "0.3.0" 40 | tokio-stream = "0.1.17" 41 | update-informer = "1.2.0" 42 | xz2 = "0.1.7" 43 | zip = "3.0.0" 44 | 45 | [target.'cfg(unix)'.dependencies] 46 | openssl = { version = "0.10.72", features = ["vendored"] } 47 | 48 | [target.'cfg(windows)'.dependencies] 49 | winreg = "0.55.0" 50 | winapi = { version = "0.3.9", features = ["winuser"] } 51 | 52 | [dev-dependencies] 53 | assert_cmd = "2.0.17" 54 | 55 | [package.metadata.binstall] 56 | bin-dir = "{ bin }{ binary-ext }" 57 | pkg-fmt = "zip" 58 | pkg-url = "{ repo }/releases/download/v{ version }/{ name }-{ target }.{ archive-format }" 59 | 60 | [profile.release] 61 | lto = "thin" 62 | strip = true 63 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 The Espup Project Developers 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # espup 2 | 3 | [![Crates.io](https://img.shields.io/crates/v/espup.svg)](https://crates.io/crates/espup) 4 | ![MSRV](https://img.shields.io/badge/MSRV-1.85.0-blue?labelColor=1C2C2E&logo=Rust&style=flat-square) 5 | [![Continuous Integration](https://github.com/esp-rs/espup/actions/workflows/ci.yaml/badge.svg)](https://github.com/esp-rs/espup/actions/workflows/ci.yaml) 6 | [![Security audit](https://github.com/esp-rs/espup/actions/workflows/audit.yaml/badge.svg)](https://github.com/esp-rs/espup/actions/workflows/audit.yaml) 7 | [![Matrix](https://img.shields.io/matrix/esp-rs:matrix.org?label=join%20matrix&color=BEC5C9&labelColor=1C2C2E&logo=matrix&style=flat-square)](https://matrix.to/#/#esp-rs:matrix.org) 8 | 9 | 10 | > `rustup` for [esp-rs](https://github.com/esp-rs/) 11 | 12 | `espup` is a tool for installing and maintaining the required toolchains for developing applications in Rust for Espressif SoC's. 13 | 14 | To better understand what `espup` installs, see [the installation chapter of `The Rust on ESP Book`](https://esp-rs.github.io/book/installation/index.html) 15 | 16 | ## Requirements 17 | 18 | Before running or installing `espup`, make sure that [`rustup`](https://rustup.rs/) is installed. 19 | 20 | Linux systems also require the following packages: 21 | - Ubuntu/Debian 22 | ```sh 23 | sudo apt-get install -y gcc build-essential curl pkg-config 24 | ``` 25 | - Fedora 26 | ```sh 27 | sudo dnf -y install perl gcc 28 | ``` 29 | - `perl` is required to build `openssl-sys` 30 | - openSUSE Thumbleweed/Leap 31 | ``` 32 | sudo zypper install -y gcc ninja make 33 | ``` 34 | 35 | ## Installation 36 | 37 | ```sh 38 | cargo install espup --locked 39 | ``` 40 | 41 | It's also possible to use [cargo-binstall](https://github.com/cargo-bins/cargo-binstall) or to directly download the pre-compiled [release binaries](https://github.com/esp-rs/espup/releases). 42 | 43 |
44 | 45 | Commands to install pre-compiled release binaries 46 | 47 | - Linux aarch64 48 | ```sh 49 | curl -L https://github.com/esp-rs/espup/releases/latest/download/espup-aarch64-unknown-linux-gnu -o espup 50 | chmod a+x espup 51 | ``` 52 | - Linux x86_64 53 | ```sh 54 | curl -L https://github.com/esp-rs/espup/releases/latest/download/espup-x86_64-unknown-linux-gnu -o espup 55 | chmod a+x espup 56 | ``` 57 | - macOS aarch64 58 | ```sh 59 | curl -L https://github.com/esp-rs/espup/releases/latest/download/espup-aarch64-apple-darwin -o espup 60 | chmod a+x espup 61 | ``` 62 | - macOS x86_64 63 | ```sh 64 | curl -L https://github.com/esp-rs/espup/releases/latest/download/espup-x86_64-apple-darwin -o espup 65 | chmod a+x espup 66 | ``` 67 | - Windows MSVC 68 | ```powershell 69 | Invoke-WebRequest 'https://github.com/esp-rs/espup/releases/latest/download/espup-x86_64-pc-windows-msvc.exe' -OutFile .\espup.exe 70 | ``` 71 | 72 |
73 | 74 | ## Quickstart 75 | 76 | See [Usage](#usage) section for more details. 77 | 78 | ```sh 79 | espup install 80 | ``` 81 | 82 | ### Environment Variables Setup 83 | 84 | After installing the toolchain, on **Unix systems**, you need to source a file that will export the environment variables. This file is generated by `espup` and is located in your home directory by default. There are different ways to source the file: 85 | - Source this file in every terminal: 86 | 1. Source the export file: `. $HOME/export-esp.sh` 87 | 88 | This approach **requires running the command in every new shell**. 89 | - Create an alias for executing the `export-esp.sh`: 90 | 1. Copy and paste the following command to your shell’s profile (`.profile`, `.bashrc`, `.zprofile`, etc.): `alias get_esprs='. $HOME/export-esp.sh'` 91 | 2. Refresh the configuration by restarting the terminal session or by running `source [path to profile]`, for example, `source ~/.bashrc`. 92 | 93 | This approach **requires running the alias in every new shell**. 94 | - Add the environment variables to your shell profile directly: 95 | 1. Add the content of `$HOME/export-esp.sh` to your shell’s profile: `cat $HOME/export-esp.sh >> [path to profile]`, for example, `cat $HOME/export-esp.sh >> ~/.bashrc`. 96 | 2. Refresh the configuration by restarting the terminal session or by running `source [path to profile]`, for example, `source ~/.bashrc`. 97 | 98 | > [!IMPORTANT] 99 | > On Windows, environment variables are automatically injected into your system and don't need to be sourced. 100 | 101 | ## Usage 102 | 103 | ``` 104 | Usage: espup 105 | 106 | Commands: 107 | completions Generate completions for the given shell 108 | install Installs Espressif Rust ecosystem 109 | uninstall Uninstalls Espressif Rust ecosystem 110 | update Updates Xtensa Rust toolchain 111 | help Print this message or the help of the given subcommand(s) 112 | 113 | Options: 114 | -h, --help Print help 115 | -V, --version Print version 116 | ``` 117 | ### Completions Subcommand 118 | 119 | For detailed instructions on how to enable tab completion, see [Enable tab completion for Bash, Fish, Zsh, or PowerShell](#enable-tab-completion-for-bash-fish-zsh-or-powershell) section. 120 | 121 | ``` 122 | Usage: espup completions [OPTIONS] 123 | 124 | Arguments: 125 | Shell to generate completions for [possible values: bash, elvish, fish, powershell, zsh] 126 | 127 | Options: 128 | -l, --log-level Verbosity level of the logs [default: info] [possible values: debug, info, warn, error] 129 | -h, --help Print help 130 | ``` 131 | 132 | ### Install Subcommand 133 | 134 | > [!NOTE] 135 | > #### Xtensa Rust destination path 136 | > Installation paths can be modified by setting the environment variables [`CARGO_HOME`](https://doc.rust-lang.org/cargo/reference/environment-variables.html) and [`RUSTUP_HOME`](https://rust-lang.github.io/rustup/environment-variables.html) before running the `install` command. By default, toolchains will be installed under `/toolchains/esp`, although this can be changed using the `-a/--name` option. 137 | 138 | > [!NOTE] 139 | > #### GitHub API 140 | > During the installation process, several GitHub queries are made, [which are subject to certain limits](https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#rate-limiting). Our number of queries should not hit the limit unless you are running `espup install` command numerous times in a short span of time. We recommend setting the [`GITHUB_TOKEN` environment variable](https://docs.github.com/en/actions/security-guides/automatic-token-authentication#about-the-github_token-secret) when using `espup` in CI, if you want to use `espup` on CI, recommend using it via the [`xtensa-toolchain` action](https://github.com/esp-rs/xtensa-toolchain/), and making sure `GITHUB_TOKEN` is not set when using it on a host machine. See https://github.com/esp-rs/xtensa-toolchain/issues/15 for more details on this. 141 | 142 | ``` 143 | Usage: espup install [OPTIONS] 144 | 145 | Options: 146 | -d, --default-host 147 | Target triple of the host 148 | 149 | [possible values: x86_64-unknown-linux-gnu, aarch64-unknown-linux-gnu, x86_64-pc-windows-msvc, x86_64-pc-windows-gnu, x86_64-apple-darwin, aarch64-apple-darwin] 150 | 151 | -r, --esp-riscv-gcc 152 | Install Espressif RISC-V toolchain built with croostool-ng 153 | 154 | Only install this if you don't want to use the systems RISC-V toolchain 155 | 156 | -f, --export-file 157 | Relative or full path for the export file that will be generated. If no path is provided, the file will be generated under home directory (https://docs.rs/dirs/latest/dirs/fn.home_dir.html) 158 | 159 | [env: ESPUP_EXPORT_FILE=] 160 | 161 | -e, --extended-llvm 162 | Extends the LLVM installation. 163 | 164 | This will install the whole LLVM instead of only installing the libs. 165 | 166 | -l, --log-level 167 | Verbosity level of the logs 168 | 169 | [default: info] 170 | [possible values: debug, info, warn, error] 171 | 172 | -a, --name 173 | Xtensa Rust toolchain name 174 | 175 | [default: esp] 176 | 177 | -b, --stable-version 178 | Stable Rust toolchain version. 179 | 180 | Note that only RISC-V targets use stable Rust channel. 181 | 182 | [default: stable] 183 | 184 | -k, --skip-version-parse 185 | Skips parsing Xtensa Rust version 186 | 187 | -s, --std 188 | Only install toolchains required for STD applications. 189 | 190 | With this option, espup will skip GCC installation (it will be handled by esp-idf-sys), hence you won't be able to build no_std applications. 191 | 192 | -t, --targets 193 | Comma or space separated list of targets [esp32,esp32c2,esp32c3,esp32c6,esp32h2,esp32s2,esp32s3,esp32p4,all] 194 | 195 | [default: all] 196 | 197 | -v, --toolchain-version 198 | Xtensa Rust toolchain version 199 | 200 | -h, --help 201 | Print help (see a summary with '-h') 202 | ``` 203 | 204 | ### Uninstall Subcommand 205 | 206 | ``` 207 | Usage: espup uninstall [OPTIONS] 208 | 209 | Options: 210 | -l, --log-level Verbosity level of the logs [default: info] [possible values: debug, info, warn, error] 211 | -a, --name Xtensa Rust toolchain name [default: esp] 212 | -h, --help Print help 213 | ``` 214 | 215 | ### Update Subcommand 216 | 217 | ``` 218 | Usage: espup update [OPTIONS] 219 | 220 | Options: 221 | -d, --default-host 222 | Target triple of the host 223 | 224 | [possible values: x86_64-unknown-linux-gnu, aarch64-unknown-linux-gnu, x86_64-pc-windows-msvc, x86_64-pc-windows-gnu, x86_64-apple-darwin, aarch64-apple-darwin] 225 | 226 | -f, --export-file 227 | Relative or full path for the export file that will be generated. If no path is provided, the file will be generated under home directory (https://docs.rs/dirs/latest/dirs/fn.home_dir.html) 228 | 229 | [env: ESPUP_EXPORT_FILE=] 230 | 231 | -e, --extended-llvm 232 | Extends the LLVM installation. 233 | 234 | This will install the whole LLVM instead of only installing the libs. 235 | 236 | -l, --log-level 237 | Verbosity level of the logs 238 | 239 | [default: info] 240 | [possible values: debug, info, warn, error] 241 | 242 | -a, --name 243 | Xtensa Rust toolchain name 244 | 245 | [default: esp] 246 | 247 | -b, --stable-version 248 | Stable Rust toolchain version. 249 | 250 | Note that only RISC-V targets use stable Rust channel. 251 | 252 | [default: stable] 253 | 254 | -k, --skip-version-parse 255 | Skips parsing Xtensa Rust version 256 | 257 | -s, --std 258 | Only install toolchains required for STD applications. 259 | 260 | With this option, espup will skip GCC installation (it will be handled by esp-idf-sys), hence you won't be able to build no_std applications. 261 | 262 | -t, --targets 263 | Comma or space separated list of targets [esp32,esp32c2,esp32c3,esp32c6,esp32h2,esp32s2,esp32s3,all] 264 | 265 | [default: all] 266 | 267 | -v, --toolchain-version 268 | Xtensa Rust toolchain version 269 | 270 | -h, --help 271 | Print help (see a summary with '-h') 272 | ``` 273 | 274 | ## Enable Tab Completion for Bash, Fish, Zsh, or PowerShell 275 | 276 | `espup` supports generating completion scripts for Bash, Fish, Zsh, and 277 | PowerShell. See `espup help completions` for full details, but the gist is as 278 | simple as using one of the following: 279 | 280 | ```console 281 | # Bash 282 | $ espup completions bash > ~/.local/share/bash-completion/completions/espup 283 | 284 | # Bash (macOS/Homebrew) 285 | $ espup completions bash > $(brew --prefix)/etc/bash_completion.d/espup.bash-completion 286 | 287 | # Fish 288 | $ mkdir -p ~/.config/fish/completions 289 | $ espup completions fish > ~/.config/fish/completions/espup.fish 290 | 291 | # Zsh 292 | $ espup completions zsh > ~/.zfunc/_espup 293 | 294 | # PowerShell v5.0+ 295 | $ espup completions powershell >> $PROFILE.CurrentUserCurrentHost 296 | # or 297 | $ espup completions powershell | Out-String | Invoke-Expression 298 | ``` 299 | 300 | **Note**: you may need to restart your shell in order for the changes to take 301 | effect. 302 | 303 | For `zsh`, you must then add the following line in your `~/.zshrc` before 304 | `compinit`: 305 | 306 | ```zsh 307 | fpath+=~/.zfunc 308 | ``` 309 | 310 | ## License 311 | 312 | Licensed under either of: 313 | 314 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 315 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 316 | 317 | at your option. 318 | 319 | ### Contribution 320 | 321 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. 322 | -------------------------------------------------------------------------------- /src/cli.rs: -------------------------------------------------------------------------------- 1 | //! Command line interface. 2 | 3 | use crate::targets::{Target, parse_targets}; 4 | use clap::Parser; 5 | use clap_complete::Shell; 6 | use std::{collections::HashSet, path::PathBuf}; 7 | 8 | #[derive(Debug, Parser)] 9 | pub struct CompletionsOpts { 10 | /// Verbosity level of the logs. 11 | #[arg(short = 'l', long, default_value = "info", value_parser = ["debug", "info", "warn", "error"])] 12 | pub log_level: String, 13 | /// Shell to generate completions for. 14 | pub shell: Shell, 15 | } 16 | 17 | #[derive(Debug, Parser)] 18 | pub struct InstallOpts { 19 | /// Target triple of the host. 20 | #[arg(short = 'd', long, value_parser = ["x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu", "x86_64-pc-windows-msvc", "x86_64-pc-windows-gnu" , "x86_64-apple-darwin" , "aarch64-apple-darwin"])] 21 | pub default_host: Option, 22 | /// Install Espressif RISC-V toolchain built with croostool-ng 23 | /// 24 | /// Only install this if you don't want to use the systems RISC-V toolchain 25 | #[arg(short = 'r', long)] 26 | pub esp_riscv_gcc: bool, 27 | /// Relative or full path for the export file that will be generated. If no path is provided, the file will be generated under home directory (https://docs.rs/dirs/latest/dirs/fn.home_dir.html). 28 | #[arg(short = 'f', long, env = "ESPUP_EXPORT_FILE")] 29 | pub export_file: Option, 30 | /// Extends the LLVM installation. 31 | /// 32 | /// This will install the whole LLVM instead of only installing the libs. 33 | #[arg(short = 'e', long)] 34 | pub extended_llvm: bool, 35 | /// Verbosity level of the logs. 36 | #[arg(short = 'l', long, default_value = "info", value_parser = ["debug", "info", "warn", "error"])] 37 | pub log_level: String, 38 | /// Xtensa Rust toolchain name. 39 | #[arg(short = 'a', long, default_value = "esp")] 40 | pub name: String, 41 | /// Stable Rust toolchain version. 42 | /// 43 | /// Note that only RISC-V targets use stable Rust channel. 44 | #[arg(short = 'b', long, default_value = "stable")] 45 | pub stable_version: String, 46 | /// Skips parsing Xtensa Rust version. 47 | #[arg(short = 'k', long, requires = "toolchain_version")] 48 | pub skip_version_parse: bool, 49 | /// Only install toolchains required for STD applications. 50 | /// 51 | /// With this option, espup will skip GCC installation (it will be handled by esp-idf-sys), hence you won't be able to build no_std applications. 52 | #[arg(short = 's', long)] 53 | pub std: bool, 54 | /// Comma or space separated list of targets [esp32,esp32c2,esp32c3,esp32c6,esp32h2,esp32s2,esp32s3,esp32p4,all]. 55 | #[arg(short = 't', long, default_value = "all", value_parser = parse_targets)] 56 | pub targets: HashSet, 57 | /// Xtensa Rust toolchain version. 58 | #[arg(short = 'v', long)] 59 | pub toolchain_version: Option, 60 | /// Crosstool-NG toolchain version, e.g. (14.2.0_20241119) 61 | #[arg(short = 'c', long)] 62 | pub crosstool_toolchain_version: Option, 63 | } 64 | 65 | #[derive(Debug, Parser)] 66 | pub struct UninstallOpts { 67 | /// Verbosity level of the logs. 68 | #[arg(short = 'l', long, default_value = "info", value_parser = ["debug", "info", "warn", "error"])] 69 | pub log_level: String, 70 | /// Xtensa Rust toolchain name. 71 | #[arg(short = 'a', long, default_value = "esp")] 72 | pub name: String, 73 | /// GCC toolchain version. 74 | #[arg(short = 'c', long)] 75 | pub crosstool_toolchain_version: Option, 76 | } 77 | -------------------------------------------------------------------------------- /src/env.rs: -------------------------------------------------------------------------------- 1 | //! Environment variables set up and export file support. 2 | 3 | use crate::error::Error; 4 | use directories::BaseDirs; 5 | use log::debug; 6 | use std::{ 7 | env, 8 | fs::File, 9 | io::Write, 10 | path::{Path, PathBuf}, 11 | }; 12 | #[cfg(windows)] 13 | use winreg::{ 14 | RegKey, 15 | enums::{HKEY_CURRENT_USER, KEY_READ, KEY_WRITE}, 16 | }; 17 | 18 | #[cfg(windows)] 19 | const DEFAULT_EXPORT_FILE: &str = "export-esp.ps1"; 20 | #[cfg(not(windows))] 21 | const DEFAULT_EXPORT_FILE: &str = "export-esp.sh"; 22 | 23 | #[cfg(windows)] 24 | /// Sets an environment variable for the current user. 25 | pub fn set_env_variable(key: &str, value: &str) -> Result<(), Error> { 26 | use std::ptr; 27 | use winapi::shared::minwindef::*; 28 | use winapi::um::winuser::{ 29 | HWND_BROADCAST, SMTO_ABORTIFHUNG, SendMessageTimeoutA, WM_SETTINGCHANGE, 30 | }; 31 | 32 | let hkcu = RegKey::predef(HKEY_CURRENT_USER); 33 | let environment_key = hkcu.open_subkey_with_flags("Environment", KEY_WRITE)?; 34 | environment_key.set_value(key, &value)?; 35 | 36 | // Tell other processes to update their environment 37 | #[allow(clippy::unnecessary_cast)] 38 | unsafe { 39 | SendMessageTimeoutA( 40 | HWND_BROADCAST, 41 | WM_SETTINGCHANGE, 42 | 0 as WPARAM, 43 | c"Environment".as_ptr() as LPARAM, 44 | SMTO_ABORTIFHUNG, 45 | 5000, 46 | ptr::null_mut(), 47 | ); 48 | } 49 | 50 | Ok(()) 51 | } 52 | 53 | #[cfg(windows)] 54 | /// Deletes an environment variable for the current user. 55 | pub fn delete_env_variable(key: &str) -> Result<(), Error> { 56 | let root = RegKey::predef(HKEY_CURRENT_USER); 57 | let environment = root.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)?; 58 | 59 | let reg_value = environment.get_raw_value(key); 60 | if reg_value.is_err() { 61 | return Ok(()); 62 | } 63 | 64 | unsafe { 65 | env::remove_var(key); 66 | } 67 | 68 | let hkcu = RegKey::predef(HKEY_CURRENT_USER); 69 | let environment_key = hkcu.open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)?; 70 | environment_key.delete_value(key)?; 71 | Ok(()) 72 | } 73 | 74 | /// Returns the absolute path to the export file, uses the DEFAULT_EXPORT_FILE if no arg is provided. 75 | pub fn get_export_file(export_file: Option) -> Result { 76 | if let Some(export_file) = export_file { 77 | if export_file.is_dir() { 78 | return Err(Error::InvalidDestination(export_file.display().to_string())); 79 | } 80 | if export_file.is_absolute() { 81 | Ok(export_file) 82 | } else { 83 | let current_dir = env::current_dir()?; 84 | Ok(current_dir.join(export_file)) 85 | } 86 | } else { 87 | Ok(BaseDirs::new() 88 | .unwrap() 89 | .home_dir() 90 | .join(DEFAULT_EXPORT_FILE)) 91 | } 92 | } 93 | 94 | /// Creates the export file with the necessary environment variables. 95 | pub fn create_export_file(export_file: &PathBuf, exports: &[String]) -> Result<(), Error> { 96 | debug!("Creating export file"); 97 | let mut file = File::create(export_file)?; 98 | for e in exports.iter() { 99 | #[cfg(windows)] 100 | let e = e.replace('/', r"\"); 101 | file.write_all(e.as_bytes())?; 102 | file.write_all(b"\n")?; 103 | } 104 | 105 | Ok(()) 106 | } 107 | 108 | #[cfg(windows)] 109 | // Get the windows PATH variable out of the registry as a String. 110 | pub fn get_windows_path_var() -> Result { 111 | let hkcu = RegKey::predef(HKEY_CURRENT_USER); 112 | let env = hkcu.open_subkey("Environment")?; 113 | let path: String = env.get_value("Path")?; 114 | Ok(path) 115 | } 116 | 117 | #[cfg(windows)] 118 | /// Instructions to export the environment variables. 119 | pub fn set_env() -> Result<(), Error> { 120 | let mut path = get_windows_path_var()?; 121 | 122 | if let Ok(xtensa_gcc) = env::var("XTENSA_GCC") { 123 | let xtensa_gcc: &str = &xtensa_gcc; 124 | if !path.contains(xtensa_gcc) { 125 | path = format!("{};{}", xtensa_gcc, path); 126 | } 127 | } 128 | 129 | if let Ok(riscv_gcc) = env::var("RISCV_GCC") { 130 | let riscv_gcc: &str = &riscv_gcc; 131 | if !path.contains(riscv_gcc) { 132 | path = format!("{};{}", riscv_gcc, path); 133 | } 134 | } 135 | 136 | if let Ok(libclang_path) = env::var("LIBCLANG_PATH") { 137 | set_env_variable("LIBCLANG_PATH", &libclang_path)?; 138 | } 139 | 140 | if let Ok(libclang_bin_path) = env::var("LIBCLANG_BIN_PATH") { 141 | let libclang_bin_path: &str = &libclang_bin_path; 142 | if !path.contains(libclang_bin_path) { 143 | path = format!("{};{}", libclang_bin_path, path); 144 | } 145 | } 146 | 147 | if let Ok(clang_path) = env::var("CLANG_PATH") { 148 | let clang_path: &str = &clang_path; 149 | if !path.contains(clang_path) { 150 | path = format!("{};{}", clang_path, path); 151 | } 152 | } 153 | 154 | set_env_variable("PATH", &path)?; 155 | Ok(()) 156 | } 157 | 158 | /// Instructions to export the environment variables. 159 | pub fn print_post_install_msg(export_file: &Path) -> Result<(), Error> { 160 | #[cfg(windows)] 161 | if cfg!(windows) { 162 | println!( 163 | "\n\tYour environments variables have been updated! Shell may need to be restarted for changes to be effective" 164 | ); 165 | println!( 166 | "\tA file was created at '{}' showing the injected environment variables", 167 | export_file.display() 168 | ); 169 | println!( 170 | "\tIf you get still get errors, try manually adding the environment variables by running '{}'", 171 | export_file.display() 172 | ); 173 | } 174 | #[cfg(unix)] 175 | if cfg!(unix) { 176 | println!( 177 | "\n\tTo get started, you need to set up some environment variables by running: '. {}'", 178 | export_file.display() 179 | ); 180 | println!( 181 | "\tThis step must be done every time you open a new terminal.\n\t See other methods for setting the environment in https://esp-rs.github.io/book/installation/riscv-and-xtensa.html#3-set-up-the-environment-variables", 182 | ); 183 | } 184 | Ok(()) 185 | } 186 | 187 | #[cfg(test)] 188 | mod tests { 189 | use crate::env::{DEFAULT_EXPORT_FILE, create_export_file, get_export_file}; 190 | use directories::BaseDirs; 191 | use std::{ 192 | env::current_dir, 193 | fs::{create_dir_all, read_to_string}, 194 | path::PathBuf, 195 | }; 196 | use tempfile::TempDir; 197 | 198 | #[test] 199 | #[allow(unused_variables)] 200 | fn test_get_export_file() { 201 | // No arg provided 202 | let home_dir = BaseDirs::new().unwrap().home_dir().to_path_buf(); 203 | let export_file = home_dir.join(DEFAULT_EXPORT_FILE); 204 | assert!(matches!(get_export_file(None), Ok(export_file))); 205 | // Relative path 206 | let current_dir = current_dir().unwrap(); 207 | let export_file = current_dir.join("export.sh"); 208 | assert!(matches!( 209 | get_export_file(Some(PathBuf::from("export.sh"))), 210 | Ok(export_file) 211 | )); 212 | // Absolute path 213 | let export_file = PathBuf::from("/home/user/export.sh"); 214 | assert!(matches!( 215 | get_export_file(Some(PathBuf::from("/home/user/export.sh"))), 216 | Ok(export_file) 217 | )); 218 | // Path is a directory instead of a file 219 | assert!(get_export_file(Some(home_dir)).is_err()); 220 | } 221 | 222 | #[test] 223 | fn test_create_export_file() { 224 | // Creates the export file and writes the correct content to it 225 | let temp_dir = TempDir::new().unwrap(); 226 | let export_file = temp_dir.path().join("export.sh"); 227 | let exports = vec![ 228 | "export VAR1=value1".to_string(), 229 | "export VAR2=value2".to_string(), 230 | ]; 231 | create_export_file(&export_file, &exports).unwrap(); 232 | let contents = read_to_string(export_file).unwrap(); 233 | assert_eq!(contents, "export VAR1=value1\nexport VAR2=value2\n"); 234 | 235 | // Returns the correct error when it fails to create the export file (it already exists) 236 | let temp_dir = TempDir::new().unwrap(); 237 | let export_file = temp_dir.path().join("export.sh"); 238 | create_dir_all(&export_file).unwrap(); 239 | let exports = vec![ 240 | "export VAR1=value1".to_string(), 241 | "export VAR2=value2".to_string(), 242 | ]; 243 | assert!(create_export_file(&export_file, &exports).is_err()); 244 | } 245 | } 246 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | //! Custom error implementations. 2 | 3 | #[derive(Debug, miette::Diagnostic, thiserror::Error)] 4 | pub enum Error { 5 | #[diagnostic(code(espup::toolchain::create_directory))] 6 | #[error("Creating directory '{0}' failed")] 7 | CreateDirectory(String), 8 | 9 | #[diagnostic(code(espup::toolchain::rust::query_github))] 10 | #[error("Failed to query GitHub API: Rate Limiting")] 11 | GithubRateLimit, 12 | 13 | #[diagnostic(code(espup::toolchain::rust::query_github))] 14 | #[error("Failed to query GitHub API: Invalid Github token")] 15 | GithubTokenInvalid, 16 | 17 | #[diagnostic(code(espup::toolchain::rust::query_github))] 18 | #[error("Failed to connect to GitHub API: {0}")] 19 | GithubConnectivityError(String), 20 | 21 | #[diagnostic(code(espup::toolchain::http_error))] 22 | #[error("HTTP GET Error: {0}")] 23 | HttpError(String), 24 | 25 | #[diagnostic(code(espup::toolchain::rust::install_riscv_target))] 26 | #[error("Failed to Install RISC-V targets for '{0}' toolchain")] 27 | InstallRiscvTarget(String), 28 | 29 | #[diagnostic(code(espup::ivalid_destination))] 30 | #[error( 31 | "Invalid export file destination: '{0}'. Please, use an absolute or releative path (including the file and its extension)" 32 | )] 33 | InvalidDestination(String), 34 | 35 | #[diagnostic(code(espup::toolchain::rust::invalid_version))] 36 | #[error( 37 | "Invalid toolchain version '{0}'. Verify that the format is correct: '...' or '..', and that the release exists in https://github.com/esp-rs/rust-build/releases" 38 | )] 39 | InvalidVersion(String), 40 | 41 | #[error(transparent)] 42 | IoError(#[from] std::io::Error), 43 | 44 | #[diagnostic(code(espup::toolchain::rust::missing_rust))] 45 | #[error("Rust is not installed. Please, install Rust via rustup: https://rustup.rs/")] 46 | MissingRust, 47 | 48 | #[diagnostic(code(espup::remove_directory))] 49 | #[error("Failed to remove '{0}'")] 50 | RemoveDirectory(String), 51 | 52 | #[error(transparent)] 53 | RewquestError(#[from] reqwest::Error), 54 | 55 | #[diagnostic(code(espup::toolchain::rust::rustup_detection_error))] 56 | #[error("Error detecting rustup: {0}")] 57 | RustupDetection(String), 58 | 59 | #[diagnostic(code(espup::toolchain::rust::serialize_json))] 60 | #[error("Failed to serialize json from string")] 61 | SerializeJson, 62 | 63 | #[diagnostic(code(espup::toolchain::rust::uninstall_riscv_target))] 64 | #[error("Failed to uninstall RISC-V target")] 65 | UninstallRiscvTarget, 66 | 67 | #[diagnostic(code(espup::toolchain::unsupported_file_extension))] 68 | #[error("Unsuported file extension: '{0}'")] 69 | UnsuportedFileExtension(String), 70 | 71 | #[diagnostic(code(espup::host_triple::unsupported_host_triple))] 72 | #[error("Host triple '{0}' is not supported")] 73 | UnsupportedHostTriple(String), 74 | 75 | #[diagnostic(code(espup::targets::unsupported_target))] 76 | #[error("Target '{0}' is not supported")] 77 | UnsupportedTarget(String), 78 | 79 | #[diagnostic(code(espup::toolchain::rust::rust))] 80 | #[error("Failed to install 'rust' component of Xtensa Rust")] 81 | XtensaRust, 82 | 83 | #[diagnostic(code(espup::toolchain::rust::rust_src))] 84 | #[error("Failed to install 'rust-src' component of Xtensa Rust")] 85 | XtensaRustSrc, 86 | } 87 | -------------------------------------------------------------------------------- /src/host_triple.rs: -------------------------------------------------------------------------------- 1 | //! Host triple variants support. 2 | 3 | use crate::error::Error; 4 | use guess_host_triple::guess_host_triple; 5 | use miette::Result; 6 | use std::str::FromStr; 7 | use strum::{Display, EnumString}; 8 | 9 | #[derive(Display, Debug, Clone, EnumString, Default)] 10 | pub enum HostTriple { 11 | /// 64-bit Linux 12 | #[strum(serialize = "x86_64-unknown-linux-gnu")] 13 | #[default] 14 | X86_64UnknownLinuxGnu, 15 | /// ARM64 Linux 16 | #[strum(serialize = "aarch64-unknown-linux-gnu")] 17 | Aarch64UnknownLinuxGnu, 18 | /// 64-bit MSVC 19 | #[strum(serialize = "x86_64-pc-windows-msvc")] 20 | X86_64PcWindowsMsvc, 21 | /// 64-bit MinGW 22 | #[strum(serialize = "x86_64-pc-windows-gnu")] 23 | X86_64PcWindowsGnu, 24 | /// 64-bit macOS 25 | #[strum(serialize = "x86_64-apple-darwin")] 26 | X86_64AppleDarwin, 27 | /// ARM64 macOS 28 | #[strum(serialize = "aarch64-apple-darwin")] 29 | Aarch64AppleDarwin, 30 | } 31 | 32 | /// Parse the host triple if specified, otherwise guess it. 33 | pub fn get_host_triple(host_triple_arg: Option) -> Result { 34 | let host_triple = if let Some(host_triple) = &host_triple_arg { 35 | host_triple 36 | } else { 37 | guess_host_triple().unwrap() 38 | }; 39 | 40 | HostTriple::from_str(host_triple).map_err(|_| Error::UnsupportedHostTriple(host_triple.into())) 41 | } 42 | 43 | #[cfg(test)] 44 | mod tests { 45 | use crate::host_triple::{HostTriple, get_host_triple}; 46 | 47 | #[test] 48 | fn test_get_host_triple() { 49 | assert!(matches!( 50 | get_host_triple(Some("x86_64-unknown-linux-gnu".to_string())), 51 | Ok(HostTriple::X86_64UnknownLinuxGnu) 52 | )); 53 | assert!(matches!( 54 | get_host_triple(Some("aarch64-unknown-linux-gnu".to_string())), 55 | Ok(HostTriple::Aarch64UnknownLinuxGnu) 56 | )); 57 | assert!(matches!( 58 | get_host_triple(Some("x86_64-pc-windows-msvc".to_string())), 59 | Ok(HostTriple::X86_64PcWindowsMsvc) 60 | )); 61 | assert!(matches!( 62 | get_host_triple(Some("x86_64-pc-windows-gnu".to_string())), 63 | Ok(HostTriple::X86_64PcWindowsGnu) 64 | )); 65 | assert!(matches!( 66 | get_host_triple(Some("x86_64-apple-darwin".to_string())), 67 | Ok(HostTriple::X86_64AppleDarwin) 68 | )); 69 | assert!(matches!( 70 | get_host_triple(Some("aarch64-apple-darwin".to_string())), 71 | Ok(HostTriple::Aarch64AppleDarwin) 72 | )); 73 | 74 | assert!(get_host_triple(Some("some-fake-triple".to_string())).is_err()); 75 | 76 | // Guessed Host Triples 77 | #[cfg(all(target_os = "linux", target_arch = "aarch64"))] 78 | assert!(matches!( 79 | get_host_triple(None), 80 | Ok(HostTriple::Aarch64UnknownLinuxGnu) 81 | )); 82 | #[cfg(all(target_os = "linux", target_arch = "x86_64"))] 83 | assert!(matches!( 84 | get_host_triple(None), 85 | Ok(HostTriple::X86_64UnknownLinuxGnu) 86 | )); 87 | #[cfg(all(target_os = "windows", target_arch = "x86_64", target_env = "msvc"))] 88 | assert!(matches!( 89 | get_host_triple(None), 90 | Ok(HostTriple::X86_64PcWindowsMsvc) 91 | )); 92 | #[cfg(all(target_os = "windows", target_arch = "x86_64", target_env = "gnu"))] 93 | assert!(matches!( 94 | get_host_triple(None), 95 | Ok(HostTriple::X86_64PcWindowsGnu) 96 | )); 97 | #[cfg(all(target_os = "macos", target_arch = "x86_64"))] 98 | assert!(matches!( 99 | get_host_triple(None), 100 | Ok(HostTriple::X86_64AppleDarwin) 101 | )); 102 | #[cfg(all(target_os = "macos", target_arch = "aarch64"))] 103 | assert!(matches!( 104 | get_host_triple(None), 105 | Ok(HostTriple::Aarch64AppleDarwin) 106 | )); 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod cli; 2 | pub mod env; 3 | pub mod error; 4 | pub mod host_triple; 5 | pub mod targets; 6 | pub mod toolchain; 7 | 8 | pub mod logging { 9 | use env_logger::{Builder, Env, WriteStyle}; 10 | 11 | use crate::toolchain::PROCESS_BARS; 12 | 13 | /// Initializes the logger 14 | pub fn initialize_logger(log_level: &str) { 15 | let logger = Builder::from_env(Env::default().default_filter_or(log_level)) 16 | .format(|buf, record| { 17 | use std::io::Write; 18 | writeln!( 19 | buf, 20 | "[{}]: {}", 21 | record.level().to_string().to_lowercase(), 22 | record.args() 23 | ) 24 | }) 25 | .write_style(WriteStyle::Always) 26 | .build(); 27 | let level = logger.filter(); 28 | // make logging and process bar no longer mixed up 29 | indicatif_log_bridge::LogWrapper::new(PROCESS_BARS.clone(), logger) 30 | .try_init() 31 | .unwrap(); 32 | log::set_max_level(level); 33 | } 34 | } 35 | 36 | pub mod update { 37 | use log::warn; 38 | use std::time::Duration; 39 | use update_informer::{Check, registry}; 40 | 41 | /// Check crates.io for a new version of the application 42 | pub fn check_for_update(name: &str, version: &str) { 43 | // By setting the interval to 0 seconds we invalidate the cache with each 44 | // invocation and ensure we're getting up-to-date results 45 | let informer = 46 | update_informer::new(registry::Crates, name, version).interval(Duration::ZERO); 47 | 48 | if let Some(version) = informer.check_version().ok().flatten() { 49 | warn!("A new version of {name} ('{version}') is available"); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use clap::{CommandFactory, Parser}; 2 | use espup::{ 3 | cli::{CompletionsOpts, InstallOpts, UninstallOpts}, 4 | logging::initialize_logger, 5 | toolchain::{ 6 | InstallMode, 7 | gcc::uninstall_gcc_toolchains, 8 | install as toolchain_install, 9 | llvm::Llvm, 10 | remove_dir, 11 | rust::{XtensaRust, get_rustup_home}, 12 | }, 13 | update::check_for_update, 14 | }; 15 | use log::info; 16 | use miette::Result; 17 | use std::{env, io::stdout}; 18 | 19 | #[derive(Parser)] 20 | #[command(about, version)] 21 | struct Cli { 22 | #[command(subcommand)] 23 | subcommand: SubCommand, 24 | } 25 | 26 | #[derive(Parser)] 27 | pub enum SubCommand { 28 | /// Generate completions for the given shell. 29 | Completions(CompletionsOpts), 30 | /// Installs Espressif Rust ecosystem. 31 | // We use a Box here to make clippy happy (see https://rust-lang.github.io/rust-clippy/master/index.html#large_enum_variant) 32 | Install(Box), 33 | /// Uninstalls Espressif Rust ecosystem. 34 | Uninstall(UninstallOpts), 35 | /// Updates Xtensa Rust toolchain. 36 | Update(Box), 37 | } 38 | 39 | /// Updates Xtensa Rust toolchain. 40 | async fn completions(args: CompletionsOpts) -> Result<()> { 41 | initialize_logger(&args.log_level); 42 | check_for_update(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); 43 | 44 | info!("Generating completions for {} shell", args.shell); 45 | 46 | clap_complete::generate(args.shell, &mut Cli::command(), "espup", &mut stdout()); 47 | 48 | info!("Completions successfully generated!"); 49 | 50 | Ok(()) 51 | } 52 | 53 | /// Installs or updates the Rust for ESP chips environment 54 | async fn install(args: InstallOpts, install_mode: InstallMode) -> Result<()> { 55 | initialize_logger(&args.log_level); 56 | check_for_update(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); 57 | 58 | toolchain_install(args, install_mode).await?; 59 | Ok(()) 60 | } 61 | 62 | /// Uninstalls the Rust for ESP chips environment 63 | async fn uninstall(args: UninstallOpts) -> Result<()> { 64 | initialize_logger(&args.log_level); 65 | check_for_update(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); 66 | 67 | info!("Uninstalling the Espressif Rust ecosystem"); 68 | let toolchain_dir = get_rustup_home().join("toolchains").join(args.name); 69 | 70 | if toolchain_dir.exists() { 71 | Llvm::uninstall(&toolchain_dir).await?; 72 | 73 | uninstall_gcc_toolchains(&toolchain_dir, args.crosstool_toolchain_version).await?; 74 | 75 | XtensaRust::uninstall(&toolchain_dir).await?; 76 | 77 | remove_dir(&toolchain_dir).await?; 78 | } 79 | 80 | info!("Uninstallation successfully completed!"); 81 | Ok(()) 82 | } 83 | 84 | #[tokio::main] 85 | async fn main() -> Result<()> { 86 | match Cli::parse().subcommand { 87 | SubCommand::Completions(args) => completions(args).await, 88 | SubCommand::Install(args) => install(*args, InstallMode::Install).await, 89 | SubCommand::Update(args) => install(*args, InstallMode::Update).await, 90 | SubCommand::Uninstall(args) => uninstall(args).await, 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/targets.rs: -------------------------------------------------------------------------------- 1 | //! ESP32 chip variants support. 2 | 3 | use crate::error::Error; 4 | use log::debug; 5 | use miette::Result; 6 | use std::{collections::HashSet, str::FromStr}; 7 | use strum::{Display, EnumIter, EnumString, IntoEnumIterator}; 8 | 9 | #[derive(Clone, Copy, EnumIter, EnumString, PartialEq, Hash, Eq, Debug, Display)] 10 | #[strum(serialize_all = "lowercase")] 11 | pub enum Target { 12 | /// Xtensa LX6 based dual core 13 | ESP32 = 0, 14 | /// RISC-V based single core 15 | ESP32C2, 16 | /// RISC-V based single core 17 | ESP32C3, 18 | /// RISC-V based single core 19 | ESP32C6, 20 | /// RISC-V based single core 21 | ESP32H2, 22 | /// Xtensa LX7 based single core 23 | ESP32S2, 24 | /// Xtensa LX7 based dual core 25 | ESP32S3, 26 | /// RISC-V based dual core 27 | ESP32P4, 28 | } 29 | 30 | impl Target { 31 | /// Returns true if the target is a RISC-V based chip. 32 | pub fn is_riscv(&self) -> bool { 33 | !self.is_xtensa() 34 | } 35 | 36 | /// Returns true if the target is a Xtensa based chip. 37 | pub fn is_xtensa(&self) -> bool { 38 | matches!(self, Target::ESP32 | Target::ESP32S2 | Target::ESP32S3) 39 | } 40 | } 41 | 42 | /// Returns a vector of Chips from a comma or space separated string. 43 | pub fn parse_targets(targets_str: &str) -> Result, Error> { 44 | debug!("Parsing targets: {}", targets_str); 45 | 46 | let targets_str = targets_str.to_lowercase(); 47 | let targets_str = targets_str.trim(); 48 | 49 | let targets: HashSet = if targets_str.contains("all") { 50 | Target::iter().collect() 51 | } else { 52 | let mut targets = HashSet::new(); 53 | for target in targets_str.split([',', ' ']) { 54 | targets.insert( 55 | Target::from_str(target).map_err(|_| Error::UnsupportedTarget(target.into()))?, 56 | ); 57 | } 58 | 59 | targets 60 | }; 61 | 62 | debug!("Parsed targets: {:?}", targets); 63 | Ok(targets) 64 | } 65 | 66 | #[cfg(test)] 67 | mod tests { 68 | use crate::targets::{Target, parse_targets}; 69 | use std::collections::HashSet; 70 | 71 | #[test] 72 | #[allow(unused_variables)] 73 | fn test_parse_targets() { 74 | let targets: HashSet = [Target::ESP32].into_iter().collect(); 75 | assert!(matches!(parse_targets("esp32"), Ok(targets))); 76 | let targets: HashSet = [Target::ESP32, Target::ESP32S2].into_iter().collect(); 77 | assert!(matches!(parse_targets("esp32,esp32s2"), Ok(targets))); 78 | let targets: HashSet = [Target::ESP32S3, Target::ESP32].into_iter().collect(); 79 | assert!(matches!(parse_targets("esp32s3 esp32"), Ok(targets))); 80 | let targets: HashSet = [Target::ESP32S3, Target::ESP32, Target::ESP32C3] 81 | .into_iter() 82 | .collect(); 83 | assert!(matches!( 84 | parse_targets("esp32s3,esp32,esp32c3"), 85 | Ok(targets) 86 | )); 87 | let targets: HashSet = [ 88 | Target::ESP32, 89 | Target::ESP32C2, 90 | Target::ESP32C3, 91 | Target::ESP32C6, 92 | Target::ESP32H2, 93 | Target::ESP32S2, 94 | Target::ESP32S3, 95 | Target::ESP32P4, 96 | ] 97 | .into_iter() 98 | .collect(); 99 | assert!(matches!(parse_targets("all"), Ok(targets))); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/toolchain/gcc.rs: -------------------------------------------------------------------------------- 1 | //! GCC Toolchain source and installation tools. 2 | 3 | #[cfg(windows)] 4 | use crate::env::{get_windows_path_var, set_env_variable}; 5 | use crate::{ 6 | error::Error, 7 | host_triple::HostTriple, 8 | toolchain::{Installable, download_file}, 9 | }; 10 | use async_trait::async_trait; 11 | use log::{debug, info, warn}; 12 | use miette::Result; 13 | use std::path::{Path, PathBuf}; 14 | #[cfg(windows)] 15 | use std::{env, fs::File}; 16 | use tokio::fs::remove_dir_all; 17 | 18 | const DEFAULT_GCC_REPOSITORY: &str = "https://github.com/espressif/crosstool-NG/releases/download"; 19 | const DEFAULT_GCC_RELEASE: &str = "14.2.0_20241119"; 20 | pub const RISCV_GCC: &str = "riscv32-esp-elf"; 21 | pub const XTENSA_GCC: &str = "xtensa-esp-elf"; 22 | 23 | #[derive(Debug, Clone)] 24 | pub struct Gcc { 25 | /// Host triple. 26 | pub host_triple: HostTriple, 27 | /// GCC Toolchain architecture. 28 | pub arch: String, 29 | /// GCC Toolchain path. 30 | pub path: PathBuf, 31 | /// GCC release version. 32 | pub release_version: String, 33 | } 34 | 35 | impl Gcc { 36 | /// Gets the binary path. 37 | pub fn get_bin_path(&self) -> String { 38 | let bin_path = format!("{}/{}/bin", &self.path.to_str().unwrap(), &self.arch); 39 | match std::cfg!(windows) { 40 | true => bin_path.replace('/', "\\"), 41 | false => bin_path, 42 | } 43 | } 44 | 45 | /// Create a new instance with default values and proper toolchain name. 46 | pub fn new( 47 | arch: &str, 48 | host_triple: &HostTriple, 49 | toolchain_path: &Path, 50 | release_version: Option, 51 | ) -> Self { 52 | let release_version = release_version.unwrap_or_else(|| DEFAULT_GCC_RELEASE.to_string()); 53 | 54 | #[cfg(unix)] 55 | let path = toolchain_path 56 | .join(arch) 57 | .join(format!("esp-{}", release_version)); 58 | #[cfg(windows)] 59 | let path: PathBuf = toolchain_path.into(); 60 | 61 | Self { 62 | host_triple: host_triple.clone(), 63 | arch: arch.to_string(), 64 | path, 65 | release_version, 66 | } 67 | } 68 | } 69 | 70 | #[async_trait] 71 | impl Installable for Gcc { 72 | async fn install(&self) -> Result, Error> { 73 | let extension = get_artifact_extension(&self.host_triple); 74 | info!("Installing GCC ({})", self.arch); 75 | debug!("GCC path: {}", self.path.display()); 76 | 77 | #[cfg(unix)] 78 | let is_installed = self.path.exists(); 79 | #[cfg(windows)] 80 | let is_installed = self 81 | .path 82 | .join(&self.arch) 83 | .join(&self.release_version) 84 | .exists(); 85 | 86 | if is_installed { 87 | warn!( 88 | "Previous installation of GCC exists in: '{}'. Reusing this installation", 89 | &self.path.display() 90 | ); 91 | } else { 92 | let gcc_file = format!( 93 | "{}-{}-{}.{}", 94 | self.arch, 95 | self.release_version, 96 | get_arch(&self.host_triple).unwrap(), 97 | extension 98 | ); 99 | let gcc_dist_url = format!( 100 | "{}/esp-{}/{}", 101 | DEFAULT_GCC_REPOSITORY, self.release_version, gcc_file 102 | ); 103 | download_file( 104 | gcc_dist_url, 105 | &format!("{}.{}", &self.arch, extension), 106 | &self.path.display().to_string(), 107 | true, 108 | false, 109 | ) 110 | .await?; 111 | } 112 | let mut exports: Vec = Vec::new(); 113 | 114 | #[cfg(windows)] 115 | if cfg!(windows) { 116 | File::create(self.path.join(&self.arch).join(&self.release_version))?; 117 | 118 | exports.push(format!( 119 | "$Env:PATH = \"{};\" + $Env:PATH", 120 | &self.get_bin_path() 121 | )); 122 | if self.arch == RISCV_GCC { 123 | unsafe { 124 | env::set_var("RISCV_GCC", self.get_bin_path()); 125 | } 126 | } else { 127 | unsafe { 128 | env::set_var("XTENSA_GCC", self.get_bin_path()); 129 | } 130 | } 131 | } 132 | #[cfg(unix)] 133 | exports.push(format!("export PATH=\"{}:$PATH\"", &self.get_bin_path())); 134 | 135 | Ok(exports) 136 | } 137 | 138 | fn name(&self) -> String { 139 | format!("GCC ({})", self.arch) 140 | } 141 | } 142 | 143 | /// Gets the name of the GCC arch based on the host triple. 144 | fn get_arch(host_triple: &HostTriple) -> Result<&str> { 145 | match host_triple { 146 | HostTriple::X86_64AppleDarwin => Ok("x86_64-apple-darwin"), 147 | HostTriple::Aarch64AppleDarwin => Ok("aarch64-apple-darwin"), 148 | HostTriple::X86_64UnknownLinuxGnu => Ok("x86_64-linux-gnu"), 149 | HostTriple::Aarch64UnknownLinuxGnu => Ok("aarch64-linux-gnu"), 150 | HostTriple::X86_64PcWindowsMsvc | HostTriple::X86_64PcWindowsGnu => { 151 | Ok("x86_64-w64-mingw32") 152 | } 153 | } 154 | } 155 | 156 | /// Gets the artifact extension based on the host triple. 157 | fn get_artifact_extension(host_triple: &HostTriple) -> &str { 158 | match host_triple { 159 | HostTriple::X86_64PcWindowsMsvc | HostTriple::X86_64PcWindowsGnu => "zip", 160 | _ => "tar.xz", 161 | } 162 | } 163 | 164 | /// Checks if the toolchain is pressent, if present uninstalls it. 165 | pub async fn uninstall_gcc_toolchains( 166 | toolchain_path: &Path, 167 | release_version: Option, 168 | ) -> Result<(), Error> { 169 | info!("Uninstalling GCC"); 170 | 171 | #[cfg_attr(not(windows), allow(unused_variables))] 172 | // release_version is only used in the windows block, but is also being passed, and so clippy will complain if not marked unused across platforms 173 | let release_version = release_version.unwrap_or_else(|| DEFAULT_GCC_RELEASE.to_string()); 174 | 175 | let gcc_toolchains = vec![XTENSA_GCC, RISCV_GCC]; 176 | 177 | for toolchain in gcc_toolchains { 178 | let gcc_path = toolchain_path.join(toolchain); 179 | if gcc_path.exists() { 180 | #[cfg(windows)] 181 | if cfg!(windows) { 182 | let mut updated_path = get_windows_path_var()?; 183 | let gcc_version_path = format!( 184 | "{}\\esp-{}\\{}\\bin", 185 | gcc_path.display(), 186 | release_version, 187 | toolchain 188 | ); 189 | updated_path = updated_path.replace(&format!("{gcc_version_path};"), ""); 190 | let bin_path = format!("{}\\bin", gcc_path.display()); 191 | updated_path = updated_path.replace(&format!("{bin_path};"), ""); 192 | 193 | set_env_variable("PATH", &updated_path)?; 194 | } 195 | remove_dir_all(&gcc_path) 196 | .await 197 | .map_err(|_| Error::RemoveDirectory(gcc_path.display().to_string()))?; 198 | } 199 | } 200 | 201 | Ok(()) 202 | } 203 | -------------------------------------------------------------------------------- /src/toolchain/llvm.rs: -------------------------------------------------------------------------------- 1 | //! LLVM Toolchain source and installation tools. 2 | 3 | #[cfg(windows)] 4 | use crate::env::{delete_env_variable, get_windows_path_var, set_env_variable}; 5 | use crate::{ 6 | error::Error, 7 | host_triple::HostTriple, 8 | toolchain::{Installable, download_file, rust::RE_EXTENDED_SEMANTIC_VERSION}, 9 | }; 10 | use async_trait::async_trait; 11 | #[cfg(unix)] 12 | use directories::BaseDirs; 13 | use log::{info, warn}; 14 | use miette::Result; 15 | use regex::Regex; 16 | use std::path::{Path, PathBuf}; 17 | #[cfg(windows)] 18 | use std::{env, fs::File}; 19 | #[cfg(unix)] 20 | use std::{fs::create_dir_all, os::unix::fs::symlink}; 21 | use tokio::fs::remove_dir_all; 22 | 23 | const DEFAULT_LLVM_REPOSITORY: &str = "https://github.com/espressif/llvm-project/releases/download"; 24 | const DEFAULT_LLVM_15_VERSION: &str = "esp-15.0.0-20221201"; 25 | #[cfg(windows)] 26 | const OLD_LLVM_16_VERSION: &str = "esp-16.0.0-20230516"; 27 | const DEFAULT_LLVM_16_VERSION: &str = "esp-16.0.4-20231113"; 28 | const DEFAULT_LLVM_17_VERSION: &str = "esp-17.0.1_20240419"; 29 | const DEFAULT_LLVM_18_VERSION: &str = "esp-18.1.2_20240912"; 30 | const DEFAULT_LLVM_19_VERSION: &str = "esp-19.1.2_20250225"; 31 | pub const CLANG_NAME: &str = "xtensa-esp32-elf-clang"; 32 | 33 | #[derive(Debug, Clone, Default)] 34 | pub struct Llvm { 35 | // /// If `true`, full LLVM, instead of only libraries, are installed. 36 | extended: bool, 37 | /// LLVM libs-only toolchain file name. 38 | pub file_name_libs: Option, 39 | /// LLVM "full" toolchain file name. 40 | pub file_name_full: Option, 41 | /// Host triple. 42 | pub host_triple: HostTriple, 43 | /// LLVM Toolchain path. 44 | pub path: PathBuf, 45 | /// The repository containing LLVM sources. 46 | pub repository_url: String, 47 | /// LLVM Version ["15", "16", "17"]. 48 | pub version: String, 49 | } 50 | 51 | impl Llvm { 52 | /// Gets the name of the LLVM arch based on the host triple. 53 | fn get_arch(host_triple: &HostTriple, version: &str) -> String { 54 | if version == DEFAULT_LLVM_17_VERSION 55 | || version == DEFAULT_LLVM_18_VERSION 56 | || version == DEFAULT_LLVM_19_VERSION 57 | { 58 | let arch = match host_triple { 59 | HostTriple::Aarch64AppleDarwin => "aarch64-apple-darwin", 60 | HostTriple::X86_64AppleDarwin => "x86_64-apple-darwin", 61 | HostTriple::X86_64UnknownLinuxGnu => "x86_64-linux-gnu", 62 | HostTriple::Aarch64UnknownLinuxGnu => "aarch64-linux-gnu", 63 | HostTriple::X86_64PcWindowsMsvc | HostTriple::X86_64PcWindowsGnu => { 64 | "x86_64-w64-mingw32" 65 | } 66 | }; 67 | arch.to_string() 68 | } else { 69 | let arch = match host_triple { 70 | HostTriple::Aarch64AppleDarwin => "macos-arm64", 71 | HostTriple::X86_64AppleDarwin => "macos", 72 | HostTriple::X86_64UnknownLinuxGnu => "linux-amd64", 73 | HostTriple::Aarch64UnknownLinuxGnu => "linux-arm64", 74 | HostTriple::X86_64PcWindowsMsvc | HostTriple::X86_64PcWindowsGnu => "win64", 75 | }; 76 | arch.to_string() 77 | } 78 | } 79 | 80 | /// Gets the binary path. 81 | fn get_lib_path(&self) -> String { 82 | match std::cfg!(windows) { 83 | true => format!("{}/esp-clang/bin", self.path.to_str().unwrap()).replace('/', "\\"), 84 | false => format!("{}/esp-clang/lib", self.path.to_str().unwrap()), 85 | } 86 | } 87 | 88 | /// Gets the binary path of clang 89 | fn get_bin_path(&self) -> String { 90 | match std::cfg!(windows) { 91 | true => format!("{}/esp-clang/bin/clang.exe", self.path.to_str().unwrap()) 92 | .replace('/', "\\"), 93 | false => format!("{}/esp-clang/bin/clang", self.path.to_str().unwrap()), 94 | } 95 | } 96 | 97 | /// Create a new instance with default values and proper toolchain version. 98 | pub fn new( 99 | toolchain_path: &Path, 100 | host_triple: &HostTriple, 101 | extended: bool, 102 | xtensa_rust_version: &str, 103 | ) -> Result { 104 | let re_extended: Regex = Regex::new(RE_EXTENDED_SEMANTIC_VERSION).unwrap(); 105 | let (major, minor, patch, subpatch) = match re_extended.captures(xtensa_rust_version) { 106 | Some(version) => ( 107 | version.get(1).unwrap().as_str().parse::().unwrap(), 108 | version.get(2).unwrap().as_str().parse::().unwrap(), 109 | version.get(3).unwrap().as_str().parse::().unwrap(), 110 | version.get(4).unwrap().as_str().parse::().unwrap(), 111 | ), 112 | None => return Err(Error::InvalidVersion(xtensa_rust_version.to_string())), 113 | }; 114 | 115 | // Use LLVM 15 for versions 1.69.0.0 and below and LLVM 16 for versions 1.77.0 and bellow 116 | let version = if (major == 1 && minor == 69 && patch == 0 && subpatch == 0) 117 | || (major == 1 && minor < 69) 118 | { 119 | DEFAULT_LLVM_15_VERSION.to_string() 120 | } else if (major == 1 && minor == 77 && patch == 0 && subpatch == 0) 121 | || (major == 1 && minor < 77) 122 | { 123 | DEFAULT_LLVM_16_VERSION.to_string() 124 | } else if (major == 1 && minor == 81 && patch == 0 && subpatch == 0) 125 | || (major == 1 && minor < 81) 126 | { 127 | DEFAULT_LLVM_17_VERSION.to_string() 128 | } else if (major == 1 && minor == 84 && patch == 0 && subpatch == 0) 129 | || (major == 1 && minor < 84) 130 | { 131 | DEFAULT_LLVM_18_VERSION.to_string() 132 | } else { 133 | DEFAULT_LLVM_19_VERSION.to_string() 134 | }; 135 | 136 | let name = if version == DEFAULT_LLVM_17_VERSION 137 | || version == DEFAULT_LLVM_18_VERSION 138 | || version == DEFAULT_LLVM_19_VERSION 139 | { 140 | "clang-" 141 | } else { 142 | "llvm-" 143 | }; 144 | 145 | let (file_name_libs, file_name_full) = { 146 | let file_name_full = format!( 147 | "{}{}-{}.tar.xz", 148 | name, 149 | version, 150 | Self::get_arch(host_triple, &version) 151 | ); 152 | 153 | let file_name_libs = if version != DEFAULT_LLVM_17_VERSION 154 | && version != DEFAULT_LLVM_18_VERSION 155 | && version != DEFAULT_LLVM_19_VERSION 156 | { 157 | format!("libs_{file_name_full}") 158 | } else { 159 | format!("libs-{file_name_full}") 160 | }; 161 | 162 | // For LLVM 15 and 16 the "full" tarball was a superset of the "libs" tarball, so if 163 | // we're in extended LLVM mode we only need the "full" tarballs for those versions. 164 | // 165 | // Later LLVM versions are built such that the "full" tarball has a statically linked 166 | // `clang` binary and therefore doesn't contain libclang, and so then we need to fetch 167 | // both tarballs. 168 | if version == DEFAULT_LLVM_15_VERSION || version == DEFAULT_LLVM_16_VERSION { 169 | if extended { 170 | (None, Some(file_name_full)) 171 | } else { 172 | (Some(file_name_libs), None) 173 | } 174 | } else if extended { 175 | (Some(file_name_libs), Some(file_name_full)) 176 | } else { 177 | (Some(file_name_libs), None) 178 | } 179 | }; 180 | 181 | let repository_url = format!("{DEFAULT_LLVM_REPOSITORY}/{version}"); 182 | #[cfg(unix)] 183 | let path = toolchain_path.join(CLANG_NAME).join(&version); 184 | #[cfg(windows)] 185 | let path = toolchain_path.join(CLANG_NAME); 186 | 187 | Ok(Self { 188 | extended, 189 | file_name_libs, 190 | file_name_full, 191 | host_triple: host_triple.clone(), 192 | path, 193 | repository_url, 194 | version, 195 | }) 196 | } 197 | 198 | /// Uninstall LLVM toolchain. 199 | pub async fn uninstall(toolchain_path: &Path) -> Result<(), Error> { 200 | info!("Uninstalling Xtensa LLVM"); 201 | let llvm_path = toolchain_path.join(CLANG_NAME); 202 | if llvm_path.exists() { 203 | #[cfg(windows)] 204 | if cfg!(windows) { 205 | let mut updated_path = get_windows_path_var()?.replace( 206 | &format!( 207 | "{}\\{}\\esp-clang\\bin;", 208 | llvm_path.display().to_string().replace('/', "\\"), 209 | DEFAULT_LLVM_15_VERSION, 210 | ), 211 | "", 212 | ); 213 | updated_path = updated_path.replace( 214 | &format!( 215 | "{}\\{}\\esp-clang\\bin;", 216 | llvm_path.display().to_string().replace('/', "\\"), 217 | OLD_LLVM_16_VERSION, 218 | ), 219 | "", 220 | ); 221 | updated_path = updated_path.replace( 222 | &format!( 223 | "{}\\{}\\esp-clang\\bin;", 224 | llvm_path.display().to_string().replace('/', "\\"), 225 | DEFAULT_LLVM_16_VERSION, 226 | ), 227 | "", 228 | ); 229 | updated_path = updated_path.replace( 230 | &format!( 231 | "{}\\{}\\esp-clang\\bin;", 232 | llvm_path.display().to_string().replace('/', "\\"), 233 | DEFAULT_LLVM_17_VERSION, 234 | ), 235 | "", 236 | ); 237 | updated_path = updated_path.replace( 238 | &format!( 239 | "{}\\{}\\esp-clang\\bin;", 240 | llvm_path.display().to_string().replace('/', "\\"), 241 | DEFAULT_LLVM_18_VERSION, 242 | ), 243 | "", 244 | ); 245 | updated_path = updated_path.replace( 246 | &format!( 247 | "{}\\{}\\esp-clang\\bin;", 248 | llvm_path.display().to_string().replace('/', "\\"), 249 | DEFAULT_LLVM_19_VERSION, 250 | ), 251 | "", 252 | ); 253 | updated_path = updated_path.replace( 254 | &format!( 255 | "{}\\esp-clang\\bin;", 256 | llvm_path.display().to_string().replace('/', "\\"), 257 | ), 258 | "", 259 | ); 260 | set_env_variable("PATH", &updated_path)?; 261 | delete_env_variable("LIBCLANG_PATH")?; 262 | delete_env_variable("CLANG_PATH")?; 263 | } 264 | remove_dir_all(&llvm_path) 265 | .await 266 | .map_err(|_| Error::RemoveDirectory(llvm_path.display().to_string()))?; 267 | #[cfg(unix)] 268 | if cfg!(unix) { 269 | let espup_dir = BaseDirs::new().unwrap().home_dir().join(".espup"); 270 | 271 | if espup_dir.exists() { 272 | remove_dir_all(espup_dir.display().to_string()) 273 | .await 274 | .map_err(|_| Error::RemoveDirectory(espup_dir.display().to_string()))?; 275 | } 276 | } 277 | } 278 | Ok(()) 279 | } 280 | } 281 | 282 | #[async_trait] 283 | impl Installable for Llvm { 284 | async fn install(&self) -> Result, Error> { 285 | let mut exports: Vec = Vec::new(); 286 | 287 | #[cfg(unix)] 288 | let install_path = if self.extended { 289 | Path::new(&self.path).join("esp-clang").join("include") 290 | } else { 291 | Path::new(&self.path).to_path_buf() 292 | }; 293 | #[cfg(windows)] 294 | let install_path = if self.extended { 295 | self.path.join(&self.version).join("include") 296 | } else { 297 | self.path.join(&self.version) 298 | }; 299 | 300 | if install_path.exists() { 301 | warn!( 302 | "Previous installation of LLVM exists in: '{}'. Reusing this installation", 303 | self.path.to_str().unwrap() 304 | ); 305 | } else { 306 | info!("Installing Xtensa LLVM"); 307 | if let Some(file_name_libs) = &self.file_name_libs { 308 | download_file( 309 | format!("{}/{}", self.repository_url, file_name_libs), 310 | "idf_tool_xtensa_elf_clang.libs.tar.xz", 311 | self.path.to_str().unwrap(), 312 | true, 313 | false, 314 | ) 315 | .await?; 316 | } 317 | if let Some(file_name_full) = &self.file_name_full { 318 | download_file( 319 | format!("{}/{}", self.repository_url, file_name_full), 320 | "idf_tool_xtensa_elf_clang.full.tar.xz", 321 | self.path.to_str().unwrap(), 322 | true, 323 | false, 324 | ) 325 | .await?; 326 | } 327 | } 328 | // Set environment variables. 329 | #[cfg(windows)] 330 | if cfg!(windows) { 331 | File::create(self.path.join(&self.version))?; 332 | let libclang_dll = format!("{}\\libclang.dll", self.get_lib_path()); 333 | exports.push(format!("$Env:LIBCLANG_PATH = \"{}\"", libclang_dll)); 334 | exports.push(format!( 335 | "$Env:PATH = \"{};\" + $Env:PATH", 336 | self.get_lib_path() 337 | )); 338 | unsafe { 339 | env::set_var("LIBCLANG_BIN_PATH", self.get_lib_path()); 340 | env::set_var("LIBCLANG_PATH", libclang_dll); 341 | } 342 | } 343 | #[cfg(unix)] 344 | if cfg!(unix) { 345 | exports.push(format!("export LIBCLANG_PATH=\"{}\"", self.get_lib_path())); 346 | let espup_dir = BaseDirs::new().unwrap().home_dir().join(".espup"); 347 | 348 | if !espup_dir.exists() { 349 | create_dir_all(espup_dir.display().to_string()) 350 | .map_err(|_| Error::CreateDirectory(espup_dir.display().to_string()))?; 351 | } 352 | let llvm_symlink_path = espup_dir.join("esp-clang"); 353 | if llvm_symlink_path.exists() { 354 | remove_dir_all(&llvm_symlink_path) 355 | .await 356 | .map_err(|_| Error::RemoveDirectory(llvm_symlink_path.display().to_string()))?; 357 | } 358 | info!( 359 | "Creating symlink between '{}' and '{}'", 360 | self.get_lib_path(), 361 | llvm_symlink_path.display() 362 | ); 363 | symlink(self.get_lib_path(), llvm_symlink_path)?; 364 | } 365 | 366 | if self.extended { 367 | #[cfg(windows)] 368 | if cfg!(windows) { 369 | exports.push(format!("$Env:CLANG_PATH = \"{}\"", self.get_bin_path())); 370 | unsafe { 371 | env::set_var("CLANG_PATH", self.get_bin_path()); 372 | } 373 | } 374 | #[cfg(unix)] 375 | exports.push(format!("export CLANG_PATH=\"{}\"", self.get_bin_path())); 376 | } 377 | 378 | Ok(exports) 379 | } 380 | 381 | fn name(&self) -> String { 382 | "LLVM".to_string() 383 | } 384 | } 385 | -------------------------------------------------------------------------------- /src/toolchain/mod.rs: -------------------------------------------------------------------------------- 1 | //! Different toolchains source and installation tools. 2 | 3 | #[cfg(windows)] 4 | use crate::env::set_env; 5 | use crate::{ 6 | cli::InstallOpts, 7 | env::{create_export_file, get_export_file, print_post_install_msg}, 8 | error::Error, 9 | host_triple::get_host_triple, 10 | targets::Target, 11 | toolchain::{ 12 | gcc::{Gcc, RISCV_GCC, XTENSA_GCC}, 13 | llvm::Llvm, 14 | rust::{RiscVTarget, XtensaRust, check_rust_installation, get_rustup_home}, 15 | }, 16 | }; 17 | use async_trait::async_trait; 18 | use flate2::bufread::GzDecoder; 19 | use log::{debug, info, warn}; 20 | use miette::Result; 21 | use reqwest::{blocking::Client, header}; 22 | use retry::{delay::Fixed, retry}; 23 | use std::{ 24 | env, 25 | fs::{File, create_dir_all, remove_file}, 26 | io::{Write, copy}, 27 | path::{Path, PathBuf}, 28 | sync::atomic::{self, AtomicUsize}, 29 | }; 30 | use tar::Archive; 31 | use tokio::{fs::remove_dir_all, sync::mpsc}; 32 | use tokio_retry::{Retry, strategy::FixedInterval}; 33 | use tokio_stream::StreamExt; 34 | use xz2::read::XzDecoder; 35 | use zip::ZipArchive; 36 | 37 | pub mod gcc; 38 | pub mod llvm; 39 | pub mod rust; 40 | 41 | lazy_static::lazy_static! { 42 | pub static ref PROCESS_BARS: indicatif::MultiProgress = indicatif::MultiProgress::new(); 43 | pub static ref DOWNLOAD_CNT: AtomicUsize = AtomicUsize::new(0); 44 | } 45 | 46 | pub enum InstallMode { 47 | Install, 48 | Update, 49 | } 50 | 51 | #[async_trait] 52 | pub trait Installable { 53 | /// Install some application, returning a vector of any required exports 54 | async fn install(&self) -> Result, Error>; 55 | /// Returns the name of the toolchain being installeds 56 | fn name(&self) -> String; 57 | } 58 | 59 | /// Get https proxy from environment variables(if any) 60 | /// 61 | /// sadly there is not standard on the environment variable name for the proxy, but it seems 62 | /// that the most common are: 63 | /// 64 | /// - https_proxy(or http_proxy for http) 65 | /// - HTTPS_PROXY(or HTTP_PROXY for http) 66 | /// - all_proxy 67 | /// - ALL_PROXY 68 | /// 69 | /// hence we will check for all of them 70 | fn https_proxy() -> Option { 71 | for proxy in ["https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY"] { 72 | if let Ok(proxy_addr) = std::env::var(proxy) { 73 | info!("Get Proxy from env var: {}={}", proxy, proxy_addr); 74 | return Some(proxy_addr); 75 | } 76 | } 77 | None 78 | } 79 | 80 | /// Build a reqwest client with proxy if env var is set 81 | fn build_proxy_blocking_client() -> Result { 82 | let mut builder = reqwest::blocking::Client::builder(); 83 | if let Some(proxy) = https_proxy() { 84 | builder = builder.proxy(reqwest::Proxy::https(&proxy).unwrap()); 85 | } 86 | let client = builder.build()?; 87 | Ok(client) 88 | } 89 | 90 | /// Build a reqwest client with proxy if env var is set 91 | fn build_proxy_async_client() -> Result { 92 | let mut builder = reqwest::Client::builder(); 93 | if let Some(proxy) = https_proxy() { 94 | builder = builder.proxy(reqwest::Proxy::https(&proxy).unwrap()); 95 | } 96 | let client = builder.build()?; 97 | Ok(client) 98 | } 99 | 100 | /// Downloads a file from a URL and uncompresses it, if necesary, to the output directory. 101 | pub async fn download_file( 102 | url: String, 103 | file_name: &str, 104 | output_directory: &str, 105 | uncompress: bool, 106 | strip: bool, 107 | ) -> Result { 108 | let file_path = format!("{output_directory}/{file_name}"); 109 | if Path::new(&file_path).exists() { 110 | warn!( 111 | "File '{}' already exists, deleting it before download", 112 | file_path 113 | ); 114 | remove_file(&file_path)?; 115 | } else if !Path::new(&output_directory).exists() { 116 | debug!("Creating directory: '{}'", output_directory); 117 | create_dir_all(output_directory) 118 | .map_err(|_| Error::CreateDirectory(output_directory.to_string()))?; 119 | } 120 | 121 | let resp = { 122 | let client = build_proxy_async_client()?; 123 | let resp = client.get(&url).send().await?; 124 | if !resp.status().is_success() { 125 | return Err(Error::HttpError(resp.status().to_string())); 126 | } 127 | resp 128 | }; 129 | let bytes = { 130 | let len = resp.content_length(); 131 | 132 | // draw a progress bar 133 | let sty = indicatif::ProgressStyle::with_template( 134 | "[{elapsed_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {msg}", 135 | ) 136 | .unwrap() 137 | .progress_chars("##-"); 138 | let bar = len 139 | .map(indicatif::ProgressBar::new) 140 | .unwrap_or(indicatif::ProgressBar::no_length()); 141 | let bar = PROCESS_BARS.add(bar); 142 | bar.set_style(sty); 143 | bar.set_message(file_name.to_string()); 144 | DOWNLOAD_CNT.fetch_add(1, atomic::Ordering::Relaxed); 145 | 146 | let mut size_downloaded = 0; 147 | let mut stream = resp.bytes_stream(); 148 | let mut bytes = bytes::BytesMut::new(); 149 | while let Some(chunk_result) = stream.next().await { 150 | let chunk = chunk_result?; 151 | size_downloaded += chunk.len(); 152 | bar.set_position(size_downloaded as u64); 153 | 154 | bytes.extend(&chunk); 155 | } 156 | bar.finish_with_message(format!("{} download complete", file_name)); 157 | // leave the progress bar after completion 158 | if DOWNLOAD_CNT.fetch_sub(1, atomic::Ordering::Relaxed) == 1 { 159 | // clear all progress bars 160 | PROCESS_BARS.clear().unwrap(); 161 | info!("All downloads complete"); 162 | } 163 | // wait while DOWNLOAD_CNT is not zero 164 | 165 | bytes.freeze() 166 | }; 167 | if uncompress { 168 | let extension = Path::new(file_name).extension().unwrap().to_str().unwrap(); 169 | match extension { 170 | "zip" => { 171 | let mut tmpfile = tempfile::tempfile()?; 172 | tmpfile.write_all(&bytes)?; 173 | let mut zipfile = ZipArchive::new(tmpfile).unwrap(); 174 | if strip { 175 | for i in 0..zipfile.len() { 176 | let mut file = zipfile.by_index(i).unwrap(); 177 | if !file.name().starts_with("esp/") { 178 | continue; 179 | } 180 | 181 | let file_path = PathBuf::from(file.name().to_string()); 182 | let stripped_name = file_path.strip_prefix("esp/").unwrap(); 183 | let outpath = Path::new(output_directory).join(stripped_name); 184 | 185 | if file.name().ends_with('/') { 186 | create_dir_all(&outpath)?; 187 | } else { 188 | create_dir_all(outpath.parent().unwrap())?; 189 | let mut outfile = File::create(&outpath)?; 190 | copy(&mut file, &mut outfile)?; 191 | } 192 | } 193 | } else { 194 | zipfile.extract(output_directory).unwrap(); 195 | } 196 | } 197 | "gz" => { 198 | debug!("Extracting tar.gz file to '{}'", output_directory); 199 | 200 | let bytes = bytes.to_vec(); 201 | let tarfile = GzDecoder::new(bytes.as_slice()); 202 | let mut archive = Archive::new(tarfile); 203 | archive.unpack(output_directory)?; 204 | } 205 | "xz" => { 206 | debug!("Extracting tar.xz file to '{}'", output_directory); 207 | let bytes = bytes.to_vec(); 208 | let tarfile = XzDecoder::new(bytes.as_slice()); 209 | let mut archive = Archive::new(tarfile); 210 | archive.unpack(output_directory)?; 211 | } 212 | _ => { 213 | return Err(Error::UnsuportedFileExtension(extension.to_string())); 214 | } 215 | } 216 | } else { 217 | debug!("Creating file: '{}'", file_path); 218 | let mut out = File::create(&file_path)?; 219 | out.write_all(&bytes)?; 220 | } 221 | Ok(file_path) 222 | } 223 | 224 | /// Installs or updates the Espressif Rust ecosystem. 225 | pub async fn install(args: InstallOpts, install_mode: InstallMode) -> Result<()> { 226 | match install_mode { 227 | InstallMode::Install => info!("Installing the Espressif Rust ecosystem"), 228 | InstallMode::Update => info!("Updating the Espressif Rust ecosystem"), 229 | } 230 | let export_file = get_export_file(args.export_file)?; 231 | let mut exports: Vec = Vec::new(); 232 | let host_triple = get_host_triple(args.default_host)?; 233 | let xtensa_rust_version = if let Some(toolchain_version) = &args.toolchain_version { 234 | if !args.skip_version_parse { 235 | XtensaRust::parse_version(toolchain_version)? 236 | } else { 237 | toolchain_version.clone() 238 | } 239 | } else { 240 | // Get the latest version of the Xtensa Rust toolchain 241 | XtensaRust::get_latest_version().await.map_err(|e| { 242 | warn!("Failed to get latest Xtensa Rust version: {}", e); 243 | e 244 | })? 245 | }; 246 | let toolchain_dir = get_rustup_home().join("toolchains").join(args.name); 247 | let llvm: Llvm = Llvm::new( 248 | &toolchain_dir, 249 | &host_triple, 250 | args.extended_llvm, 251 | &xtensa_rust_version, 252 | )?; 253 | let targets = args.targets; 254 | let xtensa_rust = if targets.contains(&Target::ESP32) 255 | || targets.contains(&Target::ESP32S2) 256 | || targets.contains(&Target::ESP32S3) 257 | { 258 | Some(XtensaRust::new( 259 | &xtensa_rust_version, 260 | &host_triple, 261 | &toolchain_dir, 262 | )) 263 | } else { 264 | None 265 | }; 266 | 267 | debug!( 268 | "Arguments: 269 | - Export file: {:?} 270 | - Host triple: {} 271 | - LLVM Toolchain: {:?} 272 | - Stable version: {:?} 273 | - Rust Toolchain: {:?} 274 | - Skip version parsing: {} 275 | - Targets: {:?} 276 | - Toolchain path: {:?} 277 | - Toolchain version: {:?}", 278 | &export_file, 279 | host_triple, 280 | &llvm, 281 | &args.stable_version, 282 | xtensa_rust, 283 | &args.skip_version_parse, 284 | targets, 285 | &toolchain_dir, 286 | args.crosstool_toolchain_version, 287 | ); 288 | 289 | check_rust_installation().await?; 290 | 291 | // Build up a vector of installable applications, all of which implement the 292 | // `Installable` async trait. 293 | let mut to_install = Vec::>::new(); 294 | 295 | if let Some(ref xtensa_rust) = xtensa_rust { 296 | to_install.push(Box::new(xtensa_rust.to_owned())); 297 | } 298 | 299 | // Check if ther is any Xtensa target 300 | if targets.iter().any(|t| t.is_xtensa()) { 301 | to_install.push(Box::new(llvm.to_owned())); 302 | } 303 | 304 | if targets.iter().any(|t| t.is_riscv()) { 305 | let riscv_target = RiscVTarget::new(&args.stable_version); 306 | to_install.push(Box::new(riscv_target)); 307 | } 308 | 309 | if !args.std { 310 | if targets 311 | .iter() 312 | .any(|t| t == &Target::ESP32 || t == &Target::ESP32S2 || t == &Target::ESP32S3) 313 | { 314 | let xtensa_gcc = Gcc::new( 315 | XTENSA_GCC, 316 | &host_triple, 317 | &toolchain_dir, 318 | args.crosstool_toolchain_version.clone(), 319 | ); 320 | to_install.push(Box::new(xtensa_gcc)); 321 | } 322 | 323 | // By default only install the Espressif RISC-V toolchain if the user explicitly wants to 324 | if args.esp_riscv_gcc && targets.iter().any(|t| t != &Target::ESP32) { 325 | let riscv_gcc = Gcc::new( 326 | RISCV_GCC, 327 | &host_triple, 328 | &toolchain_dir, 329 | args.crosstool_toolchain_version.clone(), 330 | ); 331 | to_install.push(Box::new(riscv_gcc)); 332 | } 333 | } 334 | 335 | // With a list of applications to install, install them all in parallel. 336 | let installable_items = to_install.len(); 337 | let (tx, mut rx) = mpsc::channel::, Error>>(installable_items); 338 | for app in to_install { 339 | let tx = tx.clone(); 340 | let retry_strategy = FixedInterval::from_millis(50).take(3); 341 | tokio::spawn(async move { 342 | let res = Retry::spawn(retry_strategy, || async { 343 | let res = app.install().await; 344 | if let Err(ref err) = res { 345 | warn!( 346 | "Installation for '{}' failed, retrying. Error: {}", 347 | app.name(), 348 | err 349 | ); 350 | } 351 | res 352 | }) 353 | .await; 354 | tx.send(res).await.unwrap(); 355 | }); 356 | } 357 | 358 | // Read the results of the install tasks as they complete. 359 | for _ in 0..installable_items { 360 | let names = rx.recv().await.unwrap()?; 361 | exports.extend(names); 362 | } 363 | 364 | create_export_file(&export_file, &exports)?; 365 | #[cfg(windows)] 366 | set_env()?; 367 | match install_mode { 368 | InstallMode::Install => info!("Installation successfully completed!"), 369 | InstallMode::Update => info!("Update successfully completed!"), 370 | } 371 | 372 | print_post_install_msg(&export_file)?; 373 | Ok(()) 374 | } 375 | 376 | /// Queries the GitHub API and returns the JSON response. 377 | pub fn github_query(url: &str) -> Result { 378 | debug!("Querying GitHub API: '{}'", url); 379 | let mut headers = header::HeaderMap::new(); 380 | headers.insert(header::USER_AGENT, "espup".parse().unwrap()); 381 | headers.insert( 382 | header::ACCEPT, 383 | "application/vnd.github+json".parse().unwrap(), 384 | ); 385 | 386 | headers.insert("X-GitHub-Api-Version", "2022-11-28".parse().unwrap()); 387 | if let Some(token) = env::var_os("GITHUB_TOKEN") { 388 | debug!("Auth header added"); 389 | headers.insert( 390 | "Authorization", 391 | format!("Bearer {}", token.to_string_lossy()) 392 | .parse() 393 | .unwrap(), 394 | ); 395 | } 396 | 397 | let client = build_proxy_blocking_client()?; 398 | 399 | let json: Result = retry( 400 | Fixed::from_millis(100).take(5), 401 | || -> Result { 402 | let response = client.get(url).headers(headers.clone()).send()?; 403 | let status = response.status(); 404 | 405 | if !status.is_success() { 406 | return Err(Error::HttpError(format!( 407 | "GitHub API returned status code: {}", 408 | status 409 | ))); 410 | } 411 | 412 | let res = response.text()?; 413 | 414 | // Check for rate limiting response 415 | if res.contains( 416 | "https://docs.github.com/rest/overview/resources-in-the-rest-api#rate-limiting", 417 | ) { 418 | return Err(Error::GithubRateLimit); 419 | } 420 | 421 | // Check for authentication errors 422 | if res.contains("Bad credentials") { 423 | return Err(Error::GithubTokenInvalid); 424 | } 425 | 426 | // Try to parse the JSON 427 | serde_json::from_str(&res).map_err(|_| Error::SerializeJson) 428 | }, 429 | ) 430 | .map_err(|err| err.error); 431 | 432 | json 433 | } 434 | 435 | /// Checks if the directory exists and deletes it if it does. 436 | pub async fn remove_dir(path: &Path) -> Result<()> { 437 | if path.exists() { 438 | debug!( 439 | "Deleting the Xtensa Rust toolchain located in '{}'", 440 | &path.display() 441 | ); 442 | remove_dir_all(&path) 443 | .await 444 | .map_err(|_| Error::RemoveDirectory(path.display().to_string()))?; 445 | } 446 | Ok(()) 447 | } 448 | -------------------------------------------------------------------------------- /src/toolchain/rust.rs: -------------------------------------------------------------------------------- 1 | //! Xtensa Rust Toolchain source and installation tools. 2 | 3 | use crate::{ 4 | error::Error, 5 | host_triple::HostTriple, 6 | toolchain::{ 7 | Installable, download_file, 8 | gcc::{RISCV_GCC, XTENSA_GCC}, 9 | github_query, 10 | llvm::CLANG_NAME, 11 | }, 12 | }; 13 | use async_trait::async_trait; 14 | use directories::BaseDirs; 15 | use log::{debug, info, warn}; 16 | use miette::Result; 17 | use regex::Regex; 18 | #[cfg(unix)] 19 | use std::fs::create_dir_all; 20 | use std::{ 21 | env, 22 | fmt::Debug, 23 | fs::read_dir, 24 | io, 25 | path::{Path, PathBuf}, 26 | process::{Command, Stdio}, 27 | }; 28 | #[cfg(unix)] 29 | use tempfile::tempdir_in; 30 | use tokio::fs::{remove_dir_all, remove_file}; 31 | 32 | /// Xtensa Rust Toolchain repository 33 | const DEFAULT_XTENSA_RUST_REPOSITORY: &str = 34 | "https://github.com/esp-rs/rust-build/releases/download"; 35 | 36 | /// Xtensa Rust Toolchain API URL 37 | const XTENSA_RUST_LATEST_API_URL: &str = 38 | "https://api.github.com/repos/esp-rs/rust-build/releases/latest"; 39 | const XTENSA_RUST_API_URL: &str = 40 | "https://api.github.com/repos/esp-rs/rust-build/releases?page=1&per_page=100"; 41 | 42 | /// Xtensa Rust Toolchain version regex. 43 | pub const RE_EXTENDED_SEMANTIC_VERSION: &str = r"^(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)?$"; 44 | const RE_SEMANTIC_VERSION: &str = 45 | r"^(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)\.(?P0|[1-9]\d*)?$"; 46 | 47 | #[derive(Debug, Clone, Default)] 48 | pub struct XtensaRust { 49 | /// Path to the cargo home directory. 50 | pub cargo_home: PathBuf, 51 | /// Xtensa Rust toolchain file. 52 | pub dist_file: String, 53 | /// Xtensa Rust toolchain URL. 54 | pub dist_url: String, 55 | /// Host triple. 56 | pub host_triple: String, 57 | /// LLVM Toolchain path. 58 | pub path: PathBuf, 59 | /// Path to the rustup home directory. 60 | pub rustup_home: PathBuf, 61 | #[cfg(unix)] 62 | /// Xtensa Src Rust toolchain file. 63 | pub src_dist_file: String, 64 | #[cfg(unix)] 65 | /// Xtensa Src Rust toolchain URL. 66 | pub src_dist_url: String, 67 | /// Xtensa Rust toolchain destination path. 68 | pub toolchain_destination: PathBuf, 69 | /// Xtensa Rust Toolchain version. 70 | pub version: String, 71 | } 72 | 73 | impl XtensaRust { 74 | /// Get the latest version of Xtensa Rust toolchain. 75 | pub async fn get_latest_version() -> Result { 76 | debug!("Querying latest Xtensa Rust version from GitHub API"); 77 | 78 | // First, handle the spawn_blocking result 79 | let query_result = tokio::task::spawn_blocking(|| github_query(XTENSA_RUST_LATEST_API_URL)) 80 | .await 81 | .map_err(|e| { 82 | Error::GithubConnectivityError(format!("Failed to query GitHub API: {}", e)) 83 | })?; 84 | 85 | // Then handle the github_query result 86 | let json = query_result?; 87 | 88 | if !json.is_object() || !json["tag_name"].is_string() { 89 | return Err(Error::SerializeJson); 90 | } 91 | 92 | let mut version = json["tag_name"].to_string(); 93 | version.retain(|c| c != 'v' && c != '"'); 94 | 95 | // Validate the version format - handle both spawning and parsing errors 96 | let parse_task = tokio::task::spawn_blocking(move || Self::parse_version(&version)) 97 | .await 98 | .map_err(|_| Error::SerializeJson)?; 99 | 100 | let validated_version = parse_task?; 101 | 102 | debug!("Latest Xtensa Rust version: {}", validated_version); 103 | Ok(validated_version) 104 | } 105 | 106 | /// Create a new instance. 107 | pub fn new(toolchain_version: &str, host_triple: &HostTriple, toolchain_path: &Path) -> Self { 108 | let artifact_extension = get_artifact_extension(host_triple); 109 | let version = toolchain_version.to_string(); 110 | let dist = format!("rust-{version}-{host_triple}"); 111 | let dist_file = format!("{dist}.{artifact_extension}"); 112 | let dist_url = format!("{DEFAULT_XTENSA_RUST_REPOSITORY}/v{version}/{dist_file}"); 113 | #[cfg(unix)] 114 | let src_dist = format!("rust-src-{version}"); 115 | #[cfg(unix)] 116 | let src_dist_file = format!("{src_dist}.{artifact_extension}"); 117 | #[cfg(unix)] 118 | let src_dist_url = format!("{DEFAULT_XTENSA_RUST_REPOSITORY}/v{version}/{src_dist_file}"); 119 | let cargo_home = get_cargo_home(); 120 | let rustup_home = get_rustup_home(); 121 | let toolchain_destination = toolchain_path.to_path_buf(); 122 | 123 | Self { 124 | cargo_home, 125 | dist_file, 126 | dist_url, 127 | host_triple: host_triple.to_string(), 128 | path: toolchain_path.to_path_buf(), 129 | rustup_home, 130 | #[cfg(unix)] 131 | src_dist_file, 132 | #[cfg(unix)] 133 | src_dist_url, 134 | toolchain_destination, 135 | version, 136 | } 137 | } 138 | 139 | /// Parses the version of the Xtensa toolchain. 140 | pub fn parse_version(arg: &str) -> Result { 141 | debug!("Parsing Xtensa Rust version: {}", arg); 142 | let re_extended = Regex::new(RE_EXTENDED_SEMANTIC_VERSION).unwrap(); 143 | let re_semver = Regex::new(RE_SEMANTIC_VERSION).unwrap(); 144 | let json = github_query(XTENSA_RUST_API_URL)?; 145 | if re_semver.is_match(arg) { 146 | let mut extended_versions: Vec = Vec::new(); 147 | for release in json.as_array().unwrap() { 148 | let tag_name = release["tag_name"].to_string().replace(['\"', 'v'], ""); 149 | if tag_name.starts_with(arg) { 150 | extended_versions.push(tag_name); 151 | } 152 | } 153 | if extended_versions.is_empty() { 154 | return Err(Error::InvalidVersion(arg.to_string())); 155 | } 156 | let mut max_version = extended_versions.pop().unwrap(); 157 | let mut max_subpatch = 0; 158 | for version in extended_versions { 159 | let subpatch: i8 = re_extended 160 | .captures(&version) 161 | .and_then(|cap| { 162 | cap.name("subpatch") 163 | .map(|subpatch| subpatch.as_str().parse().unwrap()) 164 | }) 165 | .unwrap(); 166 | if subpatch > max_subpatch { 167 | max_subpatch = subpatch; 168 | max_version = version; 169 | } 170 | } 171 | return Ok(max_version); 172 | } else if re_extended.is_match(arg) { 173 | for release in json.as_array().unwrap() { 174 | let tag_name = release["tag_name"].to_string().replace(['\"', 'v'], ""); 175 | if tag_name.starts_with(arg) { 176 | return Ok(arg.to_string()); 177 | } 178 | } 179 | } 180 | Err(Error::InvalidVersion(arg.to_string())) 181 | } 182 | 183 | /// Removes the Xtensa Rust toolchain. 184 | pub async fn uninstall(toolchain_path: &Path) -> Result<(), Error> { 185 | info!("Uninstalling Xtensa Rust toolchain"); 186 | let dir = read_dir(toolchain_path)?; 187 | for entry in dir { 188 | let entry_path = entry.unwrap().path(); 189 | let entry_name = entry_path.display().to_string(); 190 | if !entry_name.contains(RISCV_GCC) 191 | && !entry_name.contains(XTENSA_GCC) 192 | && !entry_name.contains(CLANG_NAME) 193 | { 194 | if entry_path.is_dir() { 195 | remove_dir_all(Path::new(&entry_name)) 196 | .await 197 | .map_err(|_| Error::RemoveDirectory(entry_name))?; 198 | } else { 199 | remove_file(&entry_name).await?; 200 | } 201 | } 202 | } 203 | Ok(()) 204 | } 205 | } 206 | 207 | #[async_trait] 208 | impl Installable for XtensaRust { 209 | async fn install(&self) -> Result, Error> { 210 | if self.toolchain_destination.exists() { 211 | let toolchain_name = format!( 212 | "+{}", 213 | self.toolchain_destination 214 | .file_name() 215 | .unwrap() 216 | .to_str() 217 | .unwrap(), 218 | ); 219 | let rustc_version = Command::new("rustc") 220 | .args([&toolchain_name, "--version"]) 221 | .stdout(Stdio::piped()) 222 | .output()?; 223 | let output = String::from_utf8_lossy(&rustc_version.stdout); 224 | if rustc_version.status.success() && output.contains(&self.version) { 225 | warn!( 226 | "Previous installation of Xtensa Rust {} exists in: '{}'. Reusing this installation", 227 | &self.version, 228 | &self.toolchain_destination.display() 229 | ); 230 | return Ok(vec![]); 231 | } else { 232 | if !rustc_version.status.success() { 233 | warn!("Failed to detect version of Xtensa Rust, reinstalling it"); 234 | } 235 | Self::uninstall(&self.toolchain_destination).await?; 236 | } 237 | } 238 | 239 | info!("Installing Xtensa Rust {} toolchain", self.version); 240 | 241 | #[cfg(unix)] 242 | if cfg!(unix) { 243 | let path = get_rustup_home().join("tmp"); 244 | if !path.exists() { 245 | info!("Creating directory: '{}'", path.display()); 246 | create_dir_all(&path) 247 | .map_err(|_| Error::CreateDirectory(path.display().to_string()))?; 248 | } 249 | let tmp_dir = tempdir_in(path)?; 250 | let tmp_dir_path = &tmp_dir.path().display().to_string(); 251 | 252 | download_file( 253 | self.src_dist_url.clone(), 254 | "rust-src.tar.xz", 255 | tmp_dir_path, 256 | true, 257 | false, 258 | ) 259 | .await?; 260 | 261 | download_file( 262 | self.dist_url.clone(), 263 | "rust.tar.xz", 264 | tmp_dir_path, 265 | true, 266 | false, 267 | ) 268 | .await?; 269 | 270 | info!("Installing 'rust' component for Xtensa Rust toolchain"); 271 | 272 | if !Command::new("/usr/bin/env") 273 | .arg("bash") 274 | .arg(format!( 275 | "{}/rust-nightly-{}/install.sh", 276 | tmp_dir_path, &self.host_triple, 277 | )) 278 | .arg(format!( 279 | "--destdir={}", 280 | self.toolchain_destination.display() 281 | )) 282 | .arg("--prefix=''") 283 | .arg("--without=rust-docs-json-preview,rust-docs") 284 | .arg("--disable-ldconfig") 285 | .stdout(Stdio::null()) 286 | .output()? 287 | .status 288 | .success() 289 | { 290 | Self::uninstall(&self.toolchain_destination).await?; 291 | return Err(Error::XtensaRust); 292 | } 293 | 294 | info!("Installing 'rust-src' component for Xtensa Rust toolchain"); 295 | if !Command::new("/usr/bin/env") 296 | .arg("bash") 297 | .arg(format!("{}/rust-src-nightly/install.sh", tmp_dir_path)) 298 | .arg(format!( 299 | "--destdir={}", 300 | self.toolchain_destination.display() 301 | )) 302 | .arg("--prefix=''") 303 | .arg("--disable-ldconfig") 304 | .stdout(Stdio::null()) 305 | .output()? 306 | .status 307 | .success() 308 | { 309 | Self::uninstall(&self.toolchain_destination).await?; 310 | return Err(Error::XtensaRustSrc); 311 | } 312 | } 313 | // Some platfroms like Windows are available in single bundle rust + src, because install 314 | // script in dist is not available for the plaform. It's sufficient to extract the toolchain 315 | #[cfg(windows)] 316 | if cfg!(windows) { 317 | download_file( 318 | self.dist_url.clone(), 319 | "rust.zip", 320 | &self.toolchain_destination.display().to_string(), 321 | true, 322 | true, 323 | ) 324 | .await?; 325 | } 326 | 327 | Ok(vec![]) // No exports 328 | } 329 | 330 | fn name(&self) -> String { 331 | "Xtensa Rust".to_string() 332 | } 333 | } 334 | 335 | #[derive(Debug, Clone)] 336 | pub struct RiscVTarget { 337 | /// Stable Rust toolchain version. 338 | pub stable_version: String, 339 | } 340 | 341 | impl RiscVTarget { 342 | /// Create a crate instance. 343 | pub fn new(stable_version: &str) -> Self { 344 | RiscVTarget { 345 | stable_version: stable_version.to_string(), 346 | } 347 | } 348 | 349 | /// Uninstalls the RISC-V target. 350 | pub fn uninstall(stable_version: &str) -> Result<(), Error> { 351 | info!("Uninstalling RISC-V target"); 352 | 353 | if !Command::new("rustup") 354 | .args([ 355 | "target", 356 | "remove", 357 | "--toolchain", 358 | stable_version, 359 | "riscv32imc-unknown-none-elf", 360 | "riscv32imac-unknown-none-elf", 361 | "riscv32imafc-unknown-none-elf", 362 | ]) 363 | .stdout(Stdio::null()) 364 | .status()? 365 | .success() 366 | { 367 | return Err(Error::UninstallRiscvTarget); 368 | } 369 | Ok(()) 370 | } 371 | } 372 | 373 | #[async_trait] 374 | impl Installable for RiscVTarget { 375 | async fn install(&self) -> Result, Error> { 376 | info!( 377 | "Installing RISC-V Rust targets ('riscv32imc-unknown-none-elf', 'riscv32imac-unknown-none-elf' and 'riscv32imafc-unknown-none-elf') for '{}' toolchain", 378 | &self.stable_version 379 | ); 380 | 381 | if !Command::new("rustup") 382 | .args([ 383 | "toolchain", 384 | "install", 385 | &self.stable_version, 386 | "--profile", 387 | "minimal", 388 | "--component", 389 | "rust-src", 390 | "--target", 391 | "riscv32imc-unknown-none-elf", 392 | "--target", 393 | "riscv32imac-unknown-none-elf", 394 | "--target", 395 | "riscv32imafc-unknown-none-elf", 396 | ]) 397 | .stdout(Stdio::null()) 398 | .stderr(Stdio::null()) 399 | .status()? 400 | .success() 401 | { 402 | return Err(Error::InstallRiscvTarget(self.stable_version.clone())); 403 | } 404 | 405 | Ok(vec![]) // No exports 406 | } 407 | 408 | fn name(&self) -> String { 409 | "RISC-V Rust target".to_string() 410 | } 411 | } 412 | 413 | /// Gets the artifact extension based on the host architecture. 414 | fn get_artifact_extension(host_triple: &HostTriple) -> &str { 415 | match host_triple { 416 | HostTriple::X86_64PcWindowsMsvc | HostTriple::X86_64PcWindowsGnu => "zip", 417 | _ => "tar.xz", 418 | } 419 | } 420 | 421 | /// Gets the default cargo home path. 422 | fn get_cargo_home() -> PathBuf { 423 | PathBuf::from(env::var("CARGO_HOME").unwrap_or_else(|_e| { 424 | format!( 425 | "{}", 426 | BaseDirs::new().unwrap().home_dir().join(".cargo").display() 427 | ) 428 | })) 429 | } 430 | 431 | /// Gets the default rustup home path. 432 | pub fn get_rustup_home() -> PathBuf { 433 | PathBuf::from(env::var("RUSTUP_HOME").unwrap_or_else(|_e| { 434 | format!( 435 | "{}", 436 | BaseDirs::new() 437 | .unwrap() 438 | .home_dir() 439 | .join(".rustup") 440 | .display() 441 | ) 442 | })) 443 | } 444 | 445 | /// Checks if rustup is installed. 446 | pub async fn check_rust_installation() -> Result<(), Error> { 447 | info!("Checking Rust installation"); 448 | 449 | if let Err(e) = Command::new("rustup") 450 | .arg("--version") 451 | .stdout(Stdio::piped()) 452 | .output() 453 | { 454 | if let io::ErrorKind::NotFound = e.kind() { 455 | return Err(Error::MissingRust); 456 | } else { 457 | return Err(Error::RustupDetection(e.to_string())); 458 | } 459 | } 460 | 461 | Ok(()) 462 | } 463 | 464 | #[cfg(test)] 465 | mod tests { 466 | use crate::{ 467 | logging::initialize_logger, 468 | toolchain::rust::{XtensaRust, get_cargo_home, get_rustup_home}, 469 | }; 470 | use directories::BaseDirs; 471 | use std::env; 472 | use tempfile::TempDir; 473 | 474 | #[test] 475 | fn test_xtensa_rust_parse_version() { 476 | initialize_logger("debug"); 477 | assert_eq!(XtensaRust::parse_version("1.65.0.0").unwrap(), "1.65.0.0"); 478 | assert_eq!(XtensaRust::parse_version("1.65.0.1").unwrap(), "1.65.0.1"); 479 | assert_eq!(XtensaRust::parse_version("1.64.0.0").unwrap(), "1.64.0.0"); 480 | assert_eq!(XtensaRust::parse_version("1.82.0").unwrap(), "1.82.0.3"); 481 | assert_eq!(XtensaRust::parse_version("1.65.0").unwrap(), "1.65.0.1"); 482 | assert_eq!(XtensaRust::parse_version("1.64.0").unwrap(), "1.64.0.0"); 483 | assert!(XtensaRust::parse_version("422.0.0").is_err()); 484 | assert!(XtensaRust::parse_version("422.0.0.0").is_err()); 485 | assert!(XtensaRust::parse_version("a.1.1.1").is_err()); 486 | assert!(XtensaRust::parse_version("1.1.1.1.1").is_err()); 487 | assert!(XtensaRust::parse_version("1..1.1").is_err()); 488 | assert!(XtensaRust::parse_version("1._.*.1").is_err()); 489 | } 490 | 491 | #[test] 492 | fn test_get_cargo_home() { 493 | // No CARGO_HOME set 494 | unsafe { 495 | env::remove_var("CARGO_HOME"); 496 | } 497 | assert_eq!( 498 | get_cargo_home(), 499 | BaseDirs::new().unwrap().home_dir().join(".cargo") 500 | ); 501 | // CARGO_HOME set 502 | let temp_dir = TempDir::new().unwrap(); 503 | let cargo_home = temp_dir.path().to_path_buf(); 504 | unsafe { 505 | env::set_var("CARGO_HOME", cargo_home.to_str().unwrap()); 506 | } 507 | assert_eq!(get_cargo_home(), cargo_home); 508 | } 509 | 510 | #[test] 511 | fn test_get_rustup_home() { 512 | // No RUSTUP_HOME set 513 | unsafe { 514 | env::remove_var("RUSTUP_HOME"); 515 | } 516 | assert_eq!( 517 | get_rustup_home(), 518 | BaseDirs::new().unwrap().home_dir().join(".rustup") 519 | ); 520 | // RUSTUP_HOME set 521 | let temp_dir = TempDir::new().unwrap(); 522 | let rustup_home = temp_dir.path().to_path_buf(); 523 | unsafe { 524 | env::set_var("RUSTUP_HOME", rustup_home.to_str().unwrap()); 525 | } 526 | assert_eq!(get_rustup_home(), rustup_home); 527 | } 528 | } 529 | -------------------------------------------------------------------------------- /tests/integration.rs: -------------------------------------------------------------------------------- 1 | #[test] 2 | fn fails_with_no_arguments() { 3 | assert_cmd::Command::cargo_bin("espup") 4 | .unwrap() 5 | .assert() 6 | .failure(); 7 | } 8 | 9 | #[test] 10 | fn verify_help() { 11 | assert_cmd::Command::cargo_bin("espup") 12 | .unwrap() 13 | .arg("--help") 14 | .assert() 15 | .success(); 16 | } 17 | 18 | #[test] 19 | fn verify_install_help() { 20 | assert_cmd::Command::cargo_bin("espup") 21 | .unwrap() 22 | .args(["install", "--help"]) 23 | .assert() 24 | .success(); 25 | } 26 | 27 | #[test] 28 | fn verify_update_help() { 29 | assert_cmd::Command::cargo_bin("espup") 30 | .unwrap() 31 | .args(["update", "--help"]) 32 | .assert() 33 | .success(); 34 | } 35 | 36 | #[test] 37 | fn verify_uninstall_help() { 38 | assert_cmd::Command::cargo_bin("espup") 39 | .unwrap() 40 | .args(["uninstall", "--help"]) 41 | .assert() 42 | .success(); 43 | } 44 | --------------------------------------------------------------------------------