-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsetup-project.js
279 lines (255 loc) · 8.02 KB
/
setup-project.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
const path = require('path');
const fs = require('fs');
const exec = require('child_process').exec;
const extract = require('extract-zip');
const BASE_PATH = `${__dirname}/../..`;
const BASE_ANDROID_PATH = `${BASE_PATH}/android`;
const BASE_IOS_PATH = `${BASE_PATH}/ios`;
const LND_MOBILE_DOWNLOAD_PATH = "https://github.com/coreyphillips/react-native-lightning/releases/download/v0.0.2/";
let packageJson = ""
try {packageJson = require(`${BASE_PATH}/package.json`);} catch {return;}
const createFile = async (source, filePath) => {
return new Promise(async (resolve) => {
if (!fs.existsSync(filePath)) {
fs.copyFile(source, filePath, err => {
if (err) throw err;
});
resolve();
} else {resolve()}
})
}
const mkDirByPathSync = (targetDir, { isRelativeToScript = false } = {}) => {
const sep = path.sep;
const initDir = path.isAbsolute(targetDir) ? sep : '';
const baseDir = isRelativeToScript ? __dirname : '.';
return targetDir.split(sep).reduce((parentDir, childDir) => {
const curDir = path.resolve(baseDir, parentDir, childDir);
try {
fs.mkdirSync(curDir);
} catch (err) {
if (err.code === 'EEXIST') { // curDir already exists!
return curDir;
}
// To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows.
if (err.code === 'ENOENT') { // Throw the original parentDir error on curDir `ENOENT` failure.
throw new Error(`EACCES: permission denied, mkdir '${parentDir}'`);
}
const caughtErr = ['EACCES', 'EPERM', 'EISDIR'].indexOf(err.code) > -1;
if (!caughtErr || caughtErr && curDir === path.resolve(targetDir)) {
throw err; // Throw if it's just the last created dir.
}
}
return curDir;
}, initDir);
}
const getFilePath = (startPath,filter,callback) => {
if (!fs.existsSync(startPath)){
console.log("No dir ",startPath);
return;
}
const files=fs.readdirSync(startPath);
for(let i=0;i<files.length;i++){
const filePath=path.join(startPath,files[i]);
const stat = fs.lstatSync(filePath);
if (stat.isDirectory()){
getFilePath(filePath,filter,callback); //recurse
}
else if (filePath.includes(filter)) {
callback(filePath);
break;
}
}
}
const downloadFile = (source, destination) => {
return new Promise((resolve) => {
try {
const cmd = `curl -L ${source} -o ${destination}`;
exec(cmd, (error, stdout, stderr) => {
if (error) console.warn(error);
resolve(stdout ? stdout : stderr);
});
} catch (e) {resolve(e);}
});
};
let generalFiles = [
{
//Copy postinstall.js -> ./
source: "src/postinstall.js",
destination: BASE_PATH,
filename: "postinstall.js"
},
];
let androidFiles = [
{
//Copy lnd.conf -> android/app/src/main/assets
source: "src/lnd.conf",
destination: `${BASE_ANDROID_PATH}/app/src/main/assets`,
filename: "lnd.conf"
},
{
//Copy build.gradle -> android/Lndmobile
source: "src/android/build.gradle",
destination: `${BASE_ANDROID_PATH}/Lndmobile`,
filename: "build.gradle"
},
];
let iosFiles = [
{
//Copy lnd.conf -> ios/lightning/
source: "src/lnd.conf",
destination: `${BASE_IOS_PATH}/lightning`,
filename: "lnd.conf"
},
{
//Copy build.gradle -> ios/lightning/
source: "src/ios/LndReactModule.h",
destination: `${BASE_IOS_PATH}/lightning`,
filename: "LndReactModule.h"
},
{
//Copy build.gradle -> ios/lightning/
source: "src/ios/LndReactModule.m",
destination: `${BASE_IOS_PATH}/lightning`,
filename: "LndReactModule.m"
},
];
const updatePackageName = (filePath, packageName) => {
// read file and convert to array by line break
let csvContent = fs.readFileSync(filePath).toString().split('\n');
csvContent[0] = `package ${packageName};`; // replace the the first element from array
csvContent = csvContent.join('\n'); // convert array back to string
fs.writeFileSync(filePath, csvContent);
}
const generalSetup = () => {
generalFiles.forEach(async ({ source, destination, filename }) => {
const filePath = `${destination}/${filename}`;
if (!fs.existsSync(filePath)) {
mkDirByPathSync(destination);
await createFile(source, filePath);
}
});
//Setup postinstall script
let postinsall = undefined;
try {postinsall = packageJson["scripts"]["postinstall"];} catch {}
const postInstallScript = "node postinstall.js";
if (postinsall && !postinsall.includes(postInstallScript)) {
injectText(
`${BASE_PATH}/package.json`,
"postinstall",
`"postinstall": "${postinsall} && ${postInstallScript}",`,
0,
true
)
} else {
injectText(
`${BASE_PATH}/package.json`,
"scripts",
`"postinstall": "${postInstallScript}",`,
1
)
}
};
const setupAndroid = () => {
getFilePath(`${BASE_ANDROID_PATH}/app/src/main/java/`,"MainActivity.java",filePath =>{
const path = filePath.replace("/MainActivity.java", "");
if (!path){
console.log("Unable to find path to MainActivity.java");
return;
} else {
const files = ["LndNativeModule.java", "LndNativePackage.java"];
files.forEach((f) => {
//Copy f -> path
androidFiles.push({
source: `src/android/${f}`,
destination: path,
filename: f
})
});
}
const packageName = path.substring(path.indexOf("com")).replace("/", ".");
androidFiles.forEach(async ({ source, destination, filename }) => {
const filePath = `${destination}/${filename}`;
if (!fs.existsSync(filePath)) {
mkDirByPathSync(destination);
await createFile(source, filePath);
if (filename.includes(".java")) updatePackageName(filePath, packageName);
}
});
//Add LND Native Package to MainApplication.java
injectText(
`${path}/MainApplication.java`,
"return packages",
"packages.add(new LndNativePackage());",
-1
);
//Add Lndmobile implementation to build.gradle
injectText(
`${BASE_ANDROID_PATH}/app/build.gradle`,
"dependencies {",
"implementation project(path: ':Lndmobile')",
1
);
//Append Lndmobile to project in settings.gradle
injectText(
`${BASE_ANDROID_PATH}/settings.gradle`,
":app",
", ':Lndmobile'",
0
);
});
//Create Lndmobile path & download Lndmobile.aar
const lndMobileDest = `${BASE_ANDROID_PATH}/Lndmobile`;
const lndMobileName = "Lndmobile.aar";
if (!fs.existsSync(lndMobileDest)) mkDirByPathSync(lndMobileDest);
if (!fs.existsSync(`${lndMobileDest}/${lndMobileName}`)) {
const source = `${LND_MOBILE_DOWNLOAD_PATH}${lndMobileName}`;
const destination = `${lndMobileDest}/${lndMobileName}`;
downloadFile(source, destination);
}
};
const setupIos = async () => {
const lndMobileDest = `${BASE_IOS_PATH}/lightning`;
//Create Lndmobile path & download Lndmobile.framework.zip
if (!fs.existsSync(lndMobileDest)) mkDirByPathSync(lndMobileDest);
iosFiles.forEach(async ({ source, destination, filename }) => {
const filePath = `${destination}/${filename}`;
if (!fs.existsSync(filePath)) {
mkDirByPathSync(destination);
await createFile(source, filePath);
}
});
//Download, extract and delete Lndmobile.framework.zip
const lndMobileName = "Lndmobile.framework.zip";
const zipDestination = `${lndMobileDest}/${lndMobileName}`;
if (!fs.existsSync(`${lndMobileDest}/${lndMobileName}`)) {
const source = `${LND_MOBILE_DOWNLOAD_PATH}${lndMobileName}`;
await downloadFile(source, zipDestination);
await extract(zipDestination, { dir: `${lndMobileDest}/` });
}
fs.unlinkSync(zipDestination);
};
const injectText = (filePath, searchString = "", textToInject = "", injectIndex = 0) => {
let csvContent = fs.readFileSync(filePath).toString().split('\n');
let index = -1;
let textAlreadyExists = false;
for (let i = 0; i < csvContent.length; i++) {
if (csvContent[i].includes(textToInject)) {
textAlreadyExists = true;
break;
}
if (csvContent[i].includes(searchString)) index = i;
}
if (index < 0 || textAlreadyExists) return;
//If 0, append to the matched index
if (injectIndex === 0) {
csvContent[index] = `${csvContent[index]}${textToInject}`;
} else {
if (injectIndex < 0) injectIndex = injectIndex + 1;
csvContent.splice(index+injectIndex, 0, textToInject);
}
csvContent = csvContent.join('\n'); // convert array back to string
fs.writeFileSync(filePath, csvContent);
};
generalSetup();
setupAndroid();
setupIos();