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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),

- Import repositories containing Git submodules with their pins and original
`.gitmodules` file. Submodules remain uninitialized.
- Show usage and available flags with `layerctl --help` and `--help` on subcommands.

## [0.1.1] - 2026-11-17

Expand Down
36 changes: 17 additions & 19 deletions cmd/layerctl/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,28 @@ import (
"runtime/debug"
"strings"

"github.com/alecthomas/kong"

"github.com/NonLogicalDev/util.layerctl/internal/cli"
)

// Set by release and package builds; local builds remain identifiable.
var version = "0.0.0-dev"
var commit = "unknown"

func main() {
logger := log.New(os.Stderr, "layerctl: ", 0)
if err := cli.Run(context.Background(), os.Args[1:], logger, os.Getwd, versionInfo, kong.Exit(os.Exit)); err != nil {
logger.Print(err)
os.Exit(1)
}
}

func versionInfo() string {
info, _ := debug.ReadBuildInfo()
return fmt.Sprintf("%s (%s)", buildVersion(version, info), buildCommit(info))
}

// A versioned go install records its module version without release linker flags.
func buildVersion(embedded string, info *debug.BuildInfo) string {
if embedded != "0.0.0-dev" {
Expand All @@ -28,12 +43,8 @@ func buildVersion(embedded string, info *debug.BuildInfo) string {
}

// Go records VCS metadata for ordinary local builds when the checkout is available.
func buildCommit() string {
if commit != "unknown" {
return commit
}
info, ok := debug.ReadBuildInfo()
if !ok {
func buildCommit(info *debug.BuildInfo) string {
if commit != "unknown" || info == nil {
return commit
}
revision, modified := commit, false
Expand All @@ -50,16 +61,3 @@ func buildCommit() string {
}
return revision
}

func main() {
if len(os.Args) == 2 && (os.Args[1] == "--version" || os.Args[1] == "version") {
info, _ := debug.ReadBuildInfo()
fmt.Printf("layerctl %s (%s)\n", buildVersion(version, info), buildCommit())
return
}
logger := log.New(os.Stderr, "layerctl: ", 0)
if err := cli.Run(context.Background(), os.Args[1:], os.Stdout, os.Stderr); err != nil {
logger.Print(err)
os.Exit(1)
}
}
66 changes: 60 additions & 6 deletions cmd/layerctl/main_test.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,65 @@
package main

import (
"bytes"
"os/exec"
"path/filepath"
"runtime/debug"
"strings"
"testing"
)

func TestHelp(t *testing.T) {
binary := buildLayerctl(t)
dir := t.TempDir()
tests := []struct {
name string
giveArgs []string
want string
}{
{"Root", []string{"--help"}, "projection create <name>"},
{"Short", []string{"-h"}, "Usage: layerctl"},
{"Projection", []string{"projection", "--help"}, "projection unlock <name>"},
{"ProjectionCreate", []string{"projection", "create", "--help"}, "--worktree=PATH"},
{"ProjectionCreateWithName", []string{"projection", "create", "demo", "--help"}, "--through=LAYER"},
{"ProjectionList", []string{"projection", "list", "--help"}, "Usage: layerctl projection list"},
{"ProjectionPath", []string{"projection", "path", "--help"}, "Usage: layerctl projection path <name>"},
{"ProjectionContinue", []string{"projection", "continue", "--help"}, "Usage: layerctl projection continue <name>"},
{"ProjectionUnlock", []string{"projection", "unlock", "--help"}, "Usage: layerctl projection unlock <name>"},
{"ProjectionDelete", []string{"projection", "delete", "--help"}, "Usage: layerctl projection delete <name>"},
{"Layer", []string{"layer", "--help"}, "layer refresh --from=PROJECTION <id>"},
{"LayerAdd", []string{"layer", "add", "--help"}, "--from=PROJECTION"},
{"LayerRefresh", []string{"layer", "refresh", "--help"}, "--from=PROJECTION"},
{"Graph", []string{"graph", "--help"}, "--format="},
{"Check", []string{"check", "--help"}, "Usage: layerctl check"},
{"Version", []string{"version", "--help"}, "Usage: layerctl version"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := exec.CommandContext(t.Context(), binary, tt.giveArgs...)
cmd.Dir = dir
var stderr bytes.Buffer
cmd.Stderr = &stderr
stdout, err := cmd.Output()
if err != nil {
t.Fatalf("layerctl %v: %v\n%s", tt.giveArgs, err, &stderr)
}
if !strings.Contains(string(stdout), tt.want) {
t.Errorf("stdout = %q, want it to contain %q", stdout, tt.want)
}
if stderr.Len() != 0 {
t.Errorf("stderr = %q, want empty output", &stderr)
}
})
}
}

// The version command must work outside a definition repository and report
// the values embedded by release builds.
func TestReleaseVersion(t *testing.T) {
binary := filepath.Join(t.TempDir(), "layerctl")
build := exec.Command("go", "build", "-ldflags", "-X main.version=1.2.3 -X main.commit=abc123", "-o", binary, ".")
if output, err := build.CombinedOutput(); err != nil {
t.Fatalf("build release binary: %v\n%s", err, output)
}
binary := buildLayerctl(t, "-ldflags", "-X main.version=1.2.3 -X main.commit=abc123")
for _, arg := range []string{"--version", "version"} {
cmd := exec.Command(binary, arg)
cmd := exec.CommandContext(t.Context(), binary, arg)
cmd.Dir = t.TempDir()
output, err := cmd.CombinedOutput()
if err != nil {
Expand Down Expand Up @@ -48,3 +91,14 @@ func TestBuildVersion(t *testing.T) {
t.Fatalf("buildVersion() without build info = %q", got)
}
}

func buildLayerctl(t *testing.T, buildFlags ...string) string {
t.Helper()
binary := filepath.Join(t.TempDir(), "layerctl")
args := append([]string{"build", "-o", binary}, buildFlags...)
build := exec.CommandContext(t.Context(), "go", append(args, ".")...)
if output, err := build.CombinedOutput(); err != nil {
t.Fatalf("build layerctl: %v\n%s", err, output)
}
return binary
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ module github.com/NonLogicalDev/util.layerctl
go 1.26

require github.com/BurntSushi/toml v1.5.0

require github.com/alecthomas/kong v1.17.0
8 changes: 8 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,10 @@
github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0=
github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
github.com/alecthomas/kong v1.17.0 h1:f52BVWChYMDkMkCoqkEWRuFOk/K4B5LO7xIijeLJRdk=
github.com/alecthomas/kong v1.17.0/go.mod h1:wrlbXem1CWqUV5Vbmss5ISYhsVPkBb1Yo7YKJghju2I=
github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs=
github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
46 changes: 46 additions & 0 deletions internal/cli/check.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Modified from abg-OAI/codex: module import path changed for this extraction.
package cli

import (
"context"
"fmt"
"os"
"path/filepath"
"strings"

"github.com/NonLogicalDev/util.layerctl/internal/projection"
)

type checkCmd struct{}

func (*checkCmd) Help() string {
return "The check runs the definition's scripts. " +
"If composition fails, " +
"the temporary projection can remain available for inspection."
}

// Run checks the definition by building a temporary projection.
func (*checkCmd) Run(ctx context.Context, repo *repositoryLoader) error {
service, err := repo.OpenProjection(ctx)
if err != nil {
return err
}

f, err := os.CreateTemp("", "layerctl-check-")
if err != nil {
return err
}
name := strings.ToLower(filepath.Base(f.Name()))
if err := f.Close(); err != nil {
return err
}
_ = os.Remove(f.Name())
_, err = service.Create(ctx, projection.CreateRequest{Name: name})
if err != nil {
return fmt.Errorf("check composition: %w", err)
}
if err := service.Delete(ctx, name); err != nil {
return fmt.Errorf("remove check projection: %w", err)
}
return nil
}
161 changes: 31 additions & 130 deletions internal/cli/cli.go
Original file line number Diff line number Diff line change
@@ -1,147 +1,48 @@
// Modified from abg-OAI/codex: module import path changed for this extraction.
// Package cli parses layerctl commands and renders their results. Domain
// packages own projection, layer, and upstream behavior.
// Package cli parses layerctl commands and renders their results.
// Domain packages own repository, projection, and layer operations.
package cli

import (
"context"
"errors"
"flag"
"fmt"
"io"
"os"
"strings"
"log"

"github.com/NonLogicalDev/util.layerctl/internal/definition"
"github.com/NonLogicalDev/util.layerctl/internal/gitrepo"
"github.com/NonLogicalDev/util.layerctl/internal/graph"
"github.com/NonLogicalDev/util.layerctl/internal/layer"
"github.com/NonLogicalDev/util.layerctl/internal/projection"
"github.com/alecthomas/kong"
)

// Run executes one layerctl invocation from the repository containing the
// current directory.
func Run(ctx context.Context, args []string, stdout, stderr io.Writer) error {
if len(args) == 0 {
return errors.New("usage: layerctl projection <create|list|path|continue|unlock|delete> ...")
}
workingDirectory, err := os.Getwd()
if err != nil {
return fmt.Errorf("get working directory: %w", err)
}
git, err := gitrepo.Discover(ctx, workingDirectory)
// Run parses and executes one invocation. getwd and version are called only
// when the selected command needs them.
func Run(
ctx context.Context,
args []string,
logger *log.Logger,
getwd func() (string, error),
version func() string,
options ...kong.Option,
) error {
parser, err := kong.New(new(rootCmd), append([]kong.Option{
kong.Name("layerctl"),
kong.Description("Compose Git repositories and changes as ordered layers."),
kong.BindTo(ctx, (*context.Context)(nil)),
kong.Bind(&repositoryLoader{Getwd: getwd, Log: logger}, versionProvider(version)),
}, options...)...)
if err != nil {
return fmt.Errorf("discover Git repository: %w", err)
return fmt.Errorf("construct CLI: %w", err)
}
canonical, err := definition.Load(git.Root)
parsed, err := parser.Parse(args)
if err != nil {
return fmt.Errorf("load canonical definition: %w", err)
}
if args[0] == "graph" {
flags := flag.NewFlagSet("graph", flag.ContinueOnError)
flags.SetOutput(stderr)
format := flags.String("format", "dot", "graph output format: dot or mermaid")
if err := flags.Parse(args[1:]); err != nil {
return err
}
if flags.NArg() != 0 {
return errors.New("usage: layerctl graph [--format dot|mermaid]")
}
return graph.Write(stdout, canonical.Layers, *format)
}
return runComposition(ctx, canonical, git, args, stdout, stderr)
}

func runLayer(ctx context.Context, service *layer.Service, args []string, stderr io.Writer) error {
if len(args) < 2 {
return errors.New("usage: layerctl layer <add|refresh> ...")
}
id := args[1]
flags := flag.NewFlagSet("layer "+args[0], flag.ContinueOnError)
flags.SetOutput(stderr)
from := flags.String("from", "", "capture from PROJECTION")
switch args[0] {
case "add":
if err := flags.Parse(args[2:]); err != nil {
return err
}
if flags.NArg() != 0 || *from == "" {
return errors.New("usage: layerctl layer add NNNN-LAYER-SLUG --from PROJECTION")
}
return service.Add(ctx, layer.AddRequest{ID: id, Projection: *from})
default:
return fmt.Errorf("unknown layer command %q", args[0])
return err
}
return parsed.Run()
}

type projectionRunner interface {
Create(context.Context, projection.CreateRequest) (projection.Projection, error)
List(context.Context) ([]projection.Projection, error)
Path(context.Context, string) (string, error)
Delete(context.Context, string) error
}
type rootCmd struct {
VersionFlag versionFlag `name:"version" help:"Print the version and source commit. Use without a command."`

func runProjection(ctx context.Context, service projectionRunner, args []string, stdout, stderr io.Writer) error {
if len(args) == 0 {
return errors.New("usage: layerctl projection <create|list|path|continue|unlock|delete> ...")
}
switch args[0] {
case "create":
return runProjectionCreate(ctx, service, args[1:], stdout, stderr)
case "list":
if len(args) != 1 {
return errors.New("usage: layerctl projection list")
}
projections, err := service.List(ctx)
if err != nil {
return err
}
for _, item := range projections {
fmt.Fprintf(stdout, "%s\t%s\t%s\t%s\n", item.Name, item.Base, item.Head, item.WorktreePath)
}
return nil
case "path":
if len(args) != 2 {
return errors.New("usage: layerctl projection path NAME")
}
path, err := service.Path(ctx, args[1])
if err != nil {
return err
}
fmt.Fprintln(stdout, path)
return nil
case "delete":
if len(args) != 2 {
return errors.New("usage: layerctl projection delete NAME")
}
return service.Delete(ctx, args[1])
default:
return fmt.Errorf("unknown projection command %q", args[0])
}
}

func runProjectionCreate(ctx context.Context, service projectionRunner, args []string, stdout, stderr io.Writer) error {
if len(args) == 0 || strings.HasPrefix(args[0], "-") {
return errors.New("usage: layerctl projection create NAME [--worktree PATH] [--through LAYER]")
}
flags := flag.NewFlagSet("projection create", flag.ContinueOnError)
flags.SetOutput(stderr)
worktree := flags.String("worktree", "", "attach the projection at PATH")
through := flags.String("through", "", "stop after LAYER")
if err := flags.Parse(args[1:]); err != nil {
return err
}
if flags.NArg() != 0 {
return errors.New("usage: layerctl projection create NAME [--worktree PATH] [--through LAYER]")
}
created, err := service.Create(ctx, projection.CreateRequest{
Name: args[0],
WorktreePath: *worktree,
Through: *through,
})
if err != nil {
return err
}
fmt.Fprintln(stdout, created.WorktreePath)
return nil
Projection projectionCmd `cmd:"" help:"Manage projection workspaces."`
Layer layerCmd `cmd:"" help:"Capture changes as layers."`
Graph graphCmd `cmd:"" help:"Render the layer dependency graph."`
Check checkCmd `cmd:"" help:"Check that the definition composes successfully."`
Version versionCmd `cmd:"" help:"Print the version and source commit."`
}
Loading
Loading