1
+ // get-version.mjs
2
+ import { readFileSync , existsSync } from 'fs' ;
3
+ import { fileURLToPath } from 'url' ;
4
+ import { dirname , join , resolve } from 'path' ;
5
+
6
+ const __filename = fileURLToPath ( import . meta. url ) ;
7
+ const __dirname = dirname ( __filename ) ;
8
+
9
+ // Function to find repository root (where package.json lives)
10
+ function findRepoRoot ( startDir ) {
11
+ let currentDir = startDir ;
12
+ while ( currentDir !== '/' ) {
13
+ const packagePath = join ( currentDir , 'package.json' ) ;
14
+ if ( existsSync ( packagePath ) ) {
15
+ return currentDir ;
16
+ }
17
+ currentDir = dirname ( currentDir ) ;
18
+ }
19
+ throw new Error ( 'Could not find repository root (no package.json found)' ) ;
20
+ }
21
+
22
+ // Get repo root
23
+ const repoRoot = findRepoRoot ( __dirname ) ;
24
+ console . error ( 'Repository root:' , repoRoot ) ;
25
+
26
+ // Get source, name and default version from command line arguments
27
+ const [ source , name , defaultVersion = '0.5.0' ] = process . argv . slice ( 2 ) ;
28
+
29
+ if ( ! source || ! name ) {
30
+ console . error ( 'Usage: node get-version.mjs [package|tool] [name] [defaultVersion]' ) ;
31
+ process . exit ( 1 ) ;
32
+ }
33
+
34
+ try {
35
+ if ( source === 'package' ) {
36
+ const packagePath = join ( repoRoot , 'package.json' ) ;
37
+ const packageJson = JSON . parse ( readFileSync ( packagePath , 'utf8' ) ) ;
38
+ const version = packageJson . dependencies ?. [ name ] || defaultVersion ;
39
+ console . log ( version )
40
+ } else if ( source === 'tool' ) {
41
+ const toolPath = join ( repoRoot , '.tool-versions' ) ;
42
+ const content = readFileSync ( toolPath , 'utf8' ) ;
43
+ const lines = content . split ( '\n' ) . map ( line => line . trim ( ) ) ;
44
+ const matchingLines = lines . filter ( line => line . startsWith ( name ) ) ;
45
+ const version = matchingLines [ 0 ] ?. split ( / \s + / ) [ 1 ] || defaultVersion ;
46
+ console . log ( version )
47
+ } else {
48
+ console . error ( 'Invalid source. Use "package" or "tool"' ) ;
49
+ process . exit ( 1 ) ;
50
+ }
51
+ } catch ( error ) {
52
+ console . log ( defaultVersion ) ;
53
+ }
0 commit comments