簡體   English   中英

下載神器Github

[英]Download Github Artifact

我正在嘗試從 Java 代碼下載 Github 工件。 為此,我將GitHub API 用於 Java 使用 API,我可以驗證並列出所有 GHWorkflowRuns 及其 GHArtifacts。

如果我嘗試從GHArtifact.getArchiveDownloadUrtl()下載,我只會收到 403 響應。

當從瀏覽器嘗試相同的 URL 時(在這種情況下未經身份驗證)我得到

{
  message:  "You must have the actions scope to download artifacts."
  documentation_url:    "https://docs.github.com/rest/reference/actions#download-an-artifact"
}

我檢查了個人訪問令牌,因此它應該具有足夠的訪問權限。 配置對話框中沒有額外的“操作”scope,但我檢查了包含存儲庫上所有內容的工作流。

還有另一個 function 叫做GHArtifact.download()但我不知道如何使用它。 有誰知道如何下載工件或如何使用該下載 function?

編輯:tgdavies 提到 repository.readTar() 具有類似的簽名。 從那開始,我嘗試創建這樣的代碼:

GHWorkflowRun run = ...
List<GHArtifact> artifacts = run.listArtifacts().toList();
for (GHArtifact artifact: artifacts) {
    if ("desiredname".equals(run.getName())) {
        artifact.download(is -> {
            return null;
        }, null);
    }
}

但我的編譯器抱怨

error: method download in class GHArtifact cannot be applied to given types;
                artifact.download(is -> {
                        ^
  required: InputStreamFunction<T>
  found:    (is)->{ re[...]ll; },<null>
  reason: cannot infer type-variable(s) T
    (actual and formal argument lists differ in length)
  where T is a type-variable:
    T extends Object declared in method <T>download(InputStreamFunction<T>)

我希望這能更好地解釋我迷路的地方。

我沒有帶有工件的項目,但這是您使用下載 API 的方式:

import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GitHub;

import java.io.File;
import java.io.IOException;

import static org.apache.commons.io.FileUtils.copyInputStreamToFile;

public class Test {
    public static void main(String[] args) throws IOException {

        GitHub github = GitHub.connect("your user id", "your access token");
        GHRepository repository = github.getRepository("tgdavies/cardcreator");
        repository.readTar(is -> {
            copyInputStreamToFile(is, new File("foo.tar"));
            return null;
        }, null);
    }
}

更改 PAT(個人訪問令牌)的權限並授予其所需的 scope。
作為訪客,您可能會遇到這個問題: https://github.com/actions/upload-artifact/issues/51

這聽起來可能很愚蠢,但我確實花了一些時間才弄清楚如何真正使用該下載 function。最后我成功了:

GHWorkflowRun run = ...
List<GHArtifact> artifacts = run.listArtifacts().toList();
for (GHArtifact artifact: artifacts) {
    if ("desiredname".equals(run.getName())) {
            File target = ...
            artifact.download(is -> {
                Files.copy(is, target.toPath(), StandardCopyOption.REPLACE_EXISTING);
                return null;
            });
    }
}

並解決認證問題: 當我使用瀏覽器訪問 API URL 時,我忘記了缺少認證。 但是當我以編程方式打開 URL 並嘗試在那里下載時,同樣如此。

這就是為什么保留 API 功能對我來說很重要 - API 負責內部身份驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM