Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion files/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ const (
WritePermission uint32 = 0600
)

// statPath inspects filesystem paths.
//
// It points to os.Stat in production. Tests replace it to exercise error
// handling after glob resolution, which otherwise depends on filesystem races
// between finding a path and inspecting it.
var statPath = os.Stat

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor / design: this (and makeAbsolutePath in fragmentation.go:63) introduces a mutable package-global into production code purely as a test seam. It works and is well-documented, and since Ginkgo parallelism is process-based the global mutation is safe. Just flagging the tradeoff for the record — an alternative that keeps production surface immutable would be injecting the stat/abs function through the existing struct (e.g. Resolver/Fragmentation) rather than a reassignable global. Not blocking.


// IsFileExist reports whether the given path exists as a file.
//
// Parameters:
Expand Down Expand Up @@ -103,7 +110,7 @@ func validatePathExists(path string) (bool, os.FileInfo, error) {
}

firstMatch := matches[0]
info, err := os.Stat(firstMatch)
info, err := statPath(firstMatch)

if err != nil {
if os.IsNotExist(err) {
Expand Down
83 changes: 83 additions & 0 deletions files/files_private_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* Copyright 2026, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

//nolint:testpackage // Covers package-private filesystem hooks used for deterministic errors.
package files

import (
"errors"
"os"
"path/filepath"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

var _ = Describe("Files internals", func() {
It("should treat a path removed after glob resolution as missing", func() {
filePath := writeTemporaryFile()

withStatError(os.ErrNotExist, func() {
exists, err := IsFileExist(filePath)

Expect(err).ShouldNot(HaveOccurred())
Expect(exists).Should(BeFalse())
})
})

It("should report stat errors after glob resolution", func() {
filePath := writeTemporaryFile()
statErr := errors.New("stat failed")

withStatError(statErr, func() {
exists, err := IsFileExist(filePath)

Expect(exists).Should(BeFalse())
Expect(err).Should(MatchError(statErr))
})
})
})

// withStatError replaces path inspection with a deterministic error.
func withStatError(statErr error, action func()) {
originalStatPath := statPath
statPath = func(_ string) (os.FileInfo, error) {
return nil, statErr
}
defer func() {
statPath = originalStatPath
}()

action()
}

// writeTemporaryFile creates an existing path for glob resolution.
func writeTemporaryFile() string {
filePath := filepath.Join(GinkgoT().TempDir(), "file.txt")
Expect(os.WriteFile(filePath, []byte("content"), os.FileMode(WritePermission))).To(Succeed())

return filePath
}
24 changes: 24 additions & 0 deletions files/files_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@ var _ = Describe("Files actions", func() {
Expect(files.IsDirExist(filePath)).Should(BeFalse())
})

It("should return error as the referenced path has an invalid glob pattern", func() {
exists, err := files.IsDirExist("[")

Expect(exists).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})

It("should return error as the referenced path is a file", func() {
currentDir, _ := os.Getwd()
path := filepath.Dir(currentDir) + "/test/resources/config_files/correct_config.yml"
Expand Down Expand Up @@ -103,6 +110,23 @@ var _ = Describe("Files actions", func() {
Expect(files.IsFileExist(filePath)).Should(BeFalse())
})

It("should return error as the referenced file has an invalid glob pattern", func() {
exists, err := files.IsFileExist("[")

Expect(exists).Should(BeFalse())
Expect(err).Should(HaveOccurred())
})

It("should return false as the referenced file is a broken symlink", func() {
linkPath := filepath.Join(GinkgoT().TempDir(), "broken-link")
Expect(os.Symlink("missing-target", linkPath)).To(Succeed())

exists, err := files.IsFileExist(linkPath)

Expect(err).ShouldNot(HaveOccurred())
Expect(exists).Should(BeFalse())
})

It("should return false as the referenced path point to directory", func() {
currentDir, _ := os.Getwd()

Expand Down
51 changes: 19 additions & 32 deletions fragmentation/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,7 @@

package fragmentation

import (
"container/list"
"sync"
)
import "sync"

// cache is a limited collection of recently used values by key.
type cache[K comparable, V any] struct {
Expand All @@ -45,21 +42,16 @@ type cache[K comparable, V any] struct {
// values contains cached values indexed by key.
values map[K]V

// entries maps keys to their positions in the usage order.
entries map[K]*list.Element

// order tracks keys from least to most recently used.
order *list.List
order []K
}

// newCache creates a cache with a loader and least-recently-used eviction.
func newCache[K comparable, V any](limit int, loader func(K) (V, error)) *cache[K, V] {
return &cache[K, V]{
limit: limit,
loader: loader,
values: make(map[K]V),
entries: make(map[K]*list.Element),
order: list.New(),
limit: limit,
loader: loader,
values: make(map[K]V),
}
}

Expand Down Expand Up @@ -91,14 +83,15 @@ func (c *cache[K, V]) get(key K) (V, error) {

// storeLoaded stores a loaded value and evicts the least recently used value when needed.
func (c *cache[K, V]) storeLoaded(key K, value V) {
c.values[key] = value
if entry, found := c.entries[key]; found {
c.order.MoveToBack(entry)
if _, found := c.values[key]; found {
c.values[key] = value
c.markUsed(key)

return
}

c.entries[key] = c.order.PushBack(key)
c.values[key] = value
c.order = append(c.order, key)
if len(c.values) <= c.limit {
return
}
Expand All @@ -108,25 +101,19 @@ func (c *cache[K, V]) storeLoaded(key K, value V) {

// markUsed moves a cache key to the most recently used position.
func (c *cache[K, V]) markUsed(key K) {
if entry, found := c.entries[key]; found {
c.order.MoveToBack(entry)
for index, existingKey := range c.order {
if existingKey == key {
c.order = append(c.order[:index], c.order[index+1:]...)
c.order = append(c.order, key)

return
}
}
}

// evictOldest removes the least recently used cache entry.
func (c *cache[K, V]) evictOldest() {
oldestEntry := c.order.Front()
if oldestEntry == nil {
return
}

oldestKey, isKey := oldestEntry.Value.(K)
if !isKey {
c.order.Remove(oldestEntry)

return
}
c.order.Remove(oldestEntry)
delete(c.entries, oldestKey)
oldestKey := c.order[0]
c.order = c.order[1:]
delete(c.values, oldestKey)
}
10 changes: 9 additions & 1 deletion fragmentation/fragmentation.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,14 @@ import (
// NamedPathPrefix is the prefix before a named code source.
const NamedPathPrefix = "$"

// makeAbsolutePath resolves paths to absolute paths.
//
// It points to filepath.Abs in production.
// Tests replace it to exercise error propagation from absolute
// path resolution, which filepath.Abs does not fail reliably
// across supported environments.
var makeAbsolutePath = filepath.Abs

// Fragmentation splits the given file into fragments.
type Fragmentation struct {
// codeFile is the absolute path of the source file being fragmented.
Expand All @@ -72,7 +80,7 @@ type Fragmentation struct {
// Fragmentation - source file fragmentation context.
// error - when codeFile cannot be made absolute.
func NewFragmentation(codeFile string) (Fragmentation, error) {
absoluteCodeFile, err := filepath.Abs(codeFile)
absoluteCodeFile, err := makeAbsolutePath(codeFile)
if err != nil {
return Fragmentation{}, err
}
Expand Down
Loading
Loading