Debian Codegraph @

node/argparse/lib/_colorize.js

raw
1 'use strict'
2
3 const ANSIColors = {
4 RESET: '\x1b[0m',
5 BOLD_BLUE: '\x1b[1;34m',
6 BOLD_CYAN: '\x1b[1;36m',
7 BOLD_GREEN: '\x1b[1;32m',
8 BOLD_MAGENTA: '\x1b[1;35m',
9 BOLD_YELLOW: '\x1b[1;33m',
10 CYAN: '\x1b[36m',
11 GREEN: '\x1b[32m',
12 MAGENTA: '\x1b[35m',
13 YELLOW: '\x1b[33m'
14 }
15
16 const argparse = {
17 usage: ANSIColors.BOLD_BLUE,
18 prog: ANSIColors.BOLD_MAGENTA,
19 prog_extra: ANSIColors.MAGENTA,
20 heading: ANSIColors.BOLD_BLUE,
21 summary_long_option: ANSIColors.CYAN,
22 summary_short_option: ANSIColors.GREEN,
23 summary_label: ANSIColors.YELLOW,
24 summary_action: ANSIColors.GREEN,
25 long_option: ANSIColors.BOLD_CYAN,
26 short_option: ANSIColors.BOLD_GREEN,
27 label: ANSIColors.BOLD_YELLOW,
28 action: ANSIColors.BOLD_GREEN,
29 reset: ANSIColors.RESET
30 }
31
32 const default_theme = { argparse }
33 const argparse_no_color = {}
34 for (const name of Object.keys(argparse)) argparse_no_color[name] = ''
35 const theme_no_color = { argparse: argparse_no_color }
36
37 function decolor (text) {
38 for (const code of Object.values(ANSIColors)) {
39 text = text.split(code).join('')
40 }
41 return text
42 }
43
44 function can_colorize (file = undefined) {
45 const getenv = name => {
46 try {
47 return process.env[name]
48 } catch (err) {
49 return undefined
50 }
51 }
52
53 if (getenv('PYTHON_COLORS') === '0') return false
54 if (getenv('PYTHON_COLORS') === '1') return true
55 if (getenv('NO_COLOR')) return false
56 if (getenv('FORCE_COLOR')) return true
57 if (getenv('TERM') === 'dumb') return false
58
59 if (file === undefined) file = process.stdout
60 if (!file) return false
61 if (typeof file.hasColors === 'function') return file.hasColors()
62 return file.isTTY === true
63 }
64
65 function get_theme ({ tty_file, force_color = false, force_no_color = false } = {}) {
66 if (force_color || (!force_no_color && can_colorize(tty_file))) {
67 return default_theme
68 }
69 return theme_no_color
70 }
71
72 module.exports = { can_colorize, decolor, get_theme }