]> gitweb.factorcode.org Git - factor.git/blob - basis/csv/csv.factor
Merge branch 'master' of git://factorcode.org/git/factor
[factor.git] / basis / csv / csv.factor
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 IN: csv
6
7 SYMBOL: delimiter
8
9 CHAR: , delimiter set-global
10
11 <PRIVATE
12
13 : delimiter> ( -- delimiter ) delimiter get ; inline
14     
15 DEFER: quoted-field ( -- endchar )
16     
17 : trim-whitespace ( str -- str )
18     [ blank? ] trim ; inline
19
20 : skip-to-field-end ( -- endchar )
21   "\n" delimiter> suffix read-until nip ; inline
22   
23 : not-quoted-field ( -- endchar )
24     "\"\n" delimiter> suffix read-until
25     dup {
26         { CHAR: "    [ 2drop quoted-field ] }
27         { delimiter> [ swap trim-whitespace % ] }
28         { CHAR: \n   [ swap trim-whitespace % ] }
29         { f          [ swap trim-whitespace % ] }
30     } case ;
31   
32 : maybe-escaped-quote ( -- endchar )
33     read1 dup {
34         { CHAR: "    [ , quoted-field ] }
35         { delimiter> [ ] }
36         { CHAR: \n   [ ] }
37         [ 2drop skip-to-field-end ]
38     } case ;
39   
40 : quoted-field ( -- endchar )
41     "\"" read-until
42     drop % maybe-escaped-quote ;
43
44 : field ( -- sep string )
45     [ not-quoted-field ] "" make  ;
46
47 : (row) ( -- sep )
48     field , 
49     dup delimiter get = [ drop (row) ] when ;
50
51 : row ( -- eof? array[string] )
52     [ (row) ] { } make ;
53
54 : (csv) ( -- )
55     row harvest [ , ] unless-empty [ (csv) ] when ;
56   
57 PRIVATE>
58
59 : csv-row ( stream -- row )
60     [ row nip ] with-input-stream ;
61
62 : csv ( stream -- rows )
63     [ [ (csv) ] { } make ] with-input-stream ;
64
65 : file>csv ( path encoding -- csv )
66     <file-reader> csv ;
67
68 : with-delimiter ( ch quot -- )
69     [ delimiter ] dip with-variable ; inline
70
71 <PRIVATE
72
73 : needs-escaping? ( cell -- ? )
74     [ { [ "\n\"" member? ] [ delimiter get = ] } 1|| ] any? ; inline
75
76 : escape-quotes ( cell -- cell' )
77     [
78         [
79             [ , ]
80             [ dup CHAR: " = [ , ] [ drop ] if ] bi
81         ] each
82     ] "" make ; inline
83
84 : enclose-in-quotes ( cell -- cell' )
85     "\"" dup surround ; inline
86     
87 : escape-if-required ( cell -- cell' )
88     dup needs-escaping?
89     [ escape-quotes enclose-in-quotes ] when ; inline
90
91 PRIVATE>
92     
93 : write-row ( row -- )
94     [ delimiter get write1 ]
95     [ escape-if-required write ] interleave nl ; inline
96     
97 : write-csv ( rows stream -- )
98     [ [ write-row ] each ] with-output-stream ;
99
100 : csv>file ( rows path encoding -- ) <file-writer> write-csv ;