-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
161 lines (145 loc) · 5.14 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
const core = require("@actions/core");
const github = require("@actions/github");
const path = require("path");
const fs = require("fs");
const glob = require("glob");
const csso = require("csso");
const {
minify
} = require("terser");
const {
Octokit
} = require("@octokit/core");
const {
createPullRequest
} = require("octokit-plugin-create-pull-request");
const MyOctokit = Octokit.plugin(createPullRequest);
/**
* Reads the personal access token and desired directory
* that needs to be minified from workflow.
*
* Exits if token is undefined or, the current branch is a newly
* created branch by minisauras.
*
* Uses 'glob' to find all possible CSS and JS
* files within the desired directory and ignores node_modules.
*
* Minify those files using 'csso' and 'terser' and
* finally push those changes within a new branch to create a PR.
*/
(async function init() {
try {
let directory = core.getInput("directory");
const token = process.env.GITHUB_TOKEN;
if (token === undefined || token.length === 0) {
throw new Error(`
Token not found. Please, set a secret token in your repository.
To know more about creating tokens, visit: https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token
To know more about setting up personal access token, visit: https://docs.github.com/en/actions/configuring-and-managing-workflows/creating-and-storing-encrypted-secrets
`);
}
const currentBranch = github.context.ref.slice(11);
if (currentBranch.startsWith('_minisauras_')) {
console.log(`Code has been minifed. Branch ${currentBranch} can be merged now.`);
return;
}
const pluginOctokit = new MyOctokit({
auth: token,
});
const context = github.context;
const repoInfo = context.repo;
if (
directory == undefined ||
directory == null ||
directory.startsWith(".")
)
directory = "";
const pattern = `${directory}**/*.{css,js}`;
const options = {
dot: true,
ignore: ["node_modules/**/*"],
};
const newBranchName = '_minisauras_' + Math.random().toString(36).slice(2);
/** Using @glob to find all CSS and JS files */
glob(pattern, options, function (er, files) {
if (er) throw new Error("File not found");
let final = [];
files.forEach(function (file) {
Promise.all([readAndMinify(file)])
.then(function (result) {
final.push({
path: file,
content: result[0],
});
})
.finally(async function () {
let encodedStructure = {};
if (final.length == files.length && !currentBranch.startsWith('_minisauras_') && files.length !== 0) {
final.forEach(function (eachData) {
encodedStructure[eachData.path] = eachData["content"];
});
// setting up pr description
const FUNNY_CAT = 'https://media1.tenor.com/images/841aeb9f113999616d097b414c539dfd/tenor.gif';
let prDescription = 'Changes in these files:\n';
files.forEach(function (f) {
prDescription += `- **${f}** \n`;
});
prDescription += `![cat](${FUNNY_CAT})`;
if (prDescription.includes(FUNNY_CAT)) {
await pluginOctokit.createPullRequest({
owner: repoInfo.owner,
repo: repoInfo.repo,
title: `Minified ${files.length} files`,
body: prDescription,
head: newBranchName,
changes: [{
files: encodedStructure,
commit: `Minified ${files.length} files`,
}, ],
}).then(function (result) {
const tableData = {
'Pull request url': result.data.url,
'Pull request title': result.data.title,
'Sent by': result.data.user.login,
'Total number of commits': result.data.commits,
'Additions': result.data.additions,
'Deletions': result.data.deletions,
'Number of files changed': result.data.changed_files
}
console.table(tableData);
}).catch(function () {
process.on('unhandledRejection', () => {});
});
}
}
})
.catch(function (error) {
throw new Error(error);
});
});
});
} catch (error) {
throw new Error(error);
}
})();
/**
* Uses terser and csso to minify JavaScript and CSS files.
* @param {string} file containing file path to be minified.
*
* @return {string} Minified content.
*/
const readAndMinify = async function (file) {
const content = fs.readFileSync(file, "utf8");
const extension = path.extname(file);
// minify file
if (extension === ".js") {
const result = await minify(content, {
compress: true,
});
return result.code;
} else if (extension === ".css") {
return csso.minify(content).css;
} else {
console.log("Other files");
}
};