e3d0c0b21495f448b928f915012980aca17fd155
[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 # The header.
23 #
24 # Contains the name of all fields in this table.
25 var header: Array[String] = new Array[String] is writable
26
27 # The list of the records.
28 #
29 # All records must have the same length than `header`.
30 var records: Array[Array[String]] = new Array[Array[String]]
31
32 # Replace the header by the specified row.
33 fun set_header(values: Object...) do
34 header.clear
35 for value in values do header.add(value.to_s)
36 end
37
38 # Append the specfied record.
39 fun add_record(values: Object...) do
40 assert values.length == header.length else
41 sys.stderr.write "CSV error: Header declares {header.length} columns, record contains {values.length} values.\n"
42 end
43 var record = new Array[String]
44 for value in values do record.add(value.to_s)
45 records.add(record)
46 end
47
48 private fun write_line_to(line: Collection[String], stream: OStream)
49 do
50 var i = line.iterator
51 if i.is_ok then
52 stream.write(i.item)
53 i.next
54 while i.is_ok do
55 stream.write(";")
56 stream.write(i.item)
57 i.next
58 end
59 end
60 stream.write("\n")
61 end
62
63 redef fun write_to(stream) do
64 write_line_to(header, stream)
65 for record in records do write_line_to(record, stream)
66 end
67
68 # Deprecated alias for `write_to_file`.
69 fun save(file: String) do write_to_file(file)
70 end