#How to Add a File To A Container

1 messages · Page 1 of 1 (latest)

tacit mango
#

Hi, I'm trying to create a file which lists all the code files in my project. The source code is mounted in a container which is passed the function below
CODE_FILE_LIST is a string which is just the name of my output file
async def list_code_files(self, ctx: dagger.Container) -> dagger.Container: file_list = [] files = await ctx.directory("/src").glob('**/*.c|**/*.cpp') for file in files: if 'CVI' not in file: file_list.append(file.replace("\\", "/")) with open(self.CODE_FILE_LIST, 'w') as f: for file_path in file_list: f.write(f"Code found at {file_path}\n") return ctx.with_file(f"/src/{self.CODE_FILE_LIST}", dagger.File(self.CODE_FILE_LIST))

The creation of the file list works fine, but I'm a real pickle with how to add the file to the container which I'm returning. I've tried a variety of solutions for the with_file but I can't figure out what I'm doing wrong. Can someone point me in the right direction please?

umbral mantle
#

I think right now the easiest way to create a new file from a string is Directory.WithNewFile, so it might look something like return ctx.with_directory(dag.Directory().with_new_file(f"/src/{self.CODE_FILE_LIST}", contents=self.CODE_FILE_LIST))

manic lark
#

Container also has a with_new_file, so just make sure you store the contents in a var before writing to the file so you don't have to read the file:

contents = "\n".join(f"Code found at {file_path}" for file_path in file_list)
return ctx.with_new_file(f"/src/{self.CODE_FILE_LIST}", contents)

But, if you're writing the file to the current workdir and you really want to use it, you can use CurrentModule.workdir_file:

return ctx.with_file(f"/src/{self.CODE_FILE_LIST}", dag.current_module().workdir_file(self.CODE_FILE_LIST))

However, I wonder what's the use case of writing to a file in self.CODE_FILE_LIST in the function. Do you understand each function execution runs in its own container instance, so that file isn't preserved when you chain one function call to another?