【问题标题】:How to programmatically access the full snippet in Gitlab?如何以编程方式访问 Gitlab 中的完整代码段?
【发布时间】:2021-12-08 03:13:18
【问题描述】:

问题

我的最终目标是拥有我的 sn-ps(包括标题和描述)的离线、可更新副本,以便我可以轻松搜索和使用它们。如何将我的所有 sn-ps 从 Gitlab 获取到我的本地机器? 我使用的Gitlab版本是13.12.10-ee

我调查的内容

克隆 sn-ps

在 Gitlab 中可以clone snippet contents,但这仅包括与 sn-p 关联的文件。标题和描述被排除在外。

例如当我做git clone git@company.gitlab.com:snippets/$snippet_id.git 时,我只收到与sn-p 相关的文件,而不是标题和描述:

我检查了documentation,但找不到任何关于通过 git 与描述进行交互的提及。

Gitlab API

我发现 Gitlab API 有一个 snippets 端点。但是,当我使用 python-gitlab CLI tool 并使用 gitlab snippet get --id 123 请求单个 sn-p 时,我只得到 ID 和标题。
当我做gitlab snippet content --id 123 时,我只得到与sn-p 关联的文件的内容。

【问题讨论】:

  • 太棒了curl --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/snippets/123"?该文档附带一个示例。 could not find any mention of interacting with the description答案是对的:"description": "Ruby test snippet",
  • 太棒了,不,我没有使用该命令,因为我使用 python-gitlab CLI 工具与 gitlab API 交互。它确实返回了描述,不幸的是我需要对其进行后处理以提取描述。如果您愿意,可以将其作为答案,谢谢!
  • 它可以为你做到这一点,只需 gitlab -f description,但最好还是使用一些 json 解析器
  • 谢谢,我不明白 -f 参数的用法,因为它只能与 json 或 yaml 输出结合使用。随意张贴作为答案。

标签: gitlab git-clone gitlab-api


【解决方案1】:
推荐的答案 GitLab

从 Unix shell,使用 CuRLjq

GITLAB_API_TOKEN=<your_api-scoped_token>
SNIPPET_ID=<snippet_id_number>

# Parse the JSON for the fields you want (.title,.description)
curl --header "PRIVATE-TOKEN: $GITLAB_API_TOKEN" \
  "https://gitlab.example.com/api/v4/snippets/$SNIPPET_ID" \
  | jq '.title,.description'

# Use the /raw endpoint to get the full snippet content
curl --header "PRIVATE-TOKEN: $GITLAB_API_TOKEN" \
  "https://gitlab.example.com/api/v4/snippets/$SNIPPET_ID/raw

使用python-gitlab:

import gitlab
GITLAB_API_TOKEN=<your_api-scoped_token>
SNIPPET_ID=<snippet_id_number>

gl = gitlab.Gitlab('https://gitlab.example.com', private_token=GITLAB_API_TOKEN)
snippet = gl.snippets.get(SNIPPET_ID)
title = snippet.title
descr = snippet.description
cont  = snippet.content()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-14
    • 2015-09-03
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    相关资源
    最近更新 更多