forked from Gerome-Elassaad/CodingIT
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathgithub-import.tsx
More file actions
446 lines (406 loc) · 14.9 KB
/
Copy pathgithub-import.tsx
File metadata and controls
446 lines (406 loc) · 14.9 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
'use client'
import { useState, useEffect, useCallback } from 'react'
import { Button } from './ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card'
import { Input } from './ui/input'
import { Badge } from './ui/badge'
import { useToast } from './ui/use-toast'
import {
Github,
Search,
Download,
Loader2,
RefreshCw,
Star,
GitFork,
Calendar,
FileText,
Folder,
ExternalLink
} from 'lucide-react'
import { useAuth } from '@/lib/auth'
import { ScrollArea } from './ui/scroll-area'
interface GitHubRepo {
id: number
name: string
full_name: string
description: string
html_url: string
clone_url: string
private: boolean
fork: boolean
language: string
stargazers_count: number
forks_count: number
updated_at: string
owner: {
login: string
avatar_url: string
}
}
interface UsageLimits {
can_import: boolean
current_usage: number
limit: number
is_unlimited: boolean
plan_name: string
upgrade_required: boolean
}
interface GitHubImportProps {
onImport?: (repo: GitHubRepo, files: any[]) => void
onClose?: () => void
}
export function GitHubImport({ onImport, onClose }: GitHubImportProps) {
const { session } = useAuth(() => {}, () => {})
const { toast } = useToast()
const [repositories, setRepositories] = useState<GitHubRepo[]>([])
const [usageLimits, setUsageLimits] = useState<UsageLimits | null>(null)
const [isLoading, setIsLoading] = useState(false)
const [searchTerm, setSearchTerm] = useState('')
const [selectedRepo, setSelectedRepo] = useState<GitHubRepo | null>(null)
const [isImporting, setIsImporting] = useState(false)
const loadRepositories = useCallback(async () => {
if (!session?.user?.id) return
setIsLoading(true)
try {
// First get the current user
const userResponse = await fetch('/api/github/user')
if (!userResponse.ok) {
throw new Error('Failed to fetch GitHub user')
}
const userData = await userResponse.json()
// Get user's repositories
const reposResponse = await fetch(`/api/github/repos?owner=${userData.login}`)
if (!reposResponse.ok) {
throw new Error('Failed to fetch repositories')
}
const userRepos = await reposResponse.json()
// Get user's organizations
const orgsResponse = await fetch('/api/github/orgs')
let orgRepos: any[] = []
if (orgsResponse.ok) {
const orgs = await orgsResponse.json()
// Fetch repos from each organization
for (const org of orgs) {
try {
const orgReposResponse = await fetch(`/api/github/repos?owner=${org.login}`)
if (orgReposResponse.ok) {
const repos = await orgReposResponse.json()
orgRepos.push(...repos)
}
} catch (error) {
console.warn(`Failed to fetch repos for org ${org.login}:`, error)
}
}
}
// Combine all repositories and format them
const allRepos = [...userRepos, ...orgRepos].map((repo: any) => ({
id: repo.id || Math.random(), // fallback ID if not present
name: repo.name,
full_name: repo.full_name,
description: repo.description,
html_url: `https://github.com/${repo.full_name}`,
clone_url: repo.clone_url,
private: repo.private,
fork: false, // not available in current API
language: repo.language,
stargazers_count: 0, // not available in current API
forks_count: 0, // not available in current API
updated_at: repo.updated_at,
owner: {
login: repo.full_name.split('/')[0],
avatar_url: userData.avatar_url // use user's avatar as fallback
}
}))
setRepositories(allRepos)
// For now, set basic usage limits - this would need to be integrated with your subscription system
setUsageLimits({
can_import: true,
current_usage: 0,
limit: 10,
is_unlimited: false,
plan_name: 'free',
upgrade_required: false
})
} catch (error) {
console.error('Error loading repositories:', error)
toast({
title: "Error",
description: "Failed to load GitHub repositories. Please check your connection.",
variant: "destructive",
})
} finally {
setIsLoading(false)
}
}, [session?.user?.id, toast])
const importRepository = async (repo: GitHubRepo) => {
if (!session?.user?.id) return
setIsImporting(true)
setSelectedRepo(repo)
try {
const [owner, repoName] = repo.full_name.split('/')
// Fetch root directory contents
const rootResponse = await fetch(`/api/github/repos/${owner}/${repoName}`)
if (!rootResponse.ok) {
throw new Error('Failed to fetch repository contents')
}
const rootData = await rootResponse.json()
// Fetch all files recursively
const allFiles = await fetchAllFiles(owner, repoName, rootData.contents || [])
// Save files to workspace using batch endpoint
const filesToImport = allFiles.map(file => ({
path: `${repo.name}/${file.path}`,
content: file.content,
isDirectory: false
}))
const response = await fetch('/api/files/batch', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
files: filesToImport
}),
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || 'Failed to import files')
}
const result = await response.json()
const importedCount = result.imported || 0
toast({
title: "Success",
description: `Successfully imported ${repo.name} with ${importedCount} files.`,
})
// Update usage limits
if (usageLimits) {
const remainingImports = usageLimits.limit - (usageLimits.current_usage + 1)
setUsageLimits({
...usageLimits,
current_usage: usageLimits.current_usage + 1,
can_import: remainingImports > 0
})
}
if (onImport) {
onImport(repo, allFiles)
}
} catch (error) {
console.error('Error importing repository:', error)
toast({
title: "Error",
description: typeof error === 'object' && error && 'message' in error ? error.message as string : "Failed to import repository. Please try again.",
variant: "destructive",
})
} finally {
setIsImporting(false)
setSelectedRepo(null)
}
}
const fetchAllFiles = async (owner: string, repo: string, contents: any[], path = ''): Promise<any[]> => {
const files: any[] = []
for (const item of contents) {
if (item.type === 'file') {
try {
const fileResponse = await fetch(
`/api/github/repos/${owner}/${repo}?path=${item.path}`
)
if (fileResponse.ok) {
const fileData = await fileResponse.json()
files.push({
name: item.name,
path: item.path,
content: fileData.content?.content ? atob(fileData.content.content) : '',
size: item.size,
type: 'file'
})
}
} catch (error) {
console.warn(`Failed to fetch file ${item.path}:`, error)
}
} else if (item.type === 'dir') {
try {
const dirResponse = await fetch(
`/api/github/repos/${owner}/${repo}?path=${item.path}`
)
if (dirResponse.ok) {
const dirData = await dirResponse.json()
const subFiles = await fetchAllFiles(owner, repo, dirData.contents || [], item.path)
files.push(...subFiles)
}
} catch (error) {
console.warn(`Failed to fetch directory ${item.path}:`, error)
}
}
}
return files
}
useEffect(() => {
loadRepositories()
}, [session?.user?.id, loadRepositories])
const filteredRepositories = repositories.filter(repo =>
repo.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
repo.description?.toLowerCase().includes(searchTerm.toLowerCase())
)
if (!session?.user?.id) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Github className="h-5 w-5" />
GitHub Import
</CardTitle>
<CardDescription>
Please log in to import repositories from GitHub.
</CardDescription>
</CardHeader>
</Card>
)
}
return (
<Card className="w-full max-w-4xl mx-auto">
<CardHeader>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Github className="h-5 w-5" />
<CardTitle>Import from GitHub</CardTitle>
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={loadRepositories}
disabled={isLoading}
>
{isLoading ? (
<Loader2 className="h-4 w-4 animate-spin mr-2" />
) : (
<RefreshCw className="h-4 w-4 mr-2" />
)}
Refresh
</Button>
{onClose && (
<Button variant="outline" size="sm" onClick={onClose}>
Close
</Button>
)}
</div>
</div>
<CardDescription>
Select a repository to import into your workspace.
{usageLimits && (
<span className="block mt-2">
<Badge variant={usageLimits.can_import ? "secondary" : "destructive"} className="mr-2">
{usageLimits.current_usage} / {usageLimits.is_unlimited ? '∞' : usageLimits.limit} imports used
</Badge>
{usageLimits.plan_name === 'free' && (
<span className="text-xs text-muted-foreground">
Upgrade to Pro for more imports
</span>
)}
</span>
)}
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="relative">
<Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search repositories..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10"
/>
</div>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-6 w-6 animate-spin" />
</div>
) : (
<ScrollArea className="h-[400px]">
<div className="space-y-2">
{filteredRepositories.map((repo) => (
<Card key={repo.id} className="relative">
<CardContent className="p-4">
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-2">
<h3 className="font-semibold text-sm truncate">
{repo.name}
</h3>
{repo.private && (
<Badge variant="secondary" className="text-xs">
Private
</Badge>
)}
{repo.fork && (
<Badge variant="outline" className="text-xs">
Fork
</Badge>
)}
</div>
{repo.description && (
<p className="text-sm text-muted-foreground mb-2 line-clamp-2">
{repo.description}
</p>
)}
<div className="flex items-center gap-4 text-xs text-muted-foreground">
{repo.language && (
<div className="flex items-center gap-1">
<div className="w-2 h-2 rounded-full bg-blue-500" />
{repo.language}
</div>
)}
<div className="flex items-center gap-1">
<Star className="h-3 w-3" />
{repo.stargazers_count}
</div>
<div className="flex items-center gap-1">
<GitFork className="h-3 w-3" />
{repo.forks_count}
</div>
<div className="flex items-center gap-1">
<Calendar className="h-3 w-3" />
{new Date(repo.updated_at).toLocaleDateString()}
</div>
</div>
</div>
<div className="flex items-center gap-2 ml-4">
<Button
variant="ghost"
size="sm"
onClick={() => window.open(repo.html_url, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
<Button
variant="default"
size="sm"
onClick={() => importRepository(repo)}
disabled={isImporting || (usageLimits ? !usageLimits.can_import : false)}
>
{isImporting && selectedRepo?.id === repo.id ? (
<Loader2 className="h-4 w-4 animate-spin mr-2" />
) : (
<Download className="h-4 w-4 mr-2" />
)}
{usageLimits && !usageLimits.can_import ? 'Upgrade Required' : 'Import'}
</Button>
</div>
</div>
</CardContent>
</Card>
))}
{filteredRepositories.length === 0 && !isLoading && (
<div className="text-center py-8 text-muted-foreground">
{searchTerm ? 'No repositories found matching your search.' : 'No repositories found.'}
</div>
)}
</div>
</ScrollArea>
)}
</div>
</CardContent>
</Card>
)
}