|
| 1 | +/** |
| 2 | + * @module @microsoft/bf-lg-cli |
| 3 | + */ |
| 4 | +/** |
| 5 | + * Copyright (c) Microsoft Corporation. All rights reserved. |
| 6 | + * Licensed under the MIT License. |
| 7 | + */ |
| 8 | + |
| 9 | +import {Command, flags, CLIError} from '@microsoft/bf-cli-command' |
| 10 | +import {Helper} from '../../utils' |
| 11 | +import {Templates, DiagnosticSeverity, Diagnostic} from 'botbuilder-lg' |
| 12 | +import * as path from 'path' |
| 13 | +import * as fs from 'fs-extra' |
| 14 | + |
| 15 | +const NEWLINE = require('os').EOL |
| 16 | + |
| 17 | +type FullTemplateName = string |
| 18 | +type TemplateName = string |
| 19 | +type Source = string |
| 20 | +type SourceToReferences = Map<Source, TemplateName[]> |
| 21 | +type TemplateToReferences = Map<FullTemplateName, SourceToReferences> |
| 22 | + |
| 23 | +export default class AnalyzeCommand extends Command { |
| 24 | + static description = 'Analyze templates in .lg files to show all the places where a template is used' |
| 25 | + |
| 26 | + static flags: flags.Input<any> = { |
| 27 | + in: flags.string({char: 'i', description: 'LG File or folder that contains .lg file(s)', required: true}), |
| 28 | + recurse: flags.boolean({char: 'r', description: 'Consider sub-folders to find .lg file(s)'}), |
| 29 | + out: flags.string({char: 'o', description: 'Output file or folder name. If not specified stdout will be used as output'}), |
| 30 | + force: flags.boolean({char: 'f', description: 'If --out flag is provided with the path to an existing file, overwrites that file'}), |
| 31 | + help: flags.help({char: 'h', description: 'lg:analyze help'}), |
| 32 | + } |
| 33 | + |
| 34 | + async run() { |
| 35 | + const {flags} = this.parse(AnalyzeCommand) |
| 36 | + |
| 37 | + const lgFilePaths = Helper.findLGFiles(flags.in, flags.recurse) |
| 38 | + |
| 39 | + Helper.checkInputAndOutput(lgFilePaths) |
| 40 | + |
| 41 | + const allTemplates = [] |
| 42 | + for (const filePath of lgFilePaths) { |
| 43 | + const templates = Templates.parseFile(filePath) |
| 44 | + this.checkDiagnostics(templates.allDiagnostics) |
| 45 | + allTemplates.push(templates) |
| 46 | + } |
| 47 | + |
| 48 | + const templateToReferences = this.templateUsage(allTemplates) |
| 49 | + await this.writeTemplateReferences(templateToReferences, flags.out, flags.force) |
| 50 | + } |
| 51 | + |
| 52 | + private templateUsage(templates: Templates[]): TemplateToReferences { |
| 53 | + const usage = new Map<FullTemplateName, SourceToReferences>() |
| 54 | + const analyzed = new Set<Source>() |
| 55 | + for (const source of templates) { |
| 56 | + // Map from simple to full name and initialize template usage |
| 57 | + const nameToFullname = new Map<string, string>() |
| 58 | + for (const template of source.allTemplates) { |
| 59 | + const fullName = `${template.sourceRange.source}:${template.name}` |
| 60 | + nameToFullname.set(template.name, fullName) |
| 61 | + if (!usage.get(fullName)) { |
| 62 | + usage.set(fullName, new Map<Source, TemplateName[]>()) |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + // Add references from each template that is in an unanalyzed source file |
| 67 | + for (const template of source.allTemplates) { |
| 68 | + // Analyze each original source template only once |
| 69 | + if (!analyzed.has(template.sourceRange.source)) { |
| 70 | + const info = source.analyzeTemplate(template.name) |
| 71 | + for (const reference of info.TemplateReferences) { |
| 72 | + const source = template.sourceRange.source as string |
| 73 | + const referenceSources = usage.get(nameToFullname.get(reference) as string) as Map<string, string[]> |
| 74 | + let referenceSource = referenceSources.get(source) |
| 75 | + if (!referenceSource) { |
| 76 | + referenceSource = [] |
| 77 | + referenceSources.set(source, referenceSource) |
| 78 | + } |
| 79 | + referenceSource.push(template.name) |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + // Add in the newly analyzed sources |
| 85 | + for (const imported of source.imports) { |
| 86 | + analyzed.add(path.resolve(path.dirname(source.source), imported.id)) |
| 87 | + } |
| 88 | + analyzed.add(source.source) |
| 89 | + } |
| 90 | + return usage |
| 91 | + } |
| 92 | + |
| 93 | + private async writeTemplateReferences(templateToReferences: TemplateToReferences, out: string, force: boolean) { |
| 94 | + if (templateToReferences !== undefined && templateToReferences.size >= 0) { |
| 95 | + const analysisContent = this.generateAnalysisResult(templateToReferences) |
| 96 | + if (out) { |
| 97 | + // write to file |
| 98 | + const outputFilePath = this.getOutputFile(out) |
| 99 | + Helper.writeContentIntoFile(outputFilePath, analysisContent, force) |
| 100 | + this.log(`Analysis result have been written into file ${outputFilePath}`) |
| 101 | + } else { |
| 102 | + // write to console |
| 103 | + this.log(analysisContent) |
| 104 | + } |
| 105 | + } else { |
| 106 | + this.log('No analysis result') |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + private checkDiagnostics(diagnostics: Diagnostic[]) { |
| 111 | + const errors = diagnostics.filter(u => u.severity === DiagnosticSeverity.Error) |
| 112 | + if (errors && errors.length > 0) { |
| 113 | + throw new CLIError(errors.map(u => u.toString()).join('\n')) |
| 114 | + } |
| 115 | + |
| 116 | + const warnings = diagnostics.filter(u => u.severity === DiagnosticSeverity.Warning) |
| 117 | + if (warnings && warnings.length > 0) { |
| 118 | + this.warn(warnings.map(u => u.toString()).join('\n')) |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + private getOutputFile(out: string): string { |
| 123 | + const base = Helper.normalizePath(path.resolve(out)) |
| 124 | + const root = path.dirname(base) |
| 125 | + if (!fs.existsSync(root)) { |
| 126 | + throw new Error(`Folder ${root} not exist`) |
| 127 | + } |
| 128 | + |
| 129 | + const extension = path.extname(base) |
| 130 | + if (extension) { |
| 131 | + // file |
| 132 | + return base |
| 133 | + } |
| 134 | + |
| 135 | + // folder |
| 136 | + // default to analysisResult.txt |
| 137 | + return path.join(base, 'analysisResult.txt') |
| 138 | + } |
| 139 | + |
| 140 | + private templateName(fullname: string): string { |
| 141 | + const colon = fullname.lastIndexOf(':') |
| 142 | + return fullname.substring(colon + 1) |
| 143 | + } |
| 144 | + |
| 145 | + private shortTemplateName(fullname: string): string { |
| 146 | + const colon = fullname.lastIndexOf(':') |
| 147 | + return path.basename(fullname.substring(0, colon)) + fullname.substring(colon) |
| 148 | + } |
| 149 | + |
| 150 | + private generateAnalysisResult(templateToReferences: TemplateToReferences): string { |
| 151 | + let result = '' |
| 152 | + for (const templateToReference of templateToReferences) { |
| 153 | + const shortTemplateName = this.shortTemplateName(templateToReference[0]) |
| 154 | + result += `${shortTemplateName} references:${NEWLINE}` |
| 155 | + const references = templateToReference[1] |
| 156 | + for (const reference of references) { |
| 157 | + result += ` ${path.basename(reference[0])}: ${reference[1].map(r => this.templateName(r)).join(', ')}${NEWLINE}` |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + return result |
| 162 | + } |
| 163 | +} |
0 commit comments