aboutsummaryrefslogtreecommitdiffstats
path: root/web_src/js/utils/filetree.ts
blob: 35f9f58189faa4f0b56434135c19c66e43a7a677 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import {dirname, basename} from '../utils.ts';

export type FileStatus = 'added' | 'modified' | 'deleted' | 'renamed' | 'copied' | 'typechange';

export type File = {
  Name: string;
  NameHash: string;
  Status: FileStatus;
  IsViewed: boolean;
  IsSubmodule: boolean;
}

type DirItem = {
    isFile: false;
    name: string;
    path: string;

    children: Item[];
}

type FileItem = {
    isFile: true;
    name: string;
    path: string;
    file: File;
}

export type Item = DirItem | FileItem;

export function pathListToTree(fileEntries: File[]): Item[] {
  const pathToItem = new Map<string, DirItem>();

    // init root node
  const root: DirItem = {name: '', path: '', isFile: false, children: []};
  pathToItem.set('', root);

  for (const fileEntry of fileEntries) {
    const [parentPath, fileName] = [dirname(fileEntry.Name), basename(fileEntry.Name)];

    let parentItem = pathToItem.get(parentPath);
    if (!parentItem) {
      parentItem = constructParents(pathToItem, parentPath);
    }

    const fileItem: FileItem = {name: fileName, path: fileEntry.Name, isFile: true, file: fileEntry};

    parentItem.children.push(fileItem);
  }

  return root.children;
}

function constructParents(pathToItem: Map<string, DirItem>, dirPath: string): DirItem {
  const [dirParentPath, dirName] = [dirname(dirPath), basename(dirPath)];

  let parentItem = pathToItem.get(dirParentPath);
  if (!parentItem) {
    // if the parent node does not exist, create it
    parentItem = constructParents(pathToItem, dirParentPath);
  }

  const dirItem: DirItem = {name: dirName, path: dirPath, isFile: false, children: []};
  parentItem.children.push(dirItem);
  pathToItem.set(dirPath, dirItem);

  return dirItem;
}

export function mergeChildIfOnlyOneDir(nodes: Item[]): void {
  for (const node of nodes) {
    if (node.isFile) {
      continue;
    }
    const dir = node as DirItem;

    mergeChildIfOnlyOneDir(dir.children);

    if (dir.children.length === 1 && dir.children[0].isFile === false) {
      const child = dir.children[0];
      dir.name = `${dir.name}/${child.name}`;
      dir.path = child.path;
      dir.children = child.children;
    }
  }
}