Skip to content

Commit

Permalink
fix: resolve baseDir in factory init method; factory extend bug
Browse files Browse the repository at this point in the history
  • Loading branch information
neikvon committed Dec 17, 2020
1 parent f81c8f0 commit 29245e3
Show file tree
Hide file tree
Showing 5 changed files with 167 additions and 123 deletions.
142 changes: 87 additions & 55 deletions src/commands/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,66 +28,80 @@ export default class CommandCreate extends Command {
})
let templates
let useSubTemplate = false
let targetTemplate
let subDirectory
let targetDir

const cwd = process.cwd()
// if is fbi project
const usingFactory = this.context.get('config.factory')
const { subDirectory, targetDir } = await this.getTargetDir(projectName)
if (usingFactory) {
const factory = this.factory.resolveFactory(usingFactory.id)
const template = factory?.resolveTemplate(usingFactory.template)
const subTemplates = template?.templates

if (factoryOrTemplateName) {
// search factory by name
const foundFactory = this.factory.resolveFactory(factoryOrTemplateName)
if (foundFactory) {
const factoryPath = foundFactory.options?.rootDir
? relative(cwd, foundFactory.options.rootDir)
: ''
this.log(
`Using ${this.style.bold`${foundFactory.id}@${foundFactory._version}`}${
factoryPath ? ' from ' + factoryPath : ''
}...`
)
templates = foundFactory.templates
}

// search all templates by name
if (!isValidArray(templates)) {
templates = this.factory.resolveTemplates(factoryOrTemplateName)
}
if (factoryOrTemplateName) {
const hitSubTemplate = subTemplates?.find((x) => x.id === factoryOrTemplateName)

if (!isValidArray(templates)) {
// not found, add factory
const factory = await this.addFromRemote(factoryOrTemplateName, {
...flags,
targetDir,
yes: true
})
if (hitSubTemplate) {
targetTemplate = hitSubTemplate
useSubTemplate = true
}
} else if (isValidArray(subTemplates)) {
const { templateType } = (await this.prompt({
type: 'select',
name: 'templateType',
hint: 'Use arrow-keys, <return> to submit',
message: `Pick an action:`,
choices: ['Use sub templates', 'Use other templates', 'Cancel']
})) as any

if (factory && factory.templates) {
templates = factory.templates
} else {
this.error(`No package named '${factoryOrTemplateName}' found in npmjs.com`)
this.error(`No repository named '${factoryOrTemplateName}' found in github.com`)
if (templateType === 'Cancel') {
this.exit()
} else if (templateType === 'Use sub templates') {
templates = subTemplates
useSubTemplate = true
}
}
} else {
if (usingFactory) {
const factory = this.factory.resolveFactory(usingFactory.id)
const template = factory?.resolveTemplate(usingFactory.template)
templates = template?.templates || []
if (isValidArray(templates)) {
const { templateType } = (await this.prompt({
type: 'select',
name: 'templateType',
hint: 'Use arrow-keys, <return> to submit',
message: `Pick an action:`,
choices: ['Use sub templates', 'Use other templates', 'Cancel']
})) as any
useSubTemplate = templateType === 'Use sub templates'
}

if (!targetTemplate && !isValidArray(templates)) {
if (factoryOrTemplateName) {
// search factory by name
const foundFactory = this.factory.resolveFactory(factoryOrTemplateName)
if (foundFactory) {
const factoryPath = foundFactory.baseDir ? relative(cwd, foundFactory.baseDir) : ''
this.log(
`Using ${this.style.bold`${foundFactory.id}${
foundFactory._version ? '@' + foundFactory._version : ''
}`}${factoryPath ? ' from ' + factoryPath : ''}...`
)
templates = foundFactory.templates
}
}

if (!useSubTemplate) {
this.factory.createAllFactories()
// search all templates by name
if (!isValidArray(templates)) {
templates = this.factory.resolveTemplates(factoryOrTemplateName)
}

if (!isValidArray(templates)) {
// not found, add factory
const target = await this.getTargetDir(projectName)
subDirectory = target.subDirectory
targetDir = target.targetDir
const factory = await this.addFromRemote(factoryOrTemplateName, {
...flags,
targetDir,
yes: true
})

if (factory && factory.templates) {
templates = factory.templates
} else {
this.error(`No package named '${factoryOrTemplateName}' found in npmjs.com`)
this.error(`No repository named '${factoryOrTemplateName}' found in github.com`)
}
}
} else {
templates = this.factory.resolveTemplates()
}
}
Expand All @@ -96,11 +110,24 @@ export default class CommandCreate extends Command {
this.error('No templates available').exit()
}

const template = await this.selectTempate(templates as [])
if (!targetTemplate) {
targetTemplate = await this.selectTempate(templates as [])
}

if (targetTemplate) {
if (!targetDir) {
if (useSubTemplate) {
targetDir = cwd
subDirectory = ''
} else {
const target = await this.getTargetDir(projectName)
subDirectory = target.subDirectory
targetDir = target.targetDir
}
}

if (template) {
await this.createProject({
template,
template: targetTemplate,
subDirectory,
targetDir,
flags,
Expand Down Expand Up @@ -134,7 +161,12 @@ export default class CommandCreate extends Command {
{
factory: {
id: factory.id,
path: storeInfo?.version?.latest?.dir || factory.options.rootDir,
path:
storeInfo?.version?.latest?.dir ||
storeInfo?.path ||
factory.baseDir ||
factory.options?.rootDir ||
join(process.cwd(), subDirectory || '', 'node_modules', factory.id),
version: storeInfo?.version?.latest?.short ?? '',
template: template.id
},
Expand Down Expand Up @@ -163,7 +195,7 @@ export default class CommandCreate extends Command {
name: info.name,
path: info.path,
factory: factory.id,
version: factory.version?.latest?.short ?? '',
version: info.factory?.version,
template: template.id,
features: info.features,
createdAt: Date.now()
Expand Down
17 changes: 8 additions & 9 deletions src/commands/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,15 +96,15 @@ export default class CommandList extends Command {

private async showDetail(factory: Factory, current: any, idx?: number) {
const showIdx = isNumber(idx)
const isCurrent = current && factory.id === current.id
const isCurrent = factory.id === current?.id
const index = showIdx ? this.style.bold(symbols.numbers[idx as number]) : ' '
const title = this.style.bold(factory.id)
const version = isCurrent && current.version ? this.style.italic(`@${current.version}`) : ''
let from =
factory.options?.type === 'git'
? this.store.get(factory.id)?.from
: `https://www.npmjs.com/package/${factory.id}`
const local = factory.options?.rootDir
factory.type === 'npm'
? `https://www.npmjs.com/package/${factory.id}`
: this.store.get(factory.id)?.from
const local = factory.type === 'local' ? '' : factory.baseDir

let txt = `\n${index} ${title}${version}
${this.style.dim`From: ${from}`}`
Expand Down Expand Up @@ -141,10 +141,9 @@ export default class CommandList extends Command {
const title = '\n\n Templates:'
txt += title
for (const t of factory.templates) {
txt += this.colWrap(
this.lines(`- ${t.id}`, this.padWidth - 1, 2, true, true),
this.lines(t.description)
)
const name = ` - ${t.id}`.padEnd(this.padWidth + 2, ' ')
const nameStr = current?.template === t.id ? this.style.green(name) : name
txt += this.colWrap([nameStr], this.lines(t.description))

if (isValidArray(t.templates)) {
for (const subt of t.templates) {
Expand Down
40 changes: 21 additions & 19 deletions src/core/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { Command } from './command'
import { Template } from './template'
import { Plugin } from './plugin'
import { Version } from './version'
import { pathResolve, pkgDir } from '../utils'

type VersionInfo = {
baseDir: string
Expand All @@ -16,11 +15,12 @@ export type FactoryType = 'git' | 'npm' | 'local'

export type FactoryInfo = {
id: string
type: string
type: FactoryType
from: string
path: string
updatedAt: number
version?: VersionInfo
global?: boolean
}

export type FactoryOptions = {
Expand All @@ -38,36 +38,38 @@ export abstract class Factory extends BaseClass {
public version: Version | null = null
public _version = ''
public isGlobal = false
public baseDir = ''
public type: FactoryType = 'npm'

constructor(public options?: FactoryOptions) {
super()
this.options = {
...this.options,
type: this.options?.type || 'git'
}
}

public init() {
if (!this.options) {
return
if (options) {
if (options.baseDir) {
this.baseDir = options.baseDir
}
if (options.type) {
this.type = options.type
}
}
}

this.options.rootDir = this.options.rootDir ? pkgDir.sync(this.options.rootDir) : ''
public init(baseDir?: string, type?: FactoryType) {
this.baseDir = this.baseDir || baseDir || ''
this.type = this.type || type || 'npm'

if (!this.options.rootDir) {
if (!this.baseDir) {
return
}

if (this.options.type === 'git') {
this.version = new Version(this.options.rootDir)
if (this.type === 'git') {
this.version = new Version(this.baseDir)
}

// get version number
try {
const pkgPath = pathResolve(join(this.options.rootDir, 'package.json'))
const { version } = require(pkgPath)
if (version) {
this._version = version
const pkg = require(join(this.baseDir, 'package.json'))
if (pkg?.version) {
this._version = pkg.version
}
} catch (err) {}
}
Expand Down
24 changes: 15 additions & 9 deletions src/core/template.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { join } from 'path'
import { isAbsolute, join } from 'path'
import { BaseClass } from './base'
import { Factory } from './factory'
import { isValidArray, isFunction, isString, ensureArray, isValidObject } from '../utils'

type FileMap = {
Expand All @@ -22,6 +23,7 @@ export abstract class Template extends BaseClass {
[key: string]: any
public abstract id = ''
public description = ''
// absolute path to template dir
public path = ''
public templates: Template[] = []
protected renderer?: Function
Expand All @@ -31,7 +33,7 @@ export abstract class Template extends BaseClass {
protected _debugPrefix = ''
private rootPath = ''

constructor() {
constructor(public factory: Factory) {
super()
}

Expand All @@ -40,12 +42,12 @@ export abstract class Template extends BaseClass {
const template = this.templates.find((x) => x.id === templateId)
if (!template) {
this.debug(
`Template (${this.id}${this.factory ? `:${this.factory.id}` : ''}):`,
`Template (${this.id}${this.factory?.id || ''}):`,
`template "${templateId}" not found`
)
} else {
this.debug(
`Template (${this.id}${this.factory ? `:${this.factory.id}` : ''}):`,
`Template (${this.id}${this.factory?.id || ''}):`,
`found template "${templateId}"`
)
}
Expand Down Expand Up @@ -100,12 +102,16 @@ export abstract class Template extends BaseClass {
this.data = data
}

if (!this.data.factory || !this.data?.factory?.path) {
this.error(`need path of factory`)
return this.exit()
}
if (isAbsolute(this.path)) {
this.rootPath = this.path
} else {
const factoryDir = this.data?.factory?.path || this.factory.baseDir

this.rootPath = join(this.data.factory.path, this.path)
if (!factoryDir) {
this.error(`Cann't find the path of factory. Please update the factory.`)
return this.exit()
}
}
}
protected async gathering(flags: any): Promise<any> {}
private async afterGathering() {
Expand Down
Loading

0 comments on commit 29245e3

Please sign in to comment.