1
- import { spawn , type SpawnOptions } from 'node:child_process' ;
1
+ import { execSync , spawn , type SpawnOptions } from 'node:child_process' ;
2
2
import fs from 'node:fs' ;
3
3
import glob from 'tiny-glob/sync' ;
4
4
5
- export async function clone_repo ( repo : string , branch : string , cwd : string ) {
6
- const regex_result = / h t t p s : \/ \/ g i t h u b .c o m \/ \w + \/ ( \w + ) .g i t / . exec ( repo ) ;
7
- if ( ! regex_result || regex_result . length < 2 ) {
8
- throw new Error ( `Expected https://github.com/xxx/xxx.git, but got ${ repo } ` ) ;
9
- }
5
+ export async function clone_repo ( repo : string , name : string , branch : string , cwd : string ) {
6
+ const dir = `${ cwd } /${ name } ` ;
7
+
8
+ if ( fs . existsSync ( dir ) ) {
9
+ const opts = { cwd : dir } ;
10
+
11
+ if ( execSync ( 'git status -s' , opts ) . toString ( ) !== '' ) {
12
+ throw new Error ( `${ name } repo is dirty — aborting` ) ;
13
+ }
14
+
15
+ await invoke ( 'git' , [ 'checkout' , branch ] , opts ) ;
16
+ await invoke ( 'git' , [ 'pull' ] , opts ) ;
10
17
11
- const dirname = `${ cwd } /${ regex_result [ 1 ] } ` ;
12
- if ( fs . existsSync ( dirname ) ) {
13
- // TODO skip if we detect that same branch is already cloned
14
- fs . rmSync ( dirname , { recursive : true } ) ;
18
+ return ;
15
19
}
16
20
17
21
await invoke ( 'git' , [ 'clone' , '--depth' , '1' , '--branch' , branch , repo ] , {
@@ -22,14 +26,15 @@ export async function clone_repo(repo: string, branch: string, cwd: string) {
22
26
export function invoke ( cmd : string , args : string [ ] , opts : SpawnOptions ) {
23
27
const child = spawn ( cmd , args , { ...opts , stdio : 'inherit' } ) ;
24
28
25
- return new Promise < void > ( ( resolve ) => {
29
+ return new Promise < void > ( ( fulfil , reject ) => {
26
30
child . on ( 'close' , ( code ) => {
27
- if ( ! code ) {
28
- console . log ( `${ [ cmd , ...args ] . join ( ' ' ) } successfully completed` ) ;
31
+ if ( code ) {
32
+ reject ( new Error ( `Exited with code ${ code } ` ) ) ;
33
+ return ;
29
34
}
30
35
31
36
// Give it some extra time to finish writing files to disk
32
- setTimeout ( ( ) => resolve ( ) , 500 ) ;
37
+ setTimeout ( fulfil , 500 ) ;
33
38
} ) ;
34
39
} ) ;
35
40
}
0 commit comments