All files / backend/src/ssg-providers/hugo hugo-downloader.ts

83.84% Statements 109/130
75% Branches 51/68
85.71% Functions 12/14
83.72% Lines 108/129

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369                                                                                          20x 20x       20x   1x 1x     18x 18x   1x             19x     14x 14x 14x     2x 2x 2x     2x   2x 1x   2x 2x     1x       18x 18x                       4x 4x   4x                 4x 4x                                           5x     4x       1x                   130x           130x 130x     130x 130x 130x 130x 130x             6x 6x             9x                     7x 7x   7x   5x 1x     4x         4x 4x   4x 4x   8x     8x 8x 4x     4x       4x 4x 4x                 12x 1x 1x       11x 2x 2x     9x 9x   9x 9x 9x 9x 9x     9x 4x       9x           9x 8x     8x     8x           7x 7x     4x           4x 4x 4x     4x         4x 3x       4x   4x   4x 4x   4x   9x 9x 9x               3x 1x     3x   3x 3x 3x   3x             7x                             3x 10x 1x          
/**
 * Hugo Downloader Service
 *
 * Downloads and installs Hugo binaries from GitHub releases.
 * Uses async generators for streaming progress updates via SSE.
 */
 
import fs from 'fs-extra';
import path from 'path';
import { extract } from 'tar';
import AdmZip from 'adm-zip';
import type { PathHelper, EnvironmentInfo } from '../../utils/path-helper.js';
import type { OutputConsole } from '../../adapters/types.js';
 
// ============================================================================
// Types
// ============================================================================
 
export interface HugoEnvironment {
  platform: 'macOS' | 'windows' | 'linux';
  arch: 'x64' | 'x32';
}
 
export interface DownloadProgress {
  percent: number;
  message: string;
  complete: boolean;
  error?: string;
}
 
export interface HugoDownloaderDependencies {
  pathHelper: PathHelper;
  outputConsole: OutputConsole;
  environmentInfo: EnvironmentInfo;
}
 
/**
 * Builds download URLs for official Hugo releases from GitHub
 */
export class OfficialHugoSourceUrlBuilder {
  /**
   * Build the download URL for a specific Hugo version and environment
   */
  build(environment: HugoEnvironment, version: string): string {
    // Strip leading 'v' if present
    const normalizedVersion = version.replace(/^v/i, '');
    const versionMain = parseInt(normalizedVersion.split('.')[1], 10);
 
    // Determine architecture string
    let arch: string;
    switch (environment.arch) {
      case 'x32':
        arch = '32bit';
        break;
      case 'x64':
        // Hugo 0.103+ uses 'amd64' instead of '64bit'
        arch = versionMain >= 103 ? 'amd64' : '64bit';
        break;
      default:
        throw new Error(`Unsupported architecture: ${environment.arch}`);
    }
 
    // Determine platform string and format
    let platform: string;
    let format: string;
 
    switch (environment.platform) {
      case 'linux':
        // Hugo 0.103+ uses lowercase platform names
        platform = versionMain >= 103 ? 'linux' : 'Linux';
        format = 'tar.gz';
        break;
 
      case 'windows':
        platform = versionMain >= 103 ? 'windows' : 'Windows';
        format = 'zip';
        break;
 
      case 'macOS':
        platform = versionMain >= 103 ? 'darwin' : 'macOS';
        // Hugo 0.102+ uses universal binary for macOS
        if (versionMain >= 102) {
          arch = 'universal';
        }
        format = 'tar.gz';
        break;
 
      default:
        throw new Error(`Unsupported platform: ${environment.platform}`);
    }
 
    // Build URL - note: extended_ prefix is part of version string, not URL path
    const cleanVersion = normalizedVersion.replace('extended_', '');
    return `https://github.com/gohugoio/hugo/releases/download/v${cleanVersion}/hugo_${normalizedVersion}_${platform}-${arch}.${format}`;
  }
}
 
/**
 * Unpacks downloaded Hugo archives using node-tar (Linux/macOS) and adm-zip (Windows)
 */
export class OfficialHugoUnpacker {
  /**
   * Unpack a Hugo archive for Linux/macOS (tar.gz format)
   */
  private async unpackLinux(packagePath: string): Promise<void> {
    const normalizedPath = path.normalize(packagePath);
    const output = path.dirname(normalizedPath);
 
    await extract({
      file: normalizedPath,
      cwd: output,
      filter: (filePath: string) => {
        const basename = path.basename(filePath);
        return basename === 'hugo' || basename.startsWith('hugo.');
      },
    });
 
    const hugoBinary = path.join(output, 'hugo');
    await fs.chmod(hugoBinary, 0o722);
  }
 
  /**
   * Unpack a Hugo archive for Windows (zip format)
   */
  private async unpackWindows(packagePath: string): Promise<void> {
    const normalizedPath = path.normalize(packagePath);
    const output = path.dirname(normalizedPath);
 
    const zip = new AdmZip(normalizedPath);
    for (const entry of zip.getEntries()) {
      if (!entry.isDirectory && entry.name.endsWith('.exe')) {
        zip.extractEntryTo(entry, output, false, true);
      }
    }
  }
 
  /**
   * Unpack a Hugo archive based on platform
   */
  async unpack(packagePath: string, environment: HugoEnvironment): Promise<void> {
    switch (environment.platform) {
      case 'linux':
      case 'macOS':
        return this.unpackLinux(packagePath);
      case 'windows':
        return this.unpackWindows(packagePath);
      default:
        throw new Error(`Unsupported platform: ${environment.platform}`);
    }
  }
}
 
/**
 * Main Hugo downloader service
 * Downloads Hugo binaries and streams progress via async generator
 */
export class HugoDownloader {
  private isRunning = false;
  private pathHelper: PathHelper;
  private outputConsole: OutputConsole;
  private environmentInfo: EnvironmentInfo;
  private urlBuilder: OfficialHugoSourceUrlBuilder;
  private unpacker: OfficialHugoUnpacker;
  private abortController: AbortController | null = null;
  private currentDownloadPath: string | null = null;
 
  constructor(dependencies: HugoDownloaderDependencies) {
    this.pathHelper = dependencies.pathHelper;
    this.outputConsole = dependencies.outputConsole;
    this.environmentInfo = dependencies.environmentInfo;
    this.urlBuilder = new OfficialHugoSourceUrlBuilder();
    this.unpacker = new OfficialHugoUnpacker();
  }
 
  /**
   * Check if a specific Hugo version is installed
   */
  isVersionInstalled(version: string): boolean {
    const bin = this.pathHelper.getSSGBinForVer('hugo', version);
    return fs.existsSync(bin);
  }
 
  /**
   * Get the Hugo environment for downloads
   */
  private getHugoEnvironment(): HugoEnvironment {
    return {
      platform: this.environmentInfo.platform,
      arch: process.arch === 'x64' ? 'x64' : 'x32',
    };
  }
 
  /**
   * Download file from URL to destination
   * Supports cancellation via AbortController
   */
  private async downloadToFile(url: string, dest: string, signal?: AbortSignal): Promise<void> {
    const dir = path.dirname(dest);
    await fs.ensureDir(dir);
 
    const response = await fetch(url, { method: 'GET', signal });
 
    if (!response.ok) {
      throw new Error(`Failed to download: ${response.status} ${response.statusText}`);
    }
 
    Iif (!response.body) {
      throw new Error('Response body is null');
    }
 
    // Convert web ReadableStream to Node.js stream
    const fileStream = fs.createWriteStream(dest);
    const reader = response.body.getReader();
 
    try {
      while (true) {
        // Check if cancelled before each read
        Iif (signal?.aborted) {
          throw new Error('Download cancelled');
        }
        const { done, value } = await reader.read();
        if (done) break;
        fileStream.write(Buffer.from(value));
      }
    } finally {
      fileStream.end();
    }
 
    // Wait for file to finish writing
    await new Promise<void>((resolve, reject) => {
      fileStream.on('finish', resolve);
      fileStream.on('error', reject);
    });
  }
 
  /**
   * Download Hugo version with progress updates via async generator
   */
  async *download(version: string, skipExistCheck = false): AsyncGenerator<DownloadProgress> {
    // Guard against concurrent downloads
    if (this.isRunning) {
      yield { percent: 0, message: 'Download already in progress', complete: false, error: 'Download already in progress' };
      return;
    }
 
    // Check if already installed
    if (!skipExistCheck && this.isVersionInstalled(version)) {
      yield { percent: 100, message: 'Hugo already installed', complete: true };
      return;
    }
 
    this.isRunning = true;
    this.abortController = new AbortController();
 
    try {
      const environment = this.getHugoEnvironment();
      const url = this.urlBuilder.build(environment, version);
      const tempDest = path.join(this.pathHelper.getSSGBinDirForVer('hugo', version), 'download.partial');
      this.currentDownloadPath = tempDest;
 
      // Clean up any existing partial download
      if (fs.existsSync(tempDest)) {
        await fs.unlink(tempDest);
      }
 
      // Check if cancelled
      Iif (this.abortController.signal.aborted) {
        yield { percent: 0, message: 'Download cancelled', complete: false, error: 'Download cancelled' };
        return;
      }
 
      // Progress: Starting
      yield { percent: 0, message: 'Starting Hugo installation...', complete: false };
      this.outputConsole.appendLine(`Hugo installation started. Downloading package from ${url}...`);
 
      // Progress: Preparing
      yield { percent: 20, message: 'Preparing download...', complete: false };
 
      // Check if cancelled
      Iif (this.abortController.signal.aborted) {
        yield { percent: 0, message: 'Download cancelled', complete: false, error: 'Download cancelled' };
        return;
      }
 
      // Progress: Downloading
      yield { percent: 30, message: 'Downloading Hugo...', complete: false };
      await this.downloadToFile(url, tempDest, this.abortController.signal);
 
      // Check if cancelled
      Iif (this.abortController.signal.aborted) {
        yield { percent: 0, message: 'Download cancelled', complete: false, error: 'Download cancelled' };
        return;
      }
 
      // Progress: Unpacking
      yield { percent: 70, message: 'Unpacking Hugo...', complete: false };
      this.outputConsole.appendLine('Unpacking...');
      await this.unpacker.unpack(tempDest, environment);
 
      // Clean up temp file
      Iif (fs.existsSync(tempDest)) {
        await fs.unlink(tempDest);
      }
 
      // Progress: Complete
      yield { percent: 100, message: 'Hugo installation completed', complete: true };
      this.outputConsole.appendLine('Hugo installation completed.');
 
    } catch (error) {
      // Clean up partial download on error
      await this.cleanupPartialDownload();
 
      const errorMessage = error instanceof Error ? error.message : String(error);
      // Don't log cancellation as an error
      Eif (errorMessage !== 'Download cancelled' && !errorMessage.includes('aborted')) {
        this.outputConsole.appendLine(`Hugo installation failed: ${errorMessage}`);
      }
      yield { percent: 0, message: `Installation failed: ${errorMessage}`, complete: false, error: errorMessage };
    } finally {
      this.isRunning = false;
      this.abortController = null;
      this.currentDownloadPath = null;
    }
  }
 
  /**
   * Cancel the current download and clean up partial files
   */
  async cancel(): Promise<void> {
    if (this.abortController) {
      this.abortController.abort();
    }
 
    await this.cleanupPartialDownload();
 
    this.isRunning = false;
    this.abortController = null;
    this.currentDownloadPath = null;
 
    this.outputConsole.appendLine('Hugo download cancelled.');
  }
 
  /**
   * Clean up any partial download files
   */
  private async cleanupPartialDownload(): Promise<void> {
    Iif (this.currentDownloadPath && fs.existsSync(this.currentDownloadPath)) {
      try {
        await fs.unlink(this.currentDownloadPath);
        this.outputConsole.appendLine('Cleaned up partial download file.');
      } catch {
        // Ignore cleanup errors
      }
    }
  }
 
  /**
   * Ensure Hugo version is available - download if not installed
   * This is a convenience method that consumes the generator
   */
  async ensureAvailable(version: string): Promise<void> {
    for await (const progress of this.download(version)) {
      if (progress.error) {
        throw new Error(progress.error);
      }
    }
  }
}