kscript

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 26, 2026 License: MIT Imports: 30 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

KScript

  • run a script by defining map data.
  • run a script file by input arguments.

DEV

   ScriptRunner
        |
        | scan and load script config files. eg: yaml
        |
   ScriptEntry map
        |
   -----|---------
   |		     |
   |		     |
Script-Task    Script-File
   |               |
Commands        Script file info
   |               |
   |               |
    \           /
   Run by input and context
graph TD
    subgraph 初始化流程
        A[ScriptRunner] --> B[扫描并加载脚本配置文件]
        B --> C{解析配置文件}
        C -->|YAML/JSON等格式| D[生成 ScriptEntry 映射表]
    end

    subgraph 映射表处理
        D --类型:Define--> E[Define-Map 处理]
        D --类型:File--> F[Script-File 处理]

        E --> E1[注册命令定义]
        E1 --> E2[绑定命令参数]

        F --> F1[解析脚本文件元数据]
        F1 --> F2[验证文件完整性]
    end

    subgraph 执行阶段
        E2 --> G[执行引擎]
        F2 --> G
        G --> H[根据输入参数和运行时上下文执行]
        H --> I[返回执行结果]
    end

    classDef default fill:#f8f9fa,stroke:#333
    classDef process fill:#d1e7dd,stroke:#155724
    classDef entity fill:#fff3cd,stroke:#856404

    class A,B,C,D process
    class E,F,E1,E2,F1,F2 entity
    class G,H,I default

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// AllowTypes shell wrapper for run a script. eg: bash, sh, zsh, cmd, pwsh
	AllowTypes = []string{"sh", "zsh", "bash", "cmd", "pwsh"}

	// AllowExt list. allowed script file ext.
	AllowExt = []string{".sh", ".zsh", ".bash", ".php", ".go", ".gop", ".kts", ".java", ".gry", ".groovy", ".py"}
)
View Source
var (
	// DefaultTaskFiles 默认自动查找的task文件名称 eg "kite.task[s].yml", "kite.script[s].yml"
	DefaultTaskFiles = []string{".kite.task", ".kite.tasks", ".kite.script", ".kite.scripts"}
	// DefaultDefineExts 默认允许的 scriptApp, scriptTask 定义文件后缀
	DefaultDefineExts = []string{".yml", ".yaml", ".toml", ".json"}
)
View Source
var ErrNotFound = errors.New("script not found")

ErrNotFound error

View Source
var ExtToBinMap = map[string]string{
	".sh":   "sh",
	".zsh":  "zsh",
	".bash": "bash",
	".php":  "php",
	".py":   "python",

	".gry":    "groovy",
	".groovy": "groovy",
	".go":     "go run",
}

ExtToBinMap data

eg:

'#!/usr/bin/env bash'
'#!/usr/bin/env -S go run'

Functions

func IsNoNotFound

func IsNoNotFound(err error) bool

IsNoNotFound error

Types

type CmdResult

type CmdResult struct {

	// Type for the command result, default is text.
	//  - Allow: text, json, xml, html, csv, yaml, toml, jsonl, json5, jsonc
	Type string
	// contains filtered or unexported fields
}

type RunCtx

type RunCtx struct {
	// Name for script run
	Name string
	Type string // shell type
	// ScriptType name
	ScriptType ScriptType

	// Verbose show more info on run
	Verbose bool
	// DryRun script
	DryRun bool
	// Workdir for run a script
	Workdir string
	// Vars for run cmd. access: $ctx.var_name
	Vars map[string]string
	// Env setting for run
	//  - 支持使用 ${var_name} 引用变量
	Env map[string]string
	// Silent mode, dont print exec command line.
	Silent bool `json:"silent"`
	// Args for run script task
	Args []string

	// BeforeFn hook. si: ScriptTask | ScriptApp | ScriptFile
	BeforeFn func(si any, ctx *RunCtx)
	// AppendVarsFn hook for run task. eg: gvs, paths, kite
	AppendVarsFn func(data map[string]any) map[string]any
	// contains filtered or unexported fields
}

RunCtx for run a task/file/app

func EnsureCtx

func EnsureCtx(ctx *RunCtx) *RunCtx

EnsureCtx to

func (*RunCtx) AppendArgsToVars

func (c *RunCtx) AppendArgsToVars(vars map[string]any)

AppendArgsToVars set args to vars. like shell $1 .. $N

func (*RunCtx) FullEnv

func (c *RunCtx) FullEnv() map[string]string

FullEnv for run script

func (*RunCtx) MergeEnv

func (c *RunCtx) MergeEnv(mps ...map[string]string)

MergeEnv and returns

func (*RunCtx) ParseVarInEnv

func (c *RunCtx) ParseVarInEnv(envPaths []string, vars map[string]any) map[string]string

func (*RunCtx) WithName

func (c *RunCtx) WithName(name string) *RunCtx

WithName to ctx

func (*RunCtx) WithNameArgs

func (c *RunCtx) WithNameArgs(name string, args []string) *RunCtx

WithNameArgs to ctx

type Runner

type Runner struct {
	RunnerMeta

	// PathResolver handler. 用于查找脚本文件
	PathResolver func(path string) string

	// ScriptAppDirs 独立的 script app 定义文件目录. 每个定义文件是一个独立的cli app
	//  - default will load from `$base/script-app`
	ScriptAppDirs []string `json:"script_app_dirs"`
	// ScriptAppExts script app file define extensions. eg: .yml, .yaml
	ScriptAppExts []string `json:"script_app_exts"`

	// DefineFiles script tasks define files, will read and add to Scripts
	//
	// Allow vars: $user, $os
	//
	// eg:
	//	- config/module/scripts.yml
	//	- ?config/module/scripts.$os.yml  // start withs '?' - an optional file, load on exists.
	DefineFiles []string `json:"define_files"`
	// 自动加载的task文件名称列表,无需设置扩展
	//  - 将自动从当前目录或父级目录中寻找 script task 定义文件
	//  - 找到第一个匹配的就停止
	AutoTaskFiles []string `json:"auto_task_files"`
	// 自动加载的task文件扩展名
	AutoTaskExts []string `json:"auto_task_exts"`
	// auto 向上搜索目录最大深度,默认为 6. 找到第一个匹配的就停止
	AutoMaxDepth int `json:"auto_max_depth"`

	// Scripts 通过配置定义的各种简单的任务命令。tasks config and loaded from DefineFiles.
	//
	// Format: {name: info, name2: info2, ...}
	//
	//  - special settings key: __settings, will read and merge to Settings
	Scripts map[string]any `json:"scripts"`

	// ParseEnv var on script command expr. eg: $SHELL
	ParseEnv bool `json:"parse_env"`
	// TypeShell wrapper for run each script.
	//
	// value like: bash, sh, zsh, cmd, pwsh or empty for direct run command
	TypeShell string `json:"type_shell"`

	// ScriptDirs 独立的 script file 文件查找目录。例如 bash, python, php 等脚本文件
	ScriptDirs []string `json:"script_dirs"`

	// AllowedExt allowed script file extensions. eg: .go, .sh
	AllowedExt []string `json:"allowed_ext"`
	// FindBinByExt on run a script file
	FindBinByExt bool `json:"find_bin_by_ext"`
	// ExtToBinMap settings. key: ext, value: bin name or path
	ExtToBinMap map[string]string `json:"ext_to_bin_map"`
	// BinPathMap settings. key: bin name, value: bin path
	BinPathMap map[string]string `json:"bin_path_map"`
	// contains filtered or unexported fields
}

Runner struct. TODO KRunner, ScriptRunner or ScriptManager

实现扩展的kite run命令,可以执行任何的 script-file, script-task, script-app 等等

func NewRunner

func NewRunner(fns ...func(kr *Runner)) *Runner

NewRunner instance

func (*Runner) GlobalScriptTasks

func (r *Runner) GlobalScriptTasks() map[string]any

GlobalScriptTasks returns tasks loaded from DefineFiles (全局配置文件中的任务)

func (*Runner) InitLoad

func (r *Runner) InitLoad() error

InitLoad define scripts and script files.

func (*Runner) IsScriptTask

func (r *Runner) IsScriptTask(name string) bool

IsScriptTask name

func (*Runner) LoadScriptApps

func (r *Runner) LoadScriptApps()

LoadScriptApps from Runner.ScriptApps

func (*Runner) LoadScriptFileInfo

func (r *Runner) LoadScriptFileInfo(name string) (*ScriptFile, error)

LoadScriptFileInfo info get

func (*Runner) LoadScriptFiles

func (r *Runner) LoadScriptFiles() error

LoadScriptFiles from the ScriptDirs

func (*Runner) LoadScriptTaskInfo

func (r *Runner) LoadScriptTaskInfo(name string) (*ScriptTask, error)

LoadScriptTaskInfo get script info as ScriptTask

func (*Runner) LoadScriptTasks

func (r *Runner) LoadScriptTasks() (err error)

LoadScriptTasks from Runner.DefineFiles

func (*Runner) ProjectScriptTasks

func (r *Runner) ProjectScriptTasks() map[string]any

ProjectScriptTasks returns tasks loaded from auto-discovered project files (当前目录自动发现的项目任务)

func (*Runner) RawScriptTask

func (r *Runner) RawScriptTask(name string) (any, bool)

RawScriptTask raw info get

func (*Runner) RawScriptTasks

func (r *Runner) RawScriptTasks() map[string]any

RawScriptTasks map

func (*Runner) Run

func (r *Runner) Run(name string, args []string, ctx *RunCtx) error

Run script or script-file by name and with args

func (*Runner) RunScriptFile

func (r *Runner) RunScriptFile(name string, args []string, ctx *RunCtx) error

RunScriptFile by input name and with arguments

func (*Runner) RunScriptTask

func (r *Runner) RunScriptTask(name string, args []string, ctx *RunCtx) error

RunScriptTask by input name and with arguments

func (*Runner) ScriptFiles

func (r *Runner) ScriptFiles() map[string]string

ScriptFiles file map

func (*Runner) Search

func (r *Runner) Search(name string, args []string, limit int) map[string]string

Search by name or description

func (*Runner) Search1ByName

func (r *Runner) Search1ByName(name string, limit int) string

Search1ByName search one script task/file by name

func (*Runner) SearchByKeywords

func (r *Runner) SearchByKeywords(parts []string, limit int) map[string]string

SearchByKeywords search script task/file by keywords

func (*Runner) SearchByName

func (r *Runner) SearchByName(name string, limit int) map[string]string

SearchByName search script task/file by name

func (*Runner) TaskNameDescs

func (r *Runner) TaskNameDescs(scripts map[string]any) map[string]string

TaskNameDescs extracts a name->desc map from raw script task data for display.

func (*Runner) TryRun

func (r *Runner) TryRun(name string, args []string, ctx *RunCtx) (found bool, err error)

TryRun script task or script-file by name and with args

type RunnerMeta

type RunnerMeta struct {
}

type ScriptApp

type ScriptApp struct {
	ScriptMeta
	// script app name, use file name
	Name string
	// File script app file path in Runner.ScriptApps
	File string
}

type ScriptApps

type ScriptApps struct {
	// contains filtered or unexported fields
}

type ScriptFile

type ScriptFile struct {
	ScriptMeta

	// script name, default uses file name. eg: demo.sh
	Name string
	// File script file path in Runner.ScriptDirs
	File string
	// BinName script file bin name. 默认从 ext 解析 e.g.: .php => php
	BinName string
	// file ext. eg: .go
	FileExt string
	// ShellBang script file shell bang line.
	// always at first line and start with: #!
	ShellBang string
	// contains filtered or unexported fields
}

func (*ScriptFile) Exec

func (sf *ScriptFile) Exec(args []string, ctx *RunCtx) error

Exec the script file with context

type ScriptFiles

type ScriptFiles struct {
	// contains filtered or unexported fields
}

type ScriptInfo

type ScriptInfo = ScriptTask

ScriptInfo one script task.

type ScriptItem

type ScriptItem interface {
	ScriptTask | ScriptApp | ScriptFile
}

type ScriptMeta

type ScriptMeta struct {
	// ScriptType name
	ScriptType ScriptType
	// Workdir for run script, default is current dir.
	Workdir string
	// CleanEnv for run script, default is false.
	CleanEnv bool
	// Env setting for run the script file/app/task
	//  - 支持使用 ${var_name} 引用变量
	Env map[string]string
	// EnvPaths custom prepend set ENV PATH.
	//  - 支持使用 ${var_name} 引用变量
	EnvPaths []string
	// Timeout for run a script, default is 0.
	Timeout time.Duration
	// contains filtered or unexported fields
}

type ScriptTask

type ScriptTask struct {
	ScriptMeta

	// Name for the script task
	Name string
	// Desc message
	Desc  string
	Usage string // usage message
	Help  string // long help message

	// Type shell wrap for run the task. allow: sh, bash, zsh
	Type string
	// Scope of the task. allow: global, project (default: project)
	//  - global: 全局任务,来自 DefineFiles 配置
	//  - project: 项目任务,来自当前目录自动发现的文件
	Scope string `json:"scope"`
	// Alias names for the script task
	Alias []string
	// Silent mode, dont print exec command line and output.
	Silent bool `json:"silent"`

	// Output target. default is stdout
	Output string
	// Vars map[string]Variable // TODO
	// Vars for run script task.
	//  - task配置中访问: $name
	//  - allow dynamic var: "@sh: git log -1" TODO
	Vars map[string]string `json:"vars"`
	// Deps task name list. 当前任务依赖的任务名称列表
	Deps []string `json:"deps"`

	// Cmds exec commands list.
	Cmds []*TaskCmd
	// Args for exec task commands.
	Args []string
	// CmdTimeout for run each command, default is 0.
	CmdTimeout time.Duration

	// Platform limit exec. allow: windows, linux, darwin
	Platform []string
	// PlatformSet 当前系统平台的设置,可以覆盖设置 Type, Cmds
	PlatformSet map[string]any

	// Ext enable extensions: proxy, clip
	Ext string
	// If condition check for run command. eg: sh:test -f .env
	// or see github.com/expr-lang/expr
	If string
	// For loop for run command. eg: for i in 1 2 3; do echo $i; done
	//  - var: 可以引用变量
	For *TaskFor
}

ScriptTask for one script task.

func (*ScriptTask) CmdsToString

func (st *ScriptTask) CmdsToString(sep ...string) string

CmdsToString build.

func (*ScriptTask) LoadFromMap

func (st *ScriptTask) LoadFromMap(mp map[string]any) error

func (*ScriptTask) ParseArgs

func (st *ScriptTask) ParseArgs() (args []string)

ParseArgs on commands

func (*ScriptTask) WithFallbackType

func (st *ScriptTask) WithFallbackType(typ string) *ScriptTask

WithFallbackType on not setting.

type ScriptTasks

type ScriptTasks struct {
	// contains filtered or unexported fields
}

type ScriptType

type ScriptType string

ScriptType definition

const (
	TypeFile ScriptType = "file"
	TypeTask ScriptType = "task" // task define.
	TypeApp  ScriptType = "app"  // app define. 独立的cli app配置文件
)

type TaskCmd

type TaskCmd struct {

	// Name for the command. if not set, use the command index: "cmd{index}"
	Name string
	// Workdir for run command
	Workdir string
	// Vars for run cmd.
	//  - task配置中访问: $name
	//  - allow dynamic var: "@sh: git log -1"
	Vars map[string]string
	// Env append ENV setting for run
	Env map[string]string
	// Run command line expr for run. eg: go run main.go
	Run string
	// Task refer task name.
	Task string
	// Type wrap for run. Allow: sh, bash, zsh
	Type string
	// If condition expr for run, return true or false
	If string
	// FailMsg custom message on run fail
	FailMsg string
	// Silent mode, dont print exec command line.
	Silent bool `json:"silent"`
	// Timeout for run the command, default is 0.
	Timeout time.Duration
	// IgnoreErr safed run command. ignore run error, continue next command.
	IgnoreErr bool `json:"ignore_err"`

	// Output for run the command, default is stdout.
	//  - allow: stdout, stderr, both, discard, collect
	//  - collect: collect command output to Result. and can use Result.Text() or Result.Bytes() to get output.
	Output string
	// ResultType for run the command, default is text. see CmdResult.Type
	//
	// Allow: text, json, xml, html, csv, yaml, toml, jsonl, json5, jsonc
	ResultType string
	// Result for run the command, default is nil.
	Result CmdResult
	// contains filtered or unexported fields
}

TaskCmd of the task TODO

type TaskFor

type TaskFor struct {
	Var   string
	Items []string
}

type TaskSettings

type TaskSettings struct {
	// Env append set ENV for all script tasks
	Env map[string]string `json:"env"`
	// EnvPaths prepend set ENV PATHs for all script tasks
	EnvPaths []string `json:"env_paths"`

	// DefaultGroup default group name for use Groups. will merge default group data to Vars
	DefaultGroup string `json:"default_group"`
	// Vars built in vars map. group name: vars
	//  - usage in a task: ${vars.key}
	Vars map[string]string `json:"vars"`
	// Grouped vars map.
	//  - group name => map[string]string grouped var map.
	Groups comdef.L2StrMap `json:"groups"`
}

TaskSettings 可以通过 script task 文件中的 "__settings" 调整设置

type Variable

type Variable struct {
	// Type of variable, allow: sh, bash, zsh, go or empty.
	Type  string
	Expr  string
	Value string
}

Variable dynamic variable definition. 动态变量 TODO

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL