1+ 'use strict' ;
2+
3+ import { Octokit } from 'octokit' ;
4+ import { simpleGit } from 'simple-git' ;
5+ import tar from 'tar'
6+ import fs from 'fs' ;
7+ import AWS from 'aws-sdk' ;
8+ import rmfr from 'rmfr' ;
9+
10+ export const backup = async ( event , context , callback ) => {
11+ const directory = `/tmp/${ Date . now ( ) } ` ;
12+
13+ try {
14+ const octokit = new Octokit ( {
15+ auth : process . env . GH_TOKEN
16+ } ) ;
17+
18+ const res = await octokit . request ( 'GET /orgs/{org}/repos{?type,sort,direction,per_page,page}' , {
19+ org : process . env . GH_ORGANIZATION ,
20+ type : process . env . GH_VISIBILITY
21+ } ) ;
22+
23+ fs . mkdirSync ( `/${ directory } /repositories` , { recursive : true } ) ;
24+
25+ await Promise . all ( res . data . map ( ( item ) => simpleGit ( ) . clone (
26+ `https://${ process . env . GH_TOKEN } @github.com/${ item . full_name } ` ,
27+ `/${ directory } /repositories/${ item . name } ` ,
28+ [ '--bare' ]
29+ ) ) ) ;
30+
31+ const filename = [
32+ ( new Date ( ) ) . toISOString ( ) . slice ( 0 , 10 ) ,
33+ Date . now ( )
34+ ] . join ( '-' ) + '.tgz' ;
35+
36+ await tar . create (
37+ { gzip : true , file : `/${ directory } /${ filename } ` } ,
38+ [ `/${ directory } /repositories` ]
39+ ) ;
40+
41+ const S3 = new AWS . S3 ( { region : process . env . REGION } ) ;
42+
43+ await S3 . upload ( {
44+ Bucket : process . env . BUCKET ,
45+ Body : fs . createReadStream ( `/${ directory } /${ filename } ` ) ,
46+ Key : filename
47+ } ) . promise ( ) ;
48+
49+ if ( process . env . SUCCESS_PING_URL !== undefined && process . env . SUCCESS_PING_URL . trim ( ) . length > 0 ) {
50+ await fetch ( process . env . SUCCESS_PING_URL ) ;
51+ }
52+ } finally {
53+ await rmfr ( directory ) ;
54+ }
55+ } ;
0 commit comments