Skip to content

Commit

Permalink
add init and fix log
Browse files Browse the repository at this point in the history
  • Loading branch information
kucingapes committed May 18, 2021
1 parent 054f911 commit 50c8d15
Show file tree
Hide file tree
Showing 10 changed files with 215 additions and 89 deletions.
40 changes: 23 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,29 +62,35 @@ sepack run

#### Build

For build android project, type `sepack build`. This command will be generate `local.properties`, setup android sdk and run build task like android studio
For build android project. This command will be generate `local.properties`, setup android sdk and run build task like android studio

#### Run

Run command same as run task in android studio. Type `sepack run`
Run command same as run task in android studio

#### Init

Turn on your android project with sepack android project, say goodbye to lagging android studio

#### Table

| Command | Options | Description |
| --------------- | ------------------- | --------------------------------------- |
| `sepack create` | | Show create project wizard |
| `sepack build` | | Build android project |
| | `--sdk` or `s` | With path android sdk |
| | `--checksdk` or `c` | Check current path android sdk |
| `sepack run` | | Install and run application |
| | `--resume` or `r` | Resume, run with skip build and install |
| | `--log` or `l` | Show log |
| | `--tag` or `t` | Filter by tag |
| | `--verbose` or `v` | Verbose level |
| | `--debug` or `d` | Debug level |
| | `--info` or `i` | Info level |
| | `--warning` or `w` | Warning level |
| | `--error` or `e` | Error level |
| Command | Options | Description | default |
| --------------- | -------------------- | --------------------------------------- | ------- |
| `sepack create` | | Project wizard | |
| `sepack build` | | Build android project | |
| | `--sdk` or `-s` | With path android sdk | |
| | `--log` or `-l` | Show log | false |
| | `--checksdk` or `-c` | Check current path android sdk | |
| `sepack run` | | Install and run application | |
| | `--resume` or `-r` | Resume, run with skip build and install | |
| | `--log` or `-l` | Show log | false |
| | `--tag` or `-t` | Filter by tag | |
| | `--verbose` or `-v` | Verbose level | |
| | `--debug` or `-d` | Debug level | |
| | `--info` or `-i` | Info level | |
| | `--warning` or `-w` | Warning level | |
| | `--error` or `-e` | Error level | |
| `sepack init` | | Turn on sepack android project | |

### Contribute

Expand Down
12 changes: 7 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
{
"name": "sepack",
"version": "0.4.38",
"version": "0.5.0",
"description": "Simple cli tool for android project. Generate android project base on template kotlin mvvm, debug and install project without Android Studio.",
"main": "dist/app.js",
"scripts": {
"start": "android-sepack",
"restart": "clear && npm run clean && npm run build",
"build": "npm run clean && tsc -p . && npm link",
"clean": "npm uninstall -g sepack && npx rimraf dist",
"test": "echo \"Error: no test specified\" && exit 1",
"patch": "npm run build && node updater/patch.js && npm publish",
"minor": "npm run build && node updater/minor.js && npm publish",
"mayor": "npm run build && node updater/mayor.js && npm publish"
"patch": "npm run build && npm run patch-update && npm publish",
"minor": "npm run build && npm run minor-update && npm publish",
"mayor": "npm run build && npm run mayor-update && npm publish",
"patch-update": "npm run build && node -e 'require(\"./updater\").patchUpdate()'",
"minor-update": "npm run build && node -e 'require(\"./updater\").minorUpdate()'",
"mayor-update": "npm run build && node -e 'require(\"./updater\").mayorUpdate()'"
},
"repository": {
"type": "git",
Expand Down
1 change: 0 additions & 1 deletion src/cloner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,6 @@ export class Cloner {
const file = "sepack_config.json"
shelljs.touch(file)
shelljs.sed("-i", "", json, file)

}

private moving(prefixDir: string) {
Expand Down
148 changes: 132 additions & 16 deletions src/command.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import fs from "fs"
import shelljs from 'shelljs'
import { errorLine, outLog, sdkPath, slash } from './utils'
import osSys from 'os'
import ora from "ora"

export class Command {
os = process.platform
isAdbInstalled: boolean
private spinnerBar: ora.Ora

constructor() {
this.spinnerBar = ora()
this.spinnerBar.color = 'white'

if (!shelljs.which('adb')) {
this.isAdbInstalled = false
} else {
Expand All @@ -20,7 +24,7 @@ export class Command {
return sdkValid.includes('build-tools')
}

public async buildProject(sdk: string): Promise<boolean> {
public async buildProject(sdk: string, isShowLog: boolean): Promise<boolean> {
const sdkFixer = sdk ?? await sdkPath()

return new Promise(async resolve => {
Expand All @@ -35,10 +39,27 @@ export class Command {
outLog('Build', 'Setting up local.properties')
const writeLocalProp = await this.writeLocalProp(sdkFixer)
if (writeLocalProp) {
resolve(await this.buildProject(sdkFixer))
resolve(await this.buildProject(sdkFixer, isShowLog))
}
} else if (isContainLocalProp) {
shelljs.exec(`${this.gradlew()} build`)
// start build !
outLog('Build', 'Start build project')

if (!isShowLog) {
this.spinnerBar.text = 'Building project...'
this.spinnerBar.start()
}

shelljs.exec(`${this.gradlew()} build`, { silent: !isShowLog }, (code, stdout, stderr) => {
if (!isShowLog) {
this.spinnerBar.stop()
outLog('Build', 'Done')

if (stderr.includes('BUILD FAILED')) {
errorLine(stderr)
}
}
})
resolve(true)
} else {
errorLine(`local.properties not found, please add flag "--sdk 'your-sdk-folder'"`)
Expand Down Expand Up @@ -77,28 +98,64 @@ export class Command {
}
}

public async runApp(resume: boolean): Promise<boolean> {
public async runApp(resume: boolean, isShowLog: boolean): Promise<boolean> {
if (this.isAdbInstalled) {
return new Promise(resolve => {
const rawData = fs.readFileSync('sepack_config.json')
const packageName = JSON.parse(rawData.toString()).package_name
if (!resume) {
shelljs.exec(`${this.gradlew()} assembleDebug`)
shelljs.exec(`${this.gradlew()} installDebug`)
}
const sepackConfigJson = 'sepack_config.json'
const isConfigExist = shelljs.find(sepackConfigJson).length > 0
if (isConfigExist) {
const rawData = fs.readFileSync(sepackConfigJson)
const packageName = JSON.parse(rawData.toString()).package_name
if (!isShowLog) {
this.spinnerBar.text = 'Building project...'
this.spinnerBar.start()
}

if (!resume) {
shelljs.exec(`${this.gradlew()} assembleDebug`, { silent: !isShowLog }, (code, stdout, stderr) => {
if (stderr.includes('FAILED')) {
this.spinnerBar.stop()
errorLine(stderr)

} else {
this.spinnerBar.text = 'Install application'
shelljs.exec(`${this.gradlew()} installDebug`, { silent: !isShowLog }, (code, stdout, stderr) => {
if (stderr.includes('FAILED')) {
this.spinnerBar.stop()
errorLine(stderr)
resolve(false)
} else {
this.launchingApp(packageName, isShowLog, resolve)
}
})
}
})
} else {
this.launchingApp(packageName, isShowLog, resolve)
}

shelljs.exec(` adb shell cmd package resolve-activity --brief -c android.intent.category.LAUNCHER ${packageName}`, { silent: true }, (data, stderr, stdout) => {
const launcher = stderr.split("\n")[1]
shelljs.exec(`adb shell cmd activity start-activity ${launcher}`)
resolve(true)
})
} else {
errorLine(`${sepackConfigJson} not found! Please run 'sepack init' for turn on sepack android project`)
}
})
} else {
errorLine("Adb not installed!")
return false
}
}

private launchingApp(packageName: any, silent: boolean, resolve: (value: boolean | PromiseLike<boolean>) => void) {
this.spinnerBar.text = 'Start build project'
shelljs.exec(`adb shell cmd package resolve-activity --brief -c android.intent.category.LAUNCHER ${packageName}`, { silent: !silent }, (data, stderr, stdout) => {
const launcher = stderr.split("\n")[1]
this.spinnerBar.stop()

outLog('Run', 'Launcing app')
shelljs.exec(`adb shell cmd activity start-activity ${launcher}`, { silent: !silent })
resolve(true)
})
}

public log(tag: string, level: string) {
if (this.isAdbInstalled) {

Expand All @@ -118,4 +175,63 @@ export class Command {
}
}

public async init(): Promise<boolean> {
return new Promise(async resolve => {
const pkgName = await this.searchPkgName()
const appName = await this.searchAppName()

const json = `
{
"project_name": "${appName}",
"package_name": "${pkgName}"
}
`

const file = "sepack_config.json"
shelljs.touch(file)
shelljs.sed("-i", "", json, file)

resolve(true)
})
}

private async searchPkgName(): Promise<string> {
return new Promise(resolve => {
const appBuildGradle = slash('app/build.gradle')
const isAppBuildGradleisExist = shelljs.find(appBuildGradle).length > 0
if (isAppBuildGradleisExist) {
const text = shelljs.grep('-i', 'applicationId', appBuildGradle).stdout
.replace('\n', '')
.replace('"', '')
.replace(`"`, '')
.replace('applicationId', '')
.trim()

resolve(text)
} else {
errorLine(slash('app/app.gradle not found'))
}
})
}

private async searchAppName(): Promise<string> {
return new Promise(resolve => {
const appSettingGradle = 'settings.gradle'
const isAppSettingGradleisExist = shelljs.find(appSettingGradle).length > 0
if (isAppSettingGradleisExist) {
const text = shelljs.grep('-i', 'rootProject.name', appSettingGradle).stdout
.replace('\n', '')
.replace('"', '')
.replace(`"`, '')
.replace('=', '')
.replace('rootProject.name', '')
.trim()

resolve(text)
} else {
errorLine(slash('settings.gradle not found'))
}
})
}

}
20 changes: 15 additions & 5 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,20 @@ export class Main {
type: 'boolean',
alias: 'c',
default: false
},
log: {
describe: 'Show log',
type: 'boolean',
alias: 'l',
default: false
}
}, async (arg) => {
if (arg.checksdk) {
const sdk = await sdkPath()
console.log(`Sdk path: ${sdk}`)
} else {
await command.buildProject(arg.sdk)
const isShowLog = arg.log
await command.buildProject(arg.sdk, isShowLog)
}

}).command(["run"], "Run application", {
Expand All @@ -48,7 +55,8 @@ export class Main {
log: {
describe: 'Show log',
type: 'boolean',
alias: 'l'
alias: 'l',
default: false
},
tag: {
describe: 'Filter tag',
Expand Down Expand Up @@ -82,7 +90,7 @@ export class Main {
alias: 'e'
},
}, async (arg) => {
const isLogEnable = arg.log
const isShowLog = arg.log
const isResume = arg.resume

const tag = arg.tag ?? "*"
Expand All @@ -108,12 +116,14 @@ export class Main {
level = "V"
}

await command.runApp(isResume)
if (isTagEnable || isLogEnable || isFilterVerbose || isFilterDebug || isFilterInfo || isFilterWarning || isFilterError) {
await command.runApp(isResume, isShowLog)
if (isTagEnable || isFilterVerbose || isFilterDebug || isFilterInfo || isFilterWarning || isFilterError) {
setTimeout(() => {
command.log(tag, level)
}, 2000);
}
}).command(["init"], "Turn on sepack android project", async () => {
await command.init()
}).argv
}

Expand Down
6 changes: 3 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,12 @@ export function welcomeMessage() {
}

export function errorLine(error: string) {
console.log(chalk.red(`Error: ${error}`))
console.log(chalk.red(`!! Error: ${error}`))
}

export function outLog(param: string, value: string) {
console.log(
chalk.blueBright(`> ${param}: `) + chalk.whiteBright(value)
chalk.blueBright(`> ${param}: `) + chalk.white(value)
)
}

Expand All @@ -54,7 +54,7 @@ export function folderNameOf(projectName: string): string {

export function slash(path: string) {
const isExtendedLengthPath = /^\\\\\?\\/.test(path)
const hasNonAscii = /[^\u0000-\u0080]+/.test(path) // eslint-disable-line no-control-regex
const hasNonAscii = /[^\u0000-\u0080]+/.test(path)

if (isExtendedLengthPath || hasNonAscii) {
return path;
Expand Down
Loading

0 comments on commit 50c8d15

Please sign in to comment.