1+ import * as bodyParser from 'body-parser' ;
2+ import { execSync , spawnSync } from 'child_process' ;
3+ import * as express from 'express' ;
4+ import { Server } from 'http' ;
5+ import { join } from 'path' ;
6+ import { directory } from 'tempy' ;
7+ import { writeFileDeepSync } from './utils' ;
8+
9+ export function startServer ( port = process . env . PORT || 3000 ) : Server {
10+ const app = express ( ) ;
11+
12+ app . use ( bodyParser . json ( ) ) ;
13+
14+ app . get ( '/' , ( _req , res ) => res . send ( 'Hello World!' ) )
15+
16+ app . post ( '/commit' , ( req , res ) => {
17+ const { remoteRepo, token, files, commitMessage } = req . body as { [ key : string ] : string | IFile [ ] } ;
18+ const [ , repoName ] = ( < string > remoteRepo ) . split ( '/' ) ;
19+
20+ const tempFolder = directory ( ) ;
21+
22+ const options = ( subFolder : string = repoName ) => ( {
23+ encoding : 'utf8' ,
24+ cwd : join ( tempFolder , subFolder )
25+ } ) ;
26+
27+ const { output} = spawnSync ( 'git' , [ 'clone' , `https://${ token } @github.com/${ remoteRepo } .git` ] , options ( '' ) ) ;
28+ console . log ( output [ 2 ] ) ;
29+
30+ ( < IFile [ ] > files ) . forEach ( ( file : IFile ) => {
31+ writeFileDeepSync ( join ( tempFolder , repoName , file . path ) , file . content ) ;
32+ } ) ;
33+
34+ console . log ( '> git add' )
35+ execSync ( 'git add .' , options ( ) ) ;
36+
37+ console . log ( '> git status' )
38+ spawnSync ( 'git' , [ 'status' ] , { ...options ( ) , stdio :'inherit' } ) ;
39+
40+ execSync ( 'git config user.email "bot@spread-the-code.com"' , options ( ) ) ;
41+ execSync ( 'git config user.name "commit-bot"' , options ( ) ) ;
42+
43+ console . log ( '> git commit' )
44+ execSync ( `git commit -m "${ commitMessage || 'unknow commit' } "` , { ...options ( ) , stdio :'inherit' } ) ;
45+
46+ console . log ( '> git push' ) ;
47+ try {
48+ const pushResult = spawnSync ( 'git' , [ 'push' ] , options ( ) ) ;
49+ console . log ( pushResult . output ) ;
50+ } catch ( error ) {
51+ console . log ( 'error' , error ) ;
52+ }
53+ res . send ( 'done' ) ;
54+ } ) ;
55+
56+ return app . listen ( port , ( ) => console . log ( `Example app listening on port ${ port } !` ) )
57+ }
58+
59+ interface IFile {
60+ path : string ;
61+ content : string ;
62+ }
0 commit comments