-
Notifications
You must be signed in to change notification settings - Fork 34
/
index.js
89 lines (77 loc) · 2.62 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const actions = require('@actions/core');
const { google } = require('googleapis');
const fs = require('fs');
const archiver = require('archiver');
/** Google Service Account credentials encoded in base64 */
const credentials = actions.getInput('credentials', { required: true });
/** Google Drive Folder ID to upload the file/folder to */
const folder = actions.getInput('folder', { required: true });
/** Local path to the file/folder to upload */
const target = actions.getInput('target', { required: true });
/** Optional name for the zipped file */
const name = actions.getInput('name', { required: false });
/** Link to the Drive folder */
const link = 'link';
const credentialsJSON = JSON.parse(Buffer.from(credentials, 'base64').toString());
const scopes = ['https://www.googleapis.com/auth/drive'];
const auth = new google.auth.JWT(credentialsJSON.client_email, null, credentialsJSON.private_key, scopes);
const drive = google.drive({ version: 'v3', auth });
const driveLink = `https://drive.google.com/drive/folders/${folder}`
let filename = target.split('/').pop();
async function main() {
actions.setOutput(link, driveLink);
if (fs.lstatSync(target).isDirectory()){
filename = `${name || target}.zip`
actions.info(`Folder detected in ${target}`)
actions.info(`Zipping ${target}...`)
zipDirectory(target, filename)
.then(() => uploadToDrive())
.catch(e => {
actions.error('Zip failed');
throw e;
});
}
else
uploadToDrive();
}
/**
* Zips a directory and stores it in memory
* @param {string} source File or folder to be zipped
* @param {string} out Name of the resulting zipped file
*/
function zipDirectory(source, out) {
const archive = archiver('zip', { zlib: { level: 9 }});
const stream = fs.createWriteStream(out);
return new Promise((resolve, reject) => {
archive
.directory(source, false)
.on('error', err => reject(err))
.pipe(stream);
stream.on('close',
() => {
actions.info(`Folder successfully zipped: ${archive.pointer()} total bytes written`);
return resolve();
});
archive.finalize();
});
}
/**
* Uploads the file to Google Drive
*/
function uploadToDrive() {
actions.info('Uploading file to Goole Drive...');
drive.files.create({
requestBody: {
name: filename,
parents: [folder]
},
media: {
body: fs.createReadStream(`${name || target}${fs.lstatSync(target).isDirectory() ? '.zip' : ''}`)
}
}).then(() => actions.info('File uploaded successfully'))
.catch(e => {
actions.error('Upload failed');
throw e;
});
}
main().catch(e => actions.setFailed(e));