ni_nitdoc: added fast copy past utility to signatures.
[nit.git] / lib / 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 private var file: String
21 private var header: Array[String] = new Array[String]
22 private var lines: Array[Array[String]] = new Array[Array[String]]
23
24 init(file: String) do self.file = file
25
26 fun set_header(values: Object...) do
27 header.clear
28 for value in values do header.add(value.to_s)
29 end
30
31 fun add_line(values: Object...) do
32 if values.length != header.length then
33 print "CSV error: header declares {header.length} columns, line contains {values.length} values"
34 abort
35 end
36 var line = new Array[String]
37 for value in values do line.add(value.to_s)
38 lines.add(line)
39 end
40
41 redef fun to_s do
42 var str = header.join(";") + "\n"
43 for line in lines do str += line.join(";") + "\n"
44 return str
45 end
46
47 fun save do
48 var out = new OFStream.open(self.file)
49 out.write(self.to_s)
50 out.close
51 end
52 end