Skip to content

core: WithNewFIle doesn't follow relative paths #3903

Closed

Description

@aluzzardi

Test (see the Relative path):

func TestDirectoryWithNewFile(t *testing.T) {
	t.Parallel()

	c, ctx := connect(t)
	defer c.Close()

	entries, err := c.Directory().WithNewFile("some-file", dagger.DirectoryWithNewFileOpts{
		Contents: "some-content",
	}).Entries(ctx)
	require.NoError(t, err)
	require.Equal(t, []string{"some-file"}, entries)

	// Relative path
	dir := c.Directory().WithNewDirectory("a").WithNewFile("some-file", dagger.DirectoryWithNewFileOpts{
		Contents: "some-content",
	})
	contents, err := dir.File("/a/some-file").Contents(ctx)
	require.NoError(t, err)
	require.Equal(t, "some-content", contents)
}

This fails. The resulting tree is:

- /a
- /some-file

/cc @vito @sipsma

Activity

  1. vito commented on Nov 22, 2022

    @vito
    Contributor

    Don't think this is a bug, just another case of confusion between chaining additive changes to the parent vs. the child.

    The problem is here:

    	dir := c.Directory().WithNewDirectory("a").WithNewFile("some-file", dagger.DirectoryWithNewFileOpts{

    This creates a directory, creates /a/ underneath it and returns the parent directory, and then creates another file beneath that parent directory.

    To create a file in a sub-directory, by far the easiest method is to fully specify the path:

    dir := c.Directory().WithNewFile("a/some-file", dagger.DirectoryWithNewFileOpts{
      Contents: "some-content",
    })

    If not for this shorthand I think you would have to create it inside-out like this:

    sub := c.Directory().WithNewFile("some-file", dagger.DirectoryWithNewFileOpts{
      Contents: "some-content",
    })
    
    dir := c.Directory().WithDirectory("a", sub)

    We've run into this confusion a few times before. The behavior feels more obvious when you chain multiple WithNewFile calls because there's no nesting in that case, but WithNewDirectory can easily mislead you into thinking it returns the child.

    I wonder if it should be called WithEmptyDirectory or something instead? (meh)

  2. added
    area/engine
    and removed on Dec 5, 2022
  3. locked and limited conversation to collaborators on Mar 24, 2026
  4. converted this issue into a discussion #12493 on Mar 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/engine

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions