yaml-pipeline-transfer

2
1
Source

YAML 流水线转换指南,涵盖 YAML 与 Model 双向转换、PAC(Pipeline as Code)实现、模板引用、触发器配置。当用户需要解析 YAML 流水线、实现 PAC 模式、处理流水线模板或进行 YAML 语法校验时使用。

Install

mkdir -p .claude/skills/yaml-pipeline-transfer && curl -L -o skill.zip "https://mcp.directory/api/skills/download/3487" && unzip -o skill.zip -d .claude/skills/yaml-pipeline-transfer && rm skill.zip

Installs to .claude/skills/yaml-pipeline-transfer

About this skill

Skill 22: YAML 流水线转换指南

概述

YAML 流水线转换是 BK-CI 的核心功能之一,支持 Pipeline as Code(PAC)模式。本 Skill 详细介绍 YAML 与 Model 之间的双向转换机制、模板系统、触发器配置等关键技术。

触发条件

当用户需要实现以下功能时,使用此 Skill:

  • YAML 流水线解析与转换
  • Model 转换为 YAML
  • PAC(Pipeline as Code)实现
  • 流水线模板引用
  • YAML 语法校验
  • 自定义 YAML 处理逻辑

核心组件架构

1. TransferMapper(转换映射器)

位置common-pipeline-yaml/src/main/kotlin/.../transfer/TransferMapper.kt

职责:YAML 与对象之间的序列化/反序列化核心引擎

关键方法

object TransferMapper {
    // YAML 字符串转对象
    fun <T> to(str: String): T
    
    // 对象转 YAML 字符串
    fun toYaml(bean: Any): String
    
    // 任意对象转换
    fun <T> anyTo(any: Any?): T
    
    // 格式化 YAML
    fun formatYaml(yaml: String): String
    
    // 合并 YAML(保留注释和锚点)
    fun mergeYaml(old: String, new: String): String
    
    // 获取 YAML 第一层级的坐标定位
    fun getYamlLevelOneIndex(yaml: String): Map<String, TransferMark>
    
    // YAML 节点索引
    fun indexYaml(yaml: String, line: Int, column: Int): NodeIndex?
    
    // 标记 YAML 节点位置
    fun markYaml(index: NodeIndex, yaml: String): TransferMark?
    
    // 获取 YAML 工厂
    fun getYamlFactory(): Yaml
    
    // 获取 ObjectMapper
    fun getObjectMapper(): ObjectMapper
}

自定义特性

1. 自定义字符串引号检查器

解决 YAML on 关键字的特殊用法:

class CustomStringQuotingChecker : StringQuotingChecker() {
    override fun needToQuoteName(name: String): Boolean {
        // 自定义逻辑:on 关键字不加引号
        if (name == "on") return false
        return reservedKeyword(name) || looksLikeYAMLNumber(name)
    }
    
    // 检测十六进制数字(0x开头需要加引号)
    private fun looksLikeHexNumber(value: String): Boolean {
        if (value.length < 3) return false
        return value.startsWith("0x", ignoreCase = true)
    }
}

2. 自定义 YAML 生成器

去除换行符前的尾随空格,支持 YAML Block 输出:

override fun writeString(text: String) {
    super.writeString(removeTrailingSpaces(text))
}

private fun removeTrailingSpaces(text: String): String {
    val result = StringBuilder(text.length)
    // 逐行处理,移除每行末尾的空格
    // ...
    return result.toString()
}

3. 锚点(Anchor)管理

// 收集 YAML 中的所有锚点
private fun anchorNode(node: Node, anchors: MutableMap<String, Node>)

// 替换相同节点为锚点引用
private fun replaceAnchor(node: Node, anchors: Map<String, Node>)

// 自定义锚点生成器(保持原命名)
class CustomAnchorGenerator : AnchorGenerator {
    override fun nextAnchor(node: Node): String {
        return node.anchor  // 不重命名
    }
}

4. mergeYaml 功能

智能合并两个 YAML,保留注释和锚点:

fun mergeYaml(old: String, new: String): String {
    if (old.isBlank()) return new
    
    val oldE = getYamlFactory().parse(old.reader()).toList()
    val newE = getYamlFactory().parse(new.reader()).toMutableList()
    
    // 使用 Myers Diff 算法计算差异
    val patch = DiffUtils.diff(oldE, newE, MeyersDiffWithLinearSpace.factory().create())
    
    // 处理注释和锚点
    for (delta in patch.deltas) {
        when (delta.type) {
            DeltaType.DELETE -> {
                // 保留源文件的注释
                val sourceComment = checkCommentEvent(delta.source.lines)
                if (sourceComment.isNotEmpty()) {
                    newE.addAll(delta.target.position, sourceComment)
                }
            }
            DeltaType.INSERT -> {
                // 保留锚点信息
                anchorChecker[delta.source.position]?.let { checker ->
                    // 恢复锚点
                }
            }
        }
    }
    
    // 重建节点,恢复锚点引用
    val newNode = eventsComposer(newE).singleNode
    replaceAnchor(newNode, anchorNodes)
    
    return getYamlFactory().serialize(newNode)
}

2. ModelTransfer(Model 转换器)

位置common-pipeline-yaml/src/main/kotlin/.../transfer/ModelTransfer.kt

职责:YAML ↔ Pipeline Model 的核心转换逻辑

关键方法

@Component
class ModelTransfer @Autowired constructor(
    val client: Client,
    val modelStage: StageTransfer,
    val elementTransfer: ElementTransfer,
    val variableTransfer: VariableTransfer,
    val transferCache: TransferCacheService
) {
    // YAML 转 Model
    fun yaml2Model(yamlInput: YamlTransferInput): Model
    
    // YAML 转 Setting
    fun yaml2Setting(yamlInput: YamlTransferInput): PipelineSetting
    
    // YAML 转 Labels
    fun yaml2Labels(yamlInput: YamlTransferInput): List<String>
    
    // Model 转 YAML
    fun model2Yaml(input: ModelTransferInput): PreTemplateScriptBuildYamlParser
}

yaml2Model 实现流程

fun yaml2Model(yamlInput: YamlTransferInput): Model {
    // 1. 前置切面处理
    yamlInput.aspectWrapper.setYaml4Yaml(yamlInput.yaml, BEFORE)
    
    // 2. 构建 Model 基础结构
    val stageList = mutableListOf<Stage>()
    val model = Model(
        name = yamlInput.yaml.name ?: yamlInput.pipelineInfo?.pipelineName ?: "",
        desc = yamlInput.yaml.desc ?: yamlInput.pipelineInfo?.pipelineDesc ?: "",
        stages = stageList,
        labels = emptyList(),
        instanceFromTemplate = false,
        pipelineCreator = yamlInput.pipelineInfo?.creator ?: yamlInput.userId
    )
    
    val stageIndex = AtomicInteger(0)
    
    // 3. 构建 Trigger Stage
    if (!yamlInput.yaml.checkForTemplateUse()) {
        stageList.add(modelStage.yaml2TriggerStage(yamlInput, stageIndex.incrementAndGet()))
    }
    
    // 4. 构建普通 Stage
    formatStage(yamlInput, stageList, stageIndex)
    
    // 5. 构建 Finally Stage
    formatFinally(yamlInput, stageList, stageIndex.incrementAndGet())
    
    // 6. 处理模板引用
    formatTemplate(yamlInput, model)
    
    // 7. 后置切面处理
    yamlInput.aspectWrapper.setModel4Model(model, AFTER)
    
    return model
}

yaml2Setting 实现

fun yaml2Setting(yamlInput: YamlTransferInput): PipelineSetting {
    val yaml = yamlInput.yaml
    return PipelineSetting(
        projectId = yamlInput.pipelineInfo?.projectId ?: "",
        pipelineId = yamlInput.pipelineInfo?.pipelineId ?: "",
        buildNumRule = yaml.customBuildNum,
        pipelineName = yaml.name ?: yamlInput.yamlFileName ?: yamlInput.pipelineInfo?.pipelineName ?: "",
        desc = yaml.desc ?: yamlInput.pipelineInfo?.pipelineDesc ?: "",
        
        // 并发控制
        concurrencyGroup = yaml.concurrency?.group ?: PIPELINE_SETTING_CONCURRENCY_GROUP_DEFAULT,
        concurrencyCancelInProgress = yaml.concurrency?.cancelInProgress ?: false,
        runLockType = when {
            yaml.disablePipeline == true -> PipelineRunLockType.LOCK
            yaml.concurrency?.group != null -> PipelineRunLockType.GROUP_LOCK
            else -> PipelineRunLockType.MULTIPLE
        },
        waitQueueTimeMinute = yaml.concurrency?.queueTimeoutMinutes ?: DEFAULT_WAIT_QUEUE_TIME_MINUTE,
        maxQueueSize = yaml.concurrency?.queueLength ?: DEFAULT_PIPELINE_SETTING_MAX_QUEUE_SIZE,
        maxConRunningQueueSize = yaml.concurrency?.maxParallel ?: PIPELINE_SETTING_MAX_CON_QUEUE_SIZE_MAX,
        
        // 标签和方言
        labels = yaml2Labels(yamlInput),
        pipelineAsCodeSettings = yamlSyntaxDialect2Setting(yaml.syntaxDialect),
        
        // 通知订阅
        successSubscriptionList = yamlNotice2Setting(
            projectId = yamlInput.projectCode,
            notices = yaml.notices?.filter { it.checkNotifyForSuccess() }
        ),
        failSubscriptionList = yamlNotice2Setting(
            projectId = yamlInput.projectCode,
            notices = yaml.notices?.filter { it.checkNotifyForFail() }
        ),
        
        // 其他配置
        failIfVariableInvalid = yaml.failIfVariableInvalid.nullIfDefault(false),
        buildCancelPolicy = BuildCancelPolicy.codeParse(yaml.cancelPolicy)
    )
}

3. ElementTransfer(元素转换器)

位置common-pipeline-yaml/src/main/kotlin/.../transfer/ElementTransfer.kt

职责:YAML Step ↔ Model Element 转换

元素类型映射

YAML StepModel Element说明
uses: checkout@v2GitCheckoutElement代码检出
uses: <atomCode>@v*MarketBuildAtomElement研发商店插件
run: <script>LinuxScriptElement / WindowsScriptElement脚本执行
uses: manual-review@v*ManualReviewUserTaskElement人工审核
template: <path>StepTemplateElement步骤模板

关键方法

@Component
class ElementTransfer @Autowired constructor(
    val client: Client,
    val creator: TransferCreator,
    val transferCache: TransferCacheService,
    val triggerTransfer: TriggerTransfer
) {
    // YAML 转触发器
    fun yaml2Triggers(yamlInput: YamlTransferInput, elements: MutableList<Element>)
    
    // 触发器转 YAML
    fun baseTriggers2yaml(elements: List<Element>, aspectWrapper: PipelineTransferAspectWrapper): TriggerOn?
    
    // SCM 触发器转 YAML
    fun scmTriggers2Yaml(elements: List<Element>, projectId: String, aspectWrapper: PipelineTransferAspectWrapper): Map<ScmType, List<TriggerOn>>
    
    // YAML Step 转 Element
    fun yaml2Step(step: Step, job: Job, yamlInput: YamlTransferInput): Element
    
    // Element 转 YAML Step
    fun element2YamlStep(element: Element, projectId: String): PreStep
}

yaml2Step 实现示例

fun yaml2Step(step: Step, job: Job, yamlInput: YamlTransferInput): Element {
    return when {
        // checkout 步骤
        step is PreCheckoutStep -> {
            GitCheckoutElement(
                name = step.name ?: "Checkout",
                repositoryHashId = step.with?.get("repository") as? String,
                branchName = step.with?.get("ref") as? String,
                // ... 其他参数
            )
        }
        
        // uses: 插件步骤
        step.uses != null -> {
            val (atomCode, version) = parseAtomCodeAndVersion(step.uses!!)
            MarketBuildAtomElement(
                name = step.name ?: atomCode,
                atomCode = atomCode,
                version = version,
                data = step.with ?: emptyMap()
            )
        }
        
        // run: 脚本步骤
        step.run != null -> {
            when (job.runsOn) {
                JobRunsOnType.WINDOWS -> WindowsScriptElement(
                    name = step.name ?: "Script",
                    script = step.run!!,
                    scriptType 

---

*Content truncated.*

project-module-architecture

TencentBlueKing

Project 项目管理模块架构指南,涵盖项目 CRUD、成员管理、项目配置、标签管理、项目迁移。当用户开发项目管理功能、处理项目成员、配置项目属性或实现项目相关逻辑时使用。

116

microservice-infrastructure

TencentBlueKing

微服务基础设施指南,涵盖条件配置、事件驱动架构、服务间通信、国际化与日志等微服务架构的核心基础设施。当用户实现服务间调用、配置多环境、实现异步通信、处理国际化或规范日志输出时使用。

114

artifactory-module-architecture

TencentBlueKing

Artifactory 制品库模块架构指南,涵盖制品上传下载、存储后端适配、制品元数据、清理策略、权限控制。当用户开发制品库功能、处理制品存储、配置清理策略或实现制品管理时使用。

173

supporting-modules-architecture

TencentBlueKing

BK-CI 支撑模块架构指南,涵盖凭证管理(Ticket)、构建机环境(Environment)、通知服务(Notify)、构建日志(Log)、质量红线(Quality)、开放接口(OpenAPI)等支撑性服务模块。当用户开发这些模块功能或需要理解支撑服务架构时使用。

112

managing-devops-pipeline

TencentBlueKing

管理蓝盾流水线的构建操作,包括查询构建历史、获取启动参数、查看构建状态、启动构建。当用户提及流水线、构建、部署、CI/CD、蓝盾或需要触发构建任务时使用。

102

go-agent-development

TencentBlueKing

Go Agent 开发指南,涵盖 Agent 架构设计、心跳机制、任务执行、日志上报、升级流程、与 Dispatch 模块交互。当用户开发构建机 Agent、实现任务执行逻辑、处理 Agent 通信或进行 Go 语言开发时使用。

02

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

1,5541,368

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

1,0771,167

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

1,4011,102

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

1,173738

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

1,129677

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,273601

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.