How to use resources from an Ammonite script?

269 views Asked by At

I have a few ammonite scripts, they are stored in a folder. That folder is on my PATH, so I can invoke those scripts easily wherever I am.

I can import other ammonite scripts in the same folder:

$import $file.<name_of_the_other_script>

However I want to 'import' a simple text file, save it's content as a string and use it later.

I can do:

val myString = os.read(os.root/"absolute"/"path"/"to"/"the"/"file")

But I would prefer not to use absolute paths, for obvious reasons. Relative path does not work, beacuse it is relative to the folder where I am invoking the script from, and not to where the script is located.

Is there any way to achieve this?

EDIT:

#/bin/bash

echo $BASH_SOURCE

The problem could be solved easily if the functionality in the above bash script could be replicated in Ammonite.

1

There are 1 answers

1
michid On

I think you can read resources using ammonite.ops like so:

val resourcePath = resource/'test/'ammonite/'ops/'folder/"file.txt"
read(resourcePath).length        ==> 18
read.bytes(resourcePath).length  ==> 18
read.lines(resourcePath).length  ==> 1

See Reading Resources in the Ammonite documentation.