-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3.js
85 lines (74 loc) · 2.17 KB
/
s3.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
const AWS = require('aws-sdk'),
debug = require('debug')('cleaner:s3');
const Bucket = process.env.BUCKET,
PREFIX = process.env.PREFIX,
region = 'us-west-1';
const utils = require('./utils');
const s3 = new AWS.S3({region});
const MAX_KEYS = process.env.MAX_KEYS || Infinity;
exports.listAllFiles = function () {
return listAllKeys({Bucket});
};
exports.applyTags = function (files) {
const updates = flattenUpdates(files.updates);
const patterns = Object.keys(updates);
const promises = [];
files.allFiles.map((file) => {
const filePath = utils.getFilePath(file.Key);
const filePrefix = `${PREFIX}${filePath.module}/${filePath.hash}`;
if (patterns.includes(filePrefix)) {
promises.push(setObjectTag(file.Key, updates[filePrefix]));
}
});
return Promise.all(promises);
};
const allKeys = [];
function listAllKeys(params) {
debug('Calling objects list...');
return s3.listObjectsV2(params)
.promise()
.then((data) => {
if (data && data.Contents) {
data.Contents.forEach(function (i) {
allKeys.push(i)
});
}
const mustContinue = data.IsTruncated===true && allKeys.length < MAX_KEYS;
debug(`Continuing : ${mustContinue}, Keys so far : ${allKeys.length}`);
if (mustContinue) {
const nextParams = JSON.parse(JSON.stringify(params)); // clone params
nextParams.ContinuationToken = data.NextContinuationToken;
return listAllKeys(nextParams);
} else {
debug('resolve with ', allKeys.length);
return Promise.resolve(allKeys);
// resolve(allKeys);
//return allKeys;
}
});
}
function flattenUpdates(updates) {
const result = [];
for (const module of Object.keys(updates)) {
for (const pattern of updates[module]) {
result[pattern.prefix] = pattern.Status;
}
}
return result;
}
function setObjectTag(Key, tag) {
const params = {
Bucket,
Key,
Tagging: {
TagSet: [
{
Key : 'Status',
Value: tag
}
]
}
};
debug(`setting tag ${tag} to file ${Key}`);
return s3.putObjectTagging(params).promise();
}