File size: 2,872 Bytes
6851d40 | 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 | /*******************************************************************************
* Copyright by the contributors to the Dafny Project
* SPDX-License-Identifier: MIT
*******************************************************************************/
var DafnyLibraries = DafnyLibraries || {};
DafnyLibraries.FileIO = (function() {
const buffer = require("buffer");
const fs = require("fs");
const nodePath = require("path");
let $module = {};
/**
* Attempts to read all bytes from the file at the given `path`, and returns an array of the following values:
*
* - `isError`: true iff an error was thrown during path string conversion or when reading the file
* - `bytesRead`: the sequence of bytes from the file, or an empty sequence if `isError` is true
* - `errorMsg`: the error message of the thrown error if `isError` is true, or an empty sequence otherwise
*
* We return these values individually because `Result` is not defined in the runtime but instead in library code.
* It is the responsibility of library code to construct an equivalent `Result` value.
*/
$module.INTERNAL_ReadBytesFromFile = function(path) {
const emptySeq = _dafny.Seq.of();
try {
const readOpts = { encoding: null }; // read as buffer, not string
const buf = fs.readFileSync(path, readOpts);
const readBytes = _dafny.Seq.from(buf.valueOf(), byte => new BigNumber(byte));
return [false, readBytes, emptySeq];
} catch (e) {
const errorMsg = _dafny.Seq.from(e.stack);
return [true, emptySeq, errorMsg];
}
}
/**
* Attempts to write all given `bytes` to the file at the given `path`, creating nonexistent parent directories as necessary,
* and returns an array of the following values:
*
* - `isError`: true iff an error was thrown during path string conversion or when writing to the file
* - `errorMsg`: the error message of the thrown error if `isError` is true, or an empty sequence otherwise
*
* We return these values individually because `Result` is not defined in the runtime but instead in library code.
* It is the responsibility of library code to construct an equivalent `Result` value.
*/
$module.INTERNAL_WriteBytesToFile = function(path, bytes) {
try {
const buf = buffer.Buffer.from(bytes);
createParentDirs(path);
fs.writeFileSync(path, buf); // no need to specify encoding because data is a Buffer
return [false, _dafny.Seq.of()];
} catch (e) {
const errorMsg = _dafny.Seq.from(e.stack);
return [true, errorMsg];
}
}
/**
* Creates the nonexistent parent directory(-ies) of the given path.
*/
const createParentDirs = function(path) {
const parentDir = nodePath.dirname(nodePath.normalize(path));
fs.mkdirSync(parentDir, { recursive: true });
};
return $module;
})();
|