Scala runtime string interpolation/formatting

前端 未结 3 1933
青春惊慌失措
青春惊慌失措 2021-01-20 11:10

Are there any standard library facilities to do string interpolation/formatting at runtime? I\'d like the formatting to behave exactly the same as the macro based s\"s

3条回答
  •  清酒与你
    2021-01-20 12:05

    I had a similar requirement where I was loading a Seq[String] from a config file which would become a command to be executed (using scala.sys.process). To simplify the format and ignore any potential escaping problems I also made the variable names a configurable option too.

    The config looked something like this:

    command = ["""C:\Program Files (x86)\PuTTY\pscp.exe""", "-P", "2222", "-i",
              ".vagrant/machines/default/virtualbox/private_key", "$source", "~/$target"]
    source = "$source"
    target = "$target"
    

    I couldn't find a nice (or efficient) way of using the StringContext or "string".format so I rolled my own VariableCommand which is quite similar to StringContext however a single variable can appear zero or more times in any order and in any of the items.

    The basic idea was to create a function which took the variable values and then would either take part of the string (e.g. "~/") or take the variable value (e.g. "test.conf") repeatedly to build up the result (e.g. "~/test.conf"). This function is created once which is where all the complexity is and then at substitution time it is really simple (and hopefully fast although I haven't done any performance testing, or much testing at all for that matter).

    For those that might wonder why I was doing this it was for running automation tests cross platform using ansible (which doesn't support Windows control machines) for provisioning. This allowed me to copy the files to the target machine and run ansible locally.

提交回复
热议问题