zspecza / common-tags

🔖 Useful template literal tags for dealing with strings in ES2015+

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Strip indent having issues when using something like util.inspect

basicdays opened this issue · comments

When I'm including data that was serialized using node's util.inspect function, stripIndent seems to be making some mistakes on how to handle the indent stripping. Here's the script and the output as an example:

'use strict';
const commonTags = require('common-tags');
const util = require('util');


const obj = {
	prop1: 'asdfasdfasdfsadfasdf asdfasdfasdfsadfasdf',
	prop2: 'asdfasdfasdfsadfasdf asdfasdfasdfsadfasdf',
	shape: {
		prop3: 'asdfasdfasdfsadfasdf asdfasdfasdfsadfasdf',
		prop4: 'asdfasdfasdfsadfasdf asdfasdfasdfsadfasdf'
	}
}

if (true) {
	if (true) {
		console.log(commonTags.stripIndent`
			Some firstline message
			Some secondline message
			${util.inspect(obj)}
		`);
	}
}

Actual output:

Some firstline message
        Some secondline message
        { prop1: 'asdfasdfasdfsadfasdf asdfasdfasdfsadfasdf',
prop2: 'asdfasdfasdfsadfasdf asdfasdfasdfsadfasdf',
shape:
 { prop3: 'asdfasdfasdfsadfasdf asdfasdfasdfsadfasdf',
   prop4: 'asdfasdfasdfsadfasdf asdfasdfasdfsadfasdf' } }
vagrant@dev:/opt/signal (alert-check-update)$ node scratch/data-test.js

Expected output:

Some firstline message
Some secondline message
{ prop1: 'asdfasdfasdfsadfasdf asdfasdfasdfsadfasdf',
  prop2: 'asdfasdfasdfsadfasdf asdfasdfasdfsadfasdf',
  shape:
   { prop3: 'asdfasdfasdfsadfasdf asdfasdfasdfsadfasdf',
     prop4: 'asdfasdfasdfsadfasdf asdfasdfasdfsadfasdf' } }

I think I came across a similar issue. The problem, I think, is that if you have some interpolated values that don't have any leading whitespace, that becomes the minimum whitespace. Then, stripIndent does also include the trim transformer, so the first line gets trimmed of the leading whitespace, but all other lines are untouched.

This is a little surprising to me, because I expected template tags to operate on the template literal before interpolation, rather than not after, but I haven't fully understood how this stuff all works yet.

Aha! In this case, you're actually meant to use the html tag which does handle embedded newlines.

This tag is also aliased to source and codeBlock, which make more sense to me, since personally I'm not writing HTML here.

Hi, I can confirm that the issue is there in v1.4.0. I can't check right now whether it was fixed in #114, but will do so later today. In any case, a version with a fix should be released in a matter of days - keep your fingers crossed 🤞

@ibrahima is right - "fixing" stripIndent would turn it into source, so I guess the only thing that's not working here is the naming (one of the unsolved problems of computer science 😉). I'll be adding a note about this particular behavior to the docs.