gitpadi 2.0.1 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,354 @@
1
+ // commands/contribute.ts — Contributor workflow for GitPadi
2
+
3
+ import chalk from 'chalk';
4
+ import ora from 'ora';
5
+ import { execSync } from 'child_process';
6
+ import * as fs from 'fs';
7
+ import boxen from 'boxen';
8
+ import {
9
+ getOctokit,
10
+ getOwner,
11
+ getRepo,
12
+ forkRepo,
13
+ getAuthenticatedUser,
14
+ getLatestCheckRuns,
15
+ setRepo
16
+ } from '../core/github.js';
17
+
18
+ const dim = chalk.dim;
19
+ const yellow = chalk.yellow;
20
+ const green = chalk.green;
21
+ const cyan = chalk.cyan;
22
+ const white = chalk.white;
23
+
24
+ /**
25
+ * Parses a GitHub Issue/Repo URL or "owner/repo" string
26
+ */
27
+ function parseTarget(input: string): { owner: string, repo: string, issue?: number } {
28
+ const urlPattern = /github\.com\/([^/]+)\/([^/]+)(\/issues\/(\d+))?/;
29
+ const match = input.match(urlPattern);
30
+
31
+ if (match) {
32
+ return {
33
+ owner: match[1],
34
+ repo: match[2],
35
+ issue: match[4] ? parseInt(match[4]) : undefined
36
+ };
37
+ }
38
+
39
+ const parts = input.split('/');
40
+ if (parts.length === 2) {
41
+ return { owner: parts[0], repo: parts[1] };
42
+ }
43
+
44
+ throw new Error('Invalid target. Use a GitHub URL or "owner/repo" format.');
45
+ }
46
+
47
+ /**
48
+ * Phase 2: Fork & Clone Workflow (The "Start" Command)
49
+ */
50
+ export async function forkAndClone(target: string) {
51
+ const { owner, repo, issue } = parseTarget(target);
52
+
53
+ // 1. Fork first (idempotent — GitHub returns existing fork if it exists)
54
+ const spinner = ora(`Forking ${cyan(`${owner}/${repo}`)}...`).start();
55
+ let myUser: string;
56
+
57
+ try {
58
+ myUser = await getAuthenticatedUser();
59
+ const forkFullName = await forkRepo(owner, repo);
60
+ spinner.succeed(`Forked to ${green(forkFullName)}`);
61
+ } catch (e: any) {
62
+ spinner.fail(e.message);
63
+ return;
64
+ }
65
+
66
+ // 2. Ask where to clone
67
+ const inquirer = (await import('inquirer')).default;
68
+ const path = (await import('path')).default;
69
+ const os = (await import('os')).default;
70
+
71
+ const { parentDir } = await inquirer.prompt([{
72
+ type: 'input',
73
+ name: 'parentDir',
74
+ message: cyan('📂 Where to clone? (parent directory):'),
75
+ default: '.',
76
+ }]);
77
+
78
+ // Resolve ~ and build full path: parentDir/repoName
79
+ const resolvedParent = parentDir.startsWith('~')
80
+ ? parentDir.replace('~', os.homedir())
81
+ : parentDir;
82
+ let cloneDir: string = path.resolve(resolvedParent, repo);
83
+
84
+ // 3. Handle existing directory
85
+ if (fs.existsSync(cloneDir)) {
86
+ // Check if it's already a valid git clone of this repo
87
+ let isValidClone = false;
88
+ try {
89
+ const remoteUrl = execSync('git remote get-url origin', { cwd: cloneDir, encoding: 'utf-8', stdio: 'pipe' }).trim();
90
+ if (remoteUrl.includes(repo)) isValidClone = true;
91
+ } catch { /* not a git repo */ }
92
+
93
+ if (isValidClone) {
94
+ console.log(yellow(`\n 📂 "${cloneDir}" already contains a clone of ${repo}.`));
95
+ console.log(dim(' Syncing with upstream...\n'));
96
+
97
+ process.chdir(cloneDir);
98
+ setRepo(owner, repo);
99
+
100
+ // Ensure upstream remote exists
101
+ try { execSync(`git remote add upstream https://github.com/${owner}/${repo}.git`, { stdio: 'pipe' }); } catch { /* exists */ }
102
+
103
+ // 1. Detect default branch
104
+ let defaultBranch = 'main';
105
+ try {
106
+ execSync('git rev-parse upstream/main', { stdio: 'pipe' });
107
+ } catch {
108
+ defaultBranch = 'master';
109
+ }
110
+
111
+ // 2. Checkout default branch before syncing
112
+ try {
113
+ execSync(`git checkout ${defaultBranch}`, { stdio: 'pipe' });
114
+ } catch {
115
+ // If it fails, maybe it's not even a valid default branch locally, but we'll try to sync anyway
116
+ }
117
+
118
+ await syncBranch();
119
+
120
+ // 3. Create or switch to issue branch
121
+ const branchName = issue ? `fix/issue-${issue}` : null;
122
+ if (branchName) {
123
+ try {
124
+ execSync(`git checkout -b ${branchName}`, { stdio: 'pipe' });
125
+ console.log(green(` ✔ Created branch ${branchName}`));
126
+ } catch {
127
+ execSync(`git checkout ${branchName}`, { stdio: 'pipe' });
128
+ console.log(green(` ✔ Switched to branch ${branchName}`));
129
+ }
130
+ }
131
+
132
+ console.log(green('\n✨ Workspace ready!'));
133
+ return;
134
+ }
135
+
136
+ // Directory exists but isn't a valid clone — ask for new path
137
+ const { newDir } = await inquirer.prompt([{
138
+ type: 'input',
139
+ name: 'newDir',
140
+ message: yellow(`"${cloneDir}" already exists. Enter a different folder name:`),
141
+ default: `${repo}-contrib`,
142
+ }]);
143
+ cloneDir = path.resolve(resolvedParent, newDir);
144
+ }
145
+
146
+ // 4. Clone
147
+ const cloneSpinner = ora(`Cloning your fork...`).start();
148
+ const cloneUrl = `https://github.com/${myUser}/${repo}.git`;
149
+
150
+ try {
151
+ execSync(`git clone ${cloneUrl} ${cloneDir}`, { stdio: 'pipe' });
152
+ cloneSpinner.succeed(`Cloned into ${green(cloneDir)}`);
153
+ } catch (e: any) {
154
+ cloneSpinner.fail(`Clone failed: ${e.message}`);
155
+ return;
156
+ }
157
+
158
+ // 5. Setup Remotes & Branch
159
+ process.chdir(cloneDir);
160
+ execSync(`git remote add upstream https://github.com/${owner}/${repo}.git`, { stdio: 'pipe' });
161
+
162
+ const branchName = issue ? `fix/issue-${issue}` : `contrib-${Math.floor(Date.now() / 1000)}`;
163
+
164
+ try {
165
+ execSync(`git checkout -b ${branchName}`, { stdio: 'pipe' });
166
+ } catch {
167
+ execSync(`git checkout ${branchName}`, { stdio: 'pipe' });
168
+ }
169
+
170
+ // Update local GitPadi state
171
+ setRepo(owner, repo);
172
+
173
+ console.log(`\n${green('✨ Workspace Ready!')}`);
174
+ console.log(`${dim('Directory:')} ${cloneDir}`);
175
+ console.log(`${dim('Branch:')} ${branchName}`);
176
+ console.log(`${dim('Upstream:')} ${owner}/${repo}`);
177
+
178
+ console.log(boxen(
179
+ green('Next step:\n') +
180
+ white(`cd ${cloneDir}\n\n`) +
181
+ dim('Start coding! When you\'re done, run ') + yellow('gitpadi submit'),
182
+ { padding: 1, borderColor: 'green', borderStyle: 'round' }
183
+ ));
184
+ }
185
+
186
+ /**
187
+ * Phase 2: Sync Fork with Upstream (full flow)
188
+ * 1. Sync fork on GitHub (API)
189
+ * 2. Pull synced changes locally
190
+ * 3. Merge upstream into current branch
191
+ */
192
+ export async function syncBranch() {
193
+ try {
194
+ // Check if we are in a git repo and if upstream exists
195
+ const remotes = execSync('git remote', { encoding: 'utf-8' });
196
+ if (!remotes.includes('upstream')) return;
197
+
198
+ const spinner = ora('Syncing fork...').start();
199
+
200
+ // 1. Detect upstream default branch (main or master)
201
+ execSync('git fetch upstream', { stdio: 'pipe' });
202
+ let upstreamBranch = 'main';
203
+ try {
204
+ execSync('git rev-parse upstream/main', { stdio: 'pipe' });
205
+ } catch {
206
+ upstreamBranch = 'master';
207
+ }
208
+
209
+ // 2. Sync fork on GitHub via API
210
+ spinner.text = 'Syncing fork on GitHub...';
211
+ try {
212
+ const octokit = getOctokit();
213
+ const myUser = await getAuthenticatedUser();
214
+ const repo = getRepo();
215
+ await octokit.request('POST /repos/{owner}/{repo}/merge-upstream', {
216
+ owner: myUser,
217
+ repo: repo,
218
+ branch: upstreamBranch,
219
+ });
220
+ spinner.succeed(green('Fork synced on GitHub ✓'));
221
+ } catch (e: any) {
222
+ // May fail if already in sync or permissions — continue anyway
223
+ spinner.info(dim('GitHub sync skipped (may already be in sync)'));
224
+ }
225
+
226
+ // 3. Pull synced changes locally
227
+ const pullSpinner = ora('Pulling latest changes...').start();
228
+ const currentBranch = execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf-8' }).trim();
229
+
230
+ // Fetch origin (our fork) with the new synced data
231
+ execSync('git fetch origin', { stdio: 'pipe' });
232
+ execSync('git fetch upstream', { stdio: 'pipe' });
233
+
234
+ // If we're on main/master, just pull
235
+ if (currentBranch === upstreamBranch) {
236
+ try {
237
+ execSync(`git pull origin ${upstreamBranch} --no-edit`, { stdio: 'pipe' });
238
+ pullSpinner.succeed(green(`Pulled latest ${upstreamBranch} ✓`));
239
+ } catch {
240
+ pullSpinner.warn(yellow('Pull had conflicts — resolve manually'));
241
+ }
242
+ } else {
243
+ // We're on a feature branch — merge upstream into it
244
+ pullSpinner.text = `Merging upstream/${upstreamBranch} into ${currentBranch}...`;
245
+ try {
246
+ execSync(`git merge upstream/${upstreamBranch} --no-edit`, { stdio: 'pipe' });
247
+ pullSpinner.succeed(green(`Merged upstream/${upstreamBranch} into ${cyan(currentBranch)} ✓`));
248
+ } catch {
249
+ pullSpinner.warn(yellow('Merge conflict detected!'));
250
+ console.log(dim(' Resolve conflicts, then run:'));
251
+ console.log(dim(' git add . && git commit'));
252
+ }
253
+ }
254
+
255
+ console.log(green('\n✨ Fork is synced and up to date!'));
256
+ } catch (e: any) {
257
+ // Silently fail if git commands error (likely not in a repo)
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Phase 2: Submit PR
263
+ */
264
+ export async function submitPR(opts: { title: string, body?: string, issue?: number, message?: string }) {
265
+ const spinner = ora('Preparing submission...').start();
266
+ try {
267
+ const owner = getOwner();
268
+ const repo = getRepo();
269
+ const branch = execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf-8' }).trim();
270
+
271
+ // 1. Stage and Commit
272
+ spinner.text = 'Staging and committing changes...';
273
+ const commitMsg = opts.message || opts.title || 'Automated contribution via GitPadi';
274
+
275
+ try {
276
+ execSync('git add .', { stdio: 'pipe' });
277
+ // Check if there are changes to commit
278
+ const status = execSync('git status --porcelain', { encoding: 'utf-8' });
279
+ if (status.trim()) {
280
+ execSync(`git commit -m "${commitMsg.replace(/"/g, '\\"')}"`, { stdio: 'pipe' });
281
+ }
282
+ } catch (e: any) {
283
+ // If commit fails (e.g. no changes), we might still want to push if there are unpushed commits
284
+ dim(' (Note: No new changes to commit or commit failed)');
285
+ }
286
+
287
+ // Auto-infer issue from branch name (e.g. fix/issue-303)
288
+ let linkedIssue = opts.issue;
289
+ if (!linkedIssue) {
290
+ const match = branch.match(/issue-(\d+)/);
291
+ if (match) linkedIssue = parseInt(match[1]);
292
+ }
293
+
294
+ spinner.text = 'Pushing to your fork...';
295
+ execSync(`git push origin ${branch}`, { stdio: 'pipe' });
296
+
297
+ spinner.text = 'Creating Pull Request...';
298
+ const body = opts.body || (linkedIssue ? `Fixes #${linkedIssue}` : 'Automated PR via GitPadi');
299
+
300
+ // Detect base branch
301
+ let baseBranch = 'main';
302
+ try {
303
+ execSync('git rev-parse origin/main', { stdio: 'pipe' });
304
+ } catch {
305
+ baseBranch = 'master';
306
+ }
307
+
308
+ const { data: pr } = await getOctokit().pulls.create({
309
+ owner,
310
+ repo,
311
+ title: opts.title,
312
+ body,
313
+ head: `${await getAuthenticatedUser()}:${branch}`,
314
+ base: baseBranch,
315
+ });
316
+
317
+ spinner.succeed(`PR Created: ${green(pr.html_url)}`);
318
+ } catch (e: any) {
319
+ spinner.fail(e.message);
320
+ }
321
+ }
322
+
323
+ /**
324
+ * Phase 2: View Logs
325
+ */
326
+ export async function viewLogs() {
327
+ const spinner = ora('Fetching GitHub Action logs...').start();
328
+ try {
329
+ const owner = getOwner();
330
+ const repo = getRepo();
331
+ const sha = execSync('git rev-parse HEAD', { encoding: 'utf-8' }).trim();
332
+
333
+ const { checkRuns, combinedState } = await getLatestCheckRuns(owner, repo, sha);
334
+ spinner.stop();
335
+
336
+ if (checkRuns.length === 0) {
337
+ console.log(dim('\n ℹ️ No active check runs found for this commit.\n'));
338
+ return;
339
+ }
340
+
341
+ console.log(`\n${chalk.bold(`📋 GitHub Actions status:`)} ${combinedState === 'success' ? green('✅ Success') : combinedState === 'failure' ? chalk.red('❌ Failure') : yellow('⏳ Pending')}\n`);
342
+
343
+ checkRuns.forEach(run => {
344
+ const icon = run.status === 'completed' ? (run.conclusion === 'success' ? green('✅') : chalk.red('❌')) : yellow('⏳');
345
+ console.log(` ${icon} ${chalk.bold(run.name)}: ${dim(run.conclusion || run.status)}`);
346
+ if (run.conclusion === 'failure') {
347
+ console.log(chalk.red(` → Build failed. View details at: ${run.html_url}`));
348
+ }
349
+ });
350
+ console.log('');
351
+ } catch (e: any) {
352
+ spinner.fail(e.message);
353
+ }
354
+ }
@@ -14,18 +14,34 @@ export async function listIssues(opts: { state?: string; labels?: string; limit?
14
14
  const spinner = ora(`Fetching issues from ${chalk.cyan(getFullRepo())}...`).start();
15
15
 
16
16
  try {
17
- const { data: issues } = await octokit.issues.listForRepo({
18
- owner: getOwner(), repo: getRepo(),
19
- state: (opts.state as 'open' | 'closed' | 'all') || 'open',
20
- labels: opts.labels || undefined,
21
- per_page: opts.limit || 50,
22
- });
17
+ const requestedLimit = opts.limit || 50;
18
+ const realIssues: any[] = [];
19
+ let page = 1;
20
+
21
+ // Fetch until we have enough real issues or run out of pages
22
+ while (realIssues.length < requestedLimit) {
23
+ const { data: issues } = await octokit.issues.listForRepo({
24
+ owner: getOwner(), repo: getRepo(),
25
+ state: (opts.state as 'open' | 'closed' | 'all') || 'open',
26
+ labels: opts.labels || undefined,
27
+ per_page: 100, // Fetch max per page to be efficient
28
+ page: page++,
29
+ });
30
+
31
+ if (issues.length === 0) break;
32
+
33
+ const batch = issues.filter((i) => !i.pull_request);
34
+ realIssues.push(...batch);
35
+
36
+ if (issues.length < 100) break; // Last page
37
+ }
38
+
39
+ // Clip to requested limit
40
+ const finalIssues = realIssues.slice(0, requestedLimit);
23
41
 
24
- // Filter out PRs (GitHub API returns PRs in issues endpoint)
25
- const realIssues = issues.filter((i) => !i.pull_request);
26
42
  spinner.stop();
27
43
 
28
- if (realIssues.length === 0) {
44
+ if (finalIssues.length === 0) {
29
45
  console.log(chalk.yellow('\n No issues found.\n'));
30
46
  return;
31
47
  }
@@ -35,14 +51,14 @@ export async function listIssues(opts: { state?: string; labels?: string; limit?
35
51
  style: { head: [], border: [] },
36
52
  });
37
53
 
38
- realIssues.forEach((i) => {
39
- const labels = i.labels.map((l) => typeof l === 'string' ? l : l.name || '').join(', ');
54
+ finalIssues.forEach((i) => {
55
+ const labels = i.labels.map((l: any) => typeof l === 'string' ? l : l.name || '').join(', ');
40
56
  const assignee = i.assignee?.login || chalk.dim('unassigned');
41
57
  const state = i.state === 'open' ? chalk.green('open') : chalk.red('closed');
42
58
  table.push([`#${i.number}`, i.title.substring(0, 60), labels.substring(0, 30), assignee, state]);
43
59
  });
44
60
 
45
- console.log(`\n${chalk.bold(`📋 Issues — ${getFullRepo()}`)} (${realIssues.length})\n`);
61
+ console.log(`\n${chalk.bold(`📋 Issues — ${getFullRepo()}`)} (${finalIssues.length})\n`);
46
62
  console.log(table.toString());
47
63
  console.log('');
48
64
  } catch (e: any) {
@@ -70,6 +86,46 @@ export async function createIssue(opts: { title: string; body?: string; labels?:
70
86
  }
71
87
  }
72
88
 
89
+ /**
90
+ * Parse a markdown file into issues.
91
+ * Format:
92
+ * ## Issue Title
93
+ * **Labels:** bug, frontend
94
+ * Body text here...
95
+ */
96
+ function parseMarkdownIssues(content: string): { issues: any[]; labels: Record<string, string> } {
97
+ const issues: any[] = [];
98
+ const sections = content.split(/^## /m).filter(s => s.trim());
99
+
100
+ let num = 1;
101
+ for (const section of sections) {
102
+ const lines = section.split('\n');
103
+ const title = lines[0].trim();
104
+ if (!title) continue;
105
+
106
+ let labels: string[] = [];
107
+ const bodyLines: string[] = [];
108
+
109
+ for (let i = 1; i < lines.length; i++) {
110
+ const labelsMatch = lines[i].match(/^\*\*Labels?:\*\*\s*(.+)/i);
111
+ if (labelsMatch) {
112
+ labels = labelsMatch[1].split(',').map(l => l.trim()).filter(Boolean);
113
+ } else {
114
+ bodyLines.push(lines[i]);
115
+ }
116
+ }
117
+
118
+ issues.push({
119
+ number: num++,
120
+ title,
121
+ body: bodyLines.join('\n').trim(),
122
+ labels,
123
+ });
124
+ }
125
+
126
+ return { issues, labels: {} };
127
+ }
128
+
73
129
  export async function createIssuesFromFile(filePath: string, opts: { dryRun?: boolean; start?: number; end?: number }) {
74
130
  requireRepo();
75
131
  const resolved = path.resolve(filePath);
@@ -78,24 +134,60 @@ export async function createIssuesFromFile(filePath: string, opts: { dryRun?: bo
78
134
  return;
79
135
  }
80
136
 
81
- const config = JSON.parse(fs.readFileSync(resolved, 'utf-8'));
82
- const issues = config.issues || [];
137
+ const raw = fs.readFileSync(resolved, 'utf-8');
138
+ const ext = path.extname(resolved).toLowerCase();
139
+
140
+ let config: { issues: any[]; labels?: Record<string, string> };
141
+ let detectedFormat = 'JSON';
142
+
143
+ if (ext === '.md' || ext === '.markdown') {
144
+ config = parseMarkdownIssues(raw);
145
+ detectedFormat = 'Markdown';
146
+ } else {
147
+ // Try JSON first, fallback to Markdown if it fails
148
+ try {
149
+ const parsed = JSON.parse(raw);
150
+ config = { issues: parsed.issues || [], labels: parsed.labels };
151
+ } catch {
152
+ // Not valid JSON — try markdown parser
153
+ if (raw.trimStart().startsWith('#')) {
154
+ console.log(chalk.yellow(`\n ⚠ File has .json extension but contains Markdown — parsing as Markdown.\n`));
155
+ config = parseMarkdownIssues(raw);
156
+ detectedFormat = 'Markdown (auto-detected)';
157
+ } else {
158
+ console.error(chalk.red(`\n ❌ Fatal: File is not valid JSON or Markdown.\n`));
159
+ return;
160
+ }
161
+ }
162
+ }
163
+
164
+ const issues = config.issues;
83
165
  const start = opts.start || 1;
84
166
  const end = opts.end || 999;
85
167
  const filtered = issues.filter((i: any) => i.number >= start && i.number <= end);
86
168
 
87
169
  console.log(`\n${chalk.bold('📋 GitPadi Issue Creator')}`);
88
- console.log(chalk.dim(` Repo: ${getFullRepo()}`));
89
- console.log(chalk.dim(` File: ${filePath}`));
90
- console.log(chalk.dim(` Range: #${start}-#${end} (${filtered.length} issues)`));
91
- console.log(chalk.dim(` Mode: ${opts.dryRun ? 'DRY RUN' : 'LIVE'}\n`));
92
-
93
- if (opts.dryRun) {
94
- filtered.forEach((i: any) => {
95
- console.log(` ${chalk.dim(`#${String(i.number).padStart(2, '0')}`)} ${i.title}`);
96
- console.log(chalk.dim(` [${i.labels.join(', ')}]`));
97
- });
98
- console.log(chalk.green(`\n✅ Dry run: ${filtered.length} issues would be created.\n`));
170
+ console.log(chalk.dim(` Repo: ${getFullRepo()}`));
171
+ console.log(chalk.dim(` File: ${filePath} (${detectedFormat})`));
172
+ console.log(chalk.dim(` Found: ${filtered.length} issues\n`));
173
+
174
+ // Always preview first
175
+ filtered.forEach((i: any) => {
176
+ console.log(` ${chalk.dim(`#${String(i.number).padStart(2, '0')}`)} ${i.title}`);
177
+ console.log(chalk.dim(` [${(i.labels || []).join(', ')}]`));
178
+ });
179
+
180
+ // Ask for confirmation
181
+ const inquirer = (await import('inquirer')).default;
182
+ const { proceed } = await inquirer.prompt([{
183
+ type: 'confirm',
184
+ name: 'proceed',
185
+ message: chalk.yellow(`Create these ${filtered.length} issues on GitHub?`),
186
+ default: true,
187
+ }]);
188
+
189
+ if (!proceed) {
190
+ console.log(chalk.dim('\n Cancelled.\n'));
99
191
  return;
100
192
  }
101
193
 
@@ -103,7 +195,7 @@ export async function createIssuesFromFile(filePath: string, opts: { dryRun?: bo
103
195
  let created = 0, failed = 0;
104
196
 
105
197
  // Create labels if defined
106
- if (config.labels) {
198
+ if (config.labels && Object.keys(config.labels).length > 0) {
107
199
  const spinner = ora('Setting up labels...').start();
108
200
  try {
109
201
  for (const [name, color] of Object.entries(config.labels)) {
@@ -52,7 +52,11 @@ export async function cloneRepo(name: string, opts: { org?: string; dir?: string
52
52
  try {
53
53
  execSync(`git clone ${url} ${dir}`, { stdio: 'pipe' });
54
54
  spinner.succeed(`Cloned to ${chalk.green(`./${dir}`)}`);
55
- } catch (e: any) { spinner.fail(`Clone failed: ${e.message}`); }
55
+ return true;
56
+ } catch (e: any) {
57
+ spinner.fail(`Clone failed: ${e.message}`);
58
+ return false;
59
+ }
56
60
  }
57
61
 
58
62
  export async function repoInfo(name: string, opts: { org?: string }) {
@@ -80,7 +84,11 @@ export async function repoInfo(name: string, opts: { org?: string }) {
80
84
 
81
85
  console.log(table.toString());
82
86
  console.log('');
83
- } catch (e: any) { spinner.fail(e.message); }
87
+ return repo;
88
+ } catch (e: any) {
89
+ spinner.fail(e.message);
90
+ return null;
91
+ }
84
92
  }
85
93
 
86
94
  export async function setTopics(name: string, topics: string[], opts: { org?: string }) {
@@ -93,37 +101,44 @@ export async function setTopics(name: string, topics: string[], opts: { org?: st
93
101
  } catch (e: any) { spinner.fail(e.message); }
94
102
  }
95
103
 
96
- export async function listRepos(opts: { org?: string; limit?: number }) {
97
- const spinner = ora('Fetching repos...').start();
104
+ export async function listRepos(opts: { org?: string; limit?: number; silent?: boolean }) {
105
+ const spinner = !opts.silent ? ora('Fetching repos...').start() : null;
98
106
  const octokit = getOctokit();
99
107
 
100
108
  try {
101
109
  let repos: any[];
102
110
  if (opts.org) {
103
- ({ data: repos } = await octokit.repos.listForOrg({ org: opts.org, per_page: opts.limit || 50, sort: 'updated' }));
111
+ ({ data: repos } = await octokit.repos.listForOrg({ org: opts.org, per_page: opts.limit || 100, sort: 'updated' }));
104
112
  } else {
105
- ({ data: repos } = await octokit.repos.listForAuthenticatedUser({ per_page: opts.limit || 50, sort: 'updated' }));
113
+ ({ data: repos } = await octokit.repos.listForAuthenticatedUser({ per_page: opts.limit || 100, sort: 'updated' }));
106
114
  }
107
115
 
108
- spinner.stop();
116
+ if (spinner) spinner.stop();
117
+
118
+ if (!opts.silent) {
119
+ const table = new Table({
120
+ head: ['Name', 'Stars', 'Language', 'Visibility', 'Updated'].map((h) => chalk.cyan(h)),
121
+ style: { head: [], border: [] },
122
+ });
123
+
124
+ repos.forEach((r: any) => {
125
+ table.push([
126
+ r.full_name,
127
+ `⭐ ${r.stargazers_count}`,
128
+ r.language || '-',
129
+ r.private ? chalk.yellow('private') : chalk.green('public'),
130
+ new Date(r.updated_at).toLocaleDateString(),
131
+ ]);
132
+ });
133
+
134
+ console.log(`\n${chalk.bold('📦 Repositories')} (${repos.length})\n`);
135
+ console.log(table.toString());
136
+ console.log('');
137
+ }
109
138
 
110
- const table = new Table({
111
- head: ['Name', 'Stars', 'Language', 'Visibility', 'Updated'].map((h) => chalk.cyan(h)),
112
- style: { head: [], border: [] },
113
- });
114
-
115
- repos.forEach((r: any) => {
116
- table.push([
117
- r.full_name,
118
- `⭐ ${r.stargazers_count}`,
119
- r.language || '-',
120
- r.private ? chalk.yellow('private') : chalk.green('public'),
121
- new Date(r.updated_at).toLocaleDateString(),
122
- ]);
123
- });
124
-
125
- console.log(`\n${chalk.bold('📦 Repositories')} (${repos.length})\n`);
126
- console.log(table.toString());
127
- console.log('');
128
- } catch (e: any) { spinner.fail(e.message); }
139
+ return repos;
140
+ } catch (e: any) {
141
+ if (spinner) spinner.fail(e.message);
142
+ return [];
143
+ }
129
144
  }