swadhinbiswas feat: implement air-gapped mode, UI fixes, and project management integrations Β· 7/9/2026
e3bd4a1
288 lines Β· 8.2 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/**
 * Insights CLI Commands
 * View developer metrics and team insights
 */

import chalk from "chalk";
import Table from "cli-table3";
import { Command } from "commander";
import ora from "ora";
import simpleGit from "simple-git";
import { getWithAuth } from "../../lib/api.js";
import { getConfig } from "../../lib/config.js";
import { getRepoInfoFromGit } from "../../lib/git.js";

const git = simpleGit();

export const insightsCommand = new Command("insights").description(
  "View developer metrics and insights",
);

// Helper to get repo info
async function getRepoInfo() {
  const repoInfo = await getRepoInfoFromGit(git);
  return repoInfo ? { owner: repoInfo.owner, name: repoInfo.repo } : null;
}

// Show personal metrics
insightsCommand
  .command("show")
  .description("Show your developer metrics")
  .option("-p, --period <period>", "Time period: 1w, 4w, 3m, 1y", "4w")
  .option("--json", "Output as JSON")
  .action(async (options) => {
    const spinner = ora("Loading metrics...").start();

    try {
      const config = getConfig();
      if (!config.token) {
        spinner.fail("Not authenticated. Run 'och auth login' first.");
        process.exit(1);
      }

      const res = await getWithAuth(
        `/api/user/metrics?period=${options.period}`,
      );

      spinner.stop();

      if (options.json) {
        console.log(JSON.stringify(res, null, 2));
        return;
      }

      const metrics = res.metrics || {
        prsOpened: 0,
        prsMerged: 0,
        reviewsGiven: 0,
        avgTimeToMerge: 0,
        avgReviewTime: 0,
      };

      console.log(chalk.bold("\nπŸ“Š Your Developer Metrics\n"));
      console.log(
        chalk.hex("#6272a4")(`  Period: Last ${formatPeriod(options.period)}\n`),
      );

      // Main metrics
      const table = new Table({
        chars: { mid: "", "left-mid": "", "mid-mid": "", "right-mid": "" },
      });

      table.push(
        [chalk.hex("#8be9fd")("PRs Opened"), chalk.bold.white(metrics.prsOpened)],
        [chalk.hex("#ff79c6")("PRs Merged"), chalk.bold.white(metrics.prsMerged)],
        [chalk.blue("Reviews Given"), chalk.bold.white(metrics.reviewsGiven)],
        [
          chalk.hex("#f1fa8c")("Avg Time to Merge"),
          chalk.bold.white(formatDuration(metrics.avgTimeToMerge)),
        ],
        [
          chalk.hex("#50fa7b")("Merge Rate"),
          chalk.bold.white(
            metrics.prsOpened > 0
              ? `${Math.round((metrics.prsMerged / metrics.prsOpened) * 100)}%`
              : "N/A",
          ),
        ],
      );

      console.log(table.toString());
      console.log();

      // Productivity tip
      if (metrics.prsOpened > 0 && metrics.avgTimeToMerge > 48) {
        console.log(
          chalk.hex("#f1fa8c")(
            "  πŸ’‘ Tip: Your PRs take an average of " +
              formatDuration(metrics.avgTimeToMerge) +
              " to merge.",
          ),
        );
        console.log(
          chalk.hex("#6272a4")("     Consider smaller PRs for faster reviews.\n"),
        );
      }
    } catch (error: any) {
      spinner.fail(`Failed: ${error.message}`);
      process.exit(1);
    }
  });

// Show team metrics
insightsCommand
  .command("team")
  .description("Show team/repository metrics and leaderboard")
  .option("-p, --period <period>", "Time period: 1w, 4w, 3m, 1y", "4w")
  .option("-n, --limit <n>", "Number of top contributors", "10")
  .option("--json", "Output as JSON")
  .action(async (options) => {
    const spinner = ora("Loading team metrics...").start();

    try {
      const config = getConfig();
      if (!config.token) {
        spinner.fail("Not authenticated. Run 'och auth login' first.");
        process.exit(1);
      }

      const repoInfo = await getRepoInfo();
      let endpoint = `/api/metrics/team?period=${options.period}&limit=${options.limit}`;

      if (repoInfo) {
        const repoRes = await getWithAuth(
          `/api/repos/${repoInfo.owner}/${repoInfo.name}`,
        );
        if (repoRes.repository?.id) {
          endpoint += `&repositoryId=${repoRes.repository.id}`;
        }
      }

      const res = await getWithAuth(endpoint);

      spinner.stop();

      if (options.json) {
        console.log(JSON.stringify(res, null, 2));
        return;
      }

      const contributors = res.contributors || [];
      const repoMetrics = res.metrics || {};

      if (repoInfo) {
        console.log(
          chalk.bold(
            `\nπŸ‘₯ Team Metrics for ${repoInfo.owner}/${repoInfo.name}\n`,
          ),
        );
      } else {
        console.log(chalk.bold("\nπŸ‘₯ Team Metrics\n"));
      }

      console.log(
        chalk.hex("#6272a4")(`  Period: Last ${formatPeriod(options.period)}\n`),
      );

      // Repository summary
      if (repoMetrics.totalPrs !== undefined) {
        console.log(`  Total PRs: ${chalk.hex("#8be9fd")(repoMetrics.totalPrs)}`);
        console.log(`  Merged: ${chalk.hex("#50fa7b")(repoMetrics.mergedPrs || 0)}`);
        console.log(`  Open: ${chalk.hex("#f1fa8c")(repoMetrics.openPrs || 0)}`);
        console.log();
      }

      // Leaderboard
      if (contributors.length > 0) {
        console.log(chalk.bold("  πŸ† Top Contributors\n"));

        const table = new Table({
          head: [
            chalk.hex("#6272a4")("#"),
            chalk.hex("#6272a4")("Developer"),
            chalk.hex("#6272a4")("PRs"),
            chalk.hex("#6272a4")("Reviews"),
            chalk.hex("#6272a4")("Score"),
          ],
        });

        contributors.forEach((c: any, i: number) => {
          const medal =
            i === 0 ? "πŸ₯‡" : i === 1 ? "πŸ₯ˆ" : i === 2 ? "πŸ₯‰" : `${i + 1}`;
          const score = (c.prs || 0) * 2 + (c.reviews || 0);

          table.push([
            medal,
            chalk.white(c.username),
            chalk.hex("#8be9fd")(c.prs || 0),
            chalk.blue(c.reviews || 0),
            chalk.hex("#f1fa8c")(score),
          ]);
        });

        console.log(table.toString());
      } else {
        console.log(chalk.hex("#6272a4")("  No contributor data available.\n"));
      }

      console.log();
    } catch (error: any) {
      spinner.fail(`Failed: ${error.message}`);
      process.exit(1);
    }
  });

// Repository metrics
insightsCommand
  .command("repo")
  .description("Show current repository metrics")
  .option("--json", "Output as JSON")
  .action(async (options) => {
    const spinner = ora("Loading repository metrics...").start();

    try {
      const repoInfo = await getRepoInfo();
      if (!repoInfo) {
        spinner.fail("Not in a git repository");
        process.exit(1);
      }

      const res = await getWithAuth(
        `/api/repos/${repoInfo.owner}/${repoInfo.name}/metrics`,
      );

      spinner.stop();

      if (options.json) {
        console.log(JSON.stringify(res, null, 2));
        return;
      }

      const m = res.metrics || {};

      console.log(
        chalk.bold(
          `\nπŸ“ˆ Repository Metrics: ${repoInfo.owner}/${repoInfo.name}\n`,
        ),
      );

      const table = new Table();
      table.push(
        [chalk.hex("#6272a4")("Stars"), chalk.hex("#f1fa8c")(`⭐ ${m.stars || 0}`)],
        [chalk.hex("#6272a4")("Forks"), chalk.blue(`🍴 ${m.forks || 0}`)],
        [chalk.hex("#6272a4")("Open PRs"), chalk.hex("#50fa7b")(`πŸ“ ${m.openPrs || 0}`)],
        [chalk.hex("#6272a4")("Open Issues"), chalk.hex("#ff5555")(`πŸ› ${m.openIssues || 0}`)],
        [chalk.hex("#6272a4")("Contributors"), chalk.hex("#8be9fd")(`πŸ‘₯ ${m.contributors || 0}`)],
        [
          chalk.hex("#6272a4")("Commits (30d)"),
          chalk.hex("#ff79c6")(`πŸ“Š ${m.recentCommits || 0}`),
        ],
      );

      console.log(table.toString());
      console.log();
    } catch (error: any) {
      spinner.fail(`Failed: ${error.message}`);
      process.exit(1);
    }
  });

function formatPeriod(period: string): string {
  const labels: Record<string, string> = {
    "1w": "1 week",
    "4w": "4 weeks",
    "3m": "3 months",
    "1y": "1 year",
  };
  return labels[period] || period;
}

function formatDuration(hours: number): string {
  if (!hours || hours === 0) return "N/A";
  if (hours < 1) return "< 1h";
  if (hours < 24) return `${Math.round(hours)}h`;
  return `${Math.round(hours / 24)}d`;
}

export default insightsCommand;