From af467ae996d6ee17d2a96056001f6aed84250a49 Mon Sep 17 00:00:00 2001
From: Vikram Subramanian <viks@google.com>
Date: Mon, 8 Oct 2018 22:59:24 -0700
Subject: [PATCH] fix(@schematics/angular): ast utils - handle NgModule with no
 newlines

Exposed in Google where the formatting is different. Check for null before using a regex match result.
---
 packages/schematics/angular/utility/ast-utils.ts  |  2 +-
 .../schematics/angular/utility/ast-utils_spec.ts  | 15 +++++++++++++++
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/packages/schematics/angular/utility/ast-utils.ts b/packages/schematics/angular/utility/ast-utils.ts
index 96479d02e964..2442f0661793 100644
--- a/packages/schematics/angular/utility/ast-utils.ts
+++ b/packages/schematics/angular/utility/ast-utils.ts
@@ -395,7 +395,7 @@ export function addSymbolToNgModuleMetadata(
       // Get the indentation of the last element, if any.
       const text = node.getFullText(source);
       const matches = text.match(/^\r?\n\s*/);
-      if (matches.length > 0) {
+      if (matches && matches.length > 0) {
         toInsert = `,${matches[0]}${metadataField}: [${symbolName}]`;
       } else {
         toInsert = `, ${metadataField}: [${symbolName}]`;
diff --git a/packages/schematics/angular/utility/ast-utils_spec.ts b/packages/schematics/angular/utility/ast-utils_spec.ts
index 1ea30a5126a5..bd694b6499a3 100644
--- a/packages/schematics/angular/utility/ast-utils_spec.ts
+++ b/packages/schematics/angular/utility/ast-utils_spec.ts
@@ -151,4 +151,19 @@ describe('ast utils', () => {
     const output = applyChanges(modulePath, moduleContent, changes || []);
     expect(output).toMatch(/imports: \[HelloWorld],\r?\n/m);
   });
+
+  it('should handle NgModule with no newlines', () => {
+    const moduleContent = `
+      import { BrowserModule } from '@angular/platform-browser';
+      import { NgModule } from '@angular/core';
+
+      @NgModule({imports: [BrowserModule], declarations: []})
+      export class AppModule { }
+    `;
+    const source = getTsSource(modulePath, moduleContent);
+    const changes = addExportToModule(source, modulePath, 'FooComponent', './foo.component');
+    const output = applyChanges(modulePath, moduleContent, changes);
+    expect(output).toMatch(/import { FooComponent } from '.\/foo.component';/);
+    expect(output).toMatch(/exports: \[FooComponent\]/);
+  });
 });