Skip to content

Commit 42e1a10

Browse files
add migration script
1 parent 1e8c5a4 commit 42e1a10

1 file changed

Lines changed: 80 additions & 0 deletions

File tree

scripts/add-hash-to-files.js

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
'use strict';
2+
require('loadenv')();
3+
var bcrypt = require('bcrypt');
4+
var InfraCodeVersion = require('models/mongo/infra-code-version.js');
5+
var debug = require('debug')('script');
6+
var mongoose = require('mongoose');
7+
mongoose.connect(process.env.MONGO);
8+
var async = require('async');
9+
var createCount = require('callback-count');
10+
11+
async.waterfall([
12+
getAllInfra,
13+
eachInfra
14+
], function(err) {
15+
if (err) {
16+
console.log('ERROR', err.stack);
17+
process.exit(1);
18+
}
19+
console.log('done everything went well');
20+
process.exit(0);
21+
});
22+
23+
function getAllInfra (cb) {
24+
debug('getAllInfra');
25+
InfraCodeVersion.find({
26+
'files': {
27+
$elemMatch: {
28+
isDir: false,
29+
hash: { $exists: false }
30+
}
31+
}
32+
}, cb);
33+
}
34+
35+
function hashString(data, cb) {
36+
debug('hashString');
37+
// salt from require('bcrypt'.enSaltSync(1);
38+
var salt = '$2a$04$fLg/VU5eeDAUARmPVfyUo.';
39+
bcrypt.hash(data
40+
.replace(/[\s\uFEFF\xA0]+\n/g, '\n') // trim whitespace after line
41+
.replace(/\n[\s\uFEFF\xA0]*\n/g, '\n') // remove blank lines
42+
.replace(/^[\s\uFEFF\xA0]*\n/g, '') // remove start of file blank lines
43+
.replace(/[\s\uFEFF\xA0]+$/g, '\n'), salt, cb);
44+
}
45+
46+
function eachInfra (infras, cb) {
47+
debug('eachInfra');
48+
var count = createCount(1, cb);
49+
// get all infracodes
50+
infras.forEach(function(infra) {
51+
debug('eachInfra:infra', infra._id);
52+
// for each file
53+
infra.files.forEach(function(file) {
54+
if(file.isDir || file.hash) { return; }
55+
count.inc();
56+
debug('eachInfra:infra:file', infra._id, file._id);
57+
var filePath = file.Key.substr(file.Key.indexOf('/source')+7);
58+
// get contance of file
59+
infra.bucket().getFile(filePath, file.VersionId, file.ETag, function (err, data) {
60+
if (err) { return cb(err); }
61+
// create hash of file
62+
hashString(data.Body.toString(), function(err, hash) {
63+
if (err) { return cb(err); }
64+
file.hash = hash;
65+
debug('eachInfra:infra:file:hash', infra._id, file._id, file.hash);
66+
// update mongo of file with hash
67+
InfraCodeVersion.update({
68+
_id: infra._id,
69+
'files._id': file._id
70+
}, {
71+
$set: {
72+
'files.$': file
73+
}
74+
}, count.next);
75+
});
76+
});
77+
});
78+
});
79+
count.next();
80+
}

0 commit comments

Comments
 (0)