3

I need to get the commit hash from the HEAD for each workspace when loading my extension, at vscode startup. For some reason, the HEAD was not initialized at boot time. If I add a 1 second sleep, then HEAD becomes initialized. Why is this happening? I suspect that I need to wait for the add-on-git/workspace/etc to initialize and add handler for some event.

Representation:

export async function activate(context: vscode.ExtensionContext) {
    // await new Promise(resolve => setTimeout(resolve, 1000)); // if uncomment this, HEAD becomes initialized
    const gitExtension = vscode.extensions.getExtension<GitExtension>('vscode.git')!.exports;
    const gitApi = gitExtension.getAPI(1);

    for (const workSpaceFolder of vscode.workspace.workspaceFolders || []) {
        const rootPath = workSpaceFolder.uri.fsPath;
        const repo = await gitApi.openRepository(vscode.Uri.parse(rootPath));

        const head = repo!.state.HEAD;

        console.log(head); // undefined
    }
}

part of package.json:

    "engines": {
        "vscode": "^1.62.0"
    },
    "activationEvents": [
        "onStartupFinished"
    ],
    "extensionDependencies": [
        "vscode.git"
    ],
Max Max
  • 389
  • 1
  • 2
  • 12

1 Answers1

0

It looks like the event onStartupFinished is triggered too early for your needs: when that event is triggered, GitExtension hasn't necessarily been initalized or activated.

I haven't delved in vscode extension code yet, but looking at the code for extensions/git in vscode's repository, you can see how GitExtension is initialized(*) :


export type APIState = 'uninitialized' | 'initialized';

// ...

export interface API {
    readonly state: APIState;
    readonly onDidChangeState: Event<APIState>;
    readonly onDidPublish: Event<PublishEvent>;
    readonly git: Git;
    // ...
}

export interface GitExtension {

    readonly enabled: boolean;
    readonly onDidChangeEnablement: Event<boolean>;

    // ...
    getAPI(version: 1): API;
}

Judging by the type declaration, you should probably check if GitExtension is enabled, then check if the API object reurned by getAPI() is initialized (API.state === 'initialized').

In both cases, you can register a listener on GitExtension.onDidChangeEnablement() and API.onDidChangeState() to have a chance to run the initialization code for your extension after GitExtension has finished initializing.


(*) note: commit 9919c760c2 referenced in the code link above is the state of master as I see it on github, on 2022-06-06 at 6 am UTC

LeGEC
  • 46,477
  • 5
  • 57
  • 104