package cli

import (
	
	
	
	
	
	
	

	
	
	
	
	
	
	
	
)

const rootUsage = `goship — layered multi-module Go release tool

Usage:
  goship <command> [flags] [args...]

Commands:
  plan   Preview a layered release plan without mutating the repository
  run    Execute a layered release locally (use -push to publish to remote)
  diff   Show exported Go API changes since each module's latest tag
  list   List loaded modules, latest tags, and change status
  graph  Render the layered module dependency graph (text, json, dot, mermaid)
  help   Show help for goship or a specific subcommand

Run "goship <command> -h" for command-specific flags.
`

// ExitError wraps an optional error with a specific process exit code.
type ExitError struct {
	Code int
	Err  error
}

// Error implements the error interface.
func ( ExitError) () string {
	if .Err == nil {
		return ""
	}
	return .Err.Error()
}

// Unwrap returns the underlying error, if any.
func ( ExitError) () error { return .Err }

// Run dispatches goship CLI arguments and writes output to stdout and stderr.
func ( context.Context,  []string, ,  io.Writer) error {
	if len() == 0 {
		_, _ = io.WriteString(, rootUsage)
		return ExitError{Code: 2}
	}

	 := [0]
	 := [1:]

	switch  {
	case "-h", "-help", "--help", "help":
		if len() == 0 {
			_, _ = io.WriteString(, rootUsage)
			return nil
		}
		return (, []string{[0], "-h"}, , )
	case "diff":
		return runDiff(, , , )
	case "list":
		return runList(, , , )
	case "graph":
		return runGraph(, , , )
	case "plan":
		return runPlan(, , , )
	case "run":
		return runExecute(, , , )
	default:
		_, _ = fmt.Fprintf(, "unknown command %q\n\n%s", , rootUsage)
		return ExitError{Code: 2}
	}
}

type stringListFlag []string

func ( *stringListFlag) () string { return strings.Join(*, ",") }

func ( *stringListFlag) ( string) error {
	* = append(*, )
	return nil
}

type commonFlags struct {
	dir             string
	configPath      string
	vcsName         string
	discovery       string
	workFile        string
	rev             string
	include         stringListFlag
	exclude         stringListFlag
	excludeVersions stringListFlag
	format          string
	color           string
}

func ( *commonFlags) ( *flag.FlagSet) {
	.StringVar(&.dir, "dir", ".", "Repository directory")
	.StringVar(&.configPath, "config", "", "JSON config file (default: goship.json)")
	.StringVar(&.vcsName, "vcs", "", "VCS backend (auto, git, hg, fossil, jj)")
	.StringVar(&.discovery, "discovery", "", "Workspace mode (auto, work, walk)")
	.StringVar(&.workFile, "work", "", "Repo-relative go.work file (e.g. go.work.example)")
	.StringVar(&.rev, "rev", "", "Target VCS revision (default: current working revision)")
	.Var(&.include, "include", "Include glob pattern for module path or dir")
	.Var(&.exclude, "exclude", "Exclude glob pattern for module path or dir")
	.Var(&.excludeVersions, "exclude-version", "Skip modules requiring this version")
	.StringVar(&.format, "format", string(ui.FormatText), "Output format")
	.StringVar(&.color, "color", string(ui.ColorAuto), "Color mode (auto, always, never)")
}

type runtimeEnv struct {
	cfg       config.Config
	vcs       vcs.VCS
	workspace workspace.Loader
	renderer  *ui.Renderer
	setFlags  map[string]bool
}

func ( config.VCSConfig) *vcs.Registry {
	// Jujutsu precedes Git so colocated jj+git repos auto-detect as jj.
	return vcs.NewRegistry(
		jjvcs.Opener(.JJ),
		gitvcs.Opener(.Git),
		hgvcs.Opener(.Hg),
		fossilvcs.Opener(.Fossil),
	)
}

func ( context.Context,  *flag.FlagSet,  *commonFlags,  io.Writer) (*runtimeEnv, error) {
	 := make(map[string]bool)
	.Visit(func( *flag.Flag) {
		[.Name] = true
	})

	,  := filepath.Abs(.dir)
	if  != nil {
		return nil, fmt.Errorf("resolve directory %q: %w", .dir, )
	}

	var  config.Config
	if .configPath != "" {
		,  = readConfigFile(.configPath)
		if  != nil {
			return nil, 
		}
	} else if ,  := findConfigFile(, config.DefaultFileName);  {
		,  = readConfigFile()
		if  != nil {
			return nil, 
		}
	}

	 := .VCS.Name()
	if ["vcs"] {
		 = .vcsName
	}
	,  := registryFor(.VCS).Open(, , )
	if  != nil {
		return nil, 
	}

	 := .Workspace.Mode()
	 := .Workspace.WorkFile()
	if ["discovery"] {
		 = workspace.Mode(.discovery)
	}
	if ["work"] {
		 = .workFile
	}
	if ["include"] {
		.Include = append(.Include, .include...)
	}
	if ["exclude"] {
		.Exclude = append(.Exclude, .exclude...)
	}
	if ["exclude-version"] {
		.ExcludeVersions = append(.ExcludeVersions, .excludeVersions...)
	}

	,  := workspace.New(, )
	if  != nil {
		return nil, 
	}

	,  := ui.ParseColorMode(.color)
	if  != nil {
		return nil, 
	}

	return &runtimeEnv{
		cfg:       ,
		vcs:       ,
		workspace: ,
		renderer:  ui.New(, , os.Environ()),
		setFlags:  ,
	}, nil
}

func ( string) (config.Config, error) {
	,  := os.ReadFile()
	if  != nil {
		return config.Config{}, fmt.Errorf("read config %q: %w", , )
	}
	,  := config.Parse()
	if  != nil {
		return config.Config{}, fmt.Errorf("config %q: %w", , )
	}
	return , nil
}

func (,  string) (string, bool) {
	 := filepath.Clean()
	for {
		 := filepath.Join(, )
		if ,  := os.Stat();  == nil && !.IsDir() {
			return , true
		}
		if hasVCSMarker() {
			return "", false
		}
		 := filepath.Dir()
		if  ==  {
			return "", false
		}
		 = 
	}
}

func ( string) bool {
	for ,  := range []string{".git", ".hg", ".jj", ".fslckout", "_FOSSIL_"} {
		if ,  := os.Stat(filepath.Join(, ));  == nil {
			return true
		}
	}
	return false
}