import { parseError } from "vscode-azureextensionui" ; import { assert } from "../fixed_assert" ; import { KnownContexts } from "./KnownContexts" ; import { ISnippetDefinitionFromFile } from "./SnippetManager" ; const stringSnippetPlaceholderCommentPatternRegex = new RegExp ( `\\/\\*\\\${` + `(?<snippetPlaceholder>(.*?))` + `}\\*\\/` + `\\s?` + `(` + `"(.*?)"` + `)` , 'g' ) ; const nonStringSnippetPlaceholderCommentPatternRegex = new RegExp ( `\\/\\*\\\${` + `(?<snippetPlaceholder>(.*?))` + `}\\*\\/` + `\\s?` + `(` + `\\w+` + `)` , 'g' ) ; export function createResourceSnippetFromFile ( snippetName , snippetFileContent ) { const json = getJsonFromResourceSnippetFile ( snippetName , snippetFileContent ) ; const body = getBodyFromResourceSnippetJson ( json ) ; const metadata = < { [ key ] : string | undefined ; } > json . metadata ; const description = metadata . description ; const prefix = metadata . prefix ; assert ( description !== undefined , `Resource snippet "${ snippetName }" is missing metadata.description` ) ; assert ( prefix , `Resource snippet "${ snippetName }" is missing metadata.prefix` ) ; return { body , context : KnownContexts . resources , description , prefix } ; } export function getBodyFromResourceSnippetFile ( snippetName , snippetFileContent ) { const parsed = getJsonFromResourceSnippetFile ( snippetName , snippetFileContent ) ; return getBodyFromResourceSnippetJson ( parsed ) ; } function getJsonFromResourceSnippetFile ( snippetName , snippetFileContent ) { let snippetNoPlaceholders = snippetFileContent . replace ( stringSnippetPlaceholderCommentPatternRegex , "\"EMBEDDEDSTRING!$1!EMBEDDEDSTRING\"" ) ; snippetNoPlaceholders = snippetNoPlaceholders . replace ( nonStringSnippetPlaceholderCommentPatternRegex , "\"NOTASTRING!$1!NOTASTRING\"" ) ; try { return < { [ key ] : unknown ; } > JSON . parse ( snippetNoPlaceholders ) ; } catch ( ex ) { throw new Error ( `Error processing resource snippet '${ snippetName }': ${ parseError ( ex ) . message }` ) ; } } function getBodyFromResourceSnippetJson ( json ) { const resources = json . resources ; const resourcesString = JSON . stringify ( resources , null , 1 ) ; let lines = resourcesString . split ( /\r\n|\r|\n/ ) ; lines = lines . slice ( 1 , lines . length - 1 ) ; const body = [ ] ; for ( const line of lines ) { const tabs = ( < string [ ] > line . match ( /^ */ ) ) [ 0 ] . length - 1 ; const lineWithTabs = line . replace ( /^ */ , '\t' . repeat ( tabs ) ) ; let text = lineWithTabs . replace ( /EMBEDDEDSTRING!/ , '${' ) . replace ( /!EMBEDDEDSTRING/ , '}' ) ; text = text . replace ( /\"NOTASTRING!/ , '${' ) . replace ( /!NOTASTRING\"/ , '}' ) ; text = text . replace ( /\$schema/g , '\\$schema' ) ; const lineNormalized = text . replace ( /"/g , '\"' ) ; body . push ( lineNormalized ) ; } return body ; }