import * as request from 'request-promise' ; import { Command , flags } from '@oclif/command' ; import { exec } from 'shelljs' ; import { prompt } from 'inquirer' ; import { red , bold } from 'chalk' ; const url = 'https://raw.githubusercontent.com/bntzio/gatsby-generator/master/src/api/starters.json' ; const fetchStarters = async ( ) => { const opts = { url , method : 'get' } ; try { const response = await request ( opts ) ; return Promise . resolve ( response ) ; } catch ( error ) { return Promise . reject ( error ) ; } } ; class GatsbyGenerator extends Command { static description = bold ( 'Generate Gatsby Starters in Seconds 🎰' ) ; static examples = [ `$ gatsby-generate` , `$ gatsby-generate --npx` ] ; static flags = { version : flags . version ( { char : 'v' } ) , help : flags . help ( { char : 'h' } ) , npx : flags . boolean ( { char : 'x' , description : 'execute binary with npx' } ) } ; async run ( ) { const { flags } = this . parse ( GatsbyGenerator ) ; type StartersType = { name : string ; description : string ; url : string ; } [ ] ; const buildChoices = ( starters ) => { let choices = [ ] ; starters . forEach ( starter => { const choice = `${ red . bold ( starter . name + ':' ) } ${ bold ( starter . description ) }` ; choices . push ( choice ) ; } ) ; return choices ; } ; const selectStarter = ( starters ) => { const choices = [ { type : 'list' , name : 'selectedStarter' , message : 'Choose your Gatsby starter 🎰' , choices : ( ) => buildChoices ( starters ) } ] ; const projectName = [ { type : 'input' , name : 'chosenName' , message : 'Enter your project name' } ] ; return prompt ( choices ) . then ( ( answer ) => { const selectedStarter = answer . selectedStarter ; starters . forEach ( starter => { const choiceOpt = `${ red . bold ( starter . name + ':' ) } ${ bold ( starter . description ) }` ; if ( choiceOpt === selectedStarter ) { return prompt ( projectName ) . then ( ( answers ) => { if ( answers . chosenName . length > 0 ) { this . log ( bold ( `\nDownloading ${ starter . name } under ${ answers . chosenName }...\n` ) ) ; if ( flags . npx ) { exec ( `npx gatsby new ${ answers . chosenName } ${ starter . url }` ) ; } else { exec ( `gatsby new ${ answers . chosenName } ${ starter . url }` ) ; } this . log ( bold ( '\nYour Gatsby Starter was downloaded successfully ✨' ) ) ; this . log ( bold ( 'Happy Gatsbying! 😄' ) ) ; } else { this . log ( red . bold ( '\n🚨 Error! ' ) + bold ( 'The project name should be at least 1 character long!' ) ) ; } } ) ; } } ) ; } ) ; } ; const starters = fetchStarters ( ) ; starters . then ( ( result ) => { const parsedStarters = JSON . parse ( result ) . starters ; selectStarter ( parsedStarters ) ; } ) . catch ( ( error ) => { this . log ( error ) ; } ) ; } } export = GatsbyGenerator ;