[Pkg-javascript-commits] [node-chalk] 02/07: New upstream version 2.1.0

Praveen Arimbrathodiyil praveen at moszumanska.debian.org
Fri Sep 8 13:37:58 UTC 2017


This is an automated email from the git hooks/post-receive script.

praveen pushed a commit to branch master
in repository node-chalk.

commit 545e57c3b2c28a330d507ae248fbe3145feae1c8
Author: Pirate Praveen <praveen at debian.org>
Date:   Fri Sep 8 12:57:33 2017 +0530

    New upstream version 2.1.0
---
 .editorconfig            |   5 +-
 .gitattributes           |   1 +
 .gitignore               |   1 +
 .npmrc                   |   1 +
 .travis.yml              |   7 +-
 benchmark.js             |  14 +--
 code-of-conduct.md       |  74 ++++++++++++++
 contributing.md          |   3 +
 examples/rainbow.js      |  38 +++++++
 examples/screenshot.js   |  18 ++++
 index.js                 | 228 ++++++++++++++++++++++++++++++------------
 license                  |  20 +---
 package.json             | 129 ++++++++++++------------
 readme.md                | 253 ++++++++++++++++++++++++++++++++---------------
 templates.js             | 128 ++++++++++++++++++++++++
 test.js                  | 157 -----------------------------
 test/_fixture.js         |   4 +
 test/_supports-color.js  |  13 +++
 test/chalk.js            | 100 +++++++++++++++++++
 test/constructor.js      |  22 +++++
 test/enabled.js          |  35 +++++++
 test/level.js            |  44 +++++++++
 test/template-literal.js | 169 +++++++++++++++++++++++++++++++
 test/windows.js          |  63 ++++++++++++
 24 files changed, 1129 insertions(+), 398 deletions(-)

diff --git a/.editorconfig b/.editorconfig
index 8f9d77e..1c6314a 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -7,9 +7,6 @@ charset = utf-8
 trim_trailing_whitespace = true
 insert_final_newline = true
 
-[{package.json,*.yml}]
+[*.yml]
 indent_style = space
 indent_size = 2
-
-[*.md]
-trim_trailing_whitespace = false
diff --git a/.gitattributes b/.gitattributes
index 176a458..391f0a4 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1 +1,2 @@
 * text=auto
+*.js text eol=lf
diff --git a/.gitignore b/.gitignore
index 1fd04da..6bff314 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
 node_modules
+yarn.lock
 coverage
 .nyc_output
diff --git a/.npmrc b/.npmrc
new file mode 100644
index 0000000..43c97e7
--- /dev/null
+++ b/.npmrc
@@ -0,0 +1 @@
+package-lock=false
diff --git a/.travis.yml b/.travis.yml
index 3da5271..ea5900d 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,7 +1,6 @@
-sudo: false
 language: node_js
 node_js:
-  - 'iojs'
-  - '0.12'
-  - '0.10'
+  - '8'
+  - '6'
+  - '4'
 after_success: npm run coveralls
diff --git a/benchmark.js b/benchmark.js
index 5c26a87..af90c06 100644
--- a/benchmark.js
+++ b/benchmark.js
@@ -1,24 +1,24 @@
 /* globals set bench */
 'use strict';
-var chalk = require('./');
+const chalk = require('.');
 
-suite('chalk', function () {
+suite('chalk', () => {
 	set('iterations', 100000);
 
-	bench('single style', function () {
+	bench('single style', () => {
 		chalk.red('the fox jumps over the lazy dog');
 	});
 
-	bench('several styles', function () {
+	bench('several styles', () => {
 		chalk.blue.bgRed.bold('the fox jumps over the lazy dog');
 	});
 
-	var cached = chalk.blue.bgRed.bold;
-	bench('cached styles', function () {
+	const cached = chalk.blue.bgRed.bold;
+	bench('cached styles', () => {
 		cached('the fox jumps over the lazy dog');
 	});
 
-	bench('nested styles', function () {
+	bench('nested styles', () => {
 		chalk.red('the fox jumps', chalk.underline.bgBlue('over the lazy dog') + '!');
 	});
 });
diff --git a/code-of-conduct.md b/code-of-conduct.md
new file mode 100644
index 0000000..a7c7db8
--- /dev/null
+++ b/code-of-conduct.md
@@ -0,0 +1,74 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as
+contributors and maintainers pledge to making participation in our project and
+our community a harassment-free experience for everyone, regardless of age, body
+size, disability, ethnicity, gender identity and expression, level of experience,
+nationality, personal appearance, race, religion, or sexual identity and
+orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment
+include:
+
+* Using welcoming and inclusive language
+* Being respectful of differing viewpoints and experiences
+* Gracefully accepting constructive criticism
+* Focusing on what is best for the community
+* Showing empathy towards other community members
+
+Examples of unacceptable behavior by participants include:
+
+* The use of sexualized language or imagery and unwelcome sexual attention or
+advances
+* Trolling, insulting/derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or electronic
+  address, without explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+  professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable
+behavior and are expected to take appropriate and fair corrective action in
+response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or
+reject comments, commits, code, wiki edits, issues, and other contributions
+that are not aligned to this Code of Conduct, or to ban temporarily or
+permanently any contributor for other behaviors that they deem inappropriate,
+threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies both within project spaces and in public spaces
+when an individual is representing the project or its community. Examples of
+representing a project or community include using an official project e-mail
+address, posting via an official social media account, or acting as an appointed
+representative at an online or offline event. Representation of a project may be
+further defined and clarified by project maintainers.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported by contacting the project team at sindresorhus at gmail.com. All
+complaints will be reviewed and investigated and will result in a response that
+is deemed necessary and appropriate to the circumstances. The project team is
+obligated to maintain confidentiality with regard to the reporter of an incident.
+Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good
+faith may face temporary or permanent repercussions as determined by other
+members of the project's leadership.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
+available at [http://contributor-covenant.org/version/1/4][version]
+
+[homepage]: http://contributor-covenant.org
+[version]: http://contributor-covenant.org/version/1/4/
diff --git a/contributing.md b/contributing.md
new file mode 100644
index 0000000..28bfd4b
--- /dev/null
+++ b/contributing.md
@@ -0,0 +1,3 @@
+# Contributing to Chalk
+
+Please note that this project is released with a [Contributor Code of Conduct](code-of-conduct.md). By participating in this project you agree to abide by its terms.
diff --git a/examples/rainbow.js b/examples/rainbow.js
new file mode 100644
index 0000000..a4a2e0a
--- /dev/null
+++ b/examples/rainbow.js
@@ -0,0 +1,38 @@
+'use strict';
+const chalk = require('..');
+
+const ignoreChars = /[^!-~]/;
+
+function rainbow(str, offset) {
+	if (!str || str.length === 0) {
+		return str;
+	}
+
+	const hueStep = 360 / str.replace(ignoreChars, '').length;
+
+	let hue = offset % 360;
+	const chars = [];
+	for (const c of str) {
+		if (c.match(ignoreChars)) {
+			chars.push(c);
+		} else {
+			chars.push(chalk.hsl(hue, 100, 50)(c));
+			hue = (hue + hueStep) % 360;
+		}
+	}
+
+	return chars.join('');
+}
+
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+
+async function animateString(str) {
+	console.log();
+	for (let i = 0; i < 360 * 5; i++) {
+		console.log('\u001B[1F\u001B[G ', rainbow(str, i));
+		await sleep(2); // eslint-disable-line no-await-in-loop
+	}
+}
+
+console.log();
+animateString('We hope you enjoy the new version of Chalk 2! <3').then(() => console.log());
diff --git a/examples/screenshot.js b/examples/screenshot.js
new file mode 100644
index 0000000..7d195a6
--- /dev/null
+++ b/examples/screenshot.js
@@ -0,0 +1,18 @@
+'use strict';
+const chalk = require('..');
+const styles = require('ansi-styles');
+
+// Generates screenshot
+for (const key of Object.keys(styles)) {
+	let ret = key;
+
+	if (key === 'reset' || key === 'hidden' || key === 'grey') {
+		continue;
+	}
+
+	if (/^bg[^B]/.test(key)) {
+		ret = chalk.black(ret);
+	}
+
+	process.stdout.write(chalk[key](ret) + ' ');
+}
diff --git a/index.js b/index.js
index 2d85a91..4c81d6d 100644
--- a/index.js
+++ b/index.js
@@ -1,116 +1,220 @@
 'use strict';
-var escapeStringRegexp = require('escape-string-regexp');
-var ansiStyles = require('ansi-styles');
-var stripAnsi = require('strip-ansi');
-var hasAnsi = require('has-ansi');
-var supportsColor = require('supports-color');
-var defineProps = Object.defineProperties;
-var isSimpleWindowsTerm = process.platform === 'win32' && !/^xterm/i.test(process.env.TERM);
+const escapeStringRegexp = require('escape-string-regexp');
+const ansiStyles = require('ansi-styles');
+const supportsColor = require('supports-color');
+
+const template = require('./templates.js');
+
+const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');
+
+// `supportsColor.level` → `ansiStyles.color[name]` mapping
+const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
+
+// `color-convert` models to exclude from the Chalk API due to conflicts and such
+const skipModels = new Set(['gray']);
+
+const styles = Object.create(null);
+
+function applyOptions(obj, options) {
+	options = options || {};
+
+	// Detect level if not set manually
+	const scLevel = supportsColor ? supportsColor.level : 0;
+	obj.level = options.level === undefined ? scLevel : options.level;
+	obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
+}
 
 function Chalk(options) {
-	// detect mode if not set manually
-	this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled;
+	// We check for this.template here since calling `chalk.constructor()`
+	// by itself will have a `this` of a previously constructed chalk object
+	if (!this || !(this instanceof Chalk) || this.template) {
+		const chalk = {};
+		applyOptions(chalk, options);
+
+		chalk.template = function () {
+			const args = [].slice.call(arguments);
+			return chalkTag.apply(null, [chalk.template].concat(args));
+		};
+
+		Object.setPrototypeOf(chalk, Chalk.prototype);
+		Object.setPrototypeOf(chalk.template, chalk);
+
+		chalk.template.constructor = Chalk;
+
+		return chalk.template;
+	}
+
+	applyOptions(this, options);
 }
 
-// use bright blue on Windows as the normal blue color is illegible
+// Use bright blue on Windows as the normal blue color is illegible
 if (isSimpleWindowsTerm) {
-	ansiStyles.blue.open = '\u001b[94m';
+	ansiStyles.blue.open = '\u001B[94m';
 }
 
-var styles = (function () {
-	var ret = {};
+for (const key of Object.keys(ansiStyles)) {
+	ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
 
-	Object.keys(ansiStyles).forEach(function (key) {
-		ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
+	styles[key] = {
+		get() {
+			const codes = ansiStyles[key];
+			return build.call(this, this._styles ? this._styles.concat(codes) : [codes], key);
+		}
+	};
+}
 
-		ret[key] = {
-			get: function () {
-				return build.call(this, this._styles.concat(key));
-			}
-		};
-	});
+ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
+for (const model of Object.keys(ansiStyles.color.ansi)) {
+	if (skipModels.has(model)) {
+		continue;
+	}
+
+	styles[model] = {
+		get() {
+			const level = this.level;
+			return function () {
+				const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
+				const codes = {
+					open,
+					close: ansiStyles.color.close,
+					closeRe: ansiStyles.color.closeRe
+				};
+				return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model);
+			};
+		}
+	};
+}
 
-	return ret;
-})();
+ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
+for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
+	if (skipModels.has(model)) {
+		continue;
+	}
+
+	const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
+	styles[bgModel] = {
+		get() {
+			const level = this.level;
+			return function () {
+				const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
+				const codes = {
+					open,
+					close: ansiStyles.bgColor.close,
+					closeRe: ansiStyles.bgColor.closeRe
+				};
+				return build.call(this, this._styles ? this._styles.concat(codes) : [codes], model);
+			};
+		}
+	};
+}
 
-var proto = defineProps(function chalk() {}, styles);
+const proto = Object.defineProperties(() => {}, styles);
 
-function build(_styles) {
-	var builder = function () {
+function build(_styles, key) {
+	const builder = function () {
 		return applyStyle.apply(builder, arguments);
 	};
 
 	builder._styles = _styles;
-	builder.enabled = this.enabled;
-	// __proto__ is used because we must return a function, but there is
-	// no way to create a function with a different prototype.
-	/* eslint-disable no-proto */
-	builder.__proto__ = proto;
+
+	const self = this;
+
+	Object.defineProperty(builder, 'level', {
+		enumerable: true,
+		get() {
+			return self.level;
+		},
+		set(level) {
+			self.level = level;
+		}
+	});
+
+	Object.defineProperty(builder, 'enabled', {
+		enumerable: true,
+		get() {
+			return self.enabled;
+		},
+		set(enabled) {
+			self.enabled = enabled;
+		}
+	});
+
+	// See below for fix regarding invisible grey/dim combination on Windows
+	builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';
+
+	// `__proto__` is used because we must return a function, but there is
+	// no way to create a function with a different prototype
+	builder.__proto__ = proto; // eslint-disable-line no-proto
 
 	return builder;
 }
 
 function applyStyle() {
-	// support varags, but simply cast to string in case there's only one arg
-	var args = arguments;
-	var argsLen = args.length;
-	var str = argsLen !== 0 && String(arguments[0]);
+	// Support varags, but simply cast to string in case there's only one arg
+	const args = arguments;
+	const argsLen = args.length;
+	let str = String(arguments[0]);
+
+	if (argsLen === 0) {
+		return '';
+	}
 
 	if (argsLen > 1) {
-		// don't slice `arguments`, it prevents v8 optimizations
-		for (var a = 1; a < argsLen; a++) {
+		// Don't slice `arguments`, it prevents V8 optimizations
+		for (let a = 1; a < argsLen; a++) {
 			str += ' ' + args[a];
 		}
 	}
 
-	if (!this.enabled || !str) {
+	if (!this.enabled || this.level <= 0 || !str) {
 		return str;
 	}
 
-	var nestedStyles = this._styles;
-	var i = nestedStyles.length;
-
 	// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
 	// see https://github.com/chalk/chalk/issues/58
 	// If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
-	var originalDim = ansiStyles.dim.open;
-	if (isSimpleWindowsTerm && (nestedStyles.indexOf('gray') !== -1 || nestedStyles.indexOf('grey') !== -1)) {
+	const originalDim = ansiStyles.dim.open;
+	if (isSimpleWindowsTerm && this.hasGrey) {
 		ansiStyles.dim.open = '';
 	}
 
-	while (i--) {
-		var code = ansiStyles[nestedStyles[i]];
-
+	for (const code of this._styles.slice().reverse()) {
 		// Replace any instances already present with a re-opening code
 		// otherwise only the part of the string until said closing code
 		// will be colored, and the rest will simply be 'plain'.
 		str = code.open + str.replace(code.closeRe, code.open) + code.close;
+
+		// Close the styling before a linebreak and reopen
+		// after next line to fix a bleed issue on macOS
+		// https://github.com/chalk/chalk/pull/92
+		str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
 	}
 
-	// Reset the original 'dim' if we changed it to work around the Windows dimmed gray issue.
+	// Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
 	ansiStyles.dim.open = originalDim;
 
 	return str;
 }
 
-function init() {
-	var ret = {};
+function chalkTag(chalk, strings) {
+	if (!Array.isArray(strings)) {
+		// If chalk() was called by itself or with a string,
+		// return the string itself as a string.
+		return [].slice.call(arguments, 1).join(' ');
+	}
 
-	Object.keys(styles).forEach(function (name) {
-		ret[name] = {
-			get: function () {
-				return build.call(this, [name]);
-			}
-		};
-	});
+	const args = [].slice.call(arguments, 2);
+	const parts = [strings.raw[0]];
+
+	for (let i = 1; i < strings.length; i++) {
+		parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
+		parts.push(String(strings.raw[i]));
+	}
 
-	return ret;
+	return template(chalk, parts.join(''));
 }
 
-defineProps(Chalk.prototype, init());
+Object.defineProperties(Chalk.prototype, styles);
 
-module.exports = new Chalk();
-module.exports.styles = ansiStyles;
-module.exports.hasColor = hasAnsi;
-module.exports.stripColor = stripAnsi;
+module.exports = Chalk(); // eslint-disable-line new-cap
 module.exports.supportsColor = supportsColor;
diff --git a/license b/license
index 654d0bf..e7af2f7 100644
--- a/license
+++ b/license
@@ -1,21 +1,9 @@
-The MIT License (MIT)
+MIT License
 
 Copyright (c) Sindre Sorhus <sindresorhus at gmail.com> (sindresorhus.com)
 
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/package.json b/package.json
index 2b5881e..a257127 100644
--- a/package.json
+++ b/package.json
@@ -1,70 +1,63 @@
 {
-  "name": "chalk",
-  "version": "1.1.3",
-  "description": "Terminal string styling done right. Much color.",
-  "license": "MIT",
-  "repository": "chalk/chalk",
-  "maintainers": [
-    "Sindre Sorhus <sindresorhus at gmail.com> (sindresorhus.com)",
-    "Joshua Appelman <jappelman at xebia.com> (jbnicolai.com)",
-    "JD Ballard <i.am.qix at gmail.com> (github.com/qix-)"
-  ],
-  "engines": {
-    "node": ">=0.10.0"
-  },
-  "scripts": {
-    "test": "xo && mocha",
-    "bench": "matcha benchmark.js",
-    "coverage": "nyc npm test && nyc report",
-    "coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls"
-  },
-  "files": [
-    "index.js"
-  ],
-  "keywords": [
-    "color",
-    "colour",
-    "colors",
-    "terminal",
-    "console",
-    "cli",
-    "string",
-    "str",
-    "ansi",
-    "style",
-    "styles",
-    "tty",
-    "formatting",
-    "rgb",
-    "256",
-    "shell",
-    "xterm",
-    "log",
-    "logging",
-    "command-line",
-    "text"
-  ],
-  "dependencies": {
-    "ansi-styles": "^2.2.1",
-    "escape-string-regexp": "^1.0.2",
-    "has-ansi": "^2.0.0",
-    "strip-ansi": "^3.0.0",
-    "supports-color": "^2.0.0"
-  },
-  "devDependencies": {
-    "coveralls": "^2.11.2",
-    "matcha": "^0.6.0",
-    "mocha": "*",
-    "nyc": "^3.0.0",
-    "require-uncached": "^1.0.2",
-    "resolve-from": "^1.0.0",
-    "semver": "^4.3.3",
-    "xo": "*"
-  },
-  "xo": {
-    "envs": [
-      "node",
-      "mocha"
-    ]
-  }
+	"name": "chalk",
+	"version": "2.1.0",
+	"description": "Terminal string styling done right",
+	"license": "MIT",
+	"repository": "chalk/chalk",
+	"engines": {
+		"node": ">=4"
+	},
+	"scripts": {
+		"test": "xo && nyc ava",
+		"bench": "matcha benchmark.js",
+		"coveralls": "nyc report --reporter=text-lcov | coveralls"
+	},
+	"files": [
+		"index.js",
+		"templates.js"
+	],
+	"keywords": [
+		"color",
+		"colour",
+		"colors",
+		"terminal",
+		"console",
+		"cli",
+		"string",
+		"str",
+		"ansi",
+		"style",
+		"styles",
+		"tty",
+		"formatting",
+		"rgb",
+		"256",
+		"shell",
+		"xterm",
+		"log",
+		"logging",
+		"command-line",
+		"text"
+	],
+	"dependencies": {
+		"ansi-styles": "^3.1.0",
+		"escape-string-regexp": "^1.0.5",
+		"supports-color": "^4.0.0"
+	},
+	"devDependencies": {
+		"ava": "*",
+		"coveralls": "^2.11.2",
+		"execa": "^0.7.0",
+		"import-fresh": "^2.0.0",
+		"matcha": "^0.7.0",
+		"nyc": "^11.0.2",
+		"resolve-from": "^3.0.0",
+		"xo": "*"
+	},
+	"xo": {
+		"envs": [
+			"node",
+			"mocha"
+		]
+	}
 }
diff --git a/readme.md b/readme.md
index 5cf111e..dfcfdf2 100644
--- a/readme.md
+++ b/readme.md
@@ -1,7 +1,7 @@
 <h1 align="center">
 	<br>
 	<br>
-	<img width="360" src="https://cdn.rawgit.com/chalk/chalk/19935d6484811c5e468817f846b7b3d417d7bf4a/logo.svg" alt="chalk">
+	<img width="320" src="https://cdn.rawgit.com/chalk/chalk/19935d6484811c5e468817f846b7b3d417d7bf4a/logo.svg" alt="chalk">
 	<br>
 	<br>
 	<br>
@@ -9,81 +9,104 @@
 
 > Terminal string styling done right
 
-[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk)
-[![Coverage Status](https://coveralls.io/repos/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/r/chalk/chalk?branch=master)
-[![](http://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4)
+[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)
 
-
-[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68). Although there are other ones, they either do too much or not enough.
-
-**Chalk is a clean and focused alternative.**
+### [See what's new in Chalk 2](https://github.com/chalk/chalk/releases/tag/v2.0.0)
 
 ![](https://github.com/chalk/ansi-styles/raw/master/screenshot.png)
 
 
-## Why
+## Highlights
 
-- Highly performant
-- Doesn't extend `String.prototype`
 - Expressive API
+- Highly performant
 - Ability to nest styles
-- Clean and focused
+- [256/Truecolor color support](#256-and-truecolor-color-support)
 - Auto-detects color support
+- Doesn't extend `String.prototype`
+- Clean and focused
 - Actively maintained
-- [Used by ~4500 modules](https://www.npmjs.com/browse/depended/chalk) as of July 15, 2015
+- [Used by ~17,000 packages](https://www.npmjs.com/browse/depended/chalk) as of June 20th, 2017
 
 
 ## Install
 
-```
-$ npm install --save chalk
+```console
+$ npm install chalk
 ```
 
 
 ## Usage
 
+```js
+const chalk = require('chalk');
+
+console.log(chalk.blue('Hello world!'));
+```
+
 Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
 
 ```js
-var chalk = require('chalk');
-
-// style a string
-chalk.blue('Hello world!');
+const chalk = require('chalk');
+const log = console.log;
 
-// combine styled and normal strings
-chalk.blue('Hello') + 'World' + chalk.red('!');
+// Combine styled and normal strings
+log(chalk.blue('Hello') + 'World' + chalk.red('!'));
 
-// compose multiple styles using the chainable API
-chalk.blue.bgRed.bold('Hello world!');
+// Compose multiple styles using the chainable API
+log(chalk.blue.bgRed.bold('Hello world!'));
 
-// pass in multiple arguments
-chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz');
+// Pass in multiple arguments
+log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
 
-// nest styles
-chalk.red('Hello', chalk.underline.bgBlue('world') + '!');
+// Nest styles
+log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
 
-// nest styles of the same type even (color, underline, background)
-chalk.green(
+// Nest styles of the same type even (color, underline, background)
+log(chalk.green(
 	'I am a green line ' +
 	chalk.blue.underline.bold('with a blue substring') +
 	' that becomes green again!'
-);
+));
+
+// ES2015 template literal
+log(`
+CPU: ${chalk.red('90%')}
+RAM: ${chalk.green('40%')}
+DISK: ${chalk.yellow('70%')}
+`);
+
+// ES2015 tagged template literal
+log(chalk`
+CPU: {red ${cpu.totalPercent}%}
+RAM: {green ${ram.used / ram.total * 100}%}
+DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
+`);
+
+// Use RGB colors in terminal emulators that support it.
+log(chalk.keyword('orange')('Yay for orange colored text!'));
+log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
+log(chalk.hex('#DEADED').bold('Bold gray!'));
 ```
 
-Easily define your own themes.
+Easily define your own themes:
 
 ```js
-var chalk = require('chalk');
-var error = chalk.bold.red;
+const chalk = require('chalk');
+
+const error = chalk.bold.red;
+const warning = chalk.keyword('orange');
+
 console.log(error('Error!'));
+console.log(warning('Warning!'));
 ```
 
-Take advantage of console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data).
+Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):
 
 ```js
-var name = 'Sindre';
+const name = 'Sindre';
 console.log(chalk.green('Hello %s'), name);
-//=> Hello Sindre
+//=> 'Hello Sindre'
 ```
 
 
@@ -93,61 +116,46 @@ console.log(chalk.green('Hello %s'), name);
 
 Example: `chalk.red.bold.underline('Hello', 'world');`
 
-Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `Chalk.red.yellow.green` is equivalent to `Chalk.green`.
+Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
 
 Multiple arguments will be separated by space.
 
 ### chalk.enabled
 
-Color support is automatically detected, but you can override it by setting the `enabled` property. You should however only do this in your own code as it applies globally to all chalk consumers.
+Color support is automatically detected, as is the level (see `chalk.level`). However, if you'd like to simply enable/disable Chalk, you can do so via the `.enabled` property.
+
+Chalk is enabled by default unless expicitly disabled via the constructor or `chalk.level` is `0`.
 
-If you need to change this in a reusable module create a new instance:
+If you need to change this in a reusable module, create a new instance:
 
 ```js
-var ctx = new chalk.constructor({enabled: false});
+const ctx = new chalk.constructor({enabled: false});
 ```
 
-### chalk.supportsColor
-
-Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
-
-Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add an environment variable `FORCE_COLOR` with any value to force color. Trumps `--no-color`.
-
-### chalk.styles
+### chalk.level
 
-Exposes the styles as [ANSI escape codes](https://github.com/chalk/ansi-styles).
+Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers.
 
-Generally not useful, but you might need just the `.open` or `.close` escape code if you're mixing externally styled strings with your own.
+If you need to change this in a reusable module, create a new instance:
 
 ```js
-var chalk = require('chalk');
-
-console.log(chalk.styles.red);
-//=> {open: '\u001b[31m', close: '\u001b[39m'}
-
-console.log(chalk.styles.red.open + 'Hello' + chalk.styles.red.close);
+const ctx = new chalk.constructor({level: 0});
 ```
 
-### chalk.hasColor(string)
-
-Check whether a string [has color](https://github.com/chalk/has-ansi).
-
-### chalk.stripColor(string)
+Levels are as follows:
 
-[Strip color](https://github.com/chalk/strip-ansi) from a string.
+0. All colors disabled
+1. Basic color support (16 colors)
+2. 256 color support
+3. Truecolor support (16 million colors)
 
-Can be useful in combination with `.supportsColor` to strip color on externally styled text when it's not supported.
+### chalk.supportsColor
 
-Example:
+Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
 
-```js
-var chalk = require('chalk');
-var styledString = getText();
+Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add the environment variable `FORCE_COLOR=1` to forcefully enable color or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
 
-if (!chalk.supportsColor) {
-	styledString = chalk.stripColor(styledString);
-}
-```
+Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
 
 
 ## Styles
@@ -157,11 +165,11 @@ if (!chalk.supportsColor) {
 - `reset`
 - `bold`
 - `dim`
-- `italic` *(not widely supported)*
+- `italic` *(Not widely supported)*
 - `underline`
 - `inverse`
 - `hidden`
-- `strikethrough` *(not widely supported)*
+- `strikethrough` *(Not widely supported)*
 
 ### Colors
 
@@ -169,11 +177,18 @@ if (!chalk.supportsColor) {
 - `red`
 - `green`
 - `yellow`
-- `blue` *(on Windows the bright version is used as normal blue is illegible)*
+- `blue` *(On Windows the bright version is used since normal blue is illegible)*
 - `magenta`
 - `cyan`
 - `white`
-- `gray`
+- `gray` ("bright black")
+- `redBright`
+- `greenBright`
+- `yellowBright`
+- `blueBright`
+- `magentaBright`
+- `cyanBright`
+- `whiteBright`
 
 ### Background colors
 
@@ -185,29 +200,107 @@ if (!chalk.supportsColor) {
 - `bgMagenta`
 - `bgCyan`
 - `bgWhite`
+- `bgBlackBright`
+- `bgRedBright`
+- `bgGreenBright`
+- `bgYellowBright`
+- `bgBlueBright`
+- `bgMagentaBright`
+- `bgCyanBright`
+- `bgWhiteBright`
+
+
+## Tagged template literal
+
+Chalk can be used as a [tagged template literal](http://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).
+
+```js
+const chalk = require('chalk');
+
+const miles = 18;
+const calculateFeet = miles => miles * 5280;
+
+console.log(chalk`
+  There are {bold 5280 feet} in a mile.
+  In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
+`);
+```
+
+Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`).
+
+Template styles are chained exactly like normal Chalk styles. The following two statements are equivalent:
+
+```js
+console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
+console.log(chalk`{bold.rgb(10,100,200) Hello!}`);
+```
+
+Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters.
 
+All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.
 
-## 256-colors
 
-Chalk does not support anything other than the base eight colors, which guarantees it will work on all terminals and systems. Some terminals, specifically `xterm` compliant ones, will support the full range of 8-bit colors. For this the lower level [ansi-256-colors](https://github.com/jbnicolai/ansi-256-colors) package can be used.
+## 256 and Truecolor color support
+
+Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps.
+
+Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).
+
+Examples:
+
+- `chalk.hex('#DEADED').underline('Hello, world!')`
+- `chalk.keyword('orange')('Some orange text')`
+- `chalk.rgb(15, 100, 204).inverse('Hello!')`
+
+Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors).
+
+- `chalk.bgHex('#DEADED').underline('Hello, world!')`
+- `chalk.bgKeyword('orange')('Some orange text')`
+- `chalk.bgRgb(15, 100, 204).inverse('Hello!')`
+
+The following color models can be used:
+
+- [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')`
+- [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')`
+- [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')`
+- [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')`
+- [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 1, 1).bold('Orange!')`
+- [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model)  - Example: `chalk.hsl(32, 0, 50).bold('Orange!')`
+- `ansi16`
+- `ansi256`
 
 
 ## Windows
 
-If you're on Windows, do yourself a favor and use [`cmder`](http://bliker.github.io/cmder/) instead of `cmd.exe`.
+If you're on Windows, do yourself a favor and use [`cmder`](http://cmder.net/) instead of `cmd.exe`.
+
+
+## Origin story
+
+[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.
 
 
 ## Related
 
 - [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
-- [ansi-styles](https://github.com/chalk/ansi-styles/) - ANSI escape codes for styling strings in the terminal
-- [supports-color](https://github.com/chalk/supports-color/) - Detect whether a terminal supports color
+- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
+- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
 - [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
 - [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
 - [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
 - [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
+- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
+- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
+- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal
+- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings
+
+
+## Maintainers
+
+- [Sindre Sorhus](https://github.com/sindresorhus)
+- [Josh Junon](https://github.com/qix-)
 
 
 ## License
 
-MIT © [Sindre Sorhus](http://sindresorhus.com)
+MIT
diff --git a/templates.js b/templates.js
new file mode 100644
index 0000000..1015515
--- /dev/null
+++ b/templates.js
@@ -0,0 +1,128 @@
+'use strict';
+const TEMPLATE_REGEX = /(?:\\(u[a-f0-9]{4}|x[a-f0-9]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
+const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
+const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
+const ESCAPE_REGEX = /\\(u[0-9a-f]{4}|x[0-9a-f]{2}|.)|([^\\])/gi;
+
+const ESCAPES = {
+	n: '\n',
+	r: '\r',
+	t: '\t',
+	b: '\b',
+	f: '\f',
+	v: '\v',
+	0: '\0',
+	'\\': '\\',
+	e: '\u001b',
+	a: '\u0007'
+};
+
+function unescape(c) {
+	if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
+		return String.fromCharCode(parseInt(c.slice(1), 16));
+	}
+
+	return ESCAPES[c] || c;
+}
+
+function parseArguments(name, args) {
+	const results = [];
+	const chunks = args.trim().split(/\s*,\s*/g);
+	let matches;
+
+	for (const chunk of chunks) {
+		if (!isNaN(chunk)) {
+			results.push(Number(chunk));
+		} else if ((matches = chunk.match(STRING_REGEX))) {
+			results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
+		} else {
+			throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
+		}
+	}
+
+	return results;
+}
+
+function parseStyle(style) {
+	STYLE_REGEX.lastIndex = 0;
+
+	const results = [];
+	let matches;
+
+	while ((matches = STYLE_REGEX.exec(style)) !== null) {
+		const name = matches[1];
+
+		if (matches[2]) {
+			const args = parseArguments(name, matches[2]);
+			results.push([name].concat(args));
+		} else {
+			results.push([name]);
+		}
+	}
+
+	return results;
+}
+
+function buildStyle(chalk, styles) {
+	const enabled = {};
+
+	for (const layer of styles) {
+		for (const style of layer.styles) {
+			enabled[style[0]] = layer.inverse ? null : style.slice(1);
+		}
+	}
+
+	let current = chalk;
+	for (const styleName of Object.keys(enabled)) {
+		if (Array.isArray(enabled[styleName])) {
+			if (!(styleName in current)) {
+				throw new Error(`Unknown Chalk style: ${styleName}`);
+			}
+
+			if (enabled[styleName].length > 0) {
+				current = current[styleName].apply(current, enabled[styleName]);
+			} else {
+				current = current[styleName];
+			}
+		}
+	}
+
+	return current;
+}
+
+module.exports = (chalk, tmp) => {
+	const styles = [];
+	const chunks = [];
+	let chunk = [];
+
+	// eslint-disable-next-line max-params
+	tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
+		if (escapeChar) {
+			chunk.push(unescape(escapeChar));
+		} else if (style) {
+			const str = chunk.join('');
+			chunk = [];
+			chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
+			styles.push({inverse, styles: parseStyle(style)});
+		} else if (close) {
+			if (styles.length === 0) {
+				throw new Error('Found extraneous } in Chalk template literal');
+			}
+
+			chunks.push(buildStyle(chalk, styles)(chunk.join('')));
+			chunk = [];
+			styles.pop();
+		} else {
+			chunk.push(chr);
+		}
+	});
+
+	chunks.push(chunk.join(''));
+
+	if (styles.length > 0) {
+		const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
+		throw new Error(errMsg);
+	}
+
+	return chunks.join('');
+};
diff --git a/test.js b/test.js
deleted file mode 100644
index 1e6d75e..0000000
--- a/test.js
+++ /dev/null
@@ -1,157 +0,0 @@
-'use strict';
-var assert = require('assert');
-var requireUncached = require('require-uncached');
-var resolveFrom = require('resolve-from');
-var semver = require('semver');
-var chalk = require('./');
-
-describe('chalk', function () {
-	it('should style string', function () {
-		assert.equal(chalk.underline('foo'), '\u001b[4mfoo\u001b[24m');
-		assert.equal(chalk.red('foo'), '\u001b[31mfoo\u001b[39m');
-		assert.equal(chalk.bgRed('foo'), '\u001b[41mfoo\u001b[49m');
-	});
-
-	it('should support applying multiple styles at once', function () {
-		assert.equal(chalk.red.bgGreen.underline('foo'), '\u001b[31m\u001b[42m\u001b[4mfoo\u001b[24m\u001b[49m\u001b[39m');
-		assert.equal(chalk.underline.red.bgGreen('foo'), '\u001b[4m\u001b[31m\u001b[42mfoo\u001b[49m\u001b[39m\u001b[24m');
-	});
-
-	it('should support nesting styles', function () {
-		assert.equal(
-			chalk.red('foo' + chalk.underline.bgBlue('bar') + '!'),
-			'\u001b[31mfoo\u001b[4m\u001b[44mbar\u001b[49m\u001b[24m!\u001b[39m'
-		);
-	});
-
-	it('should support nesting styles of the same type (color, underline, bg)', function () {
-		assert.equal(
-			chalk.red('a' + chalk.yellow('b' + chalk.green('c') + 'b') + 'c'),
-			'\u001b[31ma\u001b[33mb\u001b[32mc\u001b[33mb\u001b[31mc\u001b[39m'
-		);
-	});
-
-	it('should reset all styles with `.reset()`', function () {
-		assert.equal(chalk.reset(chalk.red.bgGreen.underline('foo') + 'foo'), '\u001b[0m\u001b[31m\u001b[42m\u001b[4mfoo\u001b[24m\u001b[49m\u001b[39mfoo\u001b[0m');
-	});
-
-	it('should be able to cache multiple styles', function () {
-		var red = chalk.red;
-		var green = chalk.green;
-		var redBold = red.bold;
-		var greenBold = green.bold;
-
-		assert.notEqual(red('foo'), green('foo'));
-		assert.notEqual(redBold('bar'), greenBold('bar'));
-		assert.notEqual(green('baz'), greenBold('baz'));
-	});
-
-	it('should alias gray to grey', function () {
-		assert.equal(chalk.grey('foo'), '\u001b[90mfoo\u001b[39m');
-	});
-
-	it('should support variable number of arguments', function () {
-		assert.equal(chalk.red('foo', 'bar'), '\u001b[31mfoo bar\u001b[39m');
-	});
-
-	it('should support falsy values', function () {
-		assert.equal(chalk.red(0), '\u001b[31m0\u001b[39m');
-	});
-
-	it('don\'t output escape codes if the input is empty', function () {
-		assert.equal(chalk.red(), '');
-	});
-});
-
-describe('chalk on windows', function () {
-	var originalEnv;
-	var originalPlatform;
-
-	// in node versions older than 0.12.x process.platform cannot be overridden
-	if (semver.lt(process.version, '0.12.0')) {
-		return;
-	}
-
-	before(function () {
-		originalEnv = process.env;
-		originalPlatform = process.platform;
-	});
-
-	after(function () {
-		process.env = originalEnv;
-		Object.defineProperty(process, 'platform', {value: originalPlatform});
-	});
-
-	beforeEach(function () {
-		process.env = {};
-		Object.defineProperty(process, 'platform', {value: 'win32'});
-		// since chalk internally modifies ansiStyles.blue.open, ansi-styles needs
-		// to be removed from the require cache for require-uncached to work
-		delete require.cache[resolveFrom(__dirname, 'ansi-styles')];
-	});
-
-	it('should replace blue foreground color in cmd.exe', function () {
-		process.env.TERM = 'dumb';
-		var chalkCtx = requireUncached('./');
-		assert.equal(chalkCtx.blue('foo'), '\u001b[94mfoo\u001b[39m');
-	});
-
-	it('shouldn\'t replace blue foreground color in xterm based terminals', function () {
-		process.env.TERM = 'xterm-256color';
-		var chalkCtx = requireUncached('./');
-		assert.equal(chalkCtx.blue('foo'), '\u001b[34mfoo\u001b[39m');
-	});
-
-	it('should not apply dimmed styling on gray strings, see https://github.com/chalk/chalk/issues/58', function () {
-		process.env.TERM = 'dumb';
-		var chalkCtx = requireUncached('./');
-		assert.equal(chalkCtx.gray.dim('foo'), '\u001b[90mfoo\u001b[22m\u001b[39m');
-	});
-
-	it('should apply dimmed styling on xterm compatible terminals', function () {
-		process.env.TERM = 'xterm';
-		var chalkCtx = requireUncached('./');
-		assert.equal(chalkCtx.gray.dim('foo'), '\u001b[90m\u001b[2mfoo\u001b[22m\u001b[39m');
-	});
-
-	it('should apply dimmed styling on strings of other colors', function () {
-		process.env.TERM = 'dumb';
-		var chalkCtx = requireUncached('./');
-		assert.equal(chalkCtx.blue.dim('foo'), '\u001b[94m\u001b[2mfoo\u001b[22m\u001b[39m');
-	});
-});
-
-describe('chalk.enabled', function () {
-	it('should not output colors when manually disabled', function () {
-		chalk.enabled = false;
-		assert.equal(chalk.red('foo'), 'foo');
-		chalk.enabled = true;
-	});
-});
-
-describe('chalk.constructor', function () {
-	it('should create a isolated context where colors can be disabled', function () {
-		var ctx = new chalk.constructor({enabled: false});
-		assert.equal(ctx.red('foo'), 'foo');
-		assert.equal(chalk.red('foo'), '\u001b[31mfoo\u001b[39m');
-	});
-});
-
-describe('chalk.styles', function () {
-	it('should expose the styles as ANSI escape codes', function () {
-		assert.equal(chalk.styles.red.open, '\u001b[31m');
-	});
-});
-
-describe('chalk.hasColor()', function () {
-	it('should detect whether a string has color', function () {
-		assert(chalk.hasColor(chalk.green('foo')));
-		assert(!chalk.hasColor(chalk.stripColor(chalk.green('foo'))));
-	});
-});
-
-describe('chalk.stripColor()', function () {
-	it('should strip color from string', function () {
-		assert.equal(chalk.stripColor(chalk.underline.red.bgGreen('foo')), 'foo');
-	});
-});
diff --git a/test/_fixture.js b/test/_fixture.js
new file mode 100644
index 0000000..5f1771d
--- /dev/null
+++ b/test/_fixture.js
@@ -0,0 +1,4 @@
+'use strict';
+const chalk = require('..');
+
+console.log(chalk.hex('#ff6159')('test'));
diff --git a/test/_supports-color.js b/test/_supports-color.js
new file mode 100644
index 0000000..d6e82bb
--- /dev/null
+++ b/test/_supports-color.js
@@ -0,0 +1,13 @@
+'use strict';
+const resolveFrom = require('resolve-from');
+
+module.exports = dir => {
+	require.cache[resolveFrom(dir, 'supports-color')] = {
+		exports: {
+			level: 3,
+			hasBasic: true,
+			has256: true,
+			has16m: true
+		}
+	};
+};
diff --git a/test/chalk.js b/test/chalk.js
new file mode 100644
index 0000000..8480dad
--- /dev/null
+++ b/test/chalk.js
@@ -0,0 +1,100 @@
+import test from 'ava';
+
+// Spoof supports-color
+require('./_supports-color')(__dirname);
+
+const m = require('..');
+
+console.log('TERM:', process.env.TERM || '[none]');
+console.log('platform:', process.platform || '[unknown]');
+
+test('don\'t add any styling when called as the base function', t => {
+	t.is(m('foo'), 'foo');
+});
+
+test('support multiple arguments in base function', t => {
+	t.is(m('hello', 'there'), 'hello there');
+});
+
+test('style string', t => {
+	t.is(m.underline('foo'), '\u001B[4mfoo\u001B[24m');
+	t.is(m.red('foo'), '\u001B[31mfoo\u001B[39m');
+	t.is(m.bgRed('foo'), '\u001B[41mfoo\u001B[49m');
+});
+
+test('support applying multiple styles at once', t => {
+	t.is(m.red.bgGreen.underline('foo'), '\u001B[31m\u001B[42m\u001B[4mfoo\u001B[24m\u001B[49m\u001B[39m');
+	t.is(m.underline.red.bgGreen('foo'), '\u001B[4m\u001B[31m\u001B[42mfoo\u001B[49m\u001B[39m\u001B[24m');
+});
+
+test('support nesting styles', t => {
+	t.is(
+		m.red('foo' + m.underline.bgBlue('bar') + '!'),
+		'\u001B[31mfoo\u001B[4m\u001B[44mbar\u001B[49m\u001B[24m!\u001B[39m'
+	);
+});
+
+test('support nesting styles of the same type (color, underline, bg)', t => {
+	t.is(
+		m.red('a' + m.yellow('b' + m.green('c') + 'b') + 'c'),
+		'\u001B[31ma\u001B[33mb\u001B[32mc\u001B[33mb\u001B[31mc\u001B[39m'
+	);
+});
+
+test('reset all styles with `.reset()`', t => {
+	t.is(m.reset(m.red.bgGreen.underline('foo') + 'foo'), '\u001B[0m\u001B[31m\u001B[42m\u001B[4mfoo\u001B[24m\u001B[49m\u001B[39mfoo\u001B[0m');
+});
+
+test('support caching multiple styles', t => {
+	const red = m.red;
+	const green = m.green;
+	const redBold = red.bold;
+	const greenBold = green.bold;
+
+	t.not(red('foo'), green('foo'));
+	t.not(redBold('bar'), greenBold('bar'));
+	t.not(green('baz'), greenBold('baz'));
+});
+
+test('alias gray to grey', t => {
+	t.is(m.grey('foo'), '\u001B[90mfoo\u001B[39m');
+});
+
+test('support variable number of arguments', t => {
+	t.is(m.red('foo', 'bar'), '\u001B[31mfoo bar\u001B[39m');
+});
+
+test('support falsy values', t => {
+	t.is(m.red(0), '\u001B[31m0\u001B[39m');
+});
+
+test('don\'t output escape codes if the input is empty', t => {
+	t.is(m.red(), '');
+	t.is(m.red.blue.black(), '');
+});
+
+test('keep Function.prototype methods', t => {
+	t.is(m.grey.apply(null, ['foo']), '\u001B[90mfoo\u001B[39m');
+	t.is(m.reset(m.red.bgGreen.underline.bind(null)('foo') + 'foo'), '\u001B[0m\u001B[31m\u001B[42m\u001B[4mfoo\u001B[24m\u001B[49m\u001B[39mfoo\u001B[0m');
+	t.is(m.red.blue.black.call(null), '');
+});
+
+test('line breaks should open and close colors', t => {
+	t.is(m.grey('hello\nworld'), '\u001B[90mhello\u001B[39m\n\u001B[90mworld\u001B[39m');
+});
+
+test('properly convert RGB to 16 colors on basic color terminals', t => {
+	t.is(new m.constructor({level: 1}).hex('#FF0000')('hello'), '\u001B[91mhello\u001B[39m');
+	t.is(new m.constructor({level: 1}).bgHex('#FF0000')('hello'), '\u001B[101mhello\u001B[49m');
+});
+
+test('properly convert RGB to 256 colors on basic color terminals', t => {
+	t.is(new m.constructor({level: 2}).hex('#FF0000')('hello'), '\u001B[38;5;196mhello\u001B[39m');
+	t.is(new m.constructor({level: 2}).bgHex('#FF0000')('hello'), '\u001B[48;5;196mhello\u001B[49m');
+	t.is(new m.constructor({level: 3}).bgHex('#FF0000')('hello'), '\u001B[48;2;255;0;0mhello\u001B[49m');
+});
+
+test('don\'t emit RGB codes if level is 0', t => {
+	t.is(new m.constructor({level: 0}).hex('#FF0000')('hello'), 'hello');
+	t.is(new m.constructor({level: 0}).bgHex('#FF0000')('hello'), 'hello');
+});
diff --git a/test/constructor.js b/test/constructor.js
new file mode 100644
index 0000000..d592e82
--- /dev/null
+++ b/test/constructor.js
@@ -0,0 +1,22 @@
+import test from 'ava';
+
+// Spoof supports-color
+require('./_supports-color')(__dirname);
+
+const m = require('..');
+
+test('create an isolated context where colors can be disabled (by level)', t => {
+	const ctx = new m.constructor({level: 0, enabled: true});
+	t.is(ctx.red('foo'), 'foo');
+	t.is(m.red('foo'), '\u001B[31mfoo\u001B[39m');
+	ctx.level = 2;
+	t.is(ctx.red('foo'), '\u001B[31mfoo\u001B[39m');
+});
+
+test('create an isolated context where colors can be disabled (by enabled flag)', t => {
+	const ctx = new m.constructor({enabled: false});
+	t.is(ctx.red('foo'), 'foo');
+	t.is(m.red('foo'), '\u001B[31mfoo\u001B[39m');
+	ctx.enabled = true;
+	t.is(ctx.red('foo'), '\u001B[31mfoo\u001B[39m');
+});
diff --git a/test/enabled.js b/test/enabled.js
new file mode 100644
index 0000000..3270e54
--- /dev/null
+++ b/test/enabled.js
@@ -0,0 +1,35 @@
+import test from 'ava';
+
+// Spoof supports-color
+require('./_supports-color')(__dirname);
+
+const m = require('..');
+
+test('don\'t output colors when manually disabled', t => {
+	m.enabled = false;
+	t.is(m.red('foo'), 'foo');
+	m.enabled = true;
+});
+
+test('enable/disable colors based on overall chalk enabled property, not individual instances', t => {
+	m.enabled = false;
+	const red = m.red;
+	t.false(red.enabled);
+	m.enabled = true;
+	t.true(red.enabled);
+	m.enabled = true;
+});
+
+test('propagate enable/disable changes from child colors', t => {
+	m.enabled = false;
+	const red = m.red;
+	t.false(red.enabled);
+	t.false(m.enabled);
+	red.enabled = true;
+	t.true(red.enabled);
+	t.true(m.enabled);
+	m.enabled = false;
+	t.false(red.enabled);
+	t.false(m.enabled);
+	m.enabled = true;
+});
diff --git a/test/level.js b/test/level.js
new file mode 100644
index 0000000..85624ea
--- /dev/null
+++ b/test/level.js
@@ -0,0 +1,44 @@
+import path from 'path';
+import test from 'ava';
+import execa from 'execa';
+
+// Spoof supports-color
+require('./_supports-color')(__dirname);
+
+const m = require('..');
+
+test('don\'t output colors when manually disabled', t => {
+	const oldLevel = m.level;
+	m.level = 0;
+	t.is(m.red('foo'), 'foo');
+	m.level = oldLevel;
+});
+
+test('enable/disable colors based on overall chalk enabled property, not individual instances', t => {
+	const oldLevel = m.level;
+	m.level = 1;
+	const red = m.red;
+	t.is(red.level, 1);
+	m.level = 0;
+	t.is(red.level, m.level);
+	m.level = oldLevel;
+});
+
+test('propagate enable/disable changes from child colors', t => {
+	const oldLevel = m.level;
+	m.level = 1;
+	const red = m.red;
+	t.is(red.level, 1);
+	t.is(m.level, 1);
+	red.level = 0;
+	t.is(red.level, 0);
+	t.is(m.level, 0);
+	m.level = 1;
+	t.is(red.level, 1);
+	t.is(m.level, 1);
+	m.level = oldLevel;
+});
+
+test('disable colors if they are not supported', async t => {
+	t.is(await execa.stdout('node', [path.join(__dirname, '_fixture')]), 'test');
+});
diff --git a/test/template-literal.js b/test/template-literal.js
new file mode 100644
index 0000000..bfa346c
--- /dev/null
+++ b/test/template-literal.js
@@ -0,0 +1,169 @@
+import test from 'ava';
+
+// Spoof supports-color
+require('./_supports-color')(__dirname);
+
+const m = require('..');
+
+test('return an empty string for an empty literal', t => {
+	const ctx = m.constructor();
+	t.is(ctx``, '');
+});
+
+test('return a regular string for a literal with no templates', t => {
+	const ctx = m.constructor({level: 0});
+	t.is(ctx`hello`, 'hello');
+});
+
+test('correctly perform template parsing', t => {
+	const ctx = m.constructor({level: 0});
+	t.is(ctx`{bold Hello, {cyan World!} This is a} test. {green Woo!}`,
+		ctx.bold('Hello,', ctx.cyan('World!'), 'This is a') + ' test. ' + ctx.green('Woo!'));
+});
+
+test('correctly perform template substitutions', t => {
+	const ctx = m.constructor({level: 0});
+	const name = 'Sindre';
+	const exclamation = 'Neat';
+	t.is(ctx`{bold Hello, {cyan.inverse ${name}!} This is a} test. {green ${exclamation}!}`,
+		ctx.bold('Hello,', ctx.cyan.inverse(name + '!'), 'This is a') + ' test. ' + ctx.green(exclamation + '!'));
+});
+
+test('correctly parse and evaluate color-convert functions', t => {
+	const ctx = m.constructor({level: 3});
+	t.is(ctx`{bold.rgb(144,10,178).inverse Hello, {~inverse there!}}`,
+		'\u001B[1m\u001B[38;2;144;10;178m\u001B[7mHello, ' +
+		'\u001B[27m\u001B[39m\u001B[22m\u001B[1m' +
+		'\u001B[38;2;144;10;178mthere!\u001B[39m\u001B[22m');
+
+	t.is(ctx`{bold.bgRgb(144,10,178).inverse Hello, {~inverse there!}}`,
+		'\u001B[1m\u001B[48;2;144;10;178m\u001B[7mHello, ' +
+		'\u001B[27m\u001B[49m\u001B[22m\u001B[1m' +
+		'\u001B[48;2;144;10;178mthere!\u001B[49m\u001B[22m');
+});
+
+test('properly handle escapes', t => {
+	const ctx = m.constructor({level: 3});
+	t.is(ctx`{bold hello \{in brackets\}}`,
+		'\u001B[1mhello {in brackets}\u001B[22m');
+});
+
+test('throw if there is an unclosed block', t => {
+	const ctx = m.constructor({level: 3});
+	try {
+		console.log(ctx`{bold this shouldn't appear ever\}`);
+		t.fail();
+	} catch (err) {
+		t.is(err.message, 'Chalk template literal is missing 1 closing bracket (`}`)');
+	}
+
+	try {
+		console.log(ctx`{bold this shouldn't {inverse appear {underline ever\} :) \}`);
+		t.fail();
+	} catch (err) {
+		t.is(err.message, 'Chalk template literal is missing 3 closing brackets (`}`)');
+	}
+});
+
+test('throw if there is an invalid style', t => {
+	const ctx = m.constructor({level: 3});
+	try {
+		console.log(ctx`{abadstylethatdoesntexist this shouldn't appear ever}`);
+		t.fail();
+	} catch (err) {
+		t.is(err.message, 'Unknown Chalk style: abadstylethatdoesntexist');
+	}
+});
+
+test('properly style multiline color blocks', t => {
+	const ctx = m.constructor({level: 3});
+	t.is(
+		ctx`{bold
+			Hello! This is a
+			${'multiline'} block!
+			:)
+		} {underline
+			I hope you enjoy
+		}`,
+		'\u001B[1m\u001B[22m\n' +
+		'\u001B[1m\t\t\tHello! This is a\u001B[22m\n' +
+		'\u001B[1m\t\t\tmultiline block!\u001B[22m\n' +
+		'\u001B[1m\t\t\t:)\u001B[22m\n' +
+		'\u001B[1m\t\t\u001B[22m \u001B[4m\u001B[24m\n' +
+		'\u001B[4m\t\t\tI hope you enjoy\u001B[24m\n' +
+		'\u001B[4m\t\t\u001B[24m'
+	);
+});
+
+test('escape interpolated values', t => {
+	const ctx = m.constructor({level: 0});
+	t.is(ctx`Hello {bold hi}`, 'Hello hi');
+	t.is(ctx`Hello ${'{bold hi}'}`, 'Hello {bold hi}');
+});
+
+test('allow custom colors (themes) on custom contexts', t => {
+	const ctx = m.constructor({level: 3});
+	ctx.rose = ctx.hex('#F6D9D9');
+	t.is(ctx`Hello, {rose Rose}.`, 'Hello, \u001B[38;2;246;217;217mRose\u001B[39m.');
+});
+
+test('correctly parse newline literals (bug #184)', t => {
+	const ctx = m.constructor({level: 0});
+	t.is(ctx`Hello
+{red there}`, 'Hello\nthere');
+});
+
+test('correctly parse newline escapes (bug #177)', t => {
+	const ctx = m.constructor({level: 0});
+	t.is(ctx`Hello\nthere!`, `Hello\nthere!`);
+});
+
+test('correctly parse escape in parameters (bug #177 comment 318622809)', t => {
+	const ctx = m.constructor({level: 0});
+	const str = '\\';
+	t.is(ctx`{blue ${str}}`, '\\');
+});
+
+test('correctly parses unicode/hex escapes', t => {
+	const ctx = m.constructor({level: 0});
+	t.is(ctx`\u0078ylophones are fo\x78y! {magenta.inverse \u0078ylophones are fo\x78y!}`,
+		'xylophones are foxy! xylophones are foxy!');
+});
+
+test('correctly parses string arguments', t => {
+	const ctx = m.constructor({level: 3});
+	t.is(ctx`{keyword('black').bold can haz cheezburger}`, '\u001B[38;2;0;0;0m\u001B[1mcan haz cheezburger\u001B[22m\u001B[39m');
+	t.is(ctx`{keyword('blac\x6B').bold can haz cheezburger}`, '\u001B[38;2;0;0;0m\u001B[1mcan haz cheezburger\u001B[22m\u001B[39m');
+	t.is(ctx`{keyword('blac\u006B').bold can haz cheezburger}`, '\u001B[38;2;0;0;0m\u001B[1mcan haz cheezburger\u001B[22m\u001B[39m');
+});
+
+test('throws if a bad argument is encountered', t => {
+	const ctx = m.constructor({level: 3}); // Keep level at least 1 in case we optimize for disabled chalk instances
+	try {
+		console.log(ctx`{keyword(????) hi}`);
+		t.fail();
+	} catch (err) {
+		t.is(err.message, 'Invalid Chalk template style argument: ???? (in style \'keyword\')');
+	}
+});
+
+test('throws if an extra unescaped } is found', t => {
+	const ctx = m.constructor({level: 0});
+	try {
+		console.log(ctx`{red hi!}}`);
+		t.fail();
+	} catch (err) {
+		t.is(err.message, 'Found extraneous } in Chalk template literal');
+	}
+});
+
+test('should not parse upper-case escapes', t => {
+	const ctx = m.constructor({level: 0});
+	t.is(ctx`\N\n\T\t\X07\x07\U000A\u000A\U000a\u000a`, 'N\nT\tX07\x07U000A\u000AU000a\u000A');
+});
+
+test('should properly handle undefined template interpolated values', t => {
+	const ctx = m.constructor({level: 0});
+	t.is(ctx`hello ${undefined}`, 'hello undefined');
+	t.is(ctx`hello ${null}`, 'hello null');
+});
diff --git a/test/windows.js b/test/windows.js
new file mode 100644
index 0000000..2f2815e
--- /dev/null
+++ b/test/windows.js
@@ -0,0 +1,63 @@
+import test from 'ava';
+import importFresh from 'import-fresh';
+import resolveFrom from 'resolve-from';
+
+// Spoof supports-color
+require('./_supports-color')(__dirname);
+
+let originalEnv;
+let originalPlatform;
+
+test.before(() => {
+	originalEnv = process.env;
+	originalPlatform = process.platform;
+});
+
+test.after(() => {
+	process.env = originalEnv;
+	Object.defineProperty(process, 'platform', {value: originalPlatform});
+});
+
+test.beforeEach(() => {
+	process.env = {};
+	Object.defineProperty(process, 'platform', {value: 'win32'});
+	// Since chalk internally modifies `ansiStyles.blue.open`, `ansi-styles` needs
+	// to be removed from the require cache for `require-uncached` to work
+	delete require.cache[resolveFrom(__dirname, 'ansi-styles')];
+});
+
+test('detect a simple term if TERM isn\'t set', t => {
+	delete process.env.TERM;
+	const m = importFresh('..');
+	t.is(m.blue('foo'), '\u001B[94mfoo\u001B[39m');
+});
+
+test('replace blue foreground color in cmd.exe', t => {
+	process.env.TERM = 'dumb';
+	const m = importFresh('..');
+	t.is(m.blue('foo'), '\u001B[94mfoo\u001B[39m');
+});
+
+test('don\'t replace blue foreground color in xterm based terminals', t => {
+	process.env.TERM = 'xterm-256color';
+	const m = importFresh('..');
+	t.is(m.blue('foo'), '\u001B[34mfoo\u001B[39m');
+});
+
+test('don\'t apply dimmed styling on gray strings, see https://github.com/chalk/chalk/issues/58', t => {
+	process.env.TERM = 'dumb';
+	const m = importFresh('..');
+	t.is(m.gray.dim('foo'), '\u001B[90mfoo\u001B[22m\u001B[39m');
+});
+
+test('apply dimmed styling on xterm compatible terminals', t => {
+	process.env.TERM = 'xterm';
+	const m = importFresh('..');
+	t.is(m.gray.dim('foo'), '\u001B[90m\u001B[2mfoo\u001B[22m\u001B[39m');
+});
+
+test('apply dimmed styling on strings of other colors', t => {
+	process.env.TERM = 'dumb';
+	const m = importFresh('..');
+	t.is(m.blue.dim('foo'), '\u001B[94m\u001B[2mfoo\u001B[22m\u001B[39m');
+});

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-chalk.git



More information about the Pkg-javascript-commits mailing list