This repository was archived by the owner on Apr 21, 2021. It is now read-only.
generated from actions/javascript-action
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathindex.js
228 lines (188 loc) · 7.83 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
const core = require('@actions/core');
const github = require('@actions/github');
// most @actions toolkit packages have async methods
async function run() {
try {
const { context } = github
const {promisify} = require('util');
const {readdir} = require('fs');
const readdirAsync = promisify(readdir);
const path = require('path');
const { createClient } = require('contentful-management');
const {default: runMigration} = require('contentful-migration/built/bin/cli');
// utility fns
const getVersionOfFile = (file) => file.replace('.js', '').replace(/_/g, '.');
const getFileOfVersion = (version) => version.replace(/\./g, '_') + '.js';
const getBranchName = () => {
let { ref } = context
if (github.context.eventName === 'pull_request') {
const pullRequestPayload = github.context.payload
core.info(`head : ${pullRequestPayload.pull_request.head}`)
// actual branch name, not something like 'pull/111/merge'
ref = pullRequestPayload.pull_request.head.ref
core.info(`The head ref is: ${pullRequestPayload.pull_request.head.ref}`)
}
return ref
.replace('refs/heads/', '')
// normalize git-flow branch names ie. feat/foo-feature -> feat-foo-feature
.replace(/\//g, '-')
}
//
// Configuration variables
//
const SPACE_ID = process.env.SPACE_ID;
const MANAGEMENT_API_KEY = process.env.MANAGEMENT_API_KEY;
const ENVIRONMENT_INPUT = getBranchName();
const DEFAULT_MIGRATIONS_DIR = 'migrations';
const MIGRATIONS_DIR = path.join(process.env.GITHUB_WORKSPACE, process.env.MIGRATIONS_DIR || DEFAULT_MIGRATIONS_DIR);
const client = createClient({
accessToken: MANAGEMENT_API_KEY
});
const space = await client.getSpace(SPACE_ID);
var ENVIRONMENT_ID = "";
let environment;
console.log('Running with the following configuration');
// ---------------------------------------------------------------------------
if (ENVIRONMENT_INPUT == 'master'){
console.log(`Running on master.`);
ENVIRONMENT_ID = "master-".concat(getStringDate());
}else{
console.log('Running on feature branch');
ENVIRONMENT_ID = "GH-".concat(ENVIRONMENT_INPUT);
}
console.log(`ENVIRONMENT_ID: ${ENVIRONMENT_ID}`);
// ---------------------------------------------------------------------------
console.log(`Checking for existing versions of environment: ${ENVIRONMENT_ID}`);
try {
environment = await space.getEnvironment(ENVIRONMENT_ID);
if (ENVIRONMENT_ID != 'master'){
await environment.delete();
console.log('Environment deleted');
}
} catch(e) {
console.log('Environment not found');
}
// ---------------------------------------------------------------------------
if (ENVIRONMENT_ID != 'master'){
console.log(`Creating environment ${ENVIRONMENT_ID}`);
environment = await space.createEnvironmentWithId(ENVIRONMENT_ID, { name: ENVIRONMENT_ID });
}
// ---------------------------------------------------------------------------
const DELAY = 3000;
const MAX_NUMBER_OF_TRIES = 10;
let count = 0;
console.log('Waiting for environment processing...')
while (count < MAX_NUMBER_OF_TRIES) {
const status = (await space.getEnvironment(environment.sys.id)).sys.status.sys.id;
if (status === 'ready' || status === 'failed') {
if (status === 'ready') {
console.log(`Successfully processed new environment (${ENVIRONMENT_ID})`);
} else {
console.log('Environment creation failed');
}
break;
}
await new Promise(resolve => setTimeout(resolve, DELAY));
count++;
}
// ---------------------------------------------------------------------------
console.log('Update API Keys to allow access to new environment');
const newEnv = {
sys: {
type: 'Link',
linkType: 'Environment',
id: ENVIRONMENT_ID
}
}
const {items: keys} = await space.getApiKeys();
await Promise.all(keys.map(key => {
console.log(`Updating - ${key.sys.id}`);
key.environments.push(newEnv);
return key.update();
}));
// ---------------------------------------------------------------------------
console.log('Set default locale to new environment');
const defaultLocale = (await environment.getLocales()).items
.find(locale => locale.default).code;
// ---------------------------------------------------------------------------
console.log('Read all the available migrations from the file system');
const availableMigrations = (await readdirAsync(MIGRATIONS_DIR))
.filter(file => /^\d+?\.js$/.test(file))
.map(file => getVersionOfFile(file));
// ---------------------------------------------------------------------------
console.log('Figure out latest ran migration of the contentful space');
const {items: versions} = await environment.getEntries({
content_type: 'versionTracking'
});
if (!versions.length || versions.length > 1) {
throw new Error(
'There should only be one entry of type \'versionTracking\''
);
}
let storedVersionEntry = versions[0];
const currentVersionString = storedVersionEntry.fields.version[defaultLocale];
// ---------------------------------------------------------------------------
console.log('Evaluate which migrations to run');
const currentMigrationIndex = availableMigrations.indexOf(currentVersionString);
if (currentMigrationIndex === -1) {
throw new Error(
`Version ${currentVersionString} is not matching with any known migration`
);
}
const migrationsToRun = availableMigrations.slice(currentMigrationIndex + 1);
const migrationOptions = {
spaceId: SPACE_ID,
environmentId: ENVIRONMENT_ID,
accessToken: MANAGEMENT_API_KEY,
yes: true
};
// ---------------------------------------------------------------------------
console.log('Run migrations and update version entry');
while(migrationToRun = migrationsToRun.shift()) {
const filePath = path.join(MIGRATIONS_DIR, getFileOfVersion(migrationToRun));
console.log(`Running ${filePath}`);
await runMigration(Object.assign(migrationOptions, {
filePath
}));
console.log(`${migrationToRun} succeeded`);
storedVersionEntry.fields.version[defaultLocale] = migrationToRun;
storedVersionEntry = await storedVersionEntry.update();
storedVersionEntry = await storedVersionEntry.publish();
console.log(`Updated version entry to ${migrationToRun}`);
}
// ---------------------------------------------------------------------------
console.log('Checking if we need to update master alias');
if (ENVIRONMENT_INPUT == 'master'){
console.log(`Running on master.`);
console.log(`Updating master alias.`);
await space.getEnvironmentAlias('master')
.then((alias) => {
alias.environment.sys.id = ENVIRONMENT_ID
return alias.update()
})
.then((alias) => console.log(`alias ${alias.sys.id} updated.`))
.catch(console.error);
console.log(`Master alias updated.`);
}else{
console.log('Running on feature branch');
console.log('No alias changes required');
}
const environmentUrl = `https://app.contentful.com/spaces/${space.sys.id}/environments/${ENVIRONMENT_ID}`
const environmentName = ENVIRONMENT_ID
core.setOutput('environment_url', environmentUrl)
core.setOutput('environment_name', environmentName)
console.log('All done!!!');
}
catch (error) {
core.setFailed(error.message);
}
}
run()
function getStringDate(){
var d = new Date();
function pad(n){return n<10 ? '0'+n : n}
return d.toISOString().substring(0, 10)
+ '-'
+ pad(d.getUTCHours())
+ pad(d.getUTCMinutes())
}