-
-
Notifications
You must be signed in to change notification settings - Fork 741
/
jswrap_fs.c
executable file
·420 lines (384 loc) · 12.1 KB
/
jswrap_fs.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* This file is designed to be parsed during the build process
*
* Contains built-in functions for SD card access, based on node.js 'fs' module
* ----------------------------------------------------------------------------
*/
#include "jswrap_fs.h"
#include "jswrap_file.h"
#include "jsutils.h"
#include "jsvar.h"
#include "jsparse.h"
#include "jsinteractive.h"
#include "jswrap_date.h"
#ifndef LINUX
#include "ff.h" // filesystem stuff
#else
#include <stdio.h>
#include <sys/stat.h>
#include <dirent.h> // for readdir
#endif
/*JSON{
"type" : "library",
"class" : "fs"
}
This library handles interfacing with a FAT32 filesystem on an SD card. The API is designed to be similar to node.js's - However Espruino does not currently support asynchronous file IO, so the functions behave like node.js's xxxxSync functions. Versions of the functions with 'Sync' after them are also provided for compatibility.
To use this, you must type ```var fs = require('fs')``` to get access to the library
See [the page on File IO](http://www.espruino.com/File+IO) for more information, and for examples on wiring up an SD card if your device doesn't come with one.
**Note:** If you want to remove an SD card after you have started using it, you *must* call `E.unmountSD()` or you may cause damage to the card.
*/
#ifndef LINUX
#define JS_DIR_BUF_SIZE 64
#else
#define JS_DIR_BUF_SIZE 256
#define FR_OK (0)
#endif
#ifndef LINUX
#if _USE_LFN
#define GET_FILENAME(Finfo) *Finfo.lfname ? Finfo.lfname : Finfo.fname
#else
#define GET_FILENAME(Finfo) Finfo.fname
#endif
#endif
// from jswrap_file
bool jsfsGetPathString(char *pathStr, JsVar *path);
extern bool jsfsInit();
extern void jsfsReportError(const char *msg, FRESULT res);
/*JSON{
"type" : "staticmethod",
"class" : "fs",
"name" : "readdir",
"generate" : "jswrap_fs_readdir",
"params" : [
["path","JsVar","The path of the directory to list. If it is not supplied, '' is assumed, which will list the root directory"]
],
"return" : ["JsVar","An array of filename strings (or undefined if the directory couldn't be listed)"]
}
List all files in the supplied directory, returning them as an array of strings.
NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.
*/
/*JSON{
"type" : "staticmethod",
"class" : "fs",
"name" : "readdirSync",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_fs_readdir",
"params" : [
["path","JsVar","The path of the directory to list. If it is not supplied, '' is assumed, which will list the root directory"]
],
"return" : ["JsVar","An array of filename strings (or undefined if the directory couldn't be listed)"]
}
List all files in the supplied directory, returning them as an array of strings.
*/
JsVar *jswrap_fs_readdir(JsVar *path) {
JsVar *arr = 0; // undefined unless we can open card
char pathStr[JS_DIR_BUF_SIZE] = "";
if (!jsvIsUndefined(path))
if (!jsfsGetPathString(pathStr, path)) return 0;
#ifdef LINUX
if (!pathStr[0]) strcpy(pathStr, "."); // deal with empty readdir
#endif
FRESULT res = 0;
if (jsfsInit()) {
#ifndef LINUX
DIR dirs;
if ((res=f_opendir(&dirs, pathStr)) == FR_OK) {
FILINFO Finfo;
#if _USE_LFN!=0
char lfnBuf[_MAX_LFN+1];
Finfo.lfname = lfnBuf;
Finfo.lfsize = sizeof(lfnBuf);
#endif
#else
DIR *dir = opendir(pathStr);
if(dir) {
#endif
arr = jsvNewEmptyArray();
if (arr) { // could be out of memory
#ifndef LINUX
while (((res=f_readdir(&dirs, &Finfo)) == FR_OK) && Finfo.fname[0]) {
char *fn = GET_FILENAME(Finfo);
#else
struct dirent *pDir=NULL;
while((pDir = readdir(dir)) != NULL) {
char *fn = (*pDir).d_name;
#endif
JsVar *fnVar = jsvNewFromString(fn);
if (fnVar) {// out of memory?
jsvArrayPush(arr, fnVar);
jsvUnLock(fnVar);
}
}
}
#ifndef LINUX
f_closedir(&dirs);
#else
closedir(dir);
#endif
}
}
if (res) jsfsReportError("Unable to list files", res);
return arr;
}
/*JSON{
"type" : "staticmethod",
"class" : "fs",
"name" : "writeFile",
"generate_full" : " jswrap_fs_writeOrAppendFile(path, data, false)",
"params" : [
["path","JsVar","The path of the file to write"],
["data","JsVar","The data to write to the file"]
],
"return" : ["bool","True on success, false on failure"]
}
Write the data to the given file
NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.
*/
/*JSON{
"type" : "staticmethod",
"class" : "fs",
"name" : "writeFileSync",
"ifndef" : "SAVE_ON_FLASH",
"generate_full" : " jswrap_fs_writeOrAppendFile(path, data, false)",
"params" : [
["path","JsVar","The path of the file to write"],
["data","JsVar","The data to write to the file"]
],
"return" : ["bool","True on success, false on failure"]
}
Write the data to the given file
*/
/*JSON{
"type" : "staticmethod",
"class" : "fs",
"name" : "appendFile",
"generate_full" : " jswrap_fs_writeOrAppendFile(path, data, true)",
"params" : [
["path","JsVar","The path of the file to write"],
["data","JsVar","The data to write to the file"]
],
"return" : ["bool","True on success, false on failure"]
}
Append the data to the given file, created a new file if it doesn't exist
NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.
*/
/*JSON{
"type" : "staticmethod",
"class" : "fs",
"name" : "appendFileSync",
"ifndef" : "SAVE_ON_FLASH",
"generate_full" : "jswrap_fs_writeOrAppendFile(path, data, true)",
"params" : [
["path","JsVar","The path of the file to write"],
["data","JsVar","The data to write to the file"]
],
"return" : ["bool","True on success, false on failure"]
}
Append the data to the given file, created a new file if it doesn't exist
*/
bool jswrap_fs_writeOrAppendFile(JsVar *path, JsVar *data, bool append) {
JsVar *fMode = jsvNewFromString(append ? "a" : "w");
JsVar *f = jswrap_E_openFile(path, fMode);
jsvUnLock(fMode);
if (!f) return 0;
size_t amt = jswrap_file_write(f, data);
jswrap_file_close(f);
jsvUnLock(f);
return amt>0;
}
/*JSON{
"type" : "staticmethod",
"class" : "fs",
"name" : "readFile",
"generate" : "jswrap_fs_readFile",
"params" : [
["path","JsVar","The path of the file to read"]
],
"return" : ["JsVar","A string containing the contents of the file (or undefined if the file doesn't exist)"]
}
Read all data from a file and return as a string
NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.
*/
/*JSON{
"type" : "staticmethod",
"class" : "fs",
"name" : "readFileSync",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_fs_readFile",
"params" : [
["path","JsVar","The path of the file to read"]
],
"return" : ["JsVar","A string containing the contents of the file (or undefined if the file doesn't exist)"]
}
Read all data from a file and return as a string.
**Note:** The size of files you can load using this method is limited by the amount of available RAM. To read files a bit at a time, see the `File` class.
*/
JsVar *jswrap_fs_readFile(JsVar *path) {
JsVar *fMode = jsvNewFromString("r");
JsVar *f = jswrap_E_openFile(path, fMode);
jsvUnLock(fMode);
if (!f) return 0;
JsVar *buffer = jswrap_file_read(f, 0x7FFFFFFF);
jswrap_file_close(f);
jsvUnLock(f);
return buffer;
}
/*JSON{
"type" : "staticmethod",
"class" : "fs",
"name" : "unlink",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_fs_unlink",
"params" : [
["path","JsVar","The path of the file to delete"]
],
"return" : ["bool","True on success, or false on failure"]
}
Delete the given file
NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.
*/
/*JSON{
"type" : "staticmethod",
"class" : "fs",
"name" : "unlinkSync",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_fs_unlink",
"params" : [
["path","JsVar","The path of the file to delete"]
],
"return" : ["bool","True on success, or false on failure"]
}
Delete the given file
*/
bool jswrap_fs_unlink(JsVar *path) {
char pathStr[JS_DIR_BUF_SIZE] = "";
if (!jsvIsUndefined(path))
if (!jsfsGetPathString(pathStr, path)) return 0;
#ifndef LINUX
FRESULT res = 0;
if (jsfsInit()) {
res = f_unlink(pathStr);
}
#else
FRESULT res = remove(pathStr);
#endif
if (res) {
jsfsReportError("Unable to delete file", res);
return false;
}
return true;
}
/*JSON{
"type" : "staticmethod",
"class" : "fs",
"name" : "statSync",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_fs_stat",
"params" : [
["path","JsVar","The path of the file to get information on"]
],
"return" : ["JsVar","An object describing the file, or undefined on failure"]
}
Return information on the given file. This returns an object with the following
fields:
size: size in bytes
dir: a boolean specifying if the file is a directory or not
mtime: A Date structure specifying the time the file was last modified
*/
JsVar *jswrap_fs_stat(JsVar *path) {
char pathStr[JS_DIR_BUF_SIZE] = "";
if (!jsvIsUndefined(path))
if (!jsfsGetPathString(pathStr, path)) return 0;
#ifndef LINUX
FRESULT res = 0;
if (jsfsInit()) {
FILINFO info;
memset(&info,0,sizeof(info));
res = f_stat(pathStr, &info);
if (res==0 /*ok*/) {
JsVar *obj = jsvNewObject();
if (!obj) return 0;
jsvObjectSetChildAndUnLock(obj, "size", jsvNewFromInteger((JsVarInt)info.fsize));
jsvObjectSetChildAndUnLock(obj, "dir", jsvNewFromBool(info.fattrib & AM_DIR));
CalendarDate date;
date.year = 1980+(int)((info.fdate>>9)&127);
date.month = (int)(((info.fdate>>5)&15)-1); // TomWS: Month is 0 based.
date.day = (int)((info.fdate)&31);
TimeInDay td;
td.daysSinceEpoch = fromCalenderDate(&date);
td.hour = (int)((info.ftime>>11)&31);
td.min = (int)((info.ftime>>5)&63);
td.sec = (int)((info.ftime)&63);
td.ms = 0;
td.zone = jsdGetTimeZone(); // TomWS: add adjustment for timezone offset introduced in date_from_milliseconds
jsvObjectSetChildAndUnLock(obj, "mtime", jswrap_date_from_milliseconds(fromTimeInDay(&td)));
return obj;
}
}
#else
struct stat info;
if (stat(pathStr, &info)==0 /*ok*/) {
JsVar *obj = jsvNewObject();
if (!obj) return 0;
jsvObjectSetChildAndUnLock(obj, "size", jsvNewFromInteger((JsVarInt)info.st_size));
jsvObjectSetChildAndUnLock(obj, "dir", jsvNewFromBool(S_ISDIR(info.st_mode)));
jsvObjectSetChildAndUnLock(obj, "mtime", jswrap_date_from_milliseconds((JsVarFloat)info.st_mtime*1000.0));
return obj;
}
#endif
return 0;
}
/*JSON{
"type" : "staticmethod",
"class" : "fs",
"name" : "mkdir",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_fs_mkdir",
"params" : [
["path","JsVar","The name of the directory to create"]
],
"return" : ["bool","True on success, or false on failure"]
}
Create the directory
NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version.
*/
/*JSON{
"type" : "staticmethod",
"class" : "fs",
"name" : "mkdirSync",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_fs_mkdir",
"params" : [
["path","JsVar","The name of the directory to create"]
],
"return" : ["bool","True on success, or false on failure"]
}
Create the directory
*/
bool jswrap_fs_mkdir(JsVar *path) {
char pathStr[JS_DIR_BUF_SIZE] = "";
if (!jsvIsUndefined(path))
if (!jsfsGetPathString(pathStr, path)) return 0;
#ifndef LINUX
FRESULT res = 0;
if (jsfsInit()) {
res = f_mkdir(pathStr);
}
#else
FRESULT res = mkdir(pathStr, 0777);
#endif
if (res) {
jsfsReportError("Unable to create the directory", res);
return false;
}
return true;
}