From 57cc2acd07b7f53bfe6aae06783606e397b90228 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 10 Nov 2026 23:03:27 +0000 Subject: [PATCH] fix(ruby): read the runtime from ruby file: and version files Bundler 2.4 `ruby file:` and a Gemfile with no ruby line left `vg scan` with no Ruby runtime, so runtime lag was skipped. Read the named version file, then `.ruby-version` and a `ruby` entry in `.tool-versions`. Signed-off-by: Cursor Agent Co-authored-by: vibgrate-team --- src/core-open/scanners/ruby-scanner.ts | 139 ++++++++++++++++++-- test/ruby-runtime-pin.test.ts | 174 +++++++++++++++++++++++++ 2 files changed, 303 insertions(+), 10 deletions(-) create mode 100644 test/ruby-runtime-pin.test.ts diff --git a/src/core-open/scanners/ruby-scanner.ts b/src/core-open/scanners/ruby-scanner.ts index 4d15e79e..5efcd050 100644 --- a/src/core-open/scanners/ruby-scanner.ts +++ b/src/core-open/scanners/ruby-scanner.ts @@ -425,16 +425,124 @@ function parseGemspec(content: string): RubyDependency[] { } /** - * Extract Ruby version from a Gemfile. + * A version token from a Ruby pin file. + * A leading `ruby-` (chruby / ruby-install) is dropped so `ruby-3.3.0` + * is `3.3.0`. Tokens that are not a version (`system`) are ignored. + */ +function normalizeRubyVersionToken(token: string): string | undefined { + const stripped = token.trim().replace(/^ruby-/, ''); + if (!/^\d+(?:\.\d+)*/.test(stripped)) return undefined; + return stripped; +} + +/** Non-blank, non-comment lines, with an end-of-line `#` comment removed. */ +function rubyPinFileLines(content: string): string[] { + const text = content.charCodeAt(0) === 0xfeff ? content.slice(1) : content; + const lines: string[] = []; + for (const raw of text.split(/\r?\n/)) { + const line = raw.replace(/#.*$/, '').trim(); + if (line) lines.push(line); + } + return lines; +} + +/** + * Runtime from an rbenv or chruby `.ruby-version` file. + * Only the first non-blank, non-comment line is read. Surrounding + * whitespace and a leading `ruby-` prefix are removed. + */ +export function rubyVersionFromRubyVersionFile(content: string): string | undefined { + const line = rubyPinFileLines(content)[0]; + if (!line) return undefined; + return normalizeRubyVersionToken(line.split(/\s+/)[0]!); +} + +/** + * Runtime from an asdf `.tool-versions` `ruby` entry. + * The first version token on that line wins (`ruby 3.3.4 3.2.2` → + * `3.3.4`). A non-version token such as `system` is skipped. A later + * `ruby` line is used only when the earlier one has no version token. + */ +export function rubyVersionFromToolVersions(content: string): string | undefined { + for (const line of rubyPinFileLines(content)) { + const parts = line.split(/\s+/); + if (parts[0]!.toLowerCase() !== 'ruby') continue; + for (const part of parts.slice(1)) { + const pin = normalizeRubyVersionToken(part); + if (pin) return pin; + } + } + return undefined; +} + +/** + * How a Gemfile names the Ruby runtime. * - * Handles: - * ruby '3.2.2' - * ruby "3.3.0" - * ruby ">= 3.1" + * An explicit version (`ruby '3.1.0'`, `ruby ">= 3.1"`) wins over a file. + * Bundler 2.4+ `ruby file: ".ruby-version"` and the hash-rocket form + * `ruby :file => ".ruby-version"` point at a version file relative to + * the Gemfile. No `ruby` line means the caller should read the pin files. + */ +function gemfileRubyRuntime(content: string): { version?: string; file?: string } { + let file: string | undefined; + for (const raw of content.split(/\r?\n/)) { + const line = raw.trim(); + if (!line || line.startsWith('#')) continue; + const versionMatch = /^ruby\s+['"]([^'"]+)['"]/.exec(line); + if (versionMatch) return { version: versionMatch[1] }; + if (file === undefined) { + const fileMatch = /^ruby\s+(?:file\s*:|:file\s*=>)\s*['"]([^'"]+)['"]/.exec(line); + if (fileMatch) file = fileMatch[1]; + } + } + return file !== undefined ? { file } : {}; +} + +/** + * Read a pin file through the scan cache when one is in use. + * A missing or unreadable file returns undefined and never fails the scan. + */ +async function readOptionalText( + filePath: string, + cache: FileCache | undefined, +): Promise { + try { + const exists = cache ? await cache.pathExists(filePath) : await pathExists(filePath); + if (!exists) return undefined; + return cache ? await cache.readTextFile(filePath) : await readTextFile(filePath); + } catch { + return undefined; + } +} + +/** + * Interpreter pin when the Gemfile does not declare one. + * `.ruby-version` next to the Gemfile wins over a `ruby` entry in + * `.tool-versions`. */ -function extractRubyVersion(content: string): string | undefined { - const match = content.match(/^\s*ruby\s+['"]([^'"]+)['"]/m); - return match?.[1]; +async function rubyRuntimeFromPinFiles( + dir: string, + cache: FileCache | undefined, +): Promise { + const rubyVersionFile = await readOptionalText(path.join(dir, '.ruby-version'), cache); + if (rubyVersionFile !== undefined) { + const pinned = rubyVersionFromRubyVersionFile(rubyVersionFile); + if (pinned) return pinned; + } + const toolVersions = await readOptionalText(path.join(dir, '.tool-versions'), cache); + if (toolVersions === undefined) return undefined; + return rubyVersionFromToolVersions(toolVersions); +} + +/** Version text from a `ruby file:` path, resolved relative to the Gemfile. */ +async function rubyRuntimeFromVersionFile( + dir: string, + versionFile: string, + cache: FileCache | undefined, +): Promise { + const text = await readOptionalText(path.resolve(dir, versionFile), cache); + if (text === undefined) return undefined; + return rubyVersionFromRubyVersionFile(text); } // ── Ruby project file names ── @@ -516,6 +624,7 @@ async function scanOneRubyProject( const relDir = path.relative(rootDir, dir) || '.'; let projectName = path.basename(dir === rootDir ? rootDir : dir); let rubyVersion: string | undefined; + let rubyVersionFile: string | undefined; const allDeps = new Map(); // Parse each manifest file, preferring Gemfile > .gemspec @@ -524,8 +633,9 @@ async function scanOneRubyProject( const content = cache ? await cache.readTextFile(f) : await readTextFile(f); if (fileName === 'Gemfile') { - const parsedVersion = extractRubyVersion(content); - if (parsedVersion) rubyVersion = parsedVersion; + const requested = gemfileRubyRuntime(content); + if (requested.version) rubyVersion = requested.version; + else if (requested.file !== undefined) rubyVersionFile = requested.file; for (const dep of parseGemfile(content)) { if (!allDeps.has(dep.name)) allDeps.set(dep.name, dep); @@ -541,6 +651,15 @@ async function scanOneRubyProject( } } + // An explicit `ruby '3.1.0'` line already won. `ruby file:` reads that + // path relative to the Gemfile and does not fall through. With no `ruby` + // line, `.ruby-version` wins over a `ruby` entry in `.tool-versions`. + if (!rubyVersion) { + rubyVersion = rubyVersionFile !== undefined + ? await rubyRuntimeFromVersionFile(dir, rubyVersionFile, cache) + : await rubyRuntimeFromPinFiles(dir, cache); + } + // Determine Ruby runtime version lag let runtimeMajorsBehind: number | undefined; let runtimeLatest: string | undefined; diff --git a/test/ruby-runtime-pin.test.ts b/test/ruby-runtime-pin.test.ts new file mode 100644 index 00000000..7b59a6b0 --- /dev/null +++ b/test/ruby-runtime-pin.test.ts @@ -0,0 +1,174 @@ +/** + * Bundler 2.4+ `ruby file: ".ruby-version"` and projects that pin Ruby + * only in `.ruby-version` or `.tool-versions` still report a runtime. + * An explicit `ruby '3.1.0'` line stays ahead of those files. + */ +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { latestStable } from '../src/core-open/runtimes/catalog.js'; +import { BUNDLED_RUNTIME_CATALOG } from '../src/core-open/runtimes/snapshot.js'; +import { + rubyVersionFromRubyVersionFile, + rubyVersionFromToolVersions, + scanRubyProjects, +} from '../src/core-open/scanners/ruby-scanner.js'; +import { RubyGemsCache } from '../src/core-open/scanners/rubygems-cache.js'; +import type { ProjectScan } from '../src/core-open/types.js'; +import { FileCache } from '../src/core-open/utils/fs.js'; +import { Semaphore } from '../src/core-open/utils/semaphore.js'; + +function rubyLag(version: string): { latest: string; behind: number } { + const match = /(\d+)\.(\d+)/.exec(version); + if (!match) throw new Error(`no ruby version in ${version}`); + const reqMajor = Number(match[1]); + const reqMinor = Number(match[2]); + const latest = latestStable(BUNDLED_RUNTIME_CATALOG, 'ruby'); + if (!latest) throw new Error('ruby catalog has no released cycle'); + const behind = reqMajor === latest.major + ? Math.max(0, latest.minor - reqMinor) + : latest.minor + (latest.major - reqMajor) * 10; + return { latest: `${latest.major}.${latest.minor}`, behind }; +} + +describe('Ruby runtime pin files', () => { + const roots: string[] = []; + + afterEach(() => { + for (const root of roots) fs.rmSync(root, { recursive: true, force: true }); + roots.length = 0; + }); + + function makeRoot(): string { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'vg-ruby-pin-')); + roots.push(root); + return root; + } + + function write(root: string, name: string, body: string): void { + const file = path.join(root, name); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, body); + } + + async function scan(root: string, cache?: FileCache): Promise { + return scanRubyProjects(root, new RubyGemsCache(new Semaphore(1), undefined, true), cache); + } + + it('strips a ruby- prefix and whitespace, and skips non-version tokens', () => { + expect(rubyVersionFromRubyVersionFile(' ruby-3.2.2 \r\n')).toBe('3.2.2'); + expect(rubyVersionFromRubyVersionFile('\n# local pin\r\n3.3.4\r\n')).toBe('3.3.4'); + expect(rubyVersionFromRubyVersionFile('\uFEFF3.3.4\n')).toBe('3.3.4'); + expect(rubyVersionFromRubyVersionFile('system\n3.3.4\n')).toBeUndefined(); + expect(rubyVersionFromToolVersions('nodejs 22.11.0\nruby ruby-3.4.1 3.3.0\n')).toBe('3.4.1'); + expect(rubyVersionFromToolVersions('# ruby 2.6.10\nruby 3.2.2 # app\n')).toBe('3.2.2'); + expect(rubyVersionFromToolVersions('ruby system\nruby 3.1.4\n')).toBe('3.1.4'); + expect(rubyVersionFromToolVersions('ruby system\n')).toBeUndefined(); + }); + + for (const cached of [false, true]) { + describe(cached ? 'with FileCache' : 'without FileCache', () => { + function cache(): FileCache | undefined { + return cached ? new FileCache() : undefined; + } + + it('reads ruby file: ".ruby-version" as runtime 3.3.4', async () => { + const root = makeRoot(); + write(root, 'Gemfile', [ + "source 'https://rubygems.org'", + 'ruby file: ".ruby-version"', + "gem 'rails', '~> 7.1'", + '', + ].join('\n')); + write(root, '.ruby-version', '3.3.4\n'); + + const projects = await scan(root, cache()); + expect(projects).toHaveLength(1); + const project = projects[0]!; + expect(project.runtime).toBe('3.3.4'); + const lag = rubyLag('3.3.4'); + expect(project.runtimeLatest).toBe(lag.latest); + expect(project.runtimeMajorsBehind).toBe(lag.behind); + }); + + it('reads single quotes, the hash rocket, and a path next to the Gemfile', async () => { + const root = makeRoot(); + write(root, 'quotes/Gemfile', "ruby file: '.ruby-version'\n"); + write(root, 'quotes/.ruby-version', ' ruby-3.3.4 \n'); + write(root, 'rocket/Gemfile', 'ruby :file => ".ruby-version"\n'); + write(root, 'rocket/.ruby-version', '3.3.4\n'); + write(root, 'nested/Gemfile', 'ruby file: "config/.ruby-version"\n'); + write(root, 'nested/config/.ruby-version', '3.3.4\n'); + write(root, '.ruby-version', '2.6.10\n'); + + const projects = await scan(root, cache()); + const byPath = new Map(projects.map((project) => [project.path, project.runtime])); + expect(byPath.get('quotes')).toBe('3.3.4'); + expect(byPath.get('rocket')).toBe('3.3.4'); + expect(byPath.get('nested')).toBe('3.3.4'); + }); + + it('falls back to .ruby-version ruby-3.2.2 when the Gemfile has no ruby line', async () => { + const root = makeRoot(); + write(root, 'Gemfile', "source 'https://rubygems.org'\ngem 'rails'\n"); + write(root, '.ruby-version', 'ruby-3.2.2\n'); + write(root, '.tool-versions', 'ruby 3.4.1\n'); + + const projects = await scan(root, cache()); + expect(projects).toHaveLength(1); + const project = projects[0]!; + expect(project.runtime).toBe('3.2.2'); + const lag = rubyLag('3.2.2'); + expect(project.runtimeLatest).toBe(lag.latest); + expect(project.runtimeMajorsBehind).toBe(lag.behind); + }); + + it('uses a ruby entry in .tool-versions when .ruby-version is absent or not a version', async () => { + const root = makeRoot(); + write(root, 'missing/Gemfile', "gem 'rails'\n"); + write(root, 'missing/.tool-versions', 'nodejs 22.11.0\nruby ruby-3.4.1\n'); + write(root, 'system/Gemfile', "gem 'rails'\n"); + write(root, 'system/.ruby-version', 'system\n'); + write(root, 'system/.tool-versions', 'ruby 3.2.2\n'); + + const projects = await scan(root, cache()); + const byPath = new Map(projects.map((project) => [project.path, project.runtime])); + expect(byPath.get('missing')).toBe('3.4.1'); + expect(byPath.get('system')).toBe('3.2.2'); + }); + + it('keeps an explicit ruby line ahead of pin files', async () => { + const root = makeRoot(); + write(root, 'Gemfile', [ + "source 'https://rubygems.org'", + "ruby '3.1.0'", + "gem 'rails'", + '', + ].join('\n')); + write(root, '.ruby-version', 'ruby-3.2.2\n'); + write(root, '.tool-versions', 'ruby 3.3.4\n'); + + const projects = await scan(root, cache()); + expect(projects).toHaveLength(1); + const project = projects[0]!; + expect(project.runtime).toBe('3.1.0'); + const lag = rubyLag('3.1.0'); + expect(project.runtimeLatest).toBe(lag.latest); + expect(project.runtimeMajorsBehind).toBe(lag.behind); + }); + + it('does not throw when the ruby file: target is missing', async () => { + const root = makeRoot(); + write(root, 'Gemfile', 'ruby file: "missing-version"\n'); + write(root, '.ruby-version', '3.2.2\n'); + write(root, '.tool-versions', 'ruby 3.3.4\n'); + + const projects = await scan(root, cache()); + expect(projects).toHaveLength(1); + expect(projects[0]!.runtime).toBeUndefined(); + expect(projects[0]!.runtimeMajorsBehind).toBeUndefined(); + }); + }); + } +});