Pijul source control integration extension for Visual Studio Code
import { Event, TreeDataProvider, TreeItem, TreeItemCollapsibleState } from 'vscode';
import { PijulRemote, Repository } from '../pijul';

/**
 * The Changelog provider class is a Treedata provider which provides
 * TreeData for the `pijul.views.changelog` TreeView
 */
export class RemotesViewProvider implements TreeDataProvider<PijulRemote> {
  /**
     * Create a new ChangelogViewProvider instance
     * @param repository
     */
  constructor (
    private readonly repository: Repository,
    public readonly onDidChangeTreeData?: Event<void>
  ) {}

  /**
   * Convert a PijulRemote into a TreeItem
   * @param element
   */
  getTreeItem (element: PijulRemote): TreeItem | Thenable<TreeItem> {
    return {
      label: element.url,
      collapsibleState: TreeItemCollapsibleState.None,
      contextValue: 'pijulRemote'
    };
  }

  /**
   * Get the children of the element or the root if no element is passed
   * @param element An optional element to get the children of
   */
  async getChildren (element?: PijulRemote): Promise<PijulRemote[] | null | undefined> {
    if (element) {
      // Remotes don't have children
      return null;
    } else {
      let children;
      // Retry if the pristine is locked. TODO: More robust solution
      while (!children) {
        try {
          children = await this.repository.getRemotes();
        } catch (err) {
          if (!(err instanceof Error) || !err.message.includes('Pristine locked')) {
            throw err;
          }
        }
      }
      return children;
    }
  }
}