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
131 changes: 131 additions & 0 deletions internal/application/diff/application.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// Copyright © 2026 envaar
// SPDX-License-Identifier: Apache-2.0

// Package diff coordinates the diff application use case. It composes source
// loading, analysis conversion and key-inventory comparison without rendering
// output or deciding command exit codes.
package diff

import (
"context"
"errors"
"fmt"
"os"

"github.com/envaar/vaar/internal/analysis"
analysisdotenv "github.com/envaar/vaar/internal/analysis/dotenv"
diffengine "github.com/envaar/vaar/internal/diff"
sourcedotenv "github.com/envaar/vaar/internal/source/dotenv"
)

// Options identifies the two user-selected dotenv operands. The values are
// retained as display labels so relative, absolute and space-containing paths
// remain unchanged in diff results.
type Options struct {
LeftPath string
RightPath string
}

// Dependencies provides the source-loading seam used by application tests.
// Analysis and diff remain concrete boundaries: the service must always build
// an analysis snapshot and invoke the analysis-backed diff engine.
type Dependencies struct {
LoadDotenv func(paths, displayPaths []string) ([]sourcedotenv.Document, error)
}

// Service coordinates one diff execution.
type Service struct {
loadDotenv func(paths, displayPaths []string) ([]sourcedotenv.Document, error)
}

// New constructs a diff application service with the standard dotenv loader.
func New() *Service {
return NewWithDependencies(Dependencies{})
}

// NewWithDependencies constructs a diff application service with explicit
// source-loading dependencies for focused orchestration tests.
func NewWithDependencies(dependencies Dependencies) *Service {
if dependencies.LoadDotenv == nil {
dependencies.LoadDotenv = sourcedotenv.LoadMany
}

return &Service{loadDotenv: dependencies.LoadDotenv}
}

// Run loads both operands through the shared dotenv source boundary, converts
// them into a value-free analysis snapshot, and compares their key inventories.
func (s *Service) Run(ctx context.Context, opts Options) (diffengine.Result, error) {
if err := ctx.Err(); err != nil {
return diffengine.Result{}, err
}

paths := []string{opts.LeftPath, opts.RightPath}
documents, err := s.loadDotenv(paths, paths)
if err != nil {
return diffengine.Result{}, normalizeLoadError(err)
}
if len(documents) != len(paths) {
return diffengine.Result{}, fmt.Errorf(
"load diff sources: got %d documents for %d selected paths",
len(documents), len(paths),
)
}
for i, document := range documents {
if document.SourcePath != paths[i] {
return diffengine.Result{}, fmt.Errorf(
"load diff sources: document %d has source path %q, want %q",
i, document.SourcePath, paths[i],
)
}
if document.Path != paths[i] {
return diffengine.Result{}, fmt.Errorf(
"load diff sources: document %d has display path %q, want %q",
i, document.Path, paths[i],
)
}
}
if err := ctx.Err(); err != nil {
return diffengine.Result{}, err
}

inputs := make([]analysisdotenv.DocumentInput, len(documents))
for i, document := range documents {
inputs[i] = analysisdotenv.DocumentInput{
ID: analysis.DocumentID(paths[i]),
Source: document,
}
}

snapshot := analysis.NewSnapshot(analysisdotenv.FromDocuments(inputs))
analysisDocuments := snapshot.Documents()
leftInventory := analysis.NewKeyInventory(analysisDocuments[0])
rightInventory := analysis.NewKeyInventory(analysisDocuments[1])

return diffengine.CompareInventories(
paths[0], leftInventory,
paths[1], rightInventory,
), nil
}

func normalizeLoadError(err error) error {
var loadErr *sourcedotenv.LoadError
if !errors.As(err, &loadErr) {
return err
}

switch {
case errors.Is(loadErr.Err, sourcedotenv.ErrIsDirectory):
return fmt.Errorf("%s is a directory, expected a dotenv file", loadErr.Path)
case errors.Is(loadErr.Err, sourcedotenv.ErrNotRegularFile):
return fmt.Errorf("%s is not a regular file, expected a dotenv file", loadErr.Path)
case errors.Is(loadErr.Err, os.ErrNotExist):
return fmt.Errorf("reading %s: file does not exist", loadErr.Path)
}

var pathErr *os.PathError
if errors.As(loadErr.Err, &pathErr) {
return fmt.Errorf("reading %s: %w", loadErr.Path, pathErr)
}
return fmt.Errorf("reading %s: %w", loadErr.Path, loadErr.Err)
}
99 changes: 99 additions & 0 deletions internal/application/diff/application_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// Copyright © 2026 envaar
// SPDX-License-Identifier: Apache-2.0

package diff_test

import (
"context"
"reflect"
"testing"

applicationdiff "github.com/envaar/vaar/internal/application/diff"
"github.com/envaar/vaar/internal/envfile"
sourcedotenv "github.com/envaar/vaar/internal/source/dotenv"
)

func TestServiceLoadsBothOperandsThroughSharedSourceLoader(t *testing.T) {
var loadCalls int
var gotPaths, gotDisplayPaths []string

service := applicationdiff.NewWithDependencies(applicationdiff.Dependencies{
LoadDotenv: func(paths, displayPaths []string) ([]sourcedotenv.Document, error) {
loadCalls++
gotPaths = append([]string(nil), paths...)
gotDisplayPaths = append([]string(nil), displayPaths...)

return []sourcedotenv.Document{
{
File: envfile.File{
Path: displayPaths[0],
Lines: []envfile.Line{
{Number: 1, Key: "COMMON", HasKey: true, HasAssignment: true},
{Number: 2, Key: "LEFT_ONLY", HasKey: true, HasAssignment: true},
},
},
SourcePath: paths[0],
},
{
File: envfile.File{
Path: displayPaths[1],
Lines: []envfile.Line{
{Number: 1, Key: "COMMON", HasKey: true, HasAssignment: true},
{Number: 2, Key: "RIGHT_ONLY", HasKey: true, HasAssignment: true},
},
},
SourcePath: paths[1],
},
}, nil
},
})

result, err := service.Run(context.Background(), applicationdiff.Options{
LeftPath: "left env",
RightPath: "right env",
})
if err != nil {
t.Fatalf("run failed: %v", err)
}

if loadCalls != 1 {
t.Fatalf("source loader calls = %d, want 1", loadCalls)
}
if want := []string{"left env", "right env"}; !reflect.DeepEqual(gotPaths, want) {
t.Fatalf("loaded paths = %#v, want %#v", gotPaths, want)
}
if want := []string{"left env", "right env"}; !reflect.DeepEqual(gotDisplayPaths, want) {
t.Fatalf("display paths = %#v, want %#v", gotDisplayPaths, want)
}

if result.Left != "left env" || result.Right != "right env" {
t.Fatalf("result labels = (%q, %q), want (%q, %q)", result.Left, result.Right, "left env", "right env")
}
if want := []string{"RIGHT_ONLY"}; !reflect.DeepEqual(result.MissingFromLeft, want) {
t.Fatalf("missing from left = %#v, want %#v", result.MissingFromLeft, want)
}
if want := []string{"LEFT_ONLY"}; !reflect.DeepEqual(result.MissingFromRight, want) {
t.Fatalf("missing from right = %#v, want %#v", result.MissingFromRight, want)
}
}

func TestServiceStopsBeforeLoadingWhenContextIsCanceled(t *testing.T) {
loadCalls := 0
service := applicationdiff.NewWithDependencies(applicationdiff.Dependencies{
LoadDotenv: func([]string, []string) ([]sourcedotenv.Document, error) {
loadCalls++
return nil, nil
},
})

ctx, cancel := context.WithCancel(context.Background())
cancel()

_, err := service.Run(ctx, applicationdiff.Options{LeftPath: "left", RightPath: "right"})
if err != context.Canceled {
t.Fatalf("run error = %v, want %v", err, context.Canceled)
}
if loadCalls != 0 {
t.Fatalf("source loader calls = %d, want 0", loadCalls)
}
}
59 changes: 12 additions & 47 deletions internal/cli/diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,17 @@ SPDX-License-Identifier: Apache-2.0
package cli

import (
"errors"
"fmt"
"os"

"github.com/envaar/vaar/internal/diff"
"github.com/envaar/vaar/internal/fs"
applicationdiff "github.com/envaar/vaar/internal/application/diff"
diffoutput "github.com/envaar/vaar/internal/output/diff"
"github.com/spf13/cobra"
)

func newDiffCmd() *cobra.Command {
var jsonOutput bool
var quiet bool
service := applicationdiff.New()

cmd := &cobra.Command{
Use: "diff <left> <right>",
Expand All @@ -32,29 +30,26 @@ func newDiffCmd() *cobra.Command {
leftPath := args[0]
rightPath := args[1]

leftData, err := readDiffFile(leftPath)
result, err := service.Run(cmd.Context(), applicationdiff.Options{
LeftPath: leftPath,
RightPath: rightPath,
})
if err != nil {
return err
}

rightData, err := readDiffFile(rightPath)
if err != nil {
return err
}

result, err := diff.Compare(leftPath, leftData, rightPath, rightData)
if err != nil {
return NewToolError("comparing dotenv files", err)
}

different := result.HasDifferences()

if jsonOutput {
if err := writeDiffJSON(cmd, result); err != nil {
data, err := diffoutput.JSON(result)
if err != nil {
return NewToolError("rendering diff JSON output failed", err)
}
if err := writeDiffLine(cmd, string(data)); err != nil {
return err
}
} else if !quiet {
if err := writeDiffText(cmd, result); err != nil {
if err := writeDiffLine(cmd, diffoutput.Text(result)); err != nil {
return err
}
}
Expand All @@ -80,36 +75,6 @@ func exactDiffArgs(_ *cobra.Command, args []string) error {
return nil
}

func readDiffFile(path string) ([]byte, error) {
data, err := fs.ReadFile(path)
if err != nil {
switch {
case errors.Is(err, fs.ErrIsDirectory):
return nil, NewToolError(fmt.Sprintf("%s is a directory, expected a dotenv file", path), nil)
case errors.Is(err, fs.ErrNotRegularFile):
return nil, NewToolError(fmt.Sprintf("%s is not a regular file, expected a dotenv file", path), nil)
case errors.Is(err, os.ErrNotExist):
return nil, NewToolError(fmt.Sprintf("reading %s: file does not exist", path), nil)
default:
return nil, NewToolError(fmt.Sprintf("reading %s", path), err)
}
}
return data, nil
}

func writeDiffText(cmd *cobra.Command, result diff.Result) error {
return writeDiffLine(cmd, diffoutput.Text(result))
}

func writeDiffJSON(cmd *cobra.Command, result diff.Result) error {
data, err := diffoutput.JSON(result)
if err != nil {
return NewToolError("rendering diff JSON output failed", err)
}

return writeDiffLine(cmd, string(data))
}

func writeDiffLine(cmd *cobra.Command, line string) error {
if _, err := fmt.Fprintln(cmd.OutOrStdout(), line); err != nil {
return NewToolError("writing diff output failed", err)
Expand Down
16 changes: 15 additions & 1 deletion internal/cli/diff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
"testing"
)

func TestDiffCLIUsesOutputDiffPackage(t *testing.T) {
func TestDiffCLIUsesApplicationAndOutputBoundaries(t *testing.T) {
workingDirectory, err := os.Getwd()
if err != nil {
t.Fatalf("get test working directory: %v", err)
Expand All @@ -45,6 +45,20 @@ func TestDiffCLIUsesOutputDiffPackage(t *testing.T) {
if !imports[outputDiffPath] {
t.Fatalf("diff CLI must import %q", outputDiffPath)
}
const applicationDiffPath = "github.com/envaar/vaar/internal/application/diff"
if !imports[applicationDiffPath] {
t.Fatalf("diff CLI must import %q", applicationDiffPath)
}
for _, forbidden := range []string{
"github.com/envaar/vaar/internal/diff",
"github.com/envaar/vaar/internal/fs",
"github.com/envaar/vaar/internal/envfile",
"github.com/envaar/vaar/internal/source/dotenv",
} {
if imports[forbidden] {
t.Fatalf("diff CLI must not import %q", forbidden)
}
}
if imports["github.com/envaar/vaar/internal/report"] {
t.Fatal("diff CLI must not import internal/report")
}
Expand Down
Loading
Loading