Skip to content

Commit ddb654e

Browse files
First Release :shipit:
1 parent d24a00c commit ddb654e

File tree

4 files changed

+237
-14
lines changed

4 files changed

+237
-14
lines changed

README.md

+122
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
# ftcsv
2+
ftcsv, a fairly fast csv library written in pure Lua. It's been tested with LuaJIT 2.0/2.1 and Lua 5.2
3+
4+
It works well for CSVs that can easily be fully loaded into memory (easily up to a hundred MB). Currently, there isn't a "large" file mode with proper readers and writers for ingesting CSVs in bulk with a fixed amount of memory. It correctly handles both `\n` (LF) and `\r\n` (CRLF) line endings (ie it should work with Windows and Mac/Linux line endings) and has UTF-8 support.
5+
6+
7+
8+
## Installing
9+
You can either grab `ftcsv.lua` from here or install via luarocks:
10+
11+
```
12+
luarocks install ftcsv
13+
```
14+
15+
16+
## Parsing
17+
###`ftcsv.parse(fileName, delimiter [, options])`
18+
19+
ftcsv will load the entire csv file into memory, then parse it in one go, returning a lua table with the parsed data. It has only two required parameters - a file name and delimiter (limited to one character). A few optional parameters can be passed in via a table (examples below).
20+
21+
Just loading a csv file:
22+
```lua
23+
local ftcsv = require('ftcsv')
24+
local zipcodes = ftcsv.parse("free-zipcode-database.csv", ",")
25+
```
26+
27+
### Options
28+
The following are optional parameters passed in via the third argument as a table. For example if you wanted to `loadFromString` and not use `headers`, you could use the following:
29+
```lua
30+
ftcsv.parse("apple,banana,carrot", ",", {loadFromString=true, headers=false})
31+
```
32+
- `loadFromString`
33+
34+
If you want to load a csv from a string instead of a file, set `loadFromString` to `true` (default: `false`)
35+
```lua
36+
ftcsv.parse("a,b,c\r\n1,2,3", ",", {loadFromString=true})
37+
```
38+
39+
- `rename`
40+
41+
If you want to rename a field, you can set `rename` to change the field names. The below example will change the headers from `a,b,c` to `d,e,f`
42+
43+
Note: You can rename two fields to the same value, ftcsv will keep the field that appears latest in the line.
44+
45+
```lua
46+
local options = {loadFromString=true, rename={["a"] = "d", ["b"] = "e", ["c"] = "f"}}
47+
local actual = ftcsv.parse("a,b,c\r\napple,banana,carrot", ",", options)
48+
```
49+
50+
- `fieldsToKeep`
51+
52+
If you only want to keep certain fields from the CSV, send them in as a table-list and it should parse a little faster and use less memory.
53+
54+
Note: If you want to keep a renamed field, put the new name of the field in `fieldsToKeep`:
55+
56+
```lua
57+
local options = {loadFromString=true, fieldsToKeep={"a","f"}, rename={["c"] = "f"}}
58+
local actual = ftcsv.parse("a,b,c\r\napple,banana,carrot\r\n", ",", options)
59+
```
60+
61+
- `headers`
62+
63+
Set `headers` to `false` if the file you are reading doesn't have any headers. This will cause ftcsv to create indexed tables rather than a key-value tables for the output.
64+
65+
```lua
66+
local options = {loadFromString=true, headers=false}
67+
local actual = ftcsv.parse("apple>banana>carrot\ndiamond>emerald>pearl", ">", options)
68+
```
69+
70+
Note: Header-less files can still use the `rename` option and after a field has been renamed, it can specified as a field to keep. The `rename` syntax changes a little bit:
71+
72+
```lua
73+
local options = {loadFromString=true, headers=false, rename={"a","b","c"}, fieldsToKeep={"a","b"}}
74+
local actual = ftcsv.parse("apple>banana>carrot\ndiamond>emerald>pearl", ">", options)
75+
```
76+
77+
In the above example, the first field becomes 'a', the second field becomes 'b' and so on.
78+
79+
For all tested examples, take a look in /spec/feature_spec.lua
80+
81+
82+
## Encoding
83+
###`ftcsv.encode(inputTable, delimiter[, options])`
84+
ftcsv can also take a lua table and turn it into a text string to be written to a file. It has two required parameters, an inputTable and a delimiter. You can use it to write out a file like this:
85+
```lua
86+
local fileOutput = ftcsv.encode(users, ",")
87+
local file = assert(io.open("ALLUSERS.csv", "w"))
88+
file:write(fileOutput)
89+
file:close()
90+
```
91+
92+
### Options
93+
- `fieldsToKeep`
94+
95+
if `fieldsToKeep` is set in the encode process, only the fields specified will be written out to a file.
96+
97+
```lua
98+
local output = ftcsv.encode(everyUser, ",", {fieldsToKeep={"Name", "Phone", "City"}})
99+
```
100+
101+
102+
103+
## Performance
104+
I did some basic testing and found that in lua, if you want to iterate over a string character-by-character and look for single chars, `string.byte` performs better than `string.sub`. As such, ftcsv iterates over the whole file and does byte compares to find quotes and delimiters and then generates a table from it. If you have thoughts on how to improve performance (either big picture or specifically within the code), create a GitHub issue - I'd love to hear about it!
105+
106+
107+
108+
## Contributing
109+
Feel free to create a new issue for any bugs you've found or help you need. If you want to contribute back to the project please do the following:
110+
1. Fork the repo
111+
2. Create a new branch
112+
3. Push your changes to the branch
113+
4. Run the test suite and make sure it still works
114+
5. Submit a pull request
115+
6. ???
116+
7. Enjoy the changes made to the repo!
117+
118+
119+
120+
## Licenses
121+
- The main library is licensed under the MIT License. Feel free to use it!
122+
- Some of the test CSVs are from [csv-spectrum](https://github.com/maxogden/csv-spectrum) (BSD-2-Clause) which includes some from [csvkit](https://github.com/wireservice/csvkit) (MIT License)

ftcsv-1.0.0-1.rockspec

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package = "ftcsv"
2+
version = "1.0.0-1"
3+
4+
source = {
5+
url = "git://github.com/FourierTransformer/ftcsv.git",
6+
tag = "1.0.0"
7+
}
8+
9+
description = {
10+
summary = "A fairly fast csv library written in pure Lua",
11+
detailed = [[
12+
ftcsv is a fast and easy to use csv library for lua. It can read in CSV files,
13+
do some basic transformations (rename fields) and can create the csv format.
14+
It supports UTF-8, header-less CSVs, and maintaining correct line endings for
15+
multi-line fields.
16+
17+
Note: Currently it cannot load CSV files where the file can't fit in memory.
18+
]],
19+
homepage = "https://github.com/FourierTransformer/ftcsv",
20+
maintainer = "Shakil Thakur <[email protected]>",
21+
license = "MIT"
22+
}
23+
24+
dependencies = {
25+
"lua >= 5.1, <5.3",
26+
}
27+
28+
build = {
29+
type = "builtin",
30+
modules = {
31+
["ftcsv"] = "ftcsv.lua"
32+
},
33+
}

ftcsv.lua

+34-13
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,8 @@ local function createNewField(inputString, quote, fieldStart, i, line, fieldNum,
4949
-- so, if we just recently de-escaped, we don't want the trailing \"
5050
-- if fieldsToKeep == nil then
5151
-- local fieldsToKeep = fieldsToKeep
52-
local output = line[fieldNum]
52+
-- print(fieldNum)
53+
-- print(fieldsToKeep[fieldNum])
5354
if fieldsToKeep == nil or fieldsToKeep[fieldNum] then
5455
-- print(fieldsToKeep)
5556
-- print("b4", i, fieldNum, line[fieldNum])
@@ -71,7 +72,7 @@ local function createNewField(inputString, quote, fieldStart, i, line, fieldNum,
7172
end
7273

7374
-- creates the headers after reading through to the first line
74-
local function createHeaders(line, rename, fieldsToKeep)
75+
local function createHeaders(line, rename)
7576
-- print("CREATING HEADERS")
7677
local headers = {}
7778
for i = 1, #line do
@@ -82,12 +83,7 @@ local function createHeaders(line, rename, fieldsToKeep)
8283
headers[i] = line[i]
8384
end
8485
end
85-
if fieldsToKeep ~= nil then
86-
for i = 1, #fieldsToKeep do
87-
fieldsToKeep[fieldsToKeep[i]] = true
88-
end
89-
end
90-
return headers, 0, true, fieldsToKeep
86+
return headers, 0, true
9187
end
9288

9389
-- main function used to parse
@@ -118,6 +114,9 @@ function ftcsv.parse(inputFile, delimiter, options)
118114
if options.fieldsToKeep ~= nil then
119115
assert(type(options.fieldsToKeep) == "table", "ftcsv only takes in a list (as a table) for the optional parameter 'fieldsToKeep'. You passed in '" .. tostring(options.fieldsToKeep) .. "' of type '" .. type(options.fieldsToKeep) .. "'.")
120116
ofieldsToKeep = options.fieldsToKeep
117+
if header == false then
118+
assert(next(rename) ~= nil, "ftcsv can only have fieldsToKeep for header-less files when they have been renamed. Please add the 'rename' option and try again.")
119+
end
121120
end
122121
if options.loadFromString ~= nil then
123122
assert(type(options.loadFromString) == "boolean", "ftcsv only takes a boolean value for optional parameter 'loadFromString'. You passed in '" .. tostring(options.loadFromString) .. "' of type '" .. type(options.loadFromString) .. "'.")
@@ -199,10 +198,32 @@ function ftcsv.parse(inputFile, delimiter, options)
199198
doubleQuoteEscape = createNewField(inputString, quote, fieldStart, i, outResults[lineNum], headerField[fieldNum], doubleQuoteEscape, fieldsToKeep)
200199

201200
-- if we have headers then we gotta do something about it
202-
if header and lineNum == 1 and not headerSet then
203-
headerField, lineNum, headerSet, fieldsToKeep = createHeaders(outResults[lineNum], rename, ofieldsToKeep)
201+
if lineNum == 1 and not headerSet then
202+
if ofieldsToKeep ~= nil then
203+
fieldsToKeep = {}
204+
for i = 1, #ofieldsToKeep do
205+
fieldsToKeep[ofieldsToKeep[i]] = true
206+
end
207+
end
208+
if header then
209+
headerField, lineNum, headerSet = createHeaders(outResults[lineNum], rename)
210+
else
211+
-- files without headers, but with a rename need to be handled too!
212+
if #rename > 0 then
213+
for j = 1, math.max(#rename, #headerField) do
214+
headerField[j] = rename[j]
215+
-- this is an odd case of where there are certain fields to be kept
216+
if fieldsToKeep == nil or fieldsToKeep[rename[j]] then
217+
outResults[1][rename[j]] = outResults[1][j]
218+
end
219+
-- print("J", j)
220+
outResults[1][j] = nil
221+
end
222+
end
223+
end
204224
end
205225

226+
-- incrememnt for new line
206227
lineNum = lineNum + 1
207228
outResults[lineNum] = {}
208229
fieldNum = 1
@@ -314,9 +335,9 @@ function ftcsv.encode(inputTable, delimiter, options)
314335
-- grab the headers from the options if they are there
315336
local headers = nil
316337
if options then
317-
if options.headers ~= nil then
318-
assert(type(options.headers) == "table", "ftcsv only takes in a list (as a table) for the optional parameter 'headers'. You passed in '" .. tostring(options.headers) .. "' of type '" .. type(options.headers) .. "'.")
319-
headers = options.headers
338+
if options.fieldsToKeep ~= nil then
339+
assert(type(options.fieldsToKeep) == "table", "ftcsv only takes in a list (as a table) for the optional parameter 'fieldsToKeep'. You passed in '" .. tostring(options.headers) .. "' of type '" .. type(options.headers) .. "'.")
340+
headers = options.fieldsToKeep
320341
end
321342
end
322343
if headers == nil then

spec/feature_spec.lua

+48-1
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,55 @@ describe("csv features", function()
102102
expected[2][1] = "diamond"
103103
expected[2][2] = "emerald"
104104
expected[2][3] = "pearl"
105-
local options = {loadFromString=true, header=false}
105+
local options = {loadFromString=true, headers=false}
106106
local actual = ftcsv.parse("apple>banana>carrot\ndiamond>emerald>pearl", ">", options)
107+
assert.are.same(expected, actual)
108+
end)
109+
110+
it("should error out for fieldsToKeep if no headers and no renaming", function()
111+
local options = {loadFromString=true, headers=false, fieldsToKeep={1, 2}}
112+
assert.has.errors(function() ftcsv.parse("apple>banana>carrot\ndiamond>emerald>pearl", ">", options) end)
113+
end)
114+
115+
it("should handle only renaming fields from files without headers", function()
116+
local expected = {}
117+
expected[1] = {}
118+
expected[1].a = "apple"
119+
expected[1].b = "banana"
120+
expected[1].c = "carrot"
121+
expected[2] = {}
122+
expected[2].a = "diamond"
123+
expected[2].b = "emerald"
124+
expected[2].c = "pearl"
125+
local options = {loadFromString=true, headers=false, rename={"a","b","c"}}
126+
local actual = ftcsv.parse("apple>banana>carrot\ndiamond>emerald>pearl", ">", options)
127+
assert.are.same(expected, actual)
128+
end)
129+
130+
it("should handle only renaming fields from files without headers and only keeping a few fields", function()
131+
local expected = {}
132+
expected[1] = {}
133+
expected[1].a = "apple"
134+
expected[1].b = "banana"
135+
expected[2] = {}
136+
expected[2].a = "diamond"
137+
expected[2].b = "emerald"
138+
local options = {loadFromString=true, headers=false, rename={"a","b","c"}, fieldsToKeep={"a","b"}}
139+
local actual = ftcsv.parse("apple>banana>carrot\ndiamond>emerald>pearl", ">", options)
140+
assert.are.same(expected, actual)
141+
end)
142+
143+
it("should handle if the number of renames doesn't equal the number of fields", function()
144+
local expected = {}
145+
expected[1] = {}
146+
expected[1].a = "apple"
147+
expected[1].b = "banana"
148+
expected[2] = {}
149+
expected[2].a = "diamond"
150+
expected[2].b = "emerald"
151+
local options = {loadFromString=true, headers=false, rename={"a","b"}, fieldsToKeep={"a","b"}}
152+
local actual = ftcsv.parse("apple>banana>carrot\ndiamond>emerald>pearl", ">", options)
153+
assert.are.same(expected, actual)
107154
end)
108155

109156
end)

0 commit comments

Comments
 (0)