This repository has been archived by the owner on Jan 20, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutils.js
324 lines (295 loc) · 8.46 KB
/
utils.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
const cmd = require('cmd-executor');
const fs = require('fs');
const git = require('cmd-executor').git;
const { Octokit } = require('@octokit/rest');
const path = require('path');
const tmp = require('tmp-promise');
const OWNER = 'hackerinnen';
const REPONAME = 'hackerinnen';
const BOT_EMAIL = '[email protected]';
const BOT_NAME = 'Hackerinnen bot';
const USER = process.env.BOT_GITHUB_USER;
const GITHUB_AUTH_TOKEN = process.env.GITHUB_AUTH_TOKEN;
const MAILGUN_API_KEY = process.env.MAILGUN_API_KEY;
const MAILGUN_DOMAIN = process.env.MAILGUN_DOMAIN;
const mailgun = require('mailgun-js')({
apiKey: MAILGUN_API_KEY,
domain: MAILGUN_DOMAIN,
});
const repo = `https://${USER}:${GITHUB_AUTH_TOKEN}@github.com/${OWNER}/${REPONAME}`;
let workingDirectory = '';
const octokit = new Octokit({
auth: GITHUB_AUTH_TOKEN,
});
/**
* Function to send an email
* @param {string} message
* @returns promise
*/
function sendEmail(message) {
const data = {
from: 'Hackerinnen bot <[email protected]>',
to: '[email protected]',
subject: 'Yay! A new hackerinen profile was submitted',
text: message,
};
return new Promise((resolve, reject) => {
mailgun.messages().send(data, (error, body) => {
if (error) {
reject(error);
}
resolve(body);
});
});
}
/**
* Async function to clone repo into tmp dir
* @returns promise
*/
async function cloneRepo() {
const tmpDir = await tmp.dir();
workingDirectory = tmpDir.path;
await process.chdir(`${workingDirectory}`);
console.log(`Cloning repo to ${workingDirectory}`);
return git.clone(repo);
}
/**
* Function to pull latest repo changes
* @returns promise
*/
async function pullRepo() {
await process.chdir(`${workingDirectory}/${REPONAME}`);
console.log(`Pull repo at ${workingDirectory}/${REPONAME}`);
return git.pull();
}
/**
* Function to copy repo into new tmp dir
* @param {string} path to tmp dir
* @returns promise
*/
function copyRepo(path) {
console.log(`Copy repo to ${path}/${REPONAME}`);
return cmd.cp(`-R ${workingDirectory}/${REPONAME} ${path}/${REPONAME}`);
}
/**
* Function to create a new directory
* @param {string} path to new dir
* @returns promise
*/
function createDir(path) {
return new Promise((resolve, reject) => {
if (!fs.existsSync(path)) {
try {
fs.mkdirSync(path);
console.log(`Directory at ${path} created.`);
resolve(path);
} catch (error) {
console.log(`Error creating directory at ${path} with error: ${error}`);
reject(path);
}
} else {
console.log(`Directory at ${path} exists already.`);
resolve(path);
}
});
}
/**
* Function to create a folder for the user profile
* @param {string} username name of the user folder
* @param {string} tmpDirPath the tmp dir path
* @returns promise
*/
function createProfileFolder(username, tmpDirPath) {
try {
const userPath = path.resolve(
tmpDirPath,
REPONAME,
'content',
'hackerinnen',
username
);
return createDir(userPath);
} catch (error) {
return new Promise((resolve, reject) => {
return reject(error);
});
}
}
/**
* Function to create a german markdown file in the user folder
* @param {string} data markdown file content
* @param {string} username name of the user folder
* @param {string} tmpDirPath the tmp dir path
* @returns promise
*/
function createMarkdownFileDE(data, username, tmpDirPath) {
const filePath = path.resolve(
tmpDirPath,
REPONAME,
'content',
'hackerinnen',
username,
'index.de.md'
);
return new Promise((resolve, reject) => {
fs.writeFile(filePath, data, error => {
if (error) {
reject(error);
}
resolve(filePath);
});
});
}
/**
* Function to create a english markdown file in the user folder
* @param {string} data markdown file content
* @param {string} username name of the user folder
* @param {string} tmpDirPath the tmp dir path
* @returns promise
*/
function createMarkdownFileEN(data, username, tmpDirPath) {
const filePath = path.resolve(
tmpDirPath,
REPONAME,
'content',
'hackerinnen',
username,
'index.en.md'
);
return new Promise((resolve, reject) => {
fs.writeFile(filePath, data, error => {
if (error) {
reject(error);
}
resolve(filePath);
});
});
}
/**
* Function to save user image
* @param {string} fileImage the image file
* @param {string} username name of the user folder
* @param {string} tmpDirPath the tmp dir path
* @returns promise
*/
function saveImage(fileImage, username, tmpDirPath) {
return new Promise((resolve, reject) => {
if (fileImage && fileImage.path && fileImage.originalname) {
const nameParts = fileImage.originalname.split('.');
if (nameParts.length < 2) {
return reject(`Error processing profile image file name`);
}
const extension = nameParts[nameParts.length - 1].toLowerCase();
if (extension !== 'jpg' && extension !== 'jpeg') {
console.log(`Error processing profile image: Wrong file extension.`);
return reject(`Wrong file extension. Please choose jpg.`);
}
const newFileName = `${username}.${extension}`;
const imageFilePath = path.resolve(
tmpDirPath,
REPONAME,
'content',
'hackerinnen',
username,
newFileName
);
fs.copyFile(fileImage.path, imageFilePath, err => {
if (err) {
console.log(`Error processing profile image with error: ${err}.`);
return reject(err);
}
console.log(`Saved profile image to ${imageFilePath}`);
return resolve();
});
} else {
console.log(`No profile image found.`);
return resolve();
}
});
}
/**
* Format string to use dashes and lowercase characters
* @param {string} str
*/
function formatString(str) {
try {
return str.replace(/\s+/g, '-').toLowerCase();
} catch (error) {
return new Promise((resolve, reject) => {
reject(error);
});
}
}
/**
* Async function to create pull request
* @param {string} username name of the user folder
* @param {string} tmpDirPath the tmp dir path
*/
async function createPullRequest(username, tmpFolder) {
try {
await process.chdir(`${tmpFolder}/${REPONAME}`);
await git.config('user.email', BOT_EMAIL);
await git.config('user.name', BOT_NAME);
const branchName = `${username}-${Date.now()}`;
await git.branch(branchName);
await git.checkout(branchName);
await git.add(`content/hackerinnen/${username}/*`);
let commitMessage = `Add profile for ${username}`;
await git.commit('-m "' + commitMessage + '"');
await git.push('-u', 'origin', branchName);
const pullrequestData = await octokit.pulls.create({
owner: OWNER,
repo: REPONAME,
title: commitMessage,
head: branchName,
base: 'master',
body:
'This pull request was automatically generated. Thanks for submitting your profile at https://submit.hackerinnen.space/',
});
console.log(
`Successfully created pull request ${pullrequestData.data.html_url} for ${username}.`
);
return pullrequestData.data.html_url;
} catch (error) {
return new Promise((resolve, reject) => {
console.error(error);
reject('Something went wrong when trying to create a pull request.');
});
}
}
/**
* Main function to submit the profile which includes creating all folders and files and the final pull request.
* @param {string} username name of the user folder
* @param {string} tmpDirPath the tmp dir path
*/
async function submitProfile(
_username,
_email,
_filecontentDE,
_filecontentEN,
_fileImage
) {
try {
const message = `Username: ${_username}\n\nE-Mail: ${_email}\n\n${_filecontentDE}\n\n${_filecontentEN}\n\n`;
await sendEmail(message);
} catch (error) {
console.error(error);
}
try {
const username = formatString(_username);
const tmpDir = await tmp.dir();
const tmpDirPath = tmpDir.path;
await pullRepo();
await copyRepo(tmpDirPath);
await createProfileFolder(username, tmpDirPath);
await createMarkdownFileDE(_filecontentDE, username, tmpDirPath);
await createMarkdownFileEN(_filecontentEN, username, tmpDirPath);
await saveImage(_fileImage, username, tmpDirPath);
return await createPullRequest(username, tmpDirPath);
} catch (error) {
return new Promise((resolve, reject) => {
reject(error);
});
}
}
module.exports = { cloneRepo, submitProfile };