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

3.9% Statements 5/128
0% Branches 0/54
7.69% Functions 1/13
3.9% Lines 5/128

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 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456                              7x                                                   103x     103x 103x 103x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
/**
 * Jekyll Downloader Service
 *
 * Manages Jekyll gem installation using Bundler.
 * Uses Bundler to install Jekyll to version-specific directories for isolation.
 */
 
import { execFile } from 'child_process';
import { promisify } from 'util';
import fs from 'fs-extra';
import path from 'path';
import type { PathHelper, EnvironmentInfo } from '../../utils/path-helper.js';
import type { OutputConsole } from '../../adapters/types.js';
import type { SSGBinaryManager } from '../types.js';
 
const execFileAsync = promisify(execFile);
 
// ============================================================================
// Types
// ============================================================================
 
export interface DownloadProgress {
  percent: number;
  message: string;
  complete: boolean;
  error?: string;
}
 
export interface JekyllDownloaderDependencies {
  pathHelper: PathHelper;
  outputConsole: OutputConsole;
  environmentInfo: EnvironmentInfo;
}
 
/**
 * JekyllDownloader - Manages gem installation for Jekyll using Bundler
 */
export class JekyllDownloader implements SSGBinaryManager {
  private pathHelper: PathHelper;
  private outputConsole: OutputConsole;
  private environmentInfo: EnvironmentInfo;
  private cancelRequested: boolean = false;
 
  constructor(dependencies: JekyllDownloaderDependencies) {
    this.pathHelper = dependencies.pathHelper;
    this.outputConsole = dependencies.outputConsole;
    this.environmentInfo = dependencies.environmentInfo;
  }
 
  /**
   * Check if Ruby is installed on the system
   */
  private async checkRubyInstalled(): Promise<boolean> {
    try {
      await execFileAsync('ruby', ['--version'], { timeout: 5000 });
      return true;
    } catch {
      return false;
    }
  }
 
  /**
   * Check if Bundler is installed
   */
  private async checkBundlerInstalled(): Promise<boolean> {
    try {
      await execFileAsync('bundle', ['--version'], { timeout: 5000 });
      return true;
    } catch {
      return false;
    }
  }
 
  /**
   * Get the bundle command (either from PATH or user gem directory)
   */
  private async getBundleCommand(): Promise<string> {
    // First, try the standard 'bundle' command
    try {
      await execFileAsync('bundle', ['--version'], { timeout: 5000 });
      return 'bundle';
    } catch {
      // Bundle not in PATH, try to find it in user gem directory
      try {
        // Get gem environment to find user gem paths
        const { stdout } = await execFileAsync('gem', ['environment', 'gempath'], { timeout: 5000 });
        const gemPaths = stdout.trim().split(':');
 
        // Check common bundle locations
        for (const gemPath of gemPaths) {
          const bundlePath = path.join(gemPath, 'bin', 'bundle');
          if (fs.existsSync(bundlePath)) {
            return bundlePath;
          }
        }
      } catch {
        // Ignore errors
      }
 
      // Last resort: try common user gem locations
      const homeDir = process.env.HOME || process.env.USERPROFILE || '';
      const commonPaths = [
        path.join(homeDir, '.gem', 'ruby', '3.3.0', 'bin', 'bundle'),
        path.join(homeDir, '.gem', 'ruby', '3.2.0', 'bin', 'bundle'),
        path.join(homeDir, '.gem', 'ruby', '3.1.0', 'bin', 'bundle'),
        path.join(homeDir, '.gem', 'ruby', '3.0.0', 'bin', 'bundle'),
        path.join(homeDir, '.local', 'share', 'gem', 'ruby', '3.3.0', 'bin', 'bundle'),
        path.join(homeDir, '.local', 'share', 'gem', 'ruby', '3.2.0', 'bin', 'bundle'),
        path.join(homeDir, '.local', 'share', 'gem', 'ruby', '3.1.0', 'bin', 'bundle'),
        path.join(homeDir, '.local', 'share', 'gem', 'ruby', '3.0.0', 'bin', 'bundle'),
      ];
 
      for (const bundlePath of commonPaths) {
        if (fs.existsSync(bundlePath)) {
          return bundlePath;
        }
      }
 
      throw new Error('Bundle command not found');
    }
  }
 
  /**
   * Check if a specific Jekyll version is installed with all required gems
   */
  isVersionInstalled(version: string): boolean {
    const installDir = this.pathHelper.getSSGBinDirForVer('jekyll', version);
    const gemfileLock = path.join(installDir, 'Gemfile.lock');
    const gemfile = path.join(installDir, 'Gemfile');
 
    // Check if Gemfile.lock exists (indicates successful bundle install)
    if (!fs.existsSync(gemfileLock)) {
      return false;
    }
 
    // Verify the Gemfile contains required gems (minima, jekyll-feed, jekyll-seo-tag)
    // This ensures old installations get updated when we add new gems
    if (fs.existsSync(gemfile)) {
      try {
        const gemfileContent = fs.readFileSync(gemfile, 'utf-8');
        const hasMinima = gemfileContent.includes("gem 'minima'");
        const hasFeed = gemfileContent.includes("gem 'jekyll-feed'");
        const hasSeoTag = gemfileContent.includes("gem 'jekyll-seo-tag'");
 
        // If any required gem is missing, consider it not installed (will trigger reinstall)
        if (!hasMinima || !hasFeed || !hasSeoTag) {
          return false;
        }
      } catch {
        return false;
      }
    }
 
    return true;
  }
 
  /**
   * Get the path to an installed Jekyll version
   * Returns the bundle exec command that should be used
   */
  getVersionPath(version: string): string | null {
    if (!this.isVersionInstalled(version)) {
      return null;
    }
 
    const installDir = this.pathHelper.getSSGBinDirForVer('jekyll', version);
 
    // Return path to the wrapper script
    const wrapperScript = path.join(installDir, this.environmentInfo.platform === 'windows' ? 'jekyll.cmd' : 'jekyll.sh');
 
    if (fs.existsSync(wrapperScript)) {
      return wrapperScript;
    }
 
    return installDir;
  }
 
  /**
   * List all installed Jekyll versions
   */
  listInstalledVersions(): string[] {
    const binRoot = this.pathHelper.getSSGBinRoot('jekyll');
 
    if (!fs.existsSync(binRoot)) {
      return [];
    }
 
    const versions: string[] = [];
    const entries = fs.readdirSync(binRoot, { withFileTypes: true });
 
    for (const entry of entries) {
      if (entry.isDirectory()) {
        const versionDir = path.join(binRoot, entry.name);
        const gemfileLock = path.join(versionDir, 'Gemfile.lock');
 
        if (fs.existsSync(gemfileLock)) {
          versions.push(entry.name);
        }
      }
    }
 
    return versions;
  }
 
  /**
   * Download and install a specific Jekyll version using Bundler
   * Implementation of SSGBinaryManager.download()
   */
  async *download(version: string, skipExistCheck?: boolean): AsyncGenerator<DownloadProgress> {
    // Check if already installed unless skipping
    if (!skipExistCheck && this.isVersionInstalled(version)) {
      yield {
        percent: 100,
        message: 'Already installed',
        complete: true,
      };
      return;
    }
 
    yield* this.downloadVersion(version);
  }
 
  /**
   * Download and install a specific Jekyll version using Bundler
   * Returns an async generator for streaming progress updates
   */
  async *downloadVersion(version: string): AsyncGenerator<DownloadProgress> {
    const installDir = this.pathHelper.getSSGBinDirForVer('jekyll', version);
 
    try {
      // Step 1: Check Ruby installation
      yield {
        percent: 5,
        message: 'Checking Ruby installation...',
        complete: false,
      };
 
      const hasRuby = await this.checkRubyInstalled();
      if (!hasRuby) {
        throw new Error('Ruby is not installed. Please install Ruby (https://www.ruby-lang.org/) to use Jekyll.');
      }
 
      // Step 2: Check Bundler installation
      yield {
        percent: 10,
        message: 'Checking Bundler installation...',
        complete: false,
      };
 
      const hasBundler = await this.checkBundlerInstalled();
      if (!hasBundler) {
        yield {
          percent: 15,
          message: 'Installing Bundler locally...',
          complete: false,
        };
 
        try {
          // Install bundler to user directory (no sudo required)
          await execFileAsync('gem', ['install', 'bundler', '--user-install', '--no-document'], {
            timeout: 120000, // 2 minutes
          });
        } catch {
          // If that fails, provide a helpful error message
          throw new Error(
            'Bundler is not installed and automatic installation failed. ' +
            'Please install Bundler manually by running: gem install bundler --user-install'
          );
        }
      }
 
      // Step 3: Prepare directory
      yield {
        percent: 20,
        message: 'Preparing installation directory...',
        complete: false,
      };
 
      await fs.ensureDir(installDir);
 
      // Step 4: Create Gemfile
      yield {
        percent: 30,
        message: 'Creating Gemfile...',
        complete: false,
      };
 
      const gemfileContent = `source 'https://rubygems.org'
 
gem 'jekyll', '${version}'
gem 'webrick', '~> 1.8'  # Required for Ruby 3.0+
 
# Common Jekyll themes and plugins
gem 'minima', '~> 2.5'
gem 'jekyll-feed', '~> 0.12'
gem 'jekyll-seo-tag', '~> 2.8'
`;
 
      await fs.writeFile(path.join(installDir, 'Gemfile'), gemfileContent);
 
      // Step 5: Install Jekyll via Bundler
      yield {
        percent: 40,
        message: `Installing Jekyll ${version} with Bundler...`,
        complete: false,
      };
 
      this.outputConsole.appendLine(`Installing Jekyll ${version} to ${installDir}`);
 
      // Get bundle command (may be in user gem directory)
      const bundleCommand = await this.getBundleCommand();
      this.outputConsole.appendLine(`Using bundle at: ${bundleCommand}`);
 
      // Configure bundle to install gems in vendor/bundle (modern bundler syntax)
      await execFileAsync(
        bundleCommand,
        ['config', 'set', '--local', 'path', 'vendor/bundle'],
        {
          cwd: installDir,
          timeout: 30000,
        }
      );
 
      // Run bundle install
      await execFileAsync(
        bundleCommand,
        ['install'],
        {
          cwd: installDir,
          timeout: 600000, // 10 minute timeout (gem installs can be slow)
        }
      );
 
      // Step 6: Create wrapper script
      yield {
        percent: 80,
        message: 'Creating wrapper script...',
        complete: false,
      };
 
      await this.createWrapperScript(installDir, bundleCommand);
 
      // Step 7: Verify installation
      yield {
        percent: 90,
        message: 'Verifying installation...',
        complete: false,
      };
 
      const gemfileLock = path.join(installDir, 'Gemfile.lock');
      const installed = fs.existsSync(gemfileLock);
 
      if (!installed) {
        throw new Error('Jekyll installation verification failed - Gemfile.lock not found');
      }
 
      yield {
        percent: 100,
        message: 'Installation complete!',
        complete: true,
      };
 
      this.outputConsole.appendLine(`Jekyll ${version} installed successfully`);
    } catch (error) {
      this.outputConsole.appendLine(`Jekyll installation error: ${error instanceof Error ? error.message : String(error)}`);
 
      // Clean up on failure
      try {
        await fs.remove(installDir);
      } catch (cleanupError) {
        this.outputConsole.appendLine(`Failed to clean up installation directory: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`);
      }
 
      yield {
        percent: 0,
        message: 'Installation failed',
        complete: false,
        error: error instanceof Error ? error.message : String(error),
      };
    }
  }
 
  /**
   * Create a wrapper script to run Jekyll with bundle exec
   */
  private async createWrapperScript(installDir: string, bundleCommand: string): Promise<void> {
    const gemfilePath = path.join(installDir, 'Gemfile');
 
    if (this.environmentInfo.platform === 'windows') {
      // Windows batch script
      const batchScript = `@echo off
set BUNDLE_GEMFILE=${gemfilePath}
"${bundleCommand}" exec jekyll %*
`;
      await fs.writeFile(path.join(installDir, 'jekyll.cmd'), batchScript);
    } else {
      // Unix shell script
      // Set BUNDLE_GEMFILE to point to the installation directory's Gemfile
      // This allows Jekyll to run from the workspace directory while using the correct gems
      const shellScript = `#!/bin/bash
export BUNDLE_GEMFILE="${gemfilePath}"
"${bundleCommand}" exec jekyll "$@"
`;
      const scriptPath = path.join(installDir, 'jekyll.sh');
      await fs.writeFile(scriptPath, shellScript);
      await fs.chmod(scriptPath, '755'); // Make executable
    }
  }
 
  /**
   * Cancel current download
   * Implementation of SSGBinaryManager.cancel()
   */
  async cancel(): Promise<void> {
    this.cancelRequested = true;
    this.outputConsole.appendLine('Jekyll download cancellation requested');
  }
 
  /**
   * Ensure a specific Jekyll version is available (download if not installed)
   * Implementation of SSGBinaryManager.ensureAvailable()
   */
  async ensureAvailable(version: string): Promise<void> {
    if (this.isVersionInstalled(version)) {
      return;
    }
 
    this.outputConsole.appendLine(`Jekyll ${version} not found, installing...`);
 
    // Run download generator to completion
    for await (const progress of this.download(version, true)) {
      this.outputConsole.appendLine(`Jekyll install: ${progress.message} (${progress.percent}%)`);
 
      if (progress.error) {
        throw new Error(`Failed to install Jekyll ${version}: ${progress.error}`);
      }
 
      if (progress.complete) {
        break;
      }
    }
  }
 
  /**
   * Remove a specific Jekyll version
   */
  async removeVersion(version: string): Promise<void> {
    const installDir = this.pathHelper.getSSGBinDirForVer('jekyll', version);
 
    if (fs.existsSync(installDir)) {
      await fs.remove(installDir);
      this.outputConsole.appendLine(`Removed Jekyll ${version}`);
    }
  }
}