1

我正在使用 java 开发自定义 git 凭据帮助程序,并尝试在后台实现 azure 设备代码流。作为实现的一部分,我必须在用户将用于身份验证的控制台上打印 URL 和设备代码,然后在控制台上按 ENTER,但打印 URL 和设备代码后 git 终端挂起。下面是我的代码。

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 clone 之类的 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.
4

1 回答 1

0

这里有几个问题。首先,您看到此消息的原因是因为在凭证助手中,标准输入和输出连接到 Git,而不是用户的 TTY。因此,您只能将格式正确的行打印到标准输出,而不能将消息打印给用户。如果您想从控制台与用户交互,则需要/dev/tty在 Windows 上使用或类似的等效项。

其次,通常人们期望凭证助手大多是非交互式的。您的程序不是非交互式的并提示用户,Git 有自己的凭据提示,因此您无用地复制 Git 内置的行为。此外,当被要求不提示用户或 TTY 不存在时,Git 也有适当的行为,而您的程序不存在。例如,它不支持GIT_TERMINAL_PROMPT,因此在脚本或某些程序(例如 Go 工具链)中使用时会中断。

第三,Git 和 Git LFS 可能会频繁调用凭证助手。因此,使用像 Java 这样启动缓慢的语言将是一个坏主意,因为它会使操作花费比用不同语言编写的程序要长得多的时间。如果您需要一种可以快速启动的跨平台语言,我建议您使用 Rust,或者 Go,为此目的。

于 2022-02-24T22:19:43.023 回答