Skip to content

Commit

Permalink
fix: avoid ansi escape codes in non-tty and no color output
Browse files Browse the repository at this point in the history
  • Loading branch information
Jahed Ahmed committed Feb 24, 2021
1 parent 5391431 commit 2a9eea9
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/cli/commands/help.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
import * as fs from 'fs';
import * as path from 'path';
import stripAnsi from 'strip-ansi';

const DEFAULT_HELP = 'snyk';

function readHelpFile(filename: string): string {
const file = fs.readFileSync(filename, 'utf8');
if (typeof process.env.NO_COLOR !== 'undefined' || !process.stdout.isTTY) {
return stripAnsi(file);
}
return file;
}

export = async function help(item: string | boolean) {
if (!item || item === true || typeof item !== 'string' || item === 'help') {
item = DEFAULT_HELP;
Expand All @@ -18,13 +27,13 @@ export = async function help(item: string | boolean) {
'../../../help/commands-txt',
item === DEFAULT_HELP ? DEFAULT_HELP + '.txt' : `snyk-${item}.txt`,
);
return fs.readFileSync(filename, 'utf8');
return readHelpFile(filename);
} catch (error) {
const filename = path.resolve(
__dirname,
'../../../help/commands-txt',
DEFAULT_HELP + '.txt',
);
return fs.readFileSync(filename, 'utf8');
return readHelpFile(filename);
}
};
24 changes: 24 additions & 0 deletions test/smoke/spec/snyk_basic_spec.sh
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,30 @@ Describe "Snyk CLI basics"
# TODO: unusable with our current docker issues
The stderr should equal ""
End

Describe "prints help info without ascii escape sequences"
It "has NO_COLOR set"
snyk_help_no_color() {
NO_COLOR='' snyk help
}

When run snyk_help_no_color
The output should not include "[1mN"
The output should not include "[0m"
The output should not include "[4mC"
End

It "is not tty"
snyk_help_no_tty() {
snyk help | cat
}

When run snyk_help_no_tty
The output should not include "[1mN"
The output should not include "[0m"
The output should not include "[4mC"
End
End
End

Describe "snyk config"
Expand Down

0 comments on commit 2a9eea9

Please sign in to comment.