簡體   English   中英

使用 java 的自定義 git 憑證助手在用戶輸入時掛起

[英]custom git credential helper using java hangs at user input

我正在使用 java 開發自定義 git 憑證助手,並嘗試在后台實現 azure 設備代碼流。 作為實施的一部分,我必須在用戶將用於身份驗證的控制台上打印 URL 和設備代碼,然后在控制台上按 ENTER,但是 git 終端在打印 URL 和設備代碼后掛起。 下面是我的代碼。

public class GitHelper {

    public static void main(String[] args) {

        String op = args[0];
        switch (op) {
        case "get":
            System.out.printf("username=%s\n", "oauth2");
            System.out.printf("password=%s\n", getToken());
            break;
        default:
            System.out.println(args[0]);
            break;
        }

    }
}
public void waitForUser() {

        System.out.println("To sign in, use a web browser to open the page " + URL
                + "\n and enter the code " + code
                + " to authenticate then return to this window and press ENTER.");
        Callable<String> userInput = () -> new Scanner(System.in).nextLine();
        String res = getUserInputWithTimeout(TIMEOUT, userInput); // 30s until timeout

        if (res != null) {
            System.out.println("Validating Authentication ...");

        }

    }

我將我的代碼捆綁為 jar,我的 gitconfig 中有以下代碼。

[credential]
    helper = "!java -jar D:/config/git-credential-helper.jar"

當我像 git 克隆一樣執行 git 操作時,我收到了警告,它只是掛在那里

warning: invalid credential line: To sign in, use a web browser to open the page www.login.com and enter the code 324523453425 to authenticate then return to this window and press ENTER.

這里有幾個問題。 首先,您看到此消息的原因是因為在憑證助手中,標准輸入和 output 連接到 Git,而不是用戶的 TTY。 因此,您只能將格式正確的行打印為標准 output,而不能向用戶發送消息。 如果你想從控制台與用戶交互,你需要在 Windows 上使用/dev/tty或類似的等價物。

其次,通常人們希望憑證助手大多是非交互式的。 您的程序不是非交互式的,而是會提示用戶,而 Git 有自己的憑據提示,因此您無用地重復了 Git 內置的行為。 此外,Git 在被要求不提示用戶或 TTY 不存在(您的程序不存在)時也有正確的行為。 例如,它不GIT_TERMINAL_PROMPT ,因此在腳本或某些程序(例如 Go 工具鏈)中使用時會中斷。

第三,憑證助手可能會被 Git 和 Git LFS 頻繁調用。 因此,使用像 Java 這樣啟動緩慢的語言並不是一個好主意,因為它會使操作花費的時間比用其他語言編寫的程序要長得多。 如果您需要一種快速上手的跨平台語言,我建議您使用 Rust,或者 Go,為此目的。

暫無
暫無

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

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