Skip to content

Commit

Permalink
refactor: avoid redundant buffer to string
Browse files Browse the repository at this point in the history
  • Loading branch information
antongolub committed Jan 9, 2025
1 parent a585326 commit 1ea6303
Show file tree
Hide file tree
Showing 5 changed files with 19 additions and 9 deletions.
2 changes: 1 addition & 1 deletion .size-limit.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
{
"name": "zx/index",
"path": "build/*.{js,cjs}",
"limit": "809 kB",
"limit": "810 kB",
"brotli": false,
"gzip": false
},
Expand Down
6 changes: 3 additions & 3 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import {
} from './index.js'
import { installDeps, parseDeps } from './deps.js'
import { startRepl } from './repl.js'
import { randomId } from './util.js'
import { randomId, bufToString } from './util.js'
import { createRequire } from './vendor.js'

const EXT = '.mjs'
Expand Down Expand Up @@ -189,7 +189,7 @@ export async function importPath(
filepath: string,
origin = filepath
): Promise<void> {
const contents = await fs.readFile(filepath)
const contents = await fs.readFile(filepath, 'utf8')
const { ext, base, dir } = path.parse(filepath)
const tempFilename = getFilepath(dir, base)

Expand Down Expand Up @@ -224,7 +224,7 @@ export function transformMarkdown(buf: Buffer | string): string {
let state = 'root'
let codeBlockEnd = ''
let prevLineIsEmpty = true
for (const line of buf.toString().split(/\r?\n/)) {
for (const line of bufToString(buf).split(/\r?\n/)) {
switch (state) {
case 'root':
if (tabRe.test(line) && prevLineIsEmpty) {
Expand Down
9 changes: 6 additions & 3 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ import {
log,
isString,
isStringLiteral,
bufToString,
getLast,
noop,
once,
parseBool,
Expand All @@ -64,6 +66,7 @@ export { log, type LogEntry } from './util.js'
const CWD = Symbol('processCwd')
const SYNC = Symbol('syncExec')
const EOL = Buffer.from(_EOL)
const BR_CC = '\n'.charCodeAt(0)
const SIGTERM = 'SIGTERM'
const ENV_PREFIX = 'ZX_'
const storage = new AsyncLocalStorage<Options>()
Expand Down Expand Up @@ -330,8 +333,8 @@ export class ProcessPromise extends Promise<ProcessOutput> {
}

// Ensures EOL
if (stdout.length && !stdout[stdout.length - 1]!.toString().endsWith('\n')) c.on.stdout!(EOL, c)
if (stderr.length && !stderr[stderr.length - 1]!.toString().endsWith('\n')) c.on.stderr!(EOL, c)
if (stdout.length && getLast(getLast(stdout)) !== BR_CC) c.on.stdout!(EOL, c)
if (stderr.length && getLast(getLast(stderr)) !== BR_CC) c.on.stderr!(EOL, c)

$.log({ kind: 'end', signal, exitCode: status, duration, error, verbose: self.isVerbose(), id })
const output = self._output = new ProcessOutput(dto)
Expand Down Expand Up @@ -598,7 +601,7 @@ export class ProcessPromise extends Promise<ProcessOutput> {
async *[Symbol.asyncIterator]() {
let last: string | undefined
const getLines = (chunk: Buffer | string) => {
const lines = ((last || '') + chunk.toString()).split('\n')
const lines = ((last || '') + bufToString(chunk)).split('\n')
last = lines.pop()
return lines
}
Expand Down
4 changes: 2 additions & 2 deletions src/deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ const builtins = new Set([
const nameRe = /^(?<name>(@[a-z\d-~][\w-.~]*\/)?[a-z\d-~][\w-.~]*)\/?.*$/i
const versionRe = /^@(?<version>[~^]?(v?[\dx*]+([-.][\d*a-z-]+)*))/i

export function parseDeps(content: Buffer | string): Record<string, string> {
return depseek(content.toString() + '\n', { comments: true }).reduce<
export function parseDeps(content: string): Record<string, string> {
return depseek(content + '\n', { comments: true }).reduce<
Record<string, string>
>((m, { type, value }, i, list) => {
if (type === 'dep') {
Expand Down
7 changes: 7 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ export function isString(obj: any) {
return typeof obj === 'string'
}

const utf8Decoder = new TextDecoder('utf-8')
export const bufToString = (buf: Buffer | string): string =>
isString(buf) ? buf : utf8Decoder.decode(buf)

export const getLast = <T>(arr: { length: number; [i: number]: any }): T =>
arr[arr.length - 1]

const pad = (v: string) => (v === ' ' ? ' ' : '')

export function preferLocalBin(
Expand Down

0 comments on commit 1ea6303

Please sign in to comment.