UNPKG

@sap/generator-cap-project

Version:

Creates a new SAP Cloud Application Programming Model project.

72 lines (71 loc) 9.15 kB
"use strict";var _=Object.create;var h=Object.defineProperty;var E=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,O=Object.prototype.hasOwnProperty;var A=(o,t)=>{for(var e in t)h(o,e,{get:t[e],enumerable:!0})},w=(o,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="functio\ n")for(let r of x(t))!O.call(o,r)&&r!==e&&h(o,r,{get:()=>t[r],enumerable:!(i=E(t,r))||i.enumerable});return o};var s=(o,t,e)=>(e=o!=null?_(k(o)):{},w(t||!o||!o.__esModule?h(e,"default",{value:o,enumerable:!0}):e,o)),R=o=>w(h({},"__\ esModule",{value:!0}),o);var J={};A(J,{default:()=>f});module.exports=R(J);var a=require("node:fs"),j=s(require("node:child_process")),y=s(require("node:os")), n=s(require("node:path")),C=s(require("node:url")),L=s(require("node:util")),N=s(require("@sap-devx/yeoman-ui-types"));var v=require("@vscode-logging/logger"),b="cap-project",F="Yeoman.CLI_",c=class{generator;childLogger;constructor(t,e){this. generator=t,this.childLogger=e?.getChildLogger({label:b})||null}debug(t="",...e){process.env.DEBUG&&(this.childLogger?.debug( t,...e),this.generator.debug(t,...e),this.generator.logContent=`${this.generator.logContent+t} `)}log(t="",...e){this.childLogger?.info(t,...e),this.generator.log(t,...e),this.generator.logContent=`${this.generator. logContent+t} `}info(t="",...e){this.log(t,...e)}warn(t="",...e){this.childLogger?.warn(t,...e),this.generator.log(t,...e),this.generator. logContent=`${this.generator.logContent+t} `}error(t,...e){this.childLogger?.error(t,...e),this.generator.log.error(t,...e),this.generator.logContent=`${this.generator. logContent+t} `}update(t){if(!this.childLogger&&t.logPath){let e={extName:`${F}${Date.now()}`,level:t.logLevel||"error",logPath:t.logPath, sourceLocationTracking:t.sourceLocationTracking||!1},i=(0,v.getExtensionLogger)(e);this.childLogger=i.getChildLogger({label:b})}}};var p=require("node:fs"),P=s(require("node:os")),m=s(require("node:path")),d=class o{static lobbyFile=m.join(P.homedir(), "tmpProjectTemplate.json");isActive=!1;input=null;projectNameValidator=null;async initialize(t,e){if(t?.[0]){if(this.isActive= !0,this.input=JSON.parse(t[0]),this.projectNameValidator=e||null,!this.input?.id)throw new Error('Missing string paramet\ er "id"');if(!this.input?.projectName)throw new Error('Missing string parameter "projectName"');if(!Array.isArray(this.input?. facets))throw new Error('Missing string array parameter "facets"');this.input.projectName=await this._sanitizeProjectName( this.input.projectName)}}async _sanitizeProjectName(t){if(!this.projectNameValidator||await this.projectNameValidator(t)=== !0)return t;let e=Date.now().toString(),i=e.length,r=t.length;return t.replace(/[^a-z0-9]/gi,"_").substring(0,Math.min(r, 65-i-1))+"-"+e}async _writeAnswer(t){let e={};try{e=JSON.parse(await p.promises.readFile(o.lobbyFile,"utf8"))}catch{}e[this. input?.id||"unknown"]=t,await p.promises.mkdir(m.dirname(o.lobbyFile),{recursive:!0}),await p.promises.writeFile(o.lobbyFile, JSON.stringify(e,null,2))}async writeError(t){let e=t.toString().split(/[\r\n]/)[0];await this._writeAnswer(`Failure: ${e}`)}async writeConfig(t){ await this._writeAnswer(t)}async fileExists(t){try{return await p.promises.access(t),!0}catch{return!1}}};var S=require("yeoman-generator"),I=L.promisify(j.execFile),u=y.platform()==="win32",H=["EvalError","InternalError","Ran\ geError","ReferenceError","SyntaxError","TypeError","URIError"],$="generation.log",f=class extends S{basWizardInstance=null;hasError=!1;uiConfig=null;logger;lobbyHandler;logContent="";answers={};prompts;setPromptsCallback;constructor(t,e){ super(t,e,{customInstallTask:!0}),this.setPromptsCallback=r=>{this.prompts?.setCallback(r)};let i=[{name:"CAP Project De\ tails",description:"Basic project information."}];this.prompts=new N.Prompts(i),this.logger=new c(this,e.logger),e.logger&& this._defineLoggerArguments(),this.basWizardInstance=e.appWizard,this.args=Array.isArray(t)?t:t?[t]:[]}async initializing(){ this.logger.debug("initializing"),this.logContent="",this.logger.update(this.options);try{process.chdir(this.destinationRoot()), this.logger.log("Starting CAP Project Generator...");let t=await this._getCdsDkInfo();this.logger.log(`Using @sap/cds-dk\ [${t.version}] from ${t.path}`),this.uiConfig=await this._loadUiConfig(n.join(t.path,"lib/init/bas"));let e=await a.promises. readFile(n.join(__dirname,"../../package.json")),i=JSON.parse(e.toString());this.logger.log(`Using ${i.name} [${i.version}\ ] from [${n.join(__dirname,"../..")}]`),this.logger.log(`Using root path [${this.destinationRoot()}]`),this.lobbyHandler= new d;let r=this.uiConfig.find(l=>l.target==="projectName")?.validate;await this.lobbyHandler.initialize(this.args||null, r),this.lobbyHandler.isActive&&(this.logger.log(),this.logger.log(`Running in Lobby mode: ${JSON.stringify(this.lobbyHandler. input)}`),this.logger.log())}catch(t){throw await this._prepareError(t)}}async prompting(){if(this.lobbyHandler.isActive) return;this.logger.debug("Prompting");let t=this._getPrompts();this.answers=t.length>0?await this.prompt(t):{}}configuring(){ if(!this.lobbyHandler.isActive){for(let t of this.uiConfig||[])t.target&&(this.answers[t.target]||(this.answers[t.target]= []),Array.isArray(this.answers[t.title||""])?this.answers[t.target].push(...this.answers[t.title||""]):this.answers[t.title|| ""]&&this.answers[t.target].push(this.answers[t.title||""]));Array.isArray(this.answers.projectName)&&(this.answers.projectName= this.answers.projectName[0])}}async writing(){this.logger.debug("writing");let t;try{this.lobbyHandler.isActive?(this.answers= {projectName:this.lobbyHandler.input?.projectName},t={...this.lobbyHandler.input,add:this.lobbyHandler.input?.add??this. lobbyHandler.input?.facets??[]}):t=this._filterOptions(this.uiConfig||[],{...this.options,...this.answers});let e=t.add. includes("java"),i=t.add.includes("nodejs");!e&&!i&&t.add.push("nodejs"),this.logger.log(),this.logger.log(`Creating pro\ ject with ${t.add.sort().join(", ")}`),e&&this.logger.log();let l=(await this._execCmd("cds",["init",this.answers.projectName|| "","--add",t.add.sort().join(",")],{cwd:this.destinationRoot(),shell:u})).stdout.split(/\n\r?/);for(let g of l)e?this.log( g):this.logger.log(g)}catch(e){throw await this._prepareError(e)}}async install(){let t=this._getProjectRoot();this.logger. log("Installing dependencies...");try{let i=(await this._execCmd("npm",["install"],{cwd:t,shell:u})).stdout.split(/\n\r?/); for(let r of i)this.logger.log(r);this.logger.log("Finished installing dependencies")}catch(e){this.logger.log("Error wh\ ile installing dependencies:"),this.logger.log(e.message??e)}}async end(){this.logger.log(),this.logger.log(`Done settin\ g up project ${this.answers.projectName}`),this.logger.log("Project is ready to use"),this.logger.log();let t=this._getProjectRoot(); this.destinationRoot(t),await this._writeLogAndSettings(t),this.lobbyHandler.isActive&&await this.lobbyHandler.writeConfig( t)}_getProjectRoot(){return n.join(this.destinationRoot(),this.answers.projectName||".")}async _writeLogAndSettings(t){this. logContent=this.logContent.replace(/\x1b\[[0-9;]*m/g,"");let e=n.join(t,".gen",$);await a.promises.mkdir(n.dirname(e),{recursive:!0}), await a.promises.writeFile(e,this.logContent);let i=n.join(t,".vscode/settings.json"),r;try{let g=await a.promises.readFile( i,"utf8");r=JSON.parse(g)}catch{r={}}r.actions??=[];let l={id:"openReadmeFile",actionType:"FILE",uri:C.pathToFileURL(e). href};r.actions.push(l),await a.promises.mkdir(n.dirname(i),{recursive:!0}),await a.promises.writeFile(i,JSON.stringify( r,null,4))}_getPrompts(){return(this.uiConfig||[]).filter(t=>!!t.target).map(t=>{let e={name:t.title||"",default:t.default, message:t.description,when:i=>t.enabled?t.enabled({...this.options,...i}):!0};return typeof t.default=="boolean"?e.type= "confirm":typeof t.default=="string"&&(t.choices?(t.multiple?e.type="checkbox":e.type="list",e.choices=t.choices):e.type= "input"),typeof t.validate=="function"&&(e.validate=t.validate),t.guiOptions&&(e.guiOptions=t.guiOptions),e})}_filterOptions(t,e){ return t.reduce((i,r)=>(r.target&&(i[r.target]=e[r.target]),i),{})}async _prepareError(t){return t instanceof Error&&(H. includes(t.name)||(t.stack=void 0)),this.logger.error(t),this.lobbyHandler?.isActive&&await this.lobbyHandler.writeError( t),t}async _getCdsDkInfo(){let t=await this._execCmd("cds",["env","get","_home_cds-dk","--json"],{cwd:y.homedir(),shell:u}), e=JSON.parse(t.stdout.toString()),i=require(n.join(e,"package.json"));return{path:n.normalize(e),version:i.version}}_defineLoggerArguments(){ this.argument("logPath",{description:"The log path",required:!1,type:String}),this.argument("logLevel",{default:"error", description:"The log level",required:!1,type:String}),this.option("sourceLocationTracking",{alias:"s",default:!1,description:"\ The source location tracking",type:Boolean})}async _execCmd(t,e,i={}){return I(t,e,{shell:u,encoding:"utf8",...i})}async _readJsonFile(t){ let e=await a.promises.readFile(t,"utf8");return JSON.parse(e)}async _loadUiConfig(t){let e=require(t);return e.default?? e}}; //# sourceMappingURL=index.js.map