bicep icon indicating copy to clipboard operation
bicep copied to clipboard

Multiline string variables

Open slavizh opened this issue 6 years ago • 27 comments

Is your feature request related to a problem? Please describe. I could not find a way to define multiple line string variables. Something like:


var test = @"
asdas
asdasasd
asdasasd
"@

or

var test = '
asdas
asdasasd
asdasasd
'

Describe the solution you'd like A clear and concise description of what you want to happen.

slavizh avatar Sep 01 '20 10:09 slavizh

To clarify, do you want the same functionality we have in ARM templates today? It keeps the line breaks when the string is sent to ARM. Alternatively, you may want us to drop the line breaks.

alex-frankel avatar Sep 03 '20 22:09 alex-frankel

I would prefer to have the string defined in multiple lines but when send to ARM the line breaks are removed. If we need to add line breaks we can do it explicitly whit escape characters. For me this is the more natural as when I have some long text (descriptions, kusto queries or something) for better viewing of the code and less horizontal scrolling this is the better behavior for me. Of course other folks can chime in and express different opinion. I am fine with both approaches as long as it is supported.

slavizh avatar Sep 04 '20 08:09 slavizh

Would you expect the multi-line strings to allow interpolation?

majastrz avatar Sep 18 '20 08:09 majastrz

Yes, Also will look weird when you have mixture of objects and arrays within each other and the arrays have to be one liner.

slavizh avatar Sep 18 '20 08:09 slavizh

OK, just been pointed to this, thanks :-)

My requirement is for inline scripts and cloud-init yaml files so would expect line breaks to be preserved and for the text to include references that are interpolated if I understand the term right so that it may be customised during deployment

lr90 avatar Oct 29 '20 17:10 lr90

Would you expect us to normalize line endings or preserve them in the file?

If it's the latter, be aware that Git does its own line ending normalization unless you opt-out. If it's the former, would \n be sufficient or would you want to control this?

majastrz avatar Oct 30 '20 01:10 majastrz

If I understand that is would I want any CRLF mapped to CR then I'm ambivalent. I try to only use CRs so would be happy to correct my own code to get the right output but if it was normalised automatically that would be fine.

lr90 avatar Oct 30 '20 10:10 lr90

Something to be careful about regarding whether to output \n vs \r\n in the generated output - I recall hearing that some APIs are fussy about getting the right character.

anthony-c-martin avatar Oct 30 '20 16:10 anthony-c-martin

Sorry, my - example keeps being turned into a bullet :)

I'm currently using this:

param customDataRaw string = '#cloud-config\n\nruncmd: \n- mkdir -p /mnt/%dir%\n'

but would prefer to use something more like this:

param customDataRaw string = '
#cloud-config

runcmd:
- mkdir -p /mnt/%dir%
'

lr90 avatar Oct 30 '20 16:10 lr90

The content I want to inject runs to ~50 lines of cloud-init yaml file

lr90 avatar Oct 30 '20 17:10 lr90

@lr90 FYI you can use markdown's fenced code blocks to paste code without having GitHub messing up the formatting. I've updated your comment to use it: https://docs.github.com/github/writing-on-github/creating-and-highlighting-code-blocks#fenced-code-blocks

anthony-c-martin avatar Oct 30 '20 17:10 anthony-c-martin

I think triple quoted strings (""") or markdown style ``` strings would be great, especially if we're talking about embedded bash/pwsh scripts

https://github.com/Azure/bicep/blob/main/docs/examples/101/deployment-script-no-auth/main.bicep

onionhammer avatar Dec 16 '20 18:12 onionhammer

Team Discussion - 02/03/21

Multiline strings

Proposed syntax

var myString = '''
this
is
a
multiline
string
'''

Multi-line strings begin with 3 consecutive single quotes (''') followed immediately by a newline character sequence, and are terminated with 3 consecutive single quotes (''') immediately following a newline character sequence.

Considerations

What should the opening/closing syntax be?

  • We agreed on ''' as it aligns with the current string syntax.
  • We discussed whether we could allow the user to optionally pick n number of ' characters (n >= 3) - e.g. '''' or ''''' in order to include strings containing '''. We decided this was overkill for now, but we could consider it for a future improvement if necessary.

Should we give users the flexibility to pick the newline character?

  • We decided that we simply use the newline sequence from the .bicep file - CRLF or LF would be converted into the appropriate JSON-escaped newline character on conversion. For example, in a file with LF newline sequences, Bicep would consider these two strings equivalent:
    var multiline = '''
    hello
    Anthony!
    '''
    var singleline = 'hello\nAnthony!'
    

Should we support string interpolation?

  • We decided that for now, we would not support string interpolation or any form of escaping. The reason being that if you have an escape sequence, you lose the ability to paste in any old text without formatting it correctly. If users need variable replacement, it would still be possible using the format() function - e.g.:
    var unformatted = '''
    hello {0}!
    '''
    var formatted = format(unformatted, 'Anthony')
    
  • A potential option for interpolation in the future we discussed is to match the number of $ characters with the number of single quotes - e.g.:
    var myString = '''
    hello $$${name}
    '''
    

How should we handle whitespace?

  • Users may want to indent the mutliline string block to match the formatting of the document. We decided that rather than trying to second-guess the intention, we would simply use the whitespace as provided. This means that the following two strings would be regarded as equivalent:
    var multiline = '''
        I'm
        Indented!
    '''
    var singleline = '    I\'m\n    Indented!'
    

Summary

We decided to go with the proposed syntax, leaving some options open for future extension w.r.t interpolation & using different multiline string opening/terminating sequences.

Samples

Valid Strings

// basic sample
var basic = '''
hello
   this
       is
           valid
'''

// some edge cases - this is all going to be treated as one valid multiline string
var horribleSample = '''
 ''' <-- it's totally fine to do this
 ' <--- or this
 \n <---- this does not need escaping
'''we still
haven't '''
terminated
  the ''' string
'''

// comment-line syntax will be included in the string output and not treated as comments
var commentsAreIgnored = '''
  these // comments
  are /* going to be
  included in the verbatim */
  string
'''

Invalid Strings

// the initial ''' must be followed immediately by a newline
var invalidStartSequence = '''this
is
invalid
'''

// the final ''' must be immediately after a newline
var invalidEndSequence = '''
this
is
invalid'''

// ''' may not be used inside a multiline string
var disallowedCharacters = '''
oh
'''
no
'''

FunctionApp with JavaScript

resource testResourceFunc 'Microsoft.Web/sites/functions@2018-11-01' = {
  name: '${backingSite.name}/${testResourceName}'
  properties: {
    config: {
      bindings: [
        {
          authLevel: 'function'
          type: 'httpTrigger'
          direction: 'in'
          name: 'req'
          methods: [
            'put'
            'get'
            'delete'
          ]
        }
        {
          type: 'http'
          direction: 'out'
          name: 'res'
        }
      ]
    }
    files: {
      'index.js': '''
module.exports = async function (context, req) {
    console.log(context);
    setResponse(context, 200, req.body);
};

function setResponse(context, code, body) {
    context.res = {
        body: body,
        status: code,
        headers: {
            \'Content-Type\': \'application/json\',
        }
    }
}
'''
    }
  }
}

DeploymentScript with PowerShell

resource scriptName_mysqlShareName 'Microsoft.Resources/deploymentScripts@2020-10-01' = {
  name: '${scriptName}-${mysqlShareName}'
  location: location
  kind: 'AzurePowerShell'
  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: {
      '${identityName.id}': {}
    }
  }
  properties: {
    forceUpdateTag: '1'
    azPowerShellVersion: '3.0'
    arguments: ' -storageAccountName ${storageAccountName} -fileShareName ${mysqlShareName} -resourceGroupName ${resourceGroup().name}'
    scriptContent: '''
param(
    [string] $storageAccountName,
    [string] $fileShareName,
    [string] $resourceGroupName
)
Get-AzStorageAccount -StorageAccountName $storageAccountName -ResourceGroupName $resourceGroupName | New-AzStorageShare -Name $fileShareName
'''
    timeout: 'PT5M'
    cleanupPreference: 'OnSuccess'
    retentionInterval: 'P1D'
  }
}

anthony-c-martin avatar Feb 04 '21 20:02 anthony-c-martin

We passed this plan by Anders, who suggested we make the following changes:

  • Newline after the opening ''' should be made optional, but will not be treated as part of the string if it is present. This means that the following strings are equivalent:
    var string1 = '''hello
    '''
    
    var string2 = '''
    hello
    '''
    
  • Newline should not be considered part of the closing set of '''. This means that if it occurs after a newline, the newline will be considered part of the string. This makes pasting in verbatim text simpler and more predictable:
    // evaluates to 'hello\n'
    var string1 = '''
    hello
    '''
    
    // evaluates to 'hello'
    var string2 = '''
    hello'''
    
  • As a consequence of the above two points, it should be possible to have a one-line verbatim string: var string1 = '''hello'''
  • Because we are loosening the restrictions on where the ''' can go, we should allow the user to specify 3+ quotes to open/close the string. This gives users the freedom to paste strings containing ''' by picking a different number of opening/closing quotes. So the following are all valid:
    var string1 = ''''
    I can paste ''' here
    ''''
    
    var string2 = ''''''''
    hello!
    ''''''''
    
  • We should stick with the plan to disallow interpolation as it makes pasting in verbatim text more straightforward.
  • The lexer should treat the full verbatim string as a single token, including the opening and closing quotes

anthony-c-martin avatar Feb 05 '21 14:02 anthony-c-martin

Also this:

  • If a multi-line string is not terminated correctly (that is starts with ''' but never ends), the remainder of the file becomes part of the string token and a lexical error about the unterminated string is emitted.

I also don't think that we need to introduce a new type of AST node to represent these strings. We should try to incorporate this into the existing StringSyntax.

majastrz avatar Feb 05 '21 18:02 majastrz

For bonus points, we can also have the decompiler generate a multi-line string when a string literal in an expression exceeds some threshold.

majastrz avatar Feb 05 '21 18:02 majastrz

Only to say I’m struggling to contain my excitement at this and have got some great scenarios to start testing it!!

lr90 avatar Feb 05 '21 19:02 lr90

One more serious comment. Disallow interpretation? Please clarify but with my multi line string I would like (require!) placeholders such as ${targetName} or some such that will be evaluated during the deployment

lr90 avatar Feb 05 '21 20:02 lr90

One more serious comment. Disallow interpretation? Please clarify but with my multi line string I would like (require!) placeholders such as ${targetName} or some such that will be evaluated during the deployment

Would you mind sharing some example use cases for this? When we discussed this, our thoughts were:

  • Allowing interpolation means that there's more to think about when copy+pasting preformatted text into a multiline code block, as you need to consider escaping. We wanted to keep it very simple so that you'd just have to consider whether your text contains '''.
  • If using this to generate e.g. script blocks, interpolation replacement may make it easy to create subtle escaping issues, because it's not going to be aware of the semantics of the underlying language - for example:
    var name = 'Bruce "The Boss" Springsteen'
    var powerShellScript = '''
    Write-Output "Hello ${name}"
    ''' // this is not going to escape the " characters, so the powershell script won't have the desired effect
    
  • It's possible (though less nice) to achieve a similar effect by DIYing it with the format function - e.g:
    var powerShellScript = format('''
    Get-AzStorageAccount -StorageAccountName "{0}" -ResourceGroupName "{1}" | `
        New-AzStorageShare -Name "{2}"
    ''', storageAccountName, fileShareName, resourceGroup().name)
    

One possible workaround we discussed for the 1st point was that we could require a matching number of $ characters for interpolation to make it at least configurable - e.g.:

var output = '''
Hello $$${name}
'''

// This is a Bicep string containing valid Bicep code.
// Note that the inner interpolation syntax will not be executed because # of $s doesn't match the number of 's
// Being able to contain valid Bicep code is a good test for the versatility of the syntax!
var manyQuotes = ''''''
var name = 'Anthony'
var thisIsEscapedBicepCode = '''
Hello $$${name}
'''
''''''

anthony-c-martin avatar Feb 10 '21 11:02 anthony-c-martin

Sure, my current burning use case is Cloud-Init and CSE scripts. While many don't require any interpolation there is a working example here:

(https://github.com/Azure/bicep/blob/b2de1c425a461950b03bc34bd2c23b7177f2a7d8/docs/examples/101/cyclecloud/main.bicep#L12) where I am replacing placeholders in the script with values determined at deployment time.

You can also get a sense of how much fun it isn't turning a perfectly good 90+ line yml file into a single line string variable :-) IIRC I had to also escape some of the ' in that line but from what I'm seeing as proposed at the moment that burden would also be removed and reduce the risk of introducing errors to the yml.

lr90 avatar Feb 10 '21 13:02 lr90