import fs from "fs" ; import os from "os" ; import path from "path" ; import klawSync from "klaw-sync" ; import * as changeCase from "change-case" ; import { getEasyopsConfig } from "@next-core/repo-config" ; import { FileWithContent } from "../interface" ; const packageJson = JSON . parse ( fs . readFileSync ( path . join ( __dirname , "../../package.json" ) , "utf8" ) ) ; const workspacePackageJson = JSON . parse ( fs . readFileSync ( path . join ( process . cwd ( ) , "package.json" ) , "utf8" ) ) ; const workspaceHomepage = workspacePackageJson . homepage ; const workspaceLicense = workspacePackageJson . license || "UNLICENSED" ; function escapeRegExp ( str ) { return str . replace ( /([.*+?^=!:${}()|[\]/\\])/g , "\\$1" ) ; } function replaceAll ( str , find , replace ) { return str . replace ( new RegExp ( escapeRegExp ( find ) , "g" ) , replace ) ; } function replaceFileContent ( filePath , translations ) { const content = fs . readFileSync ( filePath , "utf8" ) ; const contentFinds = Object . keys ( translations ) . filter ( ( key ) => content . includes ( key ) ) ; if ( contentFinds . length > 0 ) { return contentFinds . reduce ( ( acc , find ) => replaceAll ( acc , find , translations [ find ] ) , content ) ; } return content ; } function replaceDepsVersion ( jsonString , sdkVersion ) { const pkg = JSON . parse ( jsonString ) ; if ( sdkVersion ) { pkg . version = sdkVersion ; } return JSON . stringify ( pkg , null , 2 ) + os . EOL ; } export function loadTemplate ( serviceName , sdkRoot , sdkVersion ) { const { usePublicScope } = getEasyopsConfig ( ) ; const templateDir = path . join ( __dirname , "../../template" ) ; const ignores = [ ".DS_Store" ] ; const filter = ( src ) : boolean => ignores . some ( ( item ) => ! src . includes ( item ) ) ; const templateFiles = klawSync ( templateDir , { depthLimit : 2 , nodir : true , filter : ( item ) => filter ( item . path ) , } ) ; const translations = { "$npm-scope-of-sdk$" : usePublicScope ? "@next-sdk" : "@sdk" , "$workspace-homepage$" : workspaceHomepage , "$kebab-service-name$" : changeCase . paramCase ( serviceName ) , "$Title Service Name$" : changeCase . capitalCase ( serviceName ) , $PascalServiceName$ : changeCase . pascalCase ( serviceName ) , "$generator.version$" : `v${ packageJson . version }` , "$open-source-license$" : workspaceLicense , } ; const files = templateFiles . map ( ( file ) => { const content = replaceFileContent ( file . path , translations ) ; return [ path . join ( sdkRoot , path . relative ( templateDir , file . path ) ) , content ] ; } ) ; files . push ( [ path . join ( sdkRoot , "package.json" ) , replaceDepsVersion ( replaceFileContent ( path . join ( templateDir , "../template.json" ) , translations ) , sdkVersion ) , ] ) ; return files ; }