3232import java .nio .file .Paths ;
3333import java .nio .file .StandardOpenOption ;
3434import java .util .Arrays ;
35+ import java .util .List ;
36+ import java .util .stream .Collectors ;
3537import java .util .stream .Stream ;
3638
3739import tlc2 .output .EC ;
3840import tlc2 .tool .EvalException ;
3941import tlc2 .value .Values ;
4042import tlc2 .value .impl .BoolValue ;
4143import tlc2 .value .impl .IntValue ;
44+ import tlc2 .value .impl .RecordValue ;
4245import tlc2 .value .impl .StringValue ;
4346import tlc2 .value .impl .TupleValue ;
4447import tlc2 .value .impl .Value ;
48+ import util .UniqueString ;
4549
4650public class CSV {
4751
@@ -61,6 +65,36 @@ public static Value write(final StringValue template, final Value parameter, fin
6165 return BoolValue .ValTrue ;
6266 }
6367
68+ @ TLAPlusOperator (identifier = "CSVRead" , module = "CSV" , minLevel = 1 , warn = false )
69+ public static Value read (final Value columns , final StringValue delim , final StringValue absolutePath )
70+ throws IOException {
71+
72+ final TupleValue tv = (TupleValue ) columns .toTuple ();
73+ if (tv == null ) {
74+ throw new EvalException (EC .TLC_MODULE_ONE_ARGUMENT_ERROR ,
75+ new String [] { "CSVRead" , "sequence" , Values .ppr (columns .toString ()) });
76+ }
77+
78+ final Path path = Paths .get (absolutePath .val .toString ());
79+ if (!path .toFile ().exists ()) {
80+ // There are zero records in a file that doesn't exist.
81+ return TupleValue .EmptyTuple ;
82+ }
83+
84+ final UniqueString [] names = Arrays .asList (tv .elems ).stream ().map (v -> ((StringValue ) v ).val )
85+ .collect (Collectors .toList ()).toArray (UniqueString []::new );
86+
87+ final List <String > lines = Files .readAllLines (path );
88+ final Value [] records = new Value [lines .size ()];
89+ for (int i = 0 ; i < lines .size (); i ++) {
90+ StringValue [] values = Arrays .asList (lines .get (i ).split (delim .val .toString ())).stream ()
91+ .map (s -> new StringValue (s )).collect (Collectors .toList ()).toArray (StringValue []::new );
92+ records [i ] = new RecordValue (names , values , false );
93+ }
94+
95+ return new TupleValue (records );
96+ }
97+
6498 @ TLAPlusOperator (identifier = "CSVRecords" , module = "CSV" , minLevel = 1 , warn = false )
6599 public static Value records (final StringValue absolutePath )
66100 throws IOException {
0 commit comments