Skip to content

Commit b4afc60

Browse files
committed
improve logging
1 parent aacf5ac commit b4afc60

File tree

8 files changed

+86
-43
lines changed

8 files changed

+86
-43
lines changed

index.js

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,21 @@
22

33
const { join } = require("path")
44

5-
const chalk = require("kleur")
65
const { init } = require("./src/adb")
76
const { existsSync } = require("fs")
87
const { cli } = require("./src/cli")
98
const { normalize } = require("path")
109
const { recordVideo } = require("./src/recordVideo")
1110
const { takeScreenshot } = require("./src/takeScreenshot")
1211
const open = require("open")
13-
const { bgRed, bold } = require("kleur")
12+
const { bold, gray } = require("kleur")
1413
const { selectOption } = require("./src/selectOption")
1514
const logUpdate = require("log-update")
15+
const { fail } = require("./src/log")
1616

1717
const version = require(join(__dirname, "./package.json")).version
1818

19-
console.log()
20-
console.log(chalk.bold("android-capture"), version, "\n")
19+
console.log(bold().gray("android-capture"), gray(version), "\n")
2120

2221
/**
2322
* @type {Record<string, boolean>}
@@ -42,10 +41,8 @@ const imageTypes = {
4241
/**
4342
* @param {any} message
4443
*/
45-
function fail(message) {
46-
console.error(bgRed(" ERROR "), message)
47-
console.error("\nRun with", bold("--help"), "for usage information.")
48-
process.exit(1)
44+
function error(message) {
45+
fail(message, "\nRun with", bold("--help"), "for usage information.")
4946
}
5047

5148
async function run() {
@@ -74,7 +71,7 @@ async function run() {
7471
}
7572

7673
if (others.length) {
77-
fail("Unexpected arguements: " + others.join(" "))
74+
error("Unexpected arguements: " + others.join(" "))
7875
}
7976

8077
const extension = mode === "image" ? "png" : "mp4"
@@ -87,7 +84,7 @@ async function run() {
8784
)
8885

8986
if (cli.flags.copy && mode === "video") {
90-
fail(`The ${bold("--copy")} option does not work with video.`)
87+
error(`The ${bold("--copy")} option does not work with video.`)
9188
}
9289

9390
const useTemporaryFile = !filename && cli.flags.copy && !cli.flags.open

src/adb.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
const { spawn } = require("child_process")
2+
const { gray } = require("kleur")
23
const { getDevice } = require("./getDevice")
4+
const { verbose, formatSpawnArgs } = require("./log")
35
const { spawnSafeSync } = require("./spawnSafeSync")
46

57
let device = ""
68

79
module.exports.adb = (/** @type {string[]} */ ...args) =>
810
spawnSafeSync("adb", ["-s", device, ...args])
911

10-
module.exports.adbAsync = (/** @type {string[]} */ ...args) =>
11-
spawn("adb", ["-s", device, ...args])
12+
module.exports.adbAsync = (/** @type {string[]} */ ...args) => {
13+
verbose(gray("$"), "adb", formatSpawnArgs(["-s", device, ...args]))
14+
return spawn("adb", ["-s", device, ...args])
15+
}
1216

1317
module.exports.init = async () => {
1418
device = await getDevice()

src/cli.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ module.exports.cli = meow(
2626
${bold("--help, -h")}
2727
Show this help text
2828
29+
${bold("--verbose")}
30+
Show verbose output
31+
2932
Examples
3033
3134
$ npx android-capture video
@@ -57,6 +60,10 @@ module.exports.cli = meow(
5760
type: "boolean",
5861
default: false,
5962
},
63+
verbose: {
64+
type: "boolean",
65+
default: false,
66+
},
6067
},
6168
allowUnknownFlags: false,
6269
},

src/countdown.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ module.exports.countdown = async () => {
1616
0,
1717
numCharsOfCountdownStringToUse,
1818
)
19-
logUpdate(` 🎬 Get ready! ${countdownSoFar}\n\n`)
19+
logUpdate(` 🎬 Get ready! ${countdownSoFar}\n\n`)
2020
if (ratio >= 1) {
2121
clearInterval(interval)
2222
r(null)

src/getDevice.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,16 @@
1-
const { bgRed, bold } = require("kleur")
1+
const { bold } = require("kleur")
2+
const { fail } = require("./log")
23
const { selectOption } = require("./selectOption")
34

45
const { spawnSafeSync } = require("./spawnSafeSync")
56

6-
const ERROR = bgRed(" ERROR ")
7-
87
module.exports.getDevice = async () => {
9-
const res = spawnSafeSync("which", ["adb"], {
10-
logStdErrOnError: false,
11-
throwOnError: false,
12-
})
8+
const res = spawnSafeSync("which", ["adb"], { failOnError: false })
139
if (res.status !== 0) {
14-
console.error(ERROR, bold("adb"), "not found")
15-
console.error("Please install and configure the android dev tools.")
10+
fail(
11+
`${bold("adb")} not found`,
12+
"Please install and configure the android dev tools.",
13+
)
1614
}
1715

1816
const result = spawnSafeSync("adb", ["devices", "-l"]).stdout.toString()
@@ -21,9 +19,9 @@ module.exports.getDevice = async () => {
2119
.trim()
2220
.split(/\r?\n/g)
2321
.filter(Boolean)
22+
2423
if (deviceLines.length === 0) {
25-
console.error(bgRed(" ERROR "), "No devices or emulators connected.")
26-
process.exit(0)
24+
fail("No devices or emulators connected.")
2725
}
2826

2927
if (deviceLines.length === 1) {
@@ -48,7 +46,9 @@ module.exports.getDevice = async () => {
4846
*/
4947
function parseDeviceLine(line) {
5048
const [id, _type, ...properties] = line.split(/\s+/)
51-
const model = (properties.find((p) => p.startsWith("model:")) || "").split(":")[1]
49+
const model = (properties.find((p) => p.startsWith("model:")) || "").split(
50+
":",
51+
)[1]
5252
const isUSB = properties.some((p) => p.startsWith("usb:"))
5353
return { id, model, isUSB }
5454
}

src/log.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
const { bgRed } = require("kleur")
2+
const logUpdate = require("log-update")
3+
const { cli } = require("./cli")
4+
5+
/**
6+
* @param {string} msg
7+
* @param {...any} others
8+
*/
9+
module.exports.fail = (msg, ...others) => {
10+
logUpdate.done()
11+
console.error(bgRed(" ERROR "), msg)
12+
if (others.length) {
13+
console.error(...others)
14+
}
15+
process.exit(1)
16+
}
17+
18+
/**
19+
* @param {...any} args
20+
*/
21+
module.exports.verbose = (...args) => {
22+
if (cli.flags.verbose) {
23+
logUpdate.done()
24+
console.log(...args)
25+
}
26+
}
27+
28+
/**
29+
* @param {string[]} args
30+
*/
31+
module.exports.formatSpawnArgs = (args) => {
32+
return args
33+
.map((a) => (a.match(/^[\w\-]+$/) ? a : `'${a.replace(/'/g, `'\\''`)}'`))
34+
.join(" ")
35+
}

src/recordVideo.js

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ const { adb, adbAsync } = require("./adb")
44
const { cli } = require("./cli")
55
const { countdown } = require("./countdown")
66
const { pushKeyboardContext, popKeyboardContext } = require("./keyboardInput")
7+
const { fail } = require("./log")
78
const { getVisibleTouches, setVisibleTouches } = require("./visibleTouches")
89

910
function getScreenSize() {
@@ -88,18 +89,17 @@ async function createRecording(outFile) {
8889
display.stop()
8990

9091
if (err) {
91-
console.log(err)
92+
logUpdate.done()
93+
fail("Failed to capture video.", err)
9294
}
9395

9496
if (!escaped) {
95-
logUpdate(
96-
` ${green("✔")} Cut!\n\nTransferring video from phone...`,
97-
)
97+
logUpdate(` ${green("✔")} Cut!\n\nTransferring video from phone...`)
9898
await new Promise((r) => setTimeout(r, 2000))
9999
console.log()
100100
adb("pull", internalFilePath, outFile)
101101
} else {
102-
logUpdate(` ${bold().red("♺")} Cancelling...\n\n`)
102+
logUpdate(` ${bold().red("♺")} Cancelling...\n\n`)
103103
}
104104
adb("shell", "rm", internalFilePath)
105105
resolve({ escaped })
@@ -142,7 +142,7 @@ class RecordingMessage {
142142
return this
143143
}
144144
print() {
145-
logUpdate(` ${this.toggle ? red("⦿") : " "} Recording...
145+
logUpdate(` ${this.toggle ? red("⦿") : " "} Recording...
146146
147147
Press ${printKey(bold().green("SPACE"))} to finish recording, or ${printKey(
148148
"ESC",

src/spawnSafeSync.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
/**
2-
* @typedef {{ throwOnError?: boolean, logStdErrOnError?: boolean, maxBuffer?: number} & import('child_process').SpawnOptions} SpawnSafeOptions
2+
* @typedef {{ failOnError?: boolean, maxBuffer?: number} & import('child_process').SpawnOptions} SpawnSafeOptions
33
*/
44

55
/** @type {SpawnSafeOptions} */
66
const defaultOptions = {
7-
logStdErrOnError: true,
8-
throwOnError: true,
7+
failOnError: true,
98
}
109

1110
const { spawnSync } = require("child_process")
11+
const { gray } = require("kleur")
12+
const { verbose, fail, formatSpawnArgs } = require("./log")
1213

1314
class ConsoleError {
1415
/**
@@ -25,18 +26,17 @@ module.exports.spawnSafeSync = (
2526
/** @type {string[]} */ args,
2627
/** @type {SpawnSafeOptions} */ options,
2728
) => {
29+
verbose(`${gray("$")} ${command} ${formatSpawnArgs(args)}`)
2830
const mergedOptions = Object.assign({}, defaultOptions, options)
2931
const result = spawnSync(command, args, options)
3032
if (result.error || result.status !== 0) {
31-
if (mergedOptions.logStdErrOnError) {
32-
if (result.stderr) {
33-
console.error(result.stderr.toString())
34-
} else if (result.error) {
35-
console.error(result.error)
36-
}
37-
}
38-
if (mergedOptions.throwOnError) {
39-
throw new ConsoleError(result)
33+
if (mergedOptions.failOnError) {
34+
const err = result.stderr ? result.stderr.toString() : ""
35+
const out = result.stdout ? result.stdout.toString() : ""
36+
fail(
37+
`Command failed: ${command} ${formatSpawnArgs(args)}`,
38+
...[err, out, result.error].filter(Boolean),
39+
)
4040
}
4141
}
4242
return result

0 commit comments

Comments
 (0)