-
Notifications
You must be signed in to change notification settings - Fork 28
/
library.js
74 lines (70 loc) · 2.98 KB
/
library.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
const {execute} = require('./util');
/***
* @description Code to prevent GitHub from suspending your cronjob based triggers due to repository inactivity
* @param {string} githubToken - Token of the GitHub user to create dummy commit
* @param {string} committerUsername - Username of the GitHub user to create dummy commit
* @param {string} committerEmail - Email id of the GitHub user to create dummy commit
* @param {string} commitMessage - Commit message while doing dummy commit
* @param {number} timeElapsed - Time elapsed from the last commit to trigger a new automated commit (in days). Default: 50
* @param {boolean} autoPush - Boolean flag to define if the library should automatically push the changes. Default: false
* @param {boolean} autoWriteCheck - Enables automatic checking of the token for branch protection rules
* @return {Promise<string> | Promise<Object>} - Promise with success message or failure object
*/
const KeepAliveWorkflow = async (githubToken, committerUsername, committerEmail, commitMessage, timeElapsed = 50, autoPush = false, autoWriteCheck = false) => {
return new Promise(async (resolve, reject) => {
try {
// Write detection
if (autoWriteCheck) {
// Protected branches
if (process.env.GITHUB_REF_PROTECTED === 'true') {
reject(`Looks like the branch is write protected. You need to disable that for this to work: https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches`)
}
}
// Calculating the last commit date
const {outputData} = await execute('git', ['--no-pager', 'log', '-1', '--format=%ct'],
{encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe']});
const commitDate = new Date(parseInt(outputData, 10) * 1000);
const diffInDays = Math.round((new Date() - commitDate) / (1000 * 60 * 60 * 24));
if (diffInDays >= timeElapsed) {
// Do dummy commit if elapsed time is greater than 50 (default) days
await execute('git', [
'config',
'--global',
'user.email',
committerEmail,
]);
await execute('git', [
'remote',
'set-url',
'origin',
`https://x-access-token:${githubToken}@${process.env.GITHUB_SERVER_URL.replace(/^https?:\/\//, '')}/${process.env.GITHUB_REPOSITORY}.git`
]);
await execute('git', [
'config',
'--global',
'user.name',
committerUsername
]);
await execute('git', [
'commit',
'--allow-empty',
'-m',
`${commitMessage}`]);
if (autoPush) {
await execute('git', [
'push',
'origin',
'HEAD']);
}
resolve('Dummy commit created to keep the repository active...');
} else {
resolve('Nothing to do...');
}
} catch (e) {
reject(e);
}
});
};
module.exports = {
KeepAliveWorkflow
};