diff --git a/.github/workflows/homebrew.yml b/.github/workflows/homebrew.yml index 04474c3..8e219bf 100644 --- a/.github/workflows/homebrew.yml +++ b/.github/workflows/homebrew.yml @@ -19,6 +19,8 @@ permissions: contents: write packages: write actions: read + pages: write + id-token: write # Global environment variables env: @@ -535,6 +537,46 @@ jobs: echo "" echo "๐Ÿ”— Homebrew Guidelines: https://docs.brew.sh/Adding-Software-to-Homebrew" + - name: Setup Pages + uses: actions/configure-pages@v4 + + - name: Prepare deployment files + run: | + echo "๐Ÿ“ Preparing GitHub Pages deployment from scripts directory..." + + # Ensure scripts directory exists + if [ ! -d "scripts" ]; then + echo "โŒ scripts directory not found!" + exit 1 + fi + + # Display files to be deployed + echo "Files to be deployed:" + ls -la scripts/ + + # Verify critical files exist + if [ ! -f "scripts/windows" ]; then + echo "โŒ scripts/windows file not found!" + exit 1 + fi + + echo "โœ… All required files found" + + - name: Upload artifact + uses: actions/upload-pages-artifact@v3 + with: + path: ./scripts + + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 + + - name: Deployment summary + run: | + echo "๐ŸŽ‰ GitHub Pages deployment completed!" + echo "๐Ÿ“„ Site URL: ${{ steps.deployment.outputs.page_url }}" + echo "๐Ÿ”— Install command: powershell -Command \"irm https://agbcloud.github.io/agbcloud-cli/windows | iex\"" + - name: Validate Official Formula run: | echo "๐Ÿงช Validating Official Homebrew Formula (Source Build Mode)..." diff --git a/scripts/README.md b/scripts/README.md index 8dce1c4..00f8fc6 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -1,75 +1,240 @@ -# AgbCloud CLI Scripts +# AgbCloud CLI Windows Installation Guide -This directory contains scripts for the AgbCloud CLI project. +This guide provides instructions for installing AgbCloud CLI on Windows using PowerShell. -## Test Scripts +## Table of Contents -### test.sh +- [Prerequisites](#prerequisites) +- [Installation](#installation) +- [Verification](#verification) +- [Usage](#usage) +- [Troubleshooting](#troubleshooting) +- [Uninstallation](#uninstallation) -The main test runner script used by the Makefile for running unit and integration tests. +## Prerequisites -#### Usage +Before installing AgbCloud CLI, please ensure: +- Windows 10 or later (Windows Server 2016 or later) +- PowerShell 5.1 or later (PowerShell 7+ recommended) +- Internet connection +- Administrator privileges (recommended for PATH configuration) -```bash -# Run unit tests only -./scripts/test.sh --unit-only +## Installation -# Run integration tests only -./scripts/test.sh --integration-only +### Quick Installation -# Run all tests -./scripts/test.sh --all +Install AgbCloud CLI with a single PowerShell command: -# Run tests with verbose output -./scripts/test.sh --unit-only --verbose +```powershell +powershell -Command "irm https://litiantian123-code.github.io/agbcloud-cli/windows | iex" ``` -## Build and Release Scripts +### Installation Process -### generate-server-files.sh +The installation script will: +1. **Detect system architecture** (amd64/arm64) +2. **Download the latest version** from GitHub Releases +3. **Create installation directory** (`%LOCALAPPDATA%\agbcloud` by default) +4. **Install the binary** as `agb.exe` +5. **Update PATH environment variable** (user-level) +6. **Verify installation** automatically -Generates server files and installation commands for distribution. This script is used in the CI/CD pipeline to create PowerShell installation scripts and version metadata. +## Verification -#### Usage +After installation, verify that AgbCloud CLI is installed correctly: -```bash -# Generate files for a specific version -VERSION="v1.2.3" ./scripts/generate-server-files.sh +### Step 1: Restart PowerShell +```powershell +# Close current PowerShell window and open a new one +Start-Process powershell -Verb RunAs; exit +# Or refresh the environment variables +$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") +``` + +### Step 2: Check Installation +```powershell +# Check if agb command is available +agb --version +``` + +**Expected Output:** +``` +AgbCloud CLI version 1.0.0 +Git commit: abc1234 +Build date: 2025-01-15T10:30:00Z +``` + +### Step 3: Verify Command Help +```powershell +# Display help information +agb --help +``` + +**Expected Output:** +``` +Command line interface for AgbCloud services + +Usage: + agb [command] + +Available Commands: + image Manage images + login Log in to AgbCloud + logout Log out from AgbCloud + version Show version information + help Help about any command -# Generate files with default dev version -./scripts/generate-server-files.sh +Flags: + -h, --help help for agb + -v, --verbose Enable verbose output + +Use "agb [command] --help" for more information about a command. +``` + +### Step 4: Test Core Functionality +```powershell +# Test image command +agb image --help + +# Test version command +agb version ``` -#### Generated Files +## Usage + +### Basic Commands + +```powershell +# Show help +agb --help -- `server-files/install.ps1` - PowerShell installation script -- `server-files/latest.json` - Version metadata for API +# Show version +agb version -### upload-to-oss.sh +# Login to AgbCloud +agb login -Uploads build artifacts to Alibaba Cloud OSS. Can be used independently or as part of the CI/CD pipeline. +# List available images +agb image list + +# Create a custom image +agb image create myImage --dockerfile ./Dockerfile --imageId agb-code-space-1 + +# Activate an image +agb image activate img-7a8b9c1d0e + +# Deactivate an image +agb image deactivate img-7a8b9c1d0e +``` + +### Enable Verbose Output +```powershell +# Use -v flag for detailed output +agb -v image list +agb --verbose login +``` -#### Usage +## Troubleshooting -```bash -# Set required environment variables -export OSS_ACCESS_KEY_ID="your-access-key" -export OSS_ACCESS_KEY_SECRET="your-secret-key" -export VERSION="v1.2.3" +### Common Issues -# Upload packages -./scripts/upload-to-oss.sh +#### Issue 1: Command Not Found +```powershell +# Error: 'agb' is not recognized as an internal or external command ``` -## Features +**Solutions:** +1. **Restart PowerShell** or refresh environment variables: + ```powershell + $env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") + ``` + +2. **Check installation directory:** + ```powershell + Get-ChildItem "$env:LOCALAPPDATA\agbcloud" + ``` + +#### Issue 2: Installation Failed +```powershell +# Error: Failed to download AgbCloud CLI +``` + +**Solutions:** +1. **Check internet connection** +2. **Try running the installation command again** +3. **Use manual download from GitHub Releases if needed** + +#### Issue 3: Permission Denied +```powershell +# Error: Access denied or execution policy restriction +``` + +**Solutions:** +1. **Run as Administrator:** + ```powershell + # Right-click PowerShell and select "Run as Administrator" + ``` + +2. **Check execution policy:** + ```powershell + Get-ExecutionPolicy + Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser + ``` + + +### Getting Help + +If you encounter issues: +1. **Check the installation log** for error messages +2. **Verify system requirements** (Windows version, PowerShell version) +3. **Try manual installation** from GitHub Releases +4. **Contact support** with error details and system information + +## Uninstallation + +To remove AgbCloud CLI: + +### Step 1: Remove Binary +```powershell +# Remove installation directory +Remove-Item -Path "$env:LOCALAPPDATA\agbcloud" -Recurse -Force +``` + +### Step 2: Clean PATH +```powershell +# Remove from user PATH +$agbPath = "$env:LOCALAPPDATA\agbcloud" +$currentPath = [Environment]::GetEnvironmentVariable("Path", "User") +$newPath = ($currentPath.Split(';') | Where-Object { $_ -ne $agbPath }) -join ';' +[Environment]::SetEnvironmentVariable("Path", $newPath, "User") +``` + +### Step 3: Verify Removal +```powershell +# This should return an error +agb --version +``` + +--- + +## Additional Information + +### System Requirements +- **OS**: Windows 10/11, Windows Server 2016+ +- **Architecture**: x64 (amd64) or ARM64 +- **PowerShell**: 5.1+ (7+ recommended) +- **Disk Space**: ~50MB +- **Network**: Internet connection for download + +### Installation Locations +- **Default**: `%LOCALAPPDATA%\agbcloud\agb.exe` -- **Test Automation**: Comprehensive test runner with multiple modes -- **Build Integration**: Automatic generation of installation files for CI/CD -- **Cloud Storage**: Upload artifacts to OSS with proper permissions -- **Version Management**: Support for version-specific builds and releases +### Links +- **GitHub Repository**: https://github.com/agbcloud/agbcloud-cli +- **Releases**: https://github.com/agbcloud/agbcloud-cli/releases +- **Documentation**: https://github.com/agbcloud/agbcloud-cli/blob/main/docs/USER_GUIDE.md +- **Issues**: https://github.com/agbcloud/agbcloud-cli/issues -## Compatibility +--- -- Linux/macOS build environments -- Alibaba Cloud OSS integration -- Go 1.23+ test framework \ No newline at end of file +**Note**: This installation method downloads the latest stable release. For development versions or specific releases, please visit the GitHub Releases page. \ No newline at end of file diff --git a/scripts/generate-server-files.sh b/scripts/generate-server-files.sh deleted file mode 100755 index 7293a40..0000000 --- a/scripts/generate-server-files.sh +++ /dev/null @@ -1,88 +0,0 @@ -#!/bin/bash - -# Generate server files for AgbCloud CLI distribution -# This script creates only the essential files needed for PowerShell installation - -set -e - -VERSION=${VERSION:-"dev-$(date +%Y%m%d-%H%M)"} -BASE_URL="https://agbcloud-internal.oss-cn-hangzhou.aliyuncs.com" - -echo "[>>] Generating PowerShell installer files for version: $VERSION" - -# Create output directory -# Handle both running from root directory and from scripts directory -if [[ -d "scripts" ]]; then - # Running from root directory - mkdir -p server-files - OUTPUT_DIR="server-files" -else - # Running from scripts directory - mkdir -p ../server-files - OUTPUT_DIR="../server-files" -fi - -# 1. Generate latest.json for version API (essential for PowerShell script) -echo "[PAGE] Creating latest.json..." -cat > $OUTPUT_DIR/latest.json << EOF -{ - "version": "$VERSION", - "releaseDate": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")", - "windows": { - "amd64": { - "url": "$BASE_URL/agb-$VERSION-windows-amd64.exe", - "sha256": "$(cat packages/agb-$VERSION-windows-amd64.exe.sha256 2>/dev/null | cut -d' ' -f1 || echo 'PLACEHOLDER_SHA256')" - }, - "arm64": { - "url": "$BASE_URL/agb-$VERSION-windows-arm64.exe", - "sha256": "$(cat packages/agb-$VERSION-windows-arm64.exe.sha256 2>/dev/null | cut -d' ' -f1 || echo 'PLACEHOLDER_SHA256')" - } - } -} -EOF - -# 2. Generate install.ps1 (the main PowerShell installer) -echo "[PAGE] Creating install.ps1..." -# Copy the PowerShell installer script (it dynamically fetches latest version) -# Handle both running from root directory and from scripts directory -if [[ -f "scripts/install-windows-simple.ps1" ]]; then - cp scripts/install-windows-simple.ps1 $OUTPUT_DIR/install.ps1 -elif [[ -f "install-windows-simple.ps1" ]]; then - cp install-windows-simple.ps1 $OUTPUT_DIR/install.ps1 -else - echo "Error: Could not find install-windows-simple.ps1" - exit 1 -fi - -echo "[OK] PowerShell installer files generated successfully!" -echo "" -echo "[DIR] Generated files:" -ls -la $OUTPUT_DIR/ -echo "" -echo "[>>] Upload these files to your OSS bucket:" -echo " - server-files/install.ps1 โ†’ $BASE_URL/install.ps1" -echo " - server-files/latest.json โ†’ $BASE_URL/latest.json" -echo " - packages/*.exe โ†’ $BASE_URL/" -echo " - packages/*.exe.sha256 โ†’ $BASE_URL/" -echo "" -echo "[DOC] Windows Installation Commands:" -echo "" -echo "[REFRESH] Install Latest Version (recommended for production):" -echo " powershell -Command \"irm $BASE_URL/install.ps1 | iex\"" -echo "" -echo "[AIM] Install Specific Version $VERSION (for testing):" -echo " powershell -Command \"irm $BASE_URL/install.ps1 | iex\" -Version $VERSION" -echo "" -echo "[BOOK] Additional Options:" -echo " # Install to custom directory" -echo " powershell -Command \"irm $BASE_URL/install.ps1 | iex\" -InstallPath \"C:\\Tools\\agb\"" -echo "" -echo " # Install specific architecture" -echo " powershell -Command \"irm $BASE_URL/install.ps1 | iex\" -Architecture arm64" -echo "" -echo " # Show help" -echo " powershell -Command \"irm $BASE_URL/install.ps1 | iex\" -Help" -echo "" -echo "[TIP] Testing Team Usage:" -echo " Use the specific version command above to test version $VERSION" -echo " Use the latest version command for general testing" \ No newline at end of file diff --git a/scripts/test.sh b/scripts/test.sh deleted file mode 100755 index 0768643..0000000 --- a/scripts/test.sh +++ /dev/null @@ -1,141 +0,0 @@ -#!/bin/bash - -# Copyright 2025 AgbCloud CLI Contributors -# SPDX-License-Identifier: Apache-2.0 - -set -e - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -NC='\033[0m' # No Color - -# Function to print colored output -print_status() { - echo -e "${GREEN}[INFO]${NC} $1" -} - -print_warning() { - echo -e "${YELLOW}[WARN]${NC} $1" -} - -print_error() { - echo -e "${RED}[ERROR]${NC} $1" -} - -# Default values -RUN_UNIT=true -RUN_INTEGRATION=false -VERBOSE=false - -# Parse command line arguments -while [[ $# -gt 0 ]]; do - case $1 in - --unit-only) - RUN_UNIT=true - RUN_INTEGRATION=false - shift - ;; - --integration-only) - RUN_UNIT=false - RUN_INTEGRATION=true - shift - ;; - --all) - RUN_UNIT=true - RUN_INTEGRATION=true - shift - ;; - --verbose|-v) - VERBOSE=true - shift - ;; - --help|-h) - echo "Usage: $0 [OPTIONS]" - echo "" - echo "Options:" - echo " --unit-only Run only unit tests (default)" - echo " --integration-only Run only integration tests" - echo " --all Run both unit and integration tests" - echo " --verbose, -v Enable verbose output" - echo " --help, -h Show this help message" - echo "" - echo "Environment Variables:" - echo " SKIP_INTEGRATION_TESTS Set to 'true' to skip integration tests" - exit 0 - ;; - *) - print_error "Unknown option: $1" - echo "Use --help for usage information" - exit 1 - ;; - esac -done - -# Set verbose flag for go test -VERBOSE_FLAG="" -if [ "$VERBOSE" = true ]; then - VERBOSE_FLAG="-v" -fi - -# Change to project root directory -cd "$(dirname "$0")/.." - -print_status "Starting test execution..." - -# Run unit tests -if [ "$RUN_UNIT" = true ]; then - print_status "Running unit tests..." - - if go test $VERBOSE_FLAG ./test/unit/...; then - print_status "[OK] Unit tests passed" - else - print_error "[ERROR] Unit tests failed" - exit 1 - fi - - # Also run tests for internal packages (excluding integration tests) - print_status "Running internal package tests..." - if go test $VERBOSE_FLAG ./internal/...; then - print_status "[OK] Internal package tests passed" - else - print_error "[ERROR] Internal package tests failed" - exit 1 - fi -fi - -# Run integration tests -if [ "$RUN_INTEGRATION" = true ]; then - print_status "Running integration tests..." - - # Check if integration tests should be skipped - if [ "$SKIP_INTEGRATION_TESTS" = "true" ]; then - print_warning "[WARN] Integration tests skipped (SKIP_INTEGRATION_TESTS=true)" - else - print_status "Running integration tests against real API..." - print_warning "Note: Integration tests WILL FAIL if network connectivity to https://agb.cloud is unavailable" - - if go test $VERBOSE_FLAG -timeout=45m -tags=integration ./test/integration/...; then - print_status "[OK] Integration tests passed" - else - print_error "[ERROR] Integration tests failed" - print_warning "Common causes:" - print_warning " - Network connectivity issues to https://agb.cloud" - print_warning " - API endpoint changes or service unavailability" - print_warning " - Firewall or proxy blocking HTTPS requests" - print_warning "If you want to skip integration tests, set SKIP_INTEGRATION_TESTS=true" - # Don't exit with error for integration tests as they may fail due to external dependencies - fi - fi -fi - -print_status "Test execution completed!" - -# Run coverage if requested -if [ "$VERBOSE" = true ]; then - print_status "Generating test coverage report..." - go test -coverprofile=coverage.out ./test/unit/... ./internal/... - go tool cover -html=coverage.out -o coverage.html - print_status "Coverage report generated: coverage.html" -fi \ No newline at end of file diff --git a/scripts/upload-to-oss.sh b/scripts/upload-to-oss.sh deleted file mode 100644 index a868beb..0000000 --- a/scripts/upload-to-oss.sh +++ /dev/null @@ -1,131 +0,0 @@ -#!/bin/bash -# Upload packages to Alibaba Cloud OSS -set -e - -# OSS Configuration -OSS_ENDPOINT="oss-cn-hangzhou.aliyuncs.com" -OSS_BUCKET="agbcloud-internal" -OSS_PREFIX="agbcloud/releases" - -# Package directory -PACKAGE_DIR=${PACKAGE_DIR:-"packages"} -VERSION=${VERSION:-"dev-$(date +%Y%m%d-%H%M)"} - -echo "Uploading packages to OSS..." -echo "Endpoint: $OSS_ENDPOINT" -echo "Bucket: $OSS_BUCKET" -echo "Prefix: $OSS_PREFIX" -echo "Version: $VERSION" - -# Check required environment variables -if [[ -z "$OSS_ACCESS_KEY_ID" ]]; then - echo "Error: OSS_ACCESS_KEY_ID environment variable is not set" - exit 1 -fi - -if [[ -z "$OSS_ACCESS_KEY_SECRET" ]]; then - echo "Error: OSS_ACCESS_KEY_SECRET environment variable is not set" - exit 1 -fi - -# Check if package directory exists -if [[ ! -d "$PACKAGE_DIR" ]]; then - echo "Error: Package directory '$PACKAGE_DIR' not found" - exit 1 -fi - -# Check if ossutil is installed -if ! command -v ossutil >/dev/null 2>&1; then - echo "Installing ossutil..." - - # Download and install ossutil - if [[ "$OSTYPE" == "darwin"* ]]; then - # macOS - if [[ "$(uname -m)" == "arm64" ]]; then - OSSUTIL_URL="https://gosspublic.alicdn.com/ossutil/1.7.19/ossutil-v1.7.19-darwin-arm64.zip" - else - OSSUTIL_URL="https://gosspublic.alicdn.com/ossutil/1.7.19/ossutil-v1.7.19-darwin-amd64.zip" - fi - else - # Linux - OSSUTIL_URL="https://gosspublic.alicdn.com/ossutil/1.7.19/ossutil-v1.7.19-linux-amd64.zip" - fi - - curl -L "$OSSUTIL_URL" -o ossutil.zip - unzip -q ossutil.zip - chmod +x ossutil* - sudo mv ossutil* /usr/local/bin/ossutil - rm -f ossutil.zip - - echo "[OK] ossutil installed successfully" -fi - -# Configure ossutil -echo "Configuring ossutil..." -ossutil config -e "$OSS_ENDPOINT" -i "$OSS_ACCESS_KEY_ID" -k "$OSS_ACCESS_KEY_SECRET" - -# Upload all package files -echo "Uploading packages..." -upload_count=0 - -for package in "$PACKAGE_DIR"/*.tar.gz; do - if [[ -f "$package" ]]; then - filename=$(basename "$package") - oss_path="oss://$OSS_BUCKET/$OSS_PREFIX/$filename" - - echo "Uploading $filename..." - - # Upload the package - if ossutil cp "$package" "$oss_path" --force; then - echo "[OK] Uploaded: $filename" - - # Set public read permission - if ossutil set-acl "$oss_path" public-read; then - echo "[OK] Set public-read ACL for: $filename" - else - echo "[WARN] Failed to set ACL for: $filename" - fi - - # Generate public URL - public_url="https://$OSS_BUCKET.$OSS_ENDPOINT/$OSS_PREFIX/$filename" - echo " Public URL: $public_url" - - upload_count=$((upload_count + 1)) - else - echo "[ERROR] Failed to upload: $filename" - exit 1 - fi - fi -done - -# Upload SHA256 files -echo "Uploading SHA256 files..." -for sha256_file in "$PACKAGE_DIR"/*.sha256; do - if [[ -f "$sha256_file" ]]; then - filename=$(basename "$sha256_file") - oss_path="oss://$OSS_BUCKET/$OSS_PREFIX/$filename" - - echo "Uploading $filename..." - - if ossutil cp "$sha256_file" "$oss_path" --force; then - echo "[OK] Uploaded: $filename" - - # Set public read permission - ossutil set-acl "$oss_path" public-read - else - echo "[WARN] Failed to upload: $filename" - fi - fi -done - -echo "" -echo "Upload completed successfully!" -echo "Total packages uploaded: $upload_count" -echo "" -echo "Download URLs:" -for package in "$PACKAGE_DIR"/*.tar.gz; do - if [[ -f "$package" ]]; then - filename=$(basename "$package") - echo " https://$OSS_BUCKET.$OSS_ENDPOINT/$OSS_PREFIX/$filename" - fi -done \ No newline at end of file diff --git a/scripts/windows b/scripts/windows new file mode 100644 index 0000000..c9b58ac --- /dev/null +++ b/scripts/windows @@ -0,0 +1,263 @@ +# PowerShell script to download and install AgbCloud CLI binary from GitHub Releases + +param( + [string]$Version = "", + [string]$Architecture = "", + [string]$InstallPath = "", + [switch]$Help +) + +# Show help information +if ($Help) { + Write-Host "AgbCloud CLI Installation Script" + Write-Host "" + Write-Host "Usage:" + Write-Host " powershell -Command `"irm https://agbcloud.github.io/agbcloud-cli/windows | iex`"" + Write-Host "" + Write-Host "Options:" + Write-Host " -Version Specify version to install (e.g., 'v1.0.0', 'v1.2.3', 'latest')" + Write-Host " -Architecture Specify architecture ('amd64' or 'arm64')" + Write-Host " -InstallPath Specify custom installation directory" + Write-Host " -Help Show this help message" + Write-Host "" + Write-Host "Environment Variables:" + Write-Host " AGBCLOUD_VERSION Default version to install" + Write-Host " AGBCLOUD_PATH Default installation directory" + Write-Host "" + Write-Host "Examples:" + Write-Host " # Install default version (v1.0.0)" + Write-Host " powershell -Command `"irm https://agbcloud.github.io/agbcloud-cli/windows | iex`"" + Write-Host "" + exit 0 +} + +# Determine architecture +if (-not $Architecture) { + $Architecture = if ($env:PROCESSOR_ARCHITECTURE -eq "AMD64") { + "amd64" + } elseif ($env:PROCESSOR_ARCHITECTURE -eq "ARM64") { + "arm64" + } else { + "amd64" + } +} + +# GitHub repository information +$repoOwner = "agbcloud" +$repoName = "agbcloud-cli" +$githubApiUrl = "https://api.github.com/repos/$repoOwner/$repoName" + +# Installation directory +$destination = if ($InstallPath) { + $InstallPath +} elseif ($env:AGBCLOUD_PATH) { + $env:AGBCLOUD_PATH +} else { + "$env:LOCALAPPDATA\agbcloud" +} + +Write-Host "[INFO] Installing AgbCloud CLI..." +Write-Host "" + +# Determine version with parameter priority +$version = if ($Version) { + $Version +} elseif ($env:AGBCLOUD_VERSION) { + $env:AGBCLOUD_VERSION +} else { + "latest" # Default to latest version +} + +# Get latest version if needed +if ($version -eq "latest") { + Write-Host "[INFO] Fetching latest version..." + + # Try using git to get latest tag (no API calls, no 403 errors) + try { + Write-Host "[INFO] Getting latest tag using git..." + $gitVersion = git ls-remote --tags --sort=-version:refname "https://github.com/$repoOwner/$repoName.git" | Select-Object -First 1 | ForEach-Object { ($_ -split '\s+')[1] -replace 'refs/tags/', '' } + if ($gitVersion -and $gitVersion -match '^v?\d+\.\d+\.\d+') { + $version = $gitVersion + Write-Host "[SUCCESS] Found latest version: $version" + } else { + throw "Git method failed or returned invalid version" + } + } catch { + Write-Host "[WARN] Git method failed: $($_.Exception.Message)" + Write-Host "[INFO] Using fallback version v1.0.0" + Write-Host "[TIP] You can specify a version manually using: -Version v1.2.3" + Write-Host "[TIP] Check available versions at: https://github.com/$repoOwner/$repoName/releases" + $version = "v1.0.0" + } + +} else { + Write-Host "[INFO] Installing specified version: $version" +} + +# Construct download URL +# Remove 'v' prefix from version for binary name, but keep original version for download tag +$versionForBinary = $version.TrimStart('v') +$binaryName = "agb-$versionForBinary-windows-$Architecture.exe" +$downloadUrl = "https://github.com/$repoOwner/$repoName/releases/download/$version/$binaryName" + +# Display installation info +Write-Host "Installation Details:" +Write-Host " Repository: https://github.com/$repoOwner/$repoName" +Write-Host " Version: $version" +Write-Host " Architecture: $Architecture" +Write-Host " Binary: $binaryName" +Write-Host " Installation directory: $destination" +Write-Host " Download URL: $downloadUrl" +Write-Host "" + +# Create destination directory if it doesn't exist +try { + if (!(Test-Path -Path $destination)) { + Write-Host "[INFO] Creating installation directory at $destination" + New-Item -ItemType Directory -Force -Path $destination -ErrorAction Stop | Out-Null + } +} catch { + Write-Error "[ERROR] Failed to create installation directory: $_" + exit 1 +} + +# File to download +$outputFile = "$destination\agb.exe" + +# Check if already installed and get current version +$upgrading = $false +if (Test-Path $outputFile) { + try { + $currentVersionOutput = & $outputFile version 2>$null + if ($currentVersionOutput -match "version\s+([v\d\.]+)") { + $currentVersion = $matches[1] + if ($currentVersion -eq $version.TrimStart('v')) { + Write-Host "[SUCCESS] AgbCloud CLI $version is already installed!" + Write-Host " Location: $outputFile" + Write-Host "" + Write-Host "[INFO] You're all set! Use 'agb --help' to get started." + exit 0 + } else { + Write-Host "[INFO] Upgrading from $currentVersion to $version" + $upgrading = $true + } + } else { + Write-Host "[INFO] Existing installation found, upgrading..." + $upgrading = $true + } + } catch { + Write-Host "[INFO] Existing installation found, upgrading..." + $upgrading = $true + } + Write-Host "" +} + +# Download the file with progress +try { + if ($upgrading) { + Write-Host "[INFO] Downloading AgbCloud CLI update..." + } else { + Write-Host "[INFO] Downloading AgbCloud CLI..." + } + Write-Host " From: $downloadUrl" + Write-Host " To: $outputFile" + + # Use Invoke-WebRequest with progress + $ProgressPreference = 'Continue' + Invoke-WebRequest -Uri $downloadUrl -OutFile $outputFile -UseBasicParsing -ErrorAction Stop + + Write-Host "" + Write-Host "[SUCCESS] Download complete!" +} catch { + Write-Error "[ERROR] Failed to download AgbCloud CLI: $_" + Write-Host "" + Write-Host "Troubleshooting:" + Write-Host " 1. Check your internet connection" + Write-Host " 2. Verify the version exists: https://github.com/$repoOwner/$repoName/releases" + Write-Host " 3. Try the default version: -Version v1.0.0" + Write-Host " 4. Try a different version: -Version v1.2.3" + Write-Host " 5. Check if the architecture is correct: -Architecture amd64" + Write-Host " 6. Use custom install path: -InstallPath C:\MyTools" + exit 1 +} + +# Set executable permissions (Windows doesn't need this, but good practice) +try { + Write-Host "[INFO] Setting up binary permissions..." + Set-ItemProperty -Path $outputFile -Name IsReadOnly -Value $false -ErrorAction SilentlyContinue +} catch { + Write-Host " [WARN] Could not set binary permissions (this is usually fine on Windows)" +} + +# Add to PATH if not already present +try { + Write-Host "[INFO] Updating PATH environment variable..." + + $currentPath = [System.Environment]::GetEnvironmentVariable("Path", [System.EnvironmentVariableTarget]::User) + if (-not $currentPath) { $currentPath = "" } + + $pathEntries = $currentPath -split ';' | ForEach-Object { $_.TrimEnd('\') } + + if (-not ($pathEntries | Where-Object { $_ -eq $destination })) { + Write-Host " Adding $destination to user PATH..." + $newPath = if ($currentPath.EndsWith(';')) { "$currentPath$destination" } else { "$currentPath;$destination" } + [System.Environment]::SetEnvironmentVariable("Path", $newPath, [System.EnvironmentVariableTarget]::User) + Write-Host "[SUCCESS] PATH updated successfully!" + Write-Host " [TIP] Please restart your terminal or run a new PowerShell session" + } else { + Write-Host "[SUCCESS] Already in PATH" + } +} catch { + Write-Host " [WARN] Could not automatically update PATH" + Write-Host " [MANUAL] Please manually add the following to your PATH:" + Write-Host " $destination" + Write-Host "" + Write-Host " [STEPS] To add manually:" + Write-Host " 1. Press Win+R, type 'sysdm.cpl', press Enter" + Write-Host " 2. Click 'Environment Variables'" + Write-Host " 3. Under 'User variables', select 'Path' and click 'Edit'" + Write-Host " 4. Click 'New' and add: $destination" + Write-Host " 5. Click OK to save" +} + +Write-Host "" + +# Test installation +Write-Host "[INFO] Testing installation..." +try { + $installedVersion = & $outputFile version 2>$null + if ($installedVersion) { + Write-Host "[SUCCESS] Installation test successful!" + Write-Host "" + + if ($upgrading) { + Write-Host "[SUCCESS] AgbCloud CLI successfully upgraded to $version!" + } else { + Write-Host "[SUCCESS] AgbCloud CLI $version installed successfully!" + } + + Write-Host " Location: $outputFile" + Write-Host " Version: $installedVersion" + Write-Host "" + Write-Host "Quick Start:" + Write-Host " agb --help # Show help" + Write-Host " agb version # Show version" + Write-Host " agb login # Login to AgbCloud" + Write-Host "" + Write-Host "Documentation:" + Write-Host " https://github.com/$repoOwner/$repoName" + Write-Host "" + Write-Host "[SUCCESS] Installation completed! " + } else { + Write-Host "[WARN] Installation completed but version check failed" + Write-Host " This might be normal if the binary requires additional setup" + Write-Host " Try running: $outputFile --help" + } +} catch { + Write-Host "[WARN] Installation completed but test failed: $_" + Write-Host " This might be normal if the binary requires additional setup" + Write-Host " Try running: $outputFile --help" +} + +Write-Host "" +Write-Host "Thank you for using AgbCloud CLI! " \ No newline at end of file