38680d06309a49b1099dd4ccfa30e9f697cb194e
[nit.git] / lib / csv / csv.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # CSV output facilities
16 module csv
17
18 # A CSV document representation.
19 class CsvDocument
20 super Streamable
21
22 var header: Array[String] = new Array[String] is writable
23 var records: Array[Array[String]] = new Array[Array[String]]
24
25 fun set_header(values: Object...) do
26 header.clear
27 for value in values do header.add(value.to_s)
28 end
29
30 fun add_record(values: Object...) do
31 assert values.length == header.length else
32 sys.stderr.write "CSV error: Header declares {header.length} columns, record contains {values.length} values.\n"
33 end
34 var record = new Array[String]
35 for value in values do record.add(value.to_s)
36 records.add(record)
37 end
38
39 private fun write_line_to(line: Collection[String], stream: OStream)
40 do
41 var i = line.iterator
42 if i.is_ok then
43 stream.write(i.item)
44 i.next
45 while i.is_ok do
46 stream.write(";")
47 stream.write(i.item)
48 i.next
49 end
50 end
51 stream.write("\n")
52 end
53
54 redef fun write_to(stream) do
55 write_line_to(header, stream)
56 for record in records do write_line_to(record, stream)
57 end
58
59 # Deprecated alias for `write_to_file`.
60 fun save(file: String) do write_to_file(file)
61 end