gitpadi 2.0.1 → 2.0.2

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,291 @@
1
+ // commands/contribute.ts — Contributor workflow for GitPadi
2
+ import chalk from 'chalk';
3
+ import ora from 'ora';
4
+ import { execSync } from 'child_process';
5
+ import * as fs from 'fs';
6
+ import boxen from 'boxen';
7
+ import { getOctokit, getOwner, getRepo, forkRepo, getAuthenticatedUser, getLatestCheckRuns, setRepo } from '../core/github.js';
8
+ const dim = chalk.dim;
9
+ const yellow = chalk.yellow;
10
+ const green = chalk.green;
11
+ const cyan = chalk.cyan;
12
+ const white = chalk.white;
13
+ /**
14
+ * Parses a GitHub Issue/Repo URL or "owner/repo" string
15
+ */
16
+ function parseTarget(input) {
17
+ const urlPattern = /github\.com\/([^/]+)\/([^/]+)(\/issues\/(\d+))?/;
18
+ const match = input.match(urlPattern);
19
+ if (match) {
20
+ return {
21
+ owner: match[1],
22
+ repo: match[2],
23
+ issue: match[4] ? parseInt(match[4]) : undefined
24
+ };
25
+ }
26
+ const parts = input.split('/');
27
+ if (parts.length === 2) {
28
+ return { owner: parts[0], repo: parts[1] };
29
+ }
30
+ throw new Error('Invalid target. Use a GitHub URL or "owner/repo" format.');
31
+ }
32
+ /**
33
+ * Phase 2: Fork & Clone Workflow (The "Start" Command)
34
+ */
35
+ export async function forkAndClone(target) {
36
+ const { owner, repo, issue } = parseTarget(target);
37
+ // 1. Fork first (idempotent — GitHub returns existing fork if it exists)
38
+ const spinner = ora(`Forking ${cyan(`${owner}/${repo}`)}...`).start();
39
+ let myUser;
40
+ try {
41
+ myUser = await getAuthenticatedUser();
42
+ const forkFullName = await forkRepo(owner, repo);
43
+ spinner.succeed(`Forked to ${green(forkFullName)}`);
44
+ }
45
+ catch (e) {
46
+ spinner.fail(e.message);
47
+ return;
48
+ }
49
+ // 2. Ask where to clone
50
+ const inquirer = (await import('inquirer')).default;
51
+ const path = (await import('path')).default;
52
+ const os = (await import('os')).default;
53
+ const { parentDir } = await inquirer.prompt([{
54
+ type: 'input',
55
+ name: 'parentDir',
56
+ message: cyan('📂 Where to clone? (parent directory):'),
57
+ default: '.',
58
+ }]);
59
+ // Resolve ~ and build full path: parentDir/repoName
60
+ const resolvedParent = parentDir.startsWith('~')
61
+ ? parentDir.replace('~', os.homedir())
62
+ : parentDir;
63
+ let cloneDir = path.resolve(resolvedParent, repo);
64
+ // 3. Handle existing directory
65
+ if (fs.existsSync(cloneDir)) {
66
+ // Check if it's already a valid git clone of this repo
67
+ let isValidClone = false;
68
+ try {
69
+ const remoteUrl = execSync('git remote get-url origin', { cwd: cloneDir, encoding: 'utf-8', stdio: 'pipe' }).trim();
70
+ if (remoteUrl.includes(repo))
71
+ isValidClone = true;
72
+ }
73
+ catch { /* not a git repo */ }
74
+ if (isValidClone) {
75
+ console.log(yellow(`\n 📂 "${cloneDir}" already contains a clone of ${repo}.`));
76
+ console.log(dim(' Syncing with upstream...\n'));
77
+ process.chdir(cloneDir);
78
+ setRepo(owner, repo);
79
+ // Ensure upstream remote exists
80
+ try {
81
+ execSync(`git remote add upstream https://github.com/${owner}/${repo}.git`, { stdio: 'pipe' });
82
+ }
83
+ catch { /* exists */ }
84
+ await syncBranch();
85
+ // Create or switch to issue branch
86
+ const branchName = issue ? `fix/issue-${issue}` : null;
87
+ if (branchName) {
88
+ try {
89
+ execSync(`git checkout -b ${branchName}`, { stdio: 'pipe' });
90
+ console.log(green(` ✔ Created branch ${branchName}`));
91
+ }
92
+ catch {
93
+ execSync(`git checkout ${branchName}`, { stdio: 'pipe' });
94
+ console.log(green(` ✔ Switched to branch ${branchName}`));
95
+ }
96
+ }
97
+ console.log(green('\n✨ Workspace ready!'));
98
+ return;
99
+ }
100
+ // Directory exists but isn't a valid clone — ask for new path
101
+ const { newDir } = await inquirer.prompt([{
102
+ type: 'input',
103
+ name: 'newDir',
104
+ message: yellow(`"${cloneDir}" already exists. Enter a different folder name:`),
105
+ default: `${repo}-contrib`,
106
+ }]);
107
+ cloneDir = path.resolve(resolvedParent, newDir);
108
+ }
109
+ // 4. Clone
110
+ const cloneSpinner = ora(`Cloning your fork...`).start();
111
+ const cloneUrl = `https://github.com/${myUser}/${repo}.git`;
112
+ try {
113
+ execSync(`git clone ${cloneUrl} ${cloneDir}`, { stdio: 'pipe' });
114
+ cloneSpinner.succeed(`Cloned into ${green(cloneDir)}`);
115
+ }
116
+ catch (e) {
117
+ cloneSpinner.fail(`Clone failed: ${e.message}`);
118
+ return;
119
+ }
120
+ // 5. Setup Remotes & Branch
121
+ process.chdir(cloneDir);
122
+ execSync(`git remote add upstream https://github.com/${owner}/${repo}.git`, { stdio: 'pipe' });
123
+ const branchName = issue ? `fix/issue-${issue}` : `contrib-${Math.floor(Date.now() / 1000)}`;
124
+ try {
125
+ execSync(`git checkout -b ${branchName}`, { stdio: 'pipe' });
126
+ }
127
+ catch {
128
+ execSync(`git checkout ${branchName}`, { stdio: 'pipe' });
129
+ }
130
+ // Update local GitPadi state
131
+ setRepo(owner, repo);
132
+ console.log(`\n${green('✨ Workspace Ready!')}`);
133
+ console.log(`${dim('Directory:')} ${cloneDir}`);
134
+ console.log(`${dim('Branch:')} ${branchName}`);
135
+ console.log(`${dim('Upstream:')} ${owner}/${repo}`);
136
+ console.log(boxen(green('Next step:\n') +
137
+ white(`cd ${cloneDir}\n\n`) +
138
+ dim('Start coding! When you\'re done, run ') + yellow('gitpadi submit'), { padding: 1, borderColor: 'green', borderStyle: 'round' }));
139
+ }
140
+ /**
141
+ * Phase 2: Sync Fork with Upstream (full flow)
142
+ * 1. Sync fork on GitHub (API)
143
+ * 2. Pull synced changes locally
144
+ * 3. Merge upstream into current branch
145
+ */
146
+ export async function syncBranch() {
147
+ try {
148
+ // Check if we are in a git repo and if upstream exists
149
+ const remotes = execSync('git remote', { encoding: 'utf-8' });
150
+ if (!remotes.includes('upstream'))
151
+ return;
152
+ const spinner = ora('Syncing fork...').start();
153
+ // 1. Detect upstream default branch (main or master)
154
+ execSync('git fetch upstream', { stdio: 'pipe' });
155
+ let upstreamBranch = 'main';
156
+ try {
157
+ execSync('git rev-parse upstream/main', { stdio: 'pipe' });
158
+ }
159
+ catch {
160
+ upstreamBranch = 'master';
161
+ }
162
+ // 2. Sync fork on GitHub via API
163
+ spinner.text = 'Syncing fork on GitHub...';
164
+ try {
165
+ const octokit = getOctokit();
166
+ const myUser = await getAuthenticatedUser();
167
+ const repo = getRepo();
168
+ await octokit.request('POST /repos/{owner}/{repo}/merge-upstream', {
169
+ owner: myUser,
170
+ repo: repo,
171
+ branch: upstreamBranch,
172
+ });
173
+ spinner.succeed(green('Fork synced on GitHub ✓'));
174
+ }
175
+ catch (e) {
176
+ // May fail if already in sync or permissions — continue anyway
177
+ spinner.info(dim('GitHub sync skipped (may already be in sync)'));
178
+ }
179
+ // 3. Pull synced changes locally
180
+ const pullSpinner = ora('Pulling latest changes...').start();
181
+ const currentBranch = execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf-8' }).trim();
182
+ // Fetch origin (our fork) with the new synced data
183
+ execSync('git fetch origin', { stdio: 'pipe' });
184
+ execSync('git fetch upstream', { stdio: 'pipe' });
185
+ // If we're on main/master, just pull
186
+ if (currentBranch === upstreamBranch) {
187
+ try {
188
+ execSync(`git pull origin ${upstreamBranch} --no-edit`, { stdio: 'pipe' });
189
+ pullSpinner.succeed(green(`Pulled latest ${upstreamBranch} ✓`));
190
+ }
191
+ catch {
192
+ pullSpinner.warn(yellow('Pull had conflicts — resolve manually'));
193
+ }
194
+ }
195
+ else {
196
+ // We're on a feature branch — merge upstream into it
197
+ pullSpinner.text = `Merging upstream/${upstreamBranch} into ${currentBranch}...`;
198
+ try {
199
+ execSync(`git merge upstream/${upstreamBranch} --no-edit`, { stdio: 'pipe' });
200
+ pullSpinner.succeed(green(`Merged upstream/${upstreamBranch} into ${cyan(currentBranch)} ✓`));
201
+ }
202
+ catch {
203
+ pullSpinner.warn(yellow('Merge conflict detected!'));
204
+ console.log(dim(' Resolve conflicts, then run:'));
205
+ console.log(dim(' git add . && git commit'));
206
+ }
207
+ }
208
+ console.log(green('\n✨ Fork is synced and up to date!'));
209
+ }
210
+ catch (e) {
211
+ // Silently fail if git commands error (likely not in a repo)
212
+ }
213
+ }
214
+ /**
215
+ * Phase 2: Submit PR
216
+ */
217
+ export async function submitPR(opts) {
218
+ const spinner = ora('Preparing submission...').start();
219
+ try {
220
+ const owner = getOwner();
221
+ const repo = getRepo();
222
+ const branch = execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf-8' }).trim();
223
+ // 1. Stage and Commit
224
+ spinner.text = 'Staging and committing changes...';
225
+ const commitMsg = opts.message || opts.title || 'Automated contribution via GitPadi';
226
+ try {
227
+ execSync('git add .', { stdio: 'pipe' });
228
+ // Check if there are changes to commit
229
+ const status = execSync('git status --porcelain', { encoding: 'utf-8' });
230
+ if (status.trim()) {
231
+ execSync(`git commit -m "${commitMsg.replace(/"/g, '\\"')}"`, { stdio: 'pipe' });
232
+ }
233
+ }
234
+ catch (e) {
235
+ // If commit fails (e.g. no changes), we might still want to push if there are unpushed commits
236
+ dim(' (Note: No new changes to commit or commit failed)');
237
+ }
238
+ // Auto-infer issue from branch name (e.g. fix/issue-303)
239
+ let linkedIssue = opts.issue;
240
+ if (!linkedIssue) {
241
+ const match = branch.match(/issue-(\d+)/);
242
+ if (match)
243
+ linkedIssue = parseInt(match[1]);
244
+ }
245
+ spinner.text = 'Pushing to your fork...';
246
+ execSync(`git push origin ${branch}`, { stdio: 'pipe' });
247
+ spinner.text = 'Creating Pull Request...';
248
+ const body = opts.body || (linkedIssue ? `Fixes #${linkedIssue}` : 'Automated PR via GitPadi');
249
+ const { data: pr } = await getOctokit().pulls.create({
250
+ owner,
251
+ repo,
252
+ title: opts.title,
253
+ body,
254
+ head: `${await getAuthenticatedUser()}:${branch}`,
255
+ base: 'main',
256
+ });
257
+ spinner.succeed(`PR Created: ${green(pr.html_url)}`);
258
+ }
259
+ catch (e) {
260
+ spinner.fail(e.message);
261
+ }
262
+ }
263
+ /**
264
+ * Phase 2: View Logs
265
+ */
266
+ export async function viewLogs() {
267
+ const spinner = ora('Fetching GitHub Action logs...').start();
268
+ try {
269
+ const owner = getOwner();
270
+ const repo = getRepo();
271
+ const sha = execSync('git rev-parse HEAD', { encoding: 'utf-8' }).trim();
272
+ const { checkRuns, combinedState } = await getLatestCheckRuns(owner, repo, sha);
273
+ spinner.stop();
274
+ if (checkRuns.length === 0) {
275
+ console.log(dim('\n ℹ️ No active check runs found for this commit.\n'));
276
+ return;
277
+ }
278
+ console.log(`\n${chalk.bold(`📋 GitHub Actions status:`)} ${combinedState === 'success' ? green('✅ Success') : combinedState === 'failure' ? chalk.red('❌ Failure') : yellow('⏳ Pending')}\n`);
279
+ checkRuns.forEach(run => {
280
+ const icon = run.status === 'completed' ? (run.conclusion === 'success' ? green('✅') : chalk.red('❌')) : yellow('⏳');
281
+ console.log(` ${icon} ${chalk.bold(run.name)}: ${dim(run.conclusion || run.status)}`);
282
+ if (run.conclusion === 'failure') {
283
+ console.log(chalk.red(` → Build failed. View details at: ${run.html_url}`));
284
+ }
285
+ });
286
+ console.log('');
287
+ }
288
+ catch (e) {
289
+ spinner.fail(e.message);
290
+ }
291
+ }
@@ -60,6 +60,42 @@ export async function createIssue(opts) {
60
60
  spinner.fail(`Failed: ${e.message}`);
61
61
  }
62
62
  }
63
+ /**
64
+ * Parse a markdown file into issues.
65
+ * Format:
66
+ * ## Issue Title
67
+ * **Labels:** bug, frontend
68
+ * Body text here...
69
+ */
70
+ function parseMarkdownIssues(content) {
71
+ const issues = [];
72
+ const sections = content.split(/^## /m).filter(s => s.trim());
73
+ let num = 1;
74
+ for (const section of sections) {
75
+ const lines = section.split('\n');
76
+ const title = lines[0].trim();
77
+ if (!title)
78
+ continue;
79
+ let labels = [];
80
+ const bodyLines = [];
81
+ for (let i = 1; i < lines.length; i++) {
82
+ const labelsMatch = lines[i].match(/^\*\*Labels?:\*\*\s*(.+)/i);
83
+ if (labelsMatch) {
84
+ labels = labelsMatch[1].split(',').map(l => l.trim()).filter(Boolean);
85
+ }
86
+ else {
87
+ bodyLines.push(lines[i]);
88
+ }
89
+ }
90
+ issues.push({
91
+ number: num++,
92
+ title,
93
+ body: bodyLines.join('\n').trim(),
94
+ labels,
95
+ });
96
+ }
97
+ return { issues, labels: {} };
98
+ }
63
99
  export async function createIssuesFromFile(filePath, opts) {
64
100
  requireRepo();
65
101
  const resolved = path.resolve(filePath);
@@ -67,20 +103,48 @@ export async function createIssuesFromFile(filePath, opts) {
67
103
  console.error(chalk.red(`\n❌ File not found: ${resolved}\n`));
68
104
  return;
69
105
  }
70
- const config = JSON.parse(fs.readFileSync(resolved, 'utf-8'));
71
- const issues = config.issues || [];
106
+ const raw = fs.readFileSync(resolved, 'utf-8');
107
+ const ext = path.extname(resolved).toLowerCase();
108
+ let config;
109
+ let detectedFormat = 'JSON';
110
+ if (ext === '.md' || ext === '.markdown') {
111
+ config = parseMarkdownIssues(raw);
112
+ detectedFormat = 'Markdown';
113
+ }
114
+ else {
115
+ // Try JSON first, fallback to Markdown if it fails
116
+ try {
117
+ const parsed = JSON.parse(raw);
118
+ config = { issues: parsed.issues || [], labels: parsed.labels };
119
+ }
120
+ catch {
121
+ // Not valid JSON — try markdown parser
122
+ if (raw.trimStart().startsWith('#')) {
123
+ console.log(chalk.yellow(`\n ⚠ File has .json extension but contains Markdown — parsing as Markdown.\n`));
124
+ config = parseMarkdownIssues(raw);
125
+ detectedFormat = 'Markdown (auto-detected)';
126
+ }
127
+ else {
128
+ console.error(chalk.red(`\n ❌ Fatal: File is not valid JSON or Markdown.\n`));
129
+ return;
130
+ }
131
+ }
132
+ }
133
+ const issues = config.issues;
72
134
  const start = opts.start || 1;
73
135
  const end = opts.end || 999;
74
136
  const filtered = issues.filter((i) => i.number >= start && i.number <= end);
75
137
  console.log(`\n${chalk.bold('📋 GitPadi Issue Creator')}`);
76
- console.log(chalk.dim(` Repo: ${getFullRepo()}`));
77
- console.log(chalk.dim(` File: ${filePath}`));
78
- console.log(chalk.dim(` Range: #${start}-#${end} (${filtered.length} issues)`));
79
- console.log(chalk.dim(` Mode: ${opts.dryRun ? 'DRY RUN' : 'LIVE'}\n`));
138
+ console.log(chalk.dim(` Repo: ${getFullRepo()}`));
139
+ console.log(chalk.dim(` File: ${filePath} (${detectedFormat})`));
140
+ console.log(chalk.dim(` Range: #${start}-#${end} (${filtered.length} issues)`));
141
+ console.log(chalk.dim(` Mode: ${opts.dryRun ? 'DRY RUN' : 'LIVE'}\n`));
80
142
  if (opts.dryRun) {
81
143
  filtered.forEach((i) => {
82
144
  console.log(` ${chalk.dim(`#${String(i.number).padStart(2, '0')}`)} ${i.title}`);
83
- console.log(chalk.dim(` [${i.labels.join(', ')}]`));
145
+ console.log(chalk.dim(` [${(i.labels || []).join(', ')}]`));
146
+ if (i.body)
147
+ console.log(chalk.dim(` ${i.body.substring(0, 80)}...`));
84
148
  });
85
149
  console.log(chalk.green(`\n✅ Dry run: ${filtered.length} issues would be created.\n`));
86
150
  return;
@@ -88,7 +152,7 @@ export async function createIssuesFromFile(filePath, opts) {
88
152
  const octokit = getOctokit();
89
153
  let created = 0, failed = 0;
90
154
  // Create labels if defined
91
- if (config.labels) {
155
+ if (config.labels && Object.keys(config.labels).length > 0) {
92
156
  const spinner = ora('Setting up labels...').start();
93
157
  try {
94
158
  for (const [name, color] of Object.entries(config.labels)) {
@@ -51,9 +51,11 @@ export async function cloneRepo(name, opts) {
51
51
  try {
52
52
  execSync(`git clone ${url} ${dir}`, { stdio: 'pipe' });
53
53
  spinner.succeed(`Cloned to ${chalk.green(`./${dir}`)}`);
54
+ return true;
54
55
  }
55
56
  catch (e) {
56
57
  spinner.fail(`Clone failed: ${e.message}`);
58
+ return false;
57
59
  }
58
60
  }
59
61
  export async function repoInfo(name, opts) {
@@ -67,9 +69,11 @@ export async function repoInfo(name, opts) {
67
69
  table.push({ [chalk.cyan('Description')]: repo.description || chalk.dim('none') }, { [chalk.cyan('Stars')]: `⭐ ${repo.stargazers_count}` }, { [chalk.cyan('Forks')]: `🍴 ${repo.forks_count}` }, { [chalk.cyan('Issues')]: `📋 ${repo.open_issues_count} open` }, { [chalk.cyan('Language')]: repo.language || chalk.dim('none') }, { [chalk.cyan('Visibility')]: repo.private ? chalk.yellow('Private') : chalk.green('Public') }, { [chalk.cyan('Default Branch')]: repo.default_branch }, { [chalk.cyan('Created')]: new Date(repo.created_at).toLocaleDateString() }, { [chalk.cyan('URL')]: repo.html_url });
68
70
  console.log(table.toString());
69
71
  console.log('');
72
+ return repo;
70
73
  }
71
74
  catch (e) {
72
75
  spinner.fail(e.message);
76
+ return null;
73
77
  }
74
78
  }
75
79
  export async function setTopics(name, topics, opts) {
@@ -84,35 +88,41 @@ export async function setTopics(name, topics, opts) {
84
88
  }
85
89
  }
86
90
  export async function listRepos(opts) {
87
- const spinner = ora('Fetching repos...').start();
91
+ const spinner = !opts.silent ? ora('Fetching repos...').start() : null;
88
92
  const octokit = getOctokit();
89
93
  try {
90
94
  let repos;
91
95
  if (opts.org) {
92
- ({ data: repos } = await octokit.repos.listForOrg({ org: opts.org, per_page: opts.limit || 50, sort: 'updated' }));
96
+ ({ data: repos } = await octokit.repos.listForOrg({ org: opts.org, per_page: opts.limit || 100, sort: 'updated' }));
93
97
  }
94
98
  else {
95
- ({ data: repos } = await octokit.repos.listForAuthenticatedUser({ per_page: opts.limit || 50, sort: 'updated' }));
99
+ ({ data: repos } = await octokit.repos.listForAuthenticatedUser({ per_page: opts.limit || 100, sort: 'updated' }));
96
100
  }
97
- spinner.stop();
98
- const table = new Table({
99
- head: ['Name', 'Stars', 'Language', 'Visibility', 'Updated'].map((h) => chalk.cyan(h)),
100
- style: { head: [], border: [] },
101
- });
102
- repos.forEach((r) => {
103
- table.push([
104
- r.full_name,
105
- `⭐ ${r.stargazers_count}`,
106
- r.language || '-',
107
- r.private ? chalk.yellow('private') : chalk.green('public'),
108
- new Date(r.updated_at).toLocaleDateString(),
109
- ]);
110
- });
111
- console.log(`\n${chalk.bold('📦 Repositories')} (${repos.length})\n`);
112
- console.log(table.toString());
113
- console.log('');
101
+ if (spinner)
102
+ spinner.stop();
103
+ if (!opts.silent) {
104
+ const table = new Table({
105
+ head: ['Name', 'Stars', 'Language', 'Visibility', 'Updated'].map((h) => chalk.cyan(h)),
106
+ style: { head: [], border: [] },
107
+ });
108
+ repos.forEach((r) => {
109
+ table.push([
110
+ r.full_name,
111
+ `⭐ ${r.stargazers_count}`,
112
+ r.language || '-',
113
+ r.private ? chalk.yellow('private') : chalk.green('public'),
114
+ new Date(r.updated_at).toLocaleDateString(),
115
+ ]);
116
+ });
117
+ console.log(`\n${chalk.bold('📦 Repositories')} (${repos.length})\n`);
118
+ console.log(table.toString());
119
+ console.log('');
120
+ }
121
+ return repos;
114
122
  }
115
123
  catch (e) {
116
- spinner.fail(e.message);
124
+ if (spinner)
125
+ spinner.fail(e.message);
126
+ return [];
117
127
  }
118
128
  }
@@ -3,6 +3,7 @@ import chalk from 'chalk';
3
3
  import * as fs from 'fs';
4
4
  import * as path from 'path';
5
5
  import os from 'node:os';
6
+ import { execSync } from 'child_process';
6
7
  const CONFIG_DIR = path.join(os.homedir(), '.gitpadi');
7
8
  const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
8
9
  let _octokit = null;
@@ -24,11 +25,29 @@ export function saveConfig(config) {
24
25
  fs.mkdirSync(CONFIG_DIR, { recursive: true });
25
26
  fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
26
27
  }
28
+ /**
29
+ * Attempts to detect owner/repo from local git remotes
30
+ */
31
+ export function detectLocalRepo() {
32
+ try {
33
+ const remotes = execSync('git remote -v', { encoding: 'utf-8', stdio: 'pipe' });
34
+ const match = remotes.match(/github\.com[:/]([^/]+)\/([^/.]+)(?:\.git)?/);
35
+ if (match) {
36
+ return { owner: match[1], repo: match[2] };
37
+ }
38
+ }
39
+ catch {
40
+ // Not a git repo or git not found
41
+ }
42
+ return null;
43
+ }
27
44
  export function initGitHub(token, owner, repo) {
28
45
  const config = loadConfig();
46
+ const detected = detectLocalRepo();
29
47
  _token = token || process.env.GITHUB_TOKEN || process.env.GITPADI_TOKEN || config?.token || '';
30
- _owner = owner || process.env.GITHUB_OWNER || config?.owner || process.env.GITHUB_REPOSITORY?.split('/')[0] || '';
31
- _repo = repo || process.env.GITHUB_REPO || config?.repo || process.env.GITHUB_REPOSITORY?.split('/')[1] || '';
48
+ // Priority: Explicit > Env > Config > Local Git detection
49
+ _owner = owner || process.env.GITHUB_OWNER || config?.owner || detected?.owner || process.env.GITHUB_REPOSITORY?.split('/')[0] || '';
50
+ _repo = repo || process.env.GITHUB_REPO || config?.repo || detected?.repo || process.env.GITHUB_REPOSITORY?.split('/')[1] || '';
32
51
  if (_token) {
33
52
  _octokit = new Octokit({ auth: _token });
34
53
  }
@@ -59,3 +78,29 @@ export function requireRepo() {
59
78
  process.exit(1);
60
79
  }
61
80
  }
81
+ /**
82
+ * ── Phase 1: Contributor Support Helpers ──
83
+ */
84
+ export async function getAuthenticatedUser() {
85
+ const { data } = await getOctokit().users.getAuthenticated();
86
+ return data.login;
87
+ }
88
+ export async function forkRepo(owner, repo) {
89
+ const octokit = getOctokit();
90
+ const { data } = await octokit.repos.createFork({ owner, repo });
91
+ return data.full_name; // e.g. "myuser/original-repo"
92
+ }
93
+ export async function getRepoDetails(owner, repo) {
94
+ const { data } = await getOctokit().repos.get({ owner, repo });
95
+ return data;
96
+ }
97
+ export async function getLatestCheckRuns(owner, repo, ref) {
98
+ const octokit = getOctokit();
99
+ const { data: checks } = await octokit.checks.listForRef({ owner, repo, ref });
100
+ const { data: status } = await octokit.repos.getCombinedStatusForRef({ owner, repo, ref });
101
+ return {
102
+ checkRuns: checks.check_runs,
103
+ combinedState: status.state, // 'success', 'failure', 'pending'
104
+ statuses: status.statuses
105
+ };
106
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gitpadi",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "description": "🤖 GitPadi — Your AI-powered GitHub management CLI. Create repos, manage issues & PRs, score contributors, and automate everything.",
5
5
  "type": "module",
6
6
  "bin": {