1 ! Copyright (C) 2007, 2008 Phil Dawes
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel sequences io namespaces make combinators
4 unicode.categories io.files combinators.short-circuit
5 io.streams.string fry memoize ;
10 CHAR: , delimiter set-global
14 : delimiter> ( -- delimiter ) delimiter get ; inline
16 MEMO: (field-end) ( delimiter -- delimiter' )
19 : skip-to-field-end ( -- endchar )
20 delimiter> (field-end) read-until nip ; inline
24 MEMO: (quoted-field) ( delimiter -- delimiter' )
27 : not-quoted-field ( -- endchar )
28 delimiter> (quoted-field) read-until
30 { CHAR: " [ 2drop quoted-field ] }
31 { delimiter> [ swap [ blank? ] trim % ] }
32 { CHAR: \n [ swap [ blank? ] trim % ] }
33 { f [ swap [ blank? ] trim % ] }
36 : maybe-escaped-quote ( -- endchar )
38 { CHAR: " [ , quoted-field ] }
41 [ 2drop skip-to-field-end ]
44 : quoted-field ( -- endchar )
46 drop % maybe-escaped-quote ;
48 : field ( -- sep string )
49 [ not-quoted-field ] "" make ;
52 f delimiter> '[ dup _ = ]
53 [ drop field , ] do while ;
55 : row ( -- eof? array[string] )
59 [ dup [ empty? ] all? [ drop ] [ , ] if ]
64 : csv-row ( stream -- row )
65 [ row nip ] with-input-stream ;
67 : csv ( stream -- rows )
68 [ [ (csv) ] { } make ] with-input-stream
69 dup last { "" } = [ but-last ] when ;
71 : string>csv ( string -- csv )
74 : file>csv ( path encoding -- csv )
77 : with-delimiter ( ch quot -- )
78 [ delimiter ] dip with-variable ; inline
82 : needs-escaping? ( cell -- ? )
84 dup "\n\"" member? [ drop t ] [ _ = ] if
87 : escape-quotes ( cell -- cell' )
91 [ dup CHAR: " = [ , ] [ drop ] if ] bi
95 : enclose-in-quotes ( cell -- cell' )
96 "\"" dup surround ; inline
98 : escape-if-required ( cell -- cell' )
100 [ escape-quotes enclose-in-quotes ] when ; inline
104 : write-row ( row -- )
105 delimiter> '[ _ write1 ]
106 [ escape-if-required write ] interleave nl ; inline
110 : (write-csv) ( rows -- )
115 : write-csv ( rows stream -- )
116 [ (write-csv) ] with-output-stream ;
118 : csv>string ( csv -- string )
119 [ (write-csv) ] with-string-writer ;
121 : csv>file ( rows path encoding -- ) <file-writer> write-csv ;