From 2d18ac7fd9f8ddc92ddfb7de772adea8468ac3ea Mon Sep 17 00:00:00 2001 From: Shulhan Date: Tue, 30 Dec 2025 20:01:24 +0700 Subject: lib/test: implement method ExtractInput on Data Given the path to directory `destDir`, create all of the [test.Data.Input] with key as its file name. If the input name contains "/", the path before the base name will be created along with its parent as long as it is under the `destDir`. For example, given input name "a/b/c.txt", it will create path "a/b/" inside `destDir` first, followed by file "c.txt" inside that path. --- lib/test/data_example_test.go | 69 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 lib/test/data_example_test.go (limited to 'lib/test/data_example_test.go') diff --git a/lib/test/data_example_test.go b/lib/test/data_example_test.go new file mode 100644 index 00000000..b544dacd --- /dev/null +++ b/lib/test/data_example_test.go @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: BSD-3-Clause +// SPDX-FileCopyrightText: 2025 M. Shulhan + +package test_test + +import ( + "fmt" + "log" + "os" + "path/filepath" + + "git.sr.ht/~shulhan/pakakeh.go/lib/test" +) + +func ExampleData_ExtractInput() { + var tempDir string + var err error + tempDir, err = os.MkdirTemp(``, ``) + if err != nil { + log.Fatal(err) + } + defer os.RemoveAll(tempDir) + + var data = &test.Data{ + Input: map[string][]byte{ + `dir/a.txt`: []byte(`Content of dir/a.txt.`), + `dir/sub/b.txt`: []byte(`Content of dir/sub/b.txt.`), + `c.txt`: []byte(`Content of c.txt.`), + `dir/../../d.txt`: []byte(`Content of d.txt.`), + }, + } + + // The ExtractInput will create the following directory structures, + // including their files, + // + // ├── c.txt + // ├── dir + // │   ├── a.txt + // │   └── sub + // │   └── b.txt + // └── d.txt + // + err = data.ExtractInput(tempDir) + if err != nil { + log.Fatal(err) + } + + var listExtractedInput = []string{ + filepath.Join(tempDir, `dir/a.txt`), + filepath.Join(tempDir, `dir/sub/b.txt`), + filepath.Join(tempDir, `c.txt`), + // Since the path of "dir/../../d.txt" is outside of the + // tempDir, the file will be created on root of tempDir. + filepath.Join(tempDir, `d.txt`), + } + var got []byte + for _, path := range listExtractedInput { + got, err = os.ReadFile(path) + if err != nil { + log.Fatal(err) + } + fmt.Printf("%s\n", got) + } + // Output: + // Content of dir/a.txt. + // Content of dir/sub/b.txt. + // Content of c.txt. + // Content of d.txt. +} -- cgit v1.3