Skip to content

Commit

Permalink
Add to path
Browse files Browse the repository at this point in the history
  • Loading branch information
Seggan committed Nov 1, 2023
1 parent b5fb54f commit e97afdd
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
6 changes: 6 additions & 0 deletions docs/lang/std/path.papyri
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,14 @@ Opens the file at the given path for writing and returns an output stream.
@h3 { parent(path: string): string }
Returns the parent directory of the given path.

@h3 { read_all(path: string): bytes }
Reads the entire file at the given path and returns the contents as a byte array.

@h3 { resolve(base: string, other: string): string }
Resolves the given path `other` against the base path `base` and returns the resolved path as a string.

@h3 { root(path: string): string }
Returns the root of the given path.

@h3 { write_all(path: string, data: bytes) }
Writes the given byte array to the file at the given path.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ class Compiler private constructor(
private val enclosingCompiler: Compiler?
) {

/**
* Creates a new compiler
*/
constructor() : this(emptyList(), null)

private val localStack = ArrayDeque<Local>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,10 @@ object PathLib : NativeLibrary("path") {
lib["normalize"] = pathFunction { it.normalize().toString().metisValue() }
lib["absolute"] = pathFunction { it.toAbsolutePath().toString().metisValue() }
lib["resolve"] = twoArgFunction { self, other ->
fileSystem.getPath(self.stringValue()).resolve(other.stringValue()).toString().metisValue()
currentDir.resolve(fileSystem.getPath(self.stringValue()))
.resolve(other.stringValue())
.toString()
.metisValue()
}
lib["parent"] = pathFunction { it.parent.toString().metisValue() }
lib["base_name"] = pathFunction { it.fileName.toString().metisValue() }
Expand Down Expand Up @@ -167,6 +170,31 @@ object PathLib : NativeLibrary("path") {
)
}
}

lib["read_all"] = pathFunction {
try {
it.readBytes().metisValue()
} catch (e: NoSuchFileException) {
throw MetisRuntimeException(
"IoError",
"File not found: ${it.absolutePathString()}",
Value.Table(mutableMapOf("path".metisValue() to it.absolutePathString().metisValue()))
)
}
}
lib["write_all"] = twoArgFunction { self, other ->
val path = currentDir.resolve(fileSystem.getPath(self.stringValue()))
try {
path.writeBytes(other.convertTo<Value.Bytes>().value)
} catch (e: FileAlreadyExistsException) {
throw MetisRuntimeException(
"IoError",
"File already exists: ${path.absolutePathString()}",
Value.Table(mutableMapOf("path".metisValue() to path.absolutePathString().metisValue()))
)
}
Value.Null
}
}
}

Expand Down

0 comments on commit e97afdd

Please sign in to comment.