forked from AnandPilania/php-android-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerateCommand.php
More file actions
378 lines (329 loc) · 14.5 KB
/
GenerateCommand.php
File metadata and controls
378 lines (329 loc) · 14.5 KB
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
<?php
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
class GenerateCommand extends Command
{
private $dimensions = [], $flavors = [], $modules = ['app'];
private $input, $output, $projectName, $pkgName;
protected function configure()
{
$this->setName('create')
->setDescription('Create android studio gradle project skeleton')
->addArgument('project', InputArgument::REQUIRED, 'Provide the project name')
->addArgument('pkg', InputArgument::REQUIRED, 'Provide the pkg name')
->addOption('targetSdk', 'ts', InputOption::VALUE_OPTIONAL, 'Pass the targetSdk.', 29)
->addOption('minSdk', 'ms', InputOption::VALUE_OPTIONAL, 'Pass the minSdk.', 16)
->addOption('compileSdk', 'cs', InputOption::VALUE_OPTIONAL, 'Pass the compileSdk.', 29)
->addOption('buildTools', 'bt', InputOption::VALUE_OPTIONAL, 'Pass the buildVersion.', '29.0.1')
->addOption('androidX', 'x', InputOption::VALUE_OPTIONAL, 'Is androidX?', true)
->addOption('jetifier', 'j', InputOption::VALUE_OPTIONAL, 'Jetifier enabled for AndroidX?', true)
->addOption('modules', 'm', InputOption::VALUE_OPTIONAL, 'Comma-seperated modules [with semi-colon seperated type] (backend:library,client)')
->addOption('flavors', 'f', InputOption::VALUE_OPTIONAL, 'Comma-seperated flavors followed by dimension with semi-colon (free:type,paid:type,php:backend,firebase:backend)')
->addOption('force', null)
->setHelp(
<<<EOT
The <info>%command.name%</info> command helps you generates new Android-Studio Gradle Project.
By default, the command interacts with the developer to tweak the generation.
Any passed option will be used as a default value for the interaction
(<comment>project</comment> & <comment>pkg</comment> is the only two needed if you follow the conventions):
<info>php %command.full_name% HelloWorld com.example.helloworld</info>
If you want to disable any user interaction, use <comment>--no-interaction</comment>
EOT
);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
$this->output = $output;
$this->projectName = $input->getArgument('project');
$this->pkgName = $input->getArgument('pkg');
$this->generateOptions();
$this->createProject();
}
private function createProject()
{
if (is_dir($this->projectName)) {
if (!$this->input->getOption('force')) {
$this->output->writeln('<fg=red>Project ' . $this->projectName . ' is already exists!</>');
$this->output->writeln('<info>Use: --force/-ff for forcefully delete an existing project!</info>');
exit();
} else {
$this->deleteExisting($this->projectName);
}
}
$this->_mkdir($this->projectName);
$this->copyr(__DIR__ . '/stubs/gradle', $this->projectName . '/gradle');
copy(__DIR__ . '/stubs/gradlew', $this->projectName . '/gradlew');
copy(__DIR__ . '/stubs/gradlew.bat', $this->projectName . '/gradlew.bat');
$this->_mkdir($this->projectName . '/build');
file_put_contents($this->projectName . '/build.gradle', "buildscript {\n\trepositories {\n\t\tgoogle()\n\t\tjcenter()\n\t}\n\tdependencies {\n\t\tclasspath 'com.android.tools.build:gradle:3.5.1'\n\t}\n}\n\nallprojects {\n\trepositories {\n\t\tgoogle()\n\t\tjcenter()\n\t}\n}\n\ntask clean(type: Delete) {\n\tdelete rootProject.buildDir\n}\n", 0);
file_put_contents($this->projectName . '/.gitignore', "*.iml\n.gradle\n/local.properties\n/.idea/caches\n/.idea/libraries\n/.idea/modules.xml\n/.idea/workspace.xml\n/.idea/navEditor.xml\n/.idea/assetWizardSettings.xml\n.DS_Store\n/build\n/captures\n.externalNativeBuild\n/backup\n/priv", 0);
file_put_contents($this->projectName . '/gradle.properties', "org.gradle.jvmargs=-Xmx1536m\nandroid.useAndroidX=" . ($this->input->getOption('androidX') ? "true" : "false") . "\nandroid.enableJetifier=" . ($this->input->getOption('jetifier') ? "true" : "false") . "\n", 0);
$settingsContent = "include ";
foreach ($this->modules as $key => $module) {
$exModule = explode(':', $module);
if ($exModule > 0) {
$moduleName = $exModule[0];
$moduleType = isset($exModule[1]) ? $exModule[1] : 'application';
}
$this->_mkdir($this->projectName . '/' . $moduleName);
file_put_contents($this->projectName . '/' . $moduleName . '/.gitignore', "/build\n\n", 0);
$isAndroidX = $this->input->getOption('androidX');
$fdCount = 0;
$flavorContent = '';
$dimensionContent = '';
if ($count = count($this->flavors)) {
$flavorContent = "productFlavors {\n\t\t";
$dimensionContent = 'flavorDimensions ';
foreach ($this->flavors as $flavor => $dimension) {
$dimenPushed = $this->str_contains($dimensionContent, "'$dimension'");
if (!$dimenPushed) {
$dimensionContent .= "'$dimension'";
}
$flavorContent .= $flavor . " {\n\t\t\tdimension '$dimension'\n\t\t}";
if ($fdCount < ($count - 1)) {
$fdCount = $fdCount + 1;
if (!$dimenPushed) {
$dimensionContent .= ", ";
}
$flavorContent .= "\n\t\t";
}
}
$flavorContent .= "\n\t}\n";
}
$fdContent = $dimensionContent . "\n\t" . $flavorContent;
file_put_contents(
$this->projectName . '/' . $moduleName . '/build.gradle',
"apply plugin: 'com.android." . $moduleType . "'\n\n" .
"android {\n\t" .
"compileSdkVersion " . $this->input->getOption('compileSdk') . "\n\t" .
"buildToolsVersion '" . $this->input->getOption('buildTools') . "'\n\t" .
"defaultConfig {\n\t\t" . ($moduleType === 'library' ? '' : "applicationId '" . ($this->pkgName . ($moduleName === 'app' ? '' : '.' . $moduleName)) . "'\n\t\t") .
"minSdkVersion " . $this->input->getOption('minSdk') . "\n\t\t" .
"targetSdkVersion " . $this->input->getOption('targetSdk') . "\n\t\t" .
"versionCode 1\n\t\t" .
"versionName '1.0'\n\t\t" .
"testInstrumentationRunner '" . ($isAndroidX ? 'androidx.test.runner.AndroidJUnitRunner' : '') . "'\n\t" .
"}\n\n\t" .
"buildTypes {\n\t\t" .
"debug {\n\t\t\tdebuggable true\n\t\t}\n\t\t" .
"release {\n\t\t\tdebuggable false\n\t\t\tminifyEnabled true\n\t\t\tshrinkResources true\n\t\t\tzipAlignEnabled true\n\t\t\tproguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'\n\t\t}\n\t" .
"}\n\n\t" .
$fdContent .
"}\n\n" .
"dependencies {\n\t" .
"implementation fileTree(dir: 'libs', include: ['*.jar'])\n\t" .
"implementation '" . ($isAndroidX ? 'androidx.appcompat:appcompat:1.0.0' : '') . "'\n\t" .
"implementation '" . ($isAndroidX ? 'androidx.constraintlayout:constraintlayout:1.1.3' : '') . "'\n\t" .
"testImplementation 'junit:junit:4.12'\n\t" .
"androidTestImplementation '" . ($isAndroidX ? 'androidx.test:runner:1.2.0' : '') . "'\n\t" .
"androidTestImplementation '" . ($isAndroidX ? 'androidx.test.espresso:espresso-core:3.2.0' : '') . "'\n" .
"}",
0
);
file_put_contents($this->projectName . '/' . $moduleName . '/proguard-rules.pro', "\n", 0);
$this->_mkdir($this->projectName . '/' . $moduleName . '/src');
$this->_mkdir($this->projectName . '/' . $moduleName . '/build');
$this->_mkdir($this->projectName . '/' . $moduleName . '/libs');
$this->_mkdir($this->projectName . '/' . $moduleName . '/src/androidTest');
$this->_mkdir($this->projectName . '/' . $moduleName . '/src/test');
$this->_mkdir($this->projectName . '/' . $moduleName . '/src/main');
if ($moduleType === 'application') {
file_put_contents(
$this->projectName . '/' . $moduleName . '/src/main/AndroidManifest.xml',
'<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="' . $this->pkgName . '">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>',
0
);
} else {
file_put_contents(
$this->projectName . '/' . $moduleName . '/src/main/AndroidManifest.xml',
'<manifest xmlns:android="http://schemas.android.com/apk/res/android" ' . "\n\t" . 'package="' . $this->pkgName . ('app' === $moduleName ? '' : '.' . $moduleName) . '">' . "\n\n\t" . ($moduleType === 'library' ? '' : '<application' . "\n\t\t" .
'android:allowBackup="true"' . "\n\t\t" .
'android:icon="@mipmap/ic_launcher"' . "\n\t\t" .
'android:label="@string/app_name"' . "\n\t\t" .
'android:roundIcon="@mipmap/ic_launcher_round"' . "\n\t\t" .
'android:supportsRtl="true"' . "\n\t\t" .
'android:theme="@style/AppTheme">' . "\n\t\t\t" .
"\n\t</application>")
. "\n</manifest>\n",
0
);
}
$this->_mkdir($this->projectName . '/' . $moduleName . '/src/main/java');
$exPkg = explode('.', $this->pkgName);
$_dir = $this->projectName . '/' . $moduleName . '/src/main/java';
$_newDir = '';
foreach ($exPkg as $key => $pkgDir) {
$_newDir .= '/' . $pkgDir;
$this->_mkdir($_dir . $_newDir);
if ($key === (count($exPkg) - 1) && $moduleName !== 'app') {
$this->_mkdir($_dir . $_newDir . '/' . $moduleName);
}
}
if ($moduleType === 'application') {
// Activity Java File Path Bug Debug
// $this->_print_info('Package Name : ' . $this->pkgName);
// $this->_print_info('Replaced Package Name : ' . str_replace('.', '/',$this->pkgName));
// $this->output->writeln('<info>MainActivity.java Path : ' . $this->projectName . '/' . $moduleName . '/src/main/java/' . str_replace('.', '/',$this->pkgName) . '/MainActivity.java' . '</info>');
// HelloWorld Activity
file_put_contents(
$this->projectName . '/' . $moduleName . '/src/main/java/' . str_replace('.', '/', $this->pkgName) . '/MainActivity.java',
"package $this->pkgName;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}",
0
);
}
if ($moduleType === 'library') {
$this->_mkdir($this->projectName . '/' . $moduleName . '/src/main/res');
$this->_mkdir($this->projectName . '/' . $moduleName . '/src/main/res/drawable');
$this->_mkdir($this->projectName . '/' . $moduleName . '/src/main/res/layout');
$this->_mkdir($this->projectName . '/' . $moduleName . '/src/main/res/values');
} else {
$this->copyr(__DIR__ . '/stubs/res', $this->projectName . '/' . $moduleName . '/src/main/res');
// HelloWorld Layout
$this->_mkdir($this->projectName . '/' . $moduleName . '/src/main/res/layout');
file_put_contents(
$this->projectName . '/' . $moduleName . '/src/main/res/layout/activity_main.xml',
'<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>',
0
);
}
file_put_contents($this->projectName . '/' . $moduleName . '/src/main/res/values/strings.xml', "<resources>\n\t" . '<string name="app_name">' . ucfirst($moduleName) . "</string>\n</resources>\n", 0);
$settingsContent .= "':" . $moduleName . "'";
if ($key < (count($this->modules) - 1)) {
$settingsContent .= ",";
}
}
file_put_contents($this->projectName . '/settings.gradle', $settingsContent . "\n", 0);
// file_put_contents($this->projectName . '/local.properties', "ndk.dir=E/:/SDK/ndk-bundle\nsdk.dir=E/:/SDK\n", 0);
$this->output->writeln('<info>' . $this->projectName . ' created successfully!</info>');
}
private function generateOptions()
{
$this->generateFlavors($this->input->getOption('flavors'));
$this->generateModules($this->input->getOption('modules'));
}
private function generateFlavors($flavors = null)
{
if ($flavors) {
$flavors = explode(',', $flavors);
if (is_array($flavors) && count($flavors)) {
foreach ($flavors as $flavor) {
$exFlavor = explode(':', $flavor);
if (!isset($exFlavor[1])) {
$this->output('<fg=red>Flavors must-be followed by specific dimension</>');
exit();
}
$this->flavors[$exFlavor[0]] = $exFlavor[1];
}
}
}
}
private function generateModules($modules = null)
{
if ($modules) {
$modules = explode(',', $modules);
if (is_array($modules) && count($modules)) {
$_mergedModules = array_merge($this->modules, $modules);
$this->modules = $_mergedModules;
}
}
}
private function deleteExisting($target)
{
if (is_dir($target)) {
$objs = scandir($target);
foreach ($objs as $obj) {
if ($obj != '.' && $obj != '..') {
if (is_dir($target . '/' . $obj)) {
$this->deleteExisting($target . '/' . $obj);
} else {
unlink($target . '/' . $obj);
}
}
}
rmdir($target);
}
}
private function copyr($src, $dest)
{
if (is_link($src)) {
return symlink(readlink($src), $dest);
}
if (is_file($src)) {
return copy($src, $dest);
}
$this->_mkdir($dest);
$dir = dir($src);
while (false !== $entry = $dir->read()) {
if ($entry == '.' || $entry == '..') {
continue;
}
$this->copyr("$src/$entry", "$dest/$entry");
}
$dir->close();
return true;
}
private function str_contains($haystack, $needles)
{
foreach ((array) $needles as $needle) {
if ($needle != '' && mb_strpos($haystack, $needle) !== false) {
return true;
}
}
return false;
}
private function _mkdir($dest)
{
if (!file_exists($dest) || !is_dir($dest)) {
mkdir($dest);
}
}
private function _print_info($message)
{
$this->output->writeln('<info>' . $message . '</info>');
}
}