1+ const rp = require ( 'request-promise' ) ;
2+ const jwt = require ( 'jsonwebtoken' ) ;
3+ const fs = require ( 'fs-extra' ) ;
4+ const path = require ( 'path' ) ;
5+ const DeployDir = require ( './DeployDir' ) ;
6+ const cliProgress = require ( 'cli-progress' ) ;
7+ const { logStage } = require ( './utils' ) ;
8+
9+ const cloudReq = ( options ) => {
10+ const { url, auth, ...restOptions } = options ;
11+ const authorization = auth || process . env . CUBE_CLOUD_DEPLOY_AUTH ;
12+ const payload = jwt . decode ( authorization ) ;
13+ if ( ! payload . url || ! payload . deploymentId ) {
14+ throw new ( `Malformed token: ${ authorization } ` ) ;
15+ }
16+ return rp ( {
17+ headers : {
18+ authorization
19+ } ,
20+ ...restOptions ,
21+ url : `${ payload . url } /${ url ( payload . deploymentId ) } ` ,
22+ json : true
23+ } ) ;
24+ } ;
25+
26+ exports . deploy = async ( { directory, auth } ) => {
27+ const bar = new cliProgress . SingleBar ( {
28+ format : '- Uploading files | {bar} | {percentage}% || {value} / {total} | {file}' ,
29+ barCompleteChar : '\u2588' ,
30+ barIncompleteChar : '\u2591' ,
31+ hideCursor : true
32+ } ) ;
33+
34+ const deployDir = new DeployDir ( { directory } ) ;
35+ const fileHashes = await deployDir . fileHashes ( ) ;
36+ const upstreamHashes = await cloudReq ( {
37+ url : ( deploymentId ) => `build/deploy/${ deploymentId } /files` ,
38+ method : 'GET' ,
39+ auth
40+ } ) ;
41+ const { transaction, deploymentName } = await cloudReq ( {
42+ url : ( deploymentId ) => `build/deploy/${ deploymentId } /start-upload` ,
43+ method : 'POST' ,
44+ auth
45+ } ) ;
46+
47+ await logStage ( `Deploying ${ deploymentName } ...` , `Cube Cloud CLI Deploy` ) ;
48+
49+ const files = Object . keys ( fileHashes ) ;
50+ bar . start ( files . length , 0 , {
51+ file : ''
52+ } ) ;
53+
54+ try {
55+ for ( let i = 0 ; i < files . length ; i ++ ) {
56+ const file = files [ i ] ;
57+ bar . update ( i , { file } ) ;
58+ if ( ! upstreamHashes [ file ] || upstreamHashes [ file ] . hash !== fileHashes [ file ] . hash ) {
59+ await cloudReq ( {
60+ url : ( deploymentId ) => `build/deploy/${ deploymentId } /upload-file` ,
61+ method : 'POST' ,
62+ formData : {
63+ transaction : JSON . stringify ( transaction ) ,
64+ fileName : file ,
65+ file : {
66+ value : fs . createReadStream ( path . join ( directory , file ) ) ,
67+ options : {
68+ filename : path . basename ( file ) ,
69+ contentType : 'application/octet-stream'
70+ }
71+ }
72+ } ,
73+ auth
74+ } )
75+ }
76+ }
77+ bar . update ( files . length , { file : 'Post processing...' } ) ;
78+ await cloudReq ( {
79+ url : ( deploymentId ) => `build/deploy/${ deploymentId } /finish-upload` ,
80+ method : 'POST' ,
81+ body : {
82+ transaction,
83+ files : fileHashes
84+ } ,
85+ auth
86+ } ) ;
87+ } finally {
88+ bar . stop ( ) ;
89+ }
90+ await logStage ( `Done 🎉` , `Cube Cloud CLI Deploy Success` ) ;
91+ } ;
0 commit comments