backstage

Форк
0
/
list-ownership.js 
139 строк · 3.9 Кб
1
#!/usr/bin/env node
2
/*
3
 * Copyright 2021 The Backstage Authors
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 *     http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17

18
const fs = require('fs-extra');
19
const globby = require('globby');
20
const sloc = require('sloc');
21
const codeownersUtils = require('codeowners-utils');
22
const { resolve: resolvePath } = require('path');
23

24
async function loadOwners(rootDir) {
25
  const codeowners = await codeownersUtils.loadOwners(rootDir);
26

27
  return function getOwners(path) {
28
    const { owners } = codeownersUtils.matchFile(path, codeowners);
29
    if (
30
      owners.includes('@backstage/maintainers') &&
31
      owners.includes('@backstage/reviewers')
32
    ) {
33
      return owners.filter(owner => owner !== '@backstage/reviewers');
34
    }
35
    return owners;
36
  };
37
}
38

39
function createLocCounter(rootDir) {
40
  return async path => {
41
    const content = await fs.readFile(resolvePath(rootDir, path), 'utf-8');
42
    const stats = sloc(content, 'ts');
43
    return stats.source;
44
  };
45
}
46

47
async function printOwnerDirectories(allFiles, getOwners, getLoc, onlyOwner) {
48
  const countByPath = new Map();
49

50
  let total = 0;
51
  let totalShare = 0;
52
  for (const file of allFiles) {
53
    const owners = getOwners(file);
54
    const loc = await getLoc(file);
55

56
    if (owners.includes(onlyOwner)) {
57
      const share = loc / owners.length;
58
      total += loc;
59
      totalShare += share;
60

61
      const path = file.split('/').slice(0, 2).join('/');
62
      if ((await fs.stat(path)).isDirectory()) {
63
        countByPath.set(path, (countByPath.get(path) || 0) + share);
64
      }
65
    }
66
  }
67

68
  const sortedPaths = Array.from(countByPath)
69
    .map(([path, loc]) => ({ path, loc: Math.round(loc) }))
70
    .sort((a, b) => b.loc - a.loc);
71

72
  const maxPathLen = Math.max(...sortedPaths.map(({ path }) => path.length));
73
  for (const { path, loc } of sortedPaths) {
74
    console.log(`${path.padEnd(maxPathLen)} ${loc}`);
75
  }
76
  console.log();
77
  console.log('Total share:', Math.round(totalShare));
78
  console.log('Total lines of code:', total);
79
}
80

81
async function printAllOwners(allFiles, getOwners, getLoc) {
82
  const countByOwners = new Map();
83

84
  let total = 0;
85
  for (const file of allFiles) {
86
    const owners = getOwners(file);
87
    const loc = await getLoc(file);
88

89
    total += loc;
90
    const share = loc / owners.length;
91
    for (const owner of owners) {
92
      countByOwners.set(owner, (countByOwners.get(owner) || 0) + share);
93
    }
94
  }
95

96
  const sortedOwners = Array.from(countByOwners)
97
    .map(([owner, loc]) => ({ owner, loc: Math.round(loc) }))
98
    .sort((a, b) => b.loc - a.loc);
99

100
  const maxOwnerLen = Math.max(
101
    ...sortedOwners.map(({ owner }) => owner.length),
102
  );
103
  for (const { owner, loc } of sortedOwners) {
104
    console.log(`${owner.padEnd(maxOwnerLen)} ${loc}`);
105
  }
106
  console.log();
107
  console.log('Total lines of code:', total);
108
}
109

110
async function main(onlyOwner) {
111
  const rootDir = resolvePath(__dirname, '..');
112

113
  const allFiles = await globby(
114
    [
115
      '**/*.{js,jsx,ts,tsx,mjs,cjs}',
116
      '!**/*.{generated,test}.*',
117
      '!**/{__fixtures__,fixtures}',
118
    ],
119
    {
120
      cwd: rootDir,
121
      gitignore: true,
122
      followSymbolicLinks: false,
123
    },
124
  );
125

126
  const getOwners = await loadOwners(rootDir);
127
  const getLoc = createLocCounter(rootDir);
128

129
  if (onlyOwner) {
130
    await printOwnerDirectories(allFiles, getOwners, getLoc, onlyOwner);
131
  } else {
132
    await printAllOwners(allFiles, getOwners, getLoc);
133
  }
134
}
135

136
main(...process.argv.slice(2)).catch(err => {
137
  console.error(err.stack);
138
  process.exit(1);
139
});
140

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.