Skip to content

Commit

Permalink
Rework the import alias regex
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesdaniels committed Aug 17, 2021
1 parent 6218ba2 commit ec312e3
Showing 1 changed file with 22 additions and 17 deletions.
39 changes: 22 additions & 17 deletions src/schematics/update/v7/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@ import { Rule, SchematicContext, SchematicsException, Tree } from '@angular-devk
import { overwriteIfExists, safeReadJSON, stringifyFormatted } from '../../ng-add-common';
import { default as defaultDependencies, firebaseFunctions } from '../../versions.json';

const FIREBASE_IMPORT_REGEX = /(?<key>import|export)\s+(?:(?<alias>[\w,{}\s\*]+)\s+from)?\s*(?:(["'])?firebase\/(?<ref>[@\w\s\\\/.-]+)\3?)\s*;/g;
const AT_FIREBASE_IMPORT_REGEX = /(?<key>import|export)\s+(?:(?<alias>[\w,{}\s\*]+)\s+from)?\s*(?:(["'])?@firebase\/(?<ref>[@\w\s\\\/.-]+)\3?)\s*;/g;
const ANGULAR_FIRE_IMPORT_REGEX = /(?<key>import|export)\s+(?:(?<alias>[\w,{}\s\*]+)\s+from)?\s*(?:(["'])?@angular\/fire\/(?<ref>[@\w\s\\\/.-]+)\3?)\s*;/g;
const IMPORT_REGEX = /(?<key>import|export)\s+(?:(?<alias>[\w,{}\s\*]+)\s+from)?\s*(?:(?<quote>["'])?(?<ref>[@\w\s\\\/.-]+)\3?)\s*(?<term>[;\n])/g;
interface ImportRegexMatch {
key: string;
alias: string;
ref: string;
quote: string;
term: string;
}

export const ngUpdate = (): Rule => (
host: Tree,
Expand Down Expand Up @@ -49,20 +54,20 @@ export const ngUpdate = (): Rule => (
if (!content) {
return;
}
let didChangeContent = false;
if (content.match(FIREBASE_IMPORT_REGEX)) {
content.replace(FIREBASE_IMPORT_REGEX, '$1 $2 from $3firebase/compat/$4$3;');
didChangeContent = true;
}
if (content.match(AT_FIREBASE_IMPORT_REGEX)) {
content.replace(AT_FIREBASE_IMPORT_REGEX, '$1 $2 from $3@firebase/compat/$4$3;');
didChangeContent = true;
}
if (content.match(ANGULAR_FIRE_IMPORT_REGEX)) {
content.replace(ANGULAR_FIRE_IMPORT_REGEX, '$1 $2 from $3@angular/fire/compat/$4$3;');
didChangeContent = true;
}
if (didChangeContent) {
const newContent = content.replace(IMPORT_REGEX, (substring, ...args) => {
const { alias, key, ref, quote, term }: ImportRegexMatch = args.pop();
if (ref.startsWith('@angular/fire') && !ref.startsWith('@angular/fire/compat')) {
return `${key} ${alias} from ${quote}${ref.replace('@angular/fire', '@angular/fire/compat')}${quote}${term}`;
}
if (ref.startsWith('firebase') && !ref.startsWith('firebase/compat')) {
return `${key} ${alias} from ${quote}${ref.replace('firebase', 'firebase/compat')}${quote}${term}`;
}
if (ref.startsWith('@firebase')) {
return `${key} ${alias} from ${quote}${ref.replace('@firebase', 'firebase')}${quote}${term}`;
}
return substring;
});
if (content !== newContent) {
host.overwrite(filePath, content);
}
});
Expand Down

0 comments on commit ec312e3

Please sign in to comment.