From 2af69ccf0f4f7f884834258ac470e1c175248e78 Mon Sep 17 00:00:00 2001 From: psschand Date: Fri, 3 May 2019 21:31:13 +0500 Subject: [PATCH] CSV: escape quotes in toCSV (#16874) --- packages/grafana-ui/src/utils/csv.test.ts | 3 +++ packages/grafana-ui/src/utils/csv.ts | 2 +- packages/grafana-ui/src/utils/testdata/roundtrip.csv | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/grafana-ui/src/utils/csv.test.ts b/packages/grafana-ui/src/utils/csv.test.ts index 90207662907..19132b92f1e 100644 --- a/packages/grafana-ui/src/utils/csv.test.ts +++ b/packages/grafana-ui/src/utils/csv.test.ts @@ -48,11 +48,13 @@ function norm(csv: string): string { describe('write csv', () => { it('should write the same CSV that we read', () => { + const firstRow = [10, 'this "has quotes" inside', true]; const path = __dirname + '/testdata/roundtrip.csv'; const csv = fs.readFileSync(path, 'utf8'); const data = readCSV(csv); const out = toCSV(data, { headerStyle: CSVHeaderStyle.full }); expect(data.length).toBe(1); + expect(data[0].rows[0]).toEqual(firstRow); expect(data[0].fields.length).toBe(3); expect(norm(out)).toBe(norm(csv)); @@ -63,6 +65,7 @@ describe('write csv', () => { const f = readCSV(shorter); const fields = f[0].fields; expect(fields.length).toBe(3); + expect(f[0].rows[0]).toEqual(firstRow); expect(fields.map(f => f.name).join(',')).toEqual('a,b,c'); // the names }); }); diff --git a/packages/grafana-ui/src/utils/csv.ts b/packages/grafana-ui/src/utils/csv.ts index 17dbec9268d..60acadc4f21 100644 --- a/packages/grafana-ui/src/utils/csv.ts +++ b/packages/grafana-ui/src/utils/csv.ts @@ -266,7 +266,7 @@ function writeValue(value: any, config: CSVConfig): string { const str = value.toString(); if (str.includes('"')) { // Escape the double quote characters - return config.quoteChar + str.replace('"', '""') + config.quoteChar; + return config.quoteChar + str.replace(/"/gi, '""') + config.quoteChar; } if (str.includes('\n') || str.includes(config.delimiter)) { return config.quoteChar + str + config.quoteChar; diff --git a/packages/grafana-ui/src/utils/testdata/roundtrip.csv b/packages/grafana-ui/src/utils/testdata/roundtrip.csv index 0b4b86a31f3..68b59862dea 100644 --- a/packages/grafana-ui/src/utils/testdata/roundtrip.csv +++ b/packages/grafana-ui/src/utils/testdata/roundtrip.csv @@ -1,7 +1,7 @@ #name#a,b,c #type#number,string,boolean #unit#ms,,s -10,AA,true +10,"this ""has quotes"" inside",true 20,XX,false 30,YY,false 40,ZZ,true