-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
107 lines (96 loc) · 2.73 KB
/
index.js
File metadata and controls
107 lines (96 loc) · 2.73 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
var Git = require('nodegit')
var Cron = require('cron').CronJob
var defined = require('defined')
var Path = require('path')
module.exports = gitSync
function gitSync (opts, cb) {
if (!defined(opts)) return null
var remoteUrl = opts.remoteUrl
if (remoteUrl == null) { throw new Error('gitSync: remoteUrl option is required.')}
var localDir = opts.localDir
if (localDir == null) { throw new Error('gitSync: localDir option is required.')}
var branch = defined(opts.branch, 'master')
var noCertificateCheck = defined(opts.noCertificateCheck, false)
var cronTime = defined(opts.cronTime, '* */15 * * * *')
var timeZone = opts.timeZone
function createOnTick () {
var onChange = callbackOnChange(cb)
return function () {
getRepo(remoteUrl, localDir, { noCertificateCheck: noCertificateCheck })
.then(checkoutBranch(branch))
.then(onChange)
.catch(cb)
.done()
}
}
var onTick = createOnTick()
onTick()
return new Cron({
cronTime: cronTime,
onTick: onTick,
start: true,
timeZone: timeZone
})
}
function getRepo (remoteUrl, localDir, opts) {
return Git.Repository.open(localDir)
.catch(function (repo) {
return null
})
.then(function (repo) {
if (repo == null) {
return Git.Clone(remoteUrl, localDir, {
remoteCallbacks: {
certificateCheck: opts.noCertificateCheck ?
noCertificateCheckFn : undefined
}
})
}
return repo
})
}
function checkoutBranch (branch) {
return function (repo) {
// get local branch
return repo.getBranch(branch)
.catch(function (err) {
// TODO check for specific error
// create local branch from remote
return repo.getBranchCommit('origin/' + branch)
.then(function (commit) {
return repo.createBranch(
branch,
commit,
true, // force
repo.defaultSignature(), // signature
'create ' + branch + ' branch' // log message
)
})
})
// checkout local branch
.then(function (branchRef) {
return repo.checkoutBranch(branchRef, {
checkoutStrategy: Git.Checkout.STRATEGY.FORCE
})
})
// return latest commit
.then(function () {
return repo.getBranchCommit(branch)
})
}
}
function callbackOnChange (cb) {
var lastCommitId = null
return function (commit) {
var commitId = commit.id()
if (lastCommitId == null || !commitId.equal(lastCommitId)) {
lastCommitId = commitId
cb(null, commit)
}
}
}
function noCheckCertificateFn () {
// github will fail cert check on some OSX machines
// this overrides that check
return 1
}