v6
 1// Copyright 2022 Google LLC
 2//
 3// Licensed under the Apache License, Version 2.0 (the "License");
 4// you may not use this file except in compliance with the License.
 5// You may obtain a copy of the License at
 6//
 7//     https://www.apache.org/licenses/LICENSE-2.0
 8//
 9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import { getCtx, getRootCtx } from './context.js'
16import { chalk } from './goods.js'
17import ignore from 'ignore'
18import { asArray } from './util.js'
19
20export function printStd(data: any, err?: any) {
21  if (data) process.stdout.write(data)
22  if (err) process.stderr.write(err)
23}
24
25export function colorize(cmd: string) {
26  return cmd.replace(/^[\w_.-]+(\s|$)/, (substr) => {
27    return chalk.greenBright(substr)
28  })
29}
30
31export function log(
32  opts: {
33    scope: string
34    verbose?: 0 | 1 | 2
35    output?: 'stdout' | 'stderr'
36    raw?: boolean
37  },
38  ...msg: any[]
39) {
40  let { scope, verbose = 1, output, raw } = opts
41  let ctx = getCtx()
42  let {
43    logOutput = output,
44    logFormat = () => msg,
45    logPrint = printStd,
46    logIgnore = [],
47  } = ctx
48  let level = Math.min(+getRootCtx().verbose, +ctx.verbose)
49  if (verbose > level) return
50
51  const ig = ignore().add(logIgnore)
52
53  if (!ig.ignores(scope)) {
54    msg = raw ? msg[0] : asArray(logFormat(msg)).join(' ') + '\n'
55    // @ts-ignore
56    logPrint(...(logOutput === 'stderr' ? [null, msg] : [msg]))
57  }
58}
59
60export function printCmd(cmd: string): void {
61  if (/\n/.test(cmd)) {
62    log(
63      { scope: 'cmd' },
64      cmd
65        .split('\n')
66        .map((line, i) => (i === 0 ? '$' : '>') + ' ' + colorize(line))
67        .join('\n')
68    )
69  } else {
70    log({ scope: 'cmd' }, '$', colorize(cmd))
71  }
72}