package vcs

import (
	
	
	
	
	
	
	
	
	
	
)

// CleanRelPath normalizes a repo-relative path to a clean slash-separated form
// without a leading "./".
func ( string) string {
	return path.Clean(strings.TrimPrefix(filepath.ToSlash(), "./"))
}

// CleanRelDir normalizes a repo-relative directory path, returning "" for the
// repository root ("." or "").
func ( string) string {
	 := CleanRelPath()
	if  == "" ||  == "." {
		return ""
	}
	return 
}

// DirPrefix returns a trailing-slash prefix for dir, or "" for the repo root.
func ( string) string {
	if  := CleanRelDir();  != "" {
		return  + "/"
	}
	return ""
}

// WriteDirFile safely writes data to slashPath within rootDir using os.Root to
// prevent path traversal outside the session working tree.
func (,  string,  []byte) error {
	 := CleanRelPath()
	,  := os.OpenRoot()
	if  != nil {
		return 
	}
	defer func() { _ = .Close() }()

	if  := path.Dir();  != "." {
		if  := .MkdirAll(, 0o755);  != nil {
			return 
		}
	}
	return .WriteFile(, , 0o644)
}

// ExtractTar extracts regular files from a tar stream into destDir using
// os.Root to prevent path traversal. If stripPrefix is non-empty, that leading
// slash-terminated prefix is stripped from each entry name. ExtractTar always
// drains trailing padding from r so streaming producers do not block on pipes.
func ( io.Reader, ,  string) error {
	,  := os.OpenRoot()
	if  != nil {
		_, _ = io.Copy(io.Discard, )
		return fmt.Errorf("open export root %q: %w", , )
	}
	defer func() { _ = .Close() }()

	 := tar.NewReader()
	var  error
	for {
		,  := .Next()
		if  == io.EOF {
			break
		}
		if  != nil {
			 = fmt.Errorf("read tar archive: %w", )
			break
		}
		if .Typeflag != tar.TypeReg {
			continue
		}
		 := filepath.ToSlash(.Name)
		if  != "" {
			var  bool
			,  = strings.CutPrefix(, )
			if ! {
				continue
			}
		}
		 := CleanRelPath()
		if  == "" ||  == "." {
			continue
		}
		if  := path.Dir();  != "." {
			if  := .MkdirAll(, 0o755);  != nil {
				 = fmt.Errorf("mkdir %s: %w", , )
				break
			}
		}
		,  := .OpenFile(, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
		if  != nil {
			 = fmt.Errorf("create %s: %w", , )
			break
		}
		,  := io.Copy(, )
		 := .Close()
		if  != nil {
			 = fmt.Errorf("write %s: %w", , )
			break
		}
		if  != nil {
			 = fmt.Errorf("close %s: %w", , )
			break
		}
	}
	_, _ = io.Copy(io.Discard, )
	return 
}

// RunCmd executes an external VCS command in dir with optional stdin and extra
// environment variables, returning stdout bytes or a stderr-enriched error.
func ( context.Context,  string,  []byte,  []string,  string,  ...string) ([]byte, error) {
	 := exec.CommandContext(, , ...)
	.Dir = 
	if len() > 0 {
		.Env = append(os.Environ(), ...)
	}
	if  != nil {
		.Stdin = bytes.NewReader()
	}
	var ,  bytes.Buffer
	.Stdout = &
	.Stderr = &
	if  := .Run();  != nil {
		if  := strings.TrimSpace(.String());  != "" {
			return nil, fmt.Errorf("%w: %s", , )
		}
		return nil, 
	}
	return .Bytes(), nil
}