-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgit.go
More file actions
604 lines (513 loc) · 17.3 KB
/
Copy pathgit.go
File metadata and controls
604 lines (513 loc) · 17.3 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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"strings"
"time"
)
// findProjectByUserAndName finds a project by username and project name
func findProjectByUserAndName(server, username, projectName string) (string, error) {
// Get user info to get the user ID
userInfo, err := getUserInfo(server)
if err != nil {
return "", fmt.Errorf("failed to get user info: %w", err)
}
token, err := ensureValidToken()
if err != nil {
return "", fmt.Errorf("authentication required: %w", err)
}
// Get all projects using the same GraphQL query as listProjects
query := `query Projects(
$limit: Int
$offset: Int
$orderBy: [projects_order_by!]
$ownerId: bigint
$filter: projects_bool_exp
) {
aggregate: projects_aggregate(where: $filter) {
aggregate {
count
}
}
projects(limit: $limit, offset: $offset, order_by: $orderBy, where: $filter) {
id: project_id
project_id
name
owner {
username
name
}
created_at
product_id
finished
is_archived
instance_default_role
deployable
project_deployments_aggregate {
aggregate {
count
}
}
running_deployments: project_deployments_aggregate(
where: {
status: { _eq: "JobQueued" }
job: { status: { _eq: "Running" } }
}
) {
aggregate {
count
}
}
pending_deployments: project_deployments_aggregate(
where: {
status: { _eq: "JobQueued" }
job: { status: { _in: ["SubmitInitialized", "Submitted", "Pending"] } }
}
) {
aggregate {
count
}
}
resources(order_by: [{ sorting_order: asc_nulls_last }]) {
sorting_order
instance_default_role
giturl
name
resource_id
resource_type
}
product {
id
displayName: display_name
name
}
visibility
description
users: groups(where: { group_id: { _is_null: true } }) {
user {
name
}
id
assigned_role
}
groups(where: { group_id: { _is_null: false } }) {
group {
name
group_id
}
id: group_id
group_id
project_id
assigned_role
}
tags
userRole: access_control_users_aggregate(
where: { user_id: { _eq: $ownerId } }
) {
aggregate {
max {
assigned_role
}
}
}
is_simple_mode
projects_current_editor_user_id {
name
id
}
}
}`
// Execute the GraphQL query
response, err := executeProjectsQuery(server, token, query, userInfo.ID)
if err != nil {
return "", fmt.Errorf("failed to query projects: %w", err)
}
// Search for the project
var matchedProject *Project
for _, project := range response.Data.Projects {
if strings.EqualFold(project.Owner.Username, username) && strings.EqualFold(project.Name, projectName) {
matchedProject = &project
break
}
}
if matchedProject == nil {
return "", fmt.Errorf("project '%s' not found for user '%s'", projectName, username)
}
fmt.Printf("Found project: %s by %s (ID: %s)\n", matchedProject.Name, matchedProject.Owner.Username, matchedProject.ID)
return matchedProject.ID, nil
}
// executeProjectsQuery executes the GraphQL query for projects
func executeProjectsQuery(server string, token *StoredToken, query string, userID int64) (*ProjectsResponse, error) {
// This is similar to the code in listProjects but returns the response for reuse
graphqlReq := GraphQLRequest{
OperationName: "Projects",
Query: query,
Variables: map[string]interface{}{
"ownerId": userID,
},
}
jsonData, err := json.Marshal(graphqlReq)
if err != nil {
return nil, fmt.Errorf("failed to marshal GraphQL request: %w", err)
}
url := fmt.Sprintf("https://%s/v1/graphql", server)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token.IDToken))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("X-Hasura-Role", "jhuser")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to make request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("GraphQL request failed (status %d): %s", resp.StatusCode, string(body))
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
var response ProjectsResponse
if err := json.Unmarshal(body, &response); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
// Check for GraphQL errors
if len(response.Errors) > 0 {
return nil, fmt.Errorf("GraphQL errors: %v", response.Errors)
}
return &response, nil
}
// cloneProject clones a project using git with authorization
func cloneProject(server, projectIdentifier, localPath string) error {
token, err := ensureValidToken()
if err != nil {
return fmt.Errorf("authentication required: %w", err)
}
// Parse the project identifier
var username, projectName string
if strings.Contains(projectIdentifier, "/") {
parts := strings.SplitN(projectIdentifier, "/", 2)
username = parts[0]
projectName = parts[1]
} else {
// No username provided, use the logged-in user's username
userInfo, err := getUserInfo(server)
if err != nil {
return fmt.Errorf("failed to get user info for default username: %w", err)
}
username = userInfo.Username
projectName = projectIdentifier
fmt.Printf("Using logged-in user '%s' as project owner\n", username)
}
// Find the project by username and project name
projectUUID, err := findProjectByUserAndName(server, username, projectName)
if err != nil {
return err
}
// Construct the Git URL
gitURL := fmt.Sprintf("https://%s/git/projects/%s", server, projectUUID)
// Prepare the git clone command with authorization header
authHeader := fmt.Sprintf("Authorization: Bearer %s", token.IDToken)
var cmd *exec.Cmd
if localPath != "" {
cmd = exec.Command("git", "-c", fmt.Sprintf("http.extraHeader=%s", authHeader), "clone", gitURL, localPath)
} else {
cmd = exec.Command("git", "-c", fmt.Sprintf("http.extraHeader=%s", authHeader), "clone", gitURL)
}
// Set up command output
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
fmt.Printf("Cloning project: %s/%s\n", username, projectName)
fmt.Printf("Git URL: %s\n", gitURL)
// Execute the git clone command
err = cmd.Run()
if err != nil {
return fmt.Errorf("git clone failed: %w", err)
}
// If no local path was specified, rename the UUID folder to project name
var projectFolderPath string
if localPath == "" {
uuidFolderPath := fmt.Sprintf("./%s", projectUUID)
projectFolderPath = fmt.Sprintf("./%s", projectName)
// Check if the UUID folder exists
if _, err := os.Stat(uuidFolderPath); err == nil {
// Check if target folder already exists
if _, err := os.Stat(projectFolderPath); err == nil {
// Target folder exists, find an available name
projectFolderPath = findAvailableFolderName(projectName)
fmt.Printf("Warning: Folder '%s' already exists, using '%s' instead\n", projectName, strings.TrimPrefix(projectFolderPath, "./"))
}
// Rename the folder from UUID to project name
err = os.Rename(uuidFolderPath, projectFolderPath)
if err != nil {
return fmt.Errorf("failed to rename folder from %s to %s: %w", uuidFolderPath, projectFolderPath, err)
}
fmt.Printf("Renamed folder from %s to %s\n", projectUUID, strings.TrimPrefix(projectFolderPath, "./"))
}
}
finalPath := getClonePath(localPath, projectName)
if localPath == "" && projectFolderPath != "" {
// Use the actual folder name after potential renaming
finalPath = strings.TrimPrefix(projectFolderPath, "./")
}
fmt.Printf("Successfully cloned project to %s\n", finalPath)
return nil
}
// getClonePath determines the final clone path
func getClonePath(localPath, projectName string) string {
if localPath != "" {
return localPath
}
return fmt.Sprintf("./%s", projectName)
}
// findAvailableFolderName finds an available folder name by appending a number
func findAvailableFolderName(baseName string) string {
counter := 1
for {
candidateName := fmt.Sprintf("./%s-%d", baseName, counter)
if _, err := os.Stat(candidateName); os.IsNotExist(err) {
return candidateName
}
counter++
}
}
// pushProject executes git push with authentication headers and passes through all arguments
func pushProject(server string, args []string) error {
// Check if git is installed
if err := checkGitInstalled(); err != nil {
return err
}
token, err := ensureValidToken()
if err != nil {
return fmt.Errorf("authentication required: %w", err)
}
// Prepare the git push command with authorization header
authHeader := fmt.Sprintf("Authorization: Bearer %s", token.IDToken)
// Build the git command with auth header and all passed arguments
gitArgs := []string{"-c", fmt.Sprintf("http.extraHeader=%s", authHeader), "push"}
gitArgs = append(gitArgs, args...)
cmd := exec.Command("git", gitArgs...)
// Set up command output
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
// Execute the git push command
err = cmd.Run()
if err != nil {
return fmt.Errorf("git push failed: %w", err)
}
return nil
}
// fetchProject executes git fetch with authentication headers and passes through all arguments
func fetchProject(server string, args []string) error {
// Check if git is installed
if err := checkGitInstalled(); err != nil {
return err
}
token, err := ensureValidToken()
if err != nil {
return fmt.Errorf("authentication required: %w", err)
}
// Prepare the git fetch command with authorization header
authHeader := fmt.Sprintf("Authorization: Bearer %s", token.IDToken)
// Build the git command with auth header and all passed arguments
gitArgs := []string{"-c", fmt.Sprintf("http.extraHeader=%s", authHeader), "fetch"}
gitArgs = append(gitArgs, args...)
cmd := exec.Command("git", gitArgs...)
// Set up command output
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
// Execute the git fetch command
err = cmd.Run()
if err != nil {
return fmt.Errorf("git fetch failed: %w", err)
}
return nil
}
// pullProject executes git pull with authentication headers and passes through all arguments
func pullProject(server string, args []string) error {
// Check if git is installed
if err := checkGitInstalled(); err != nil {
return err
}
token, err := ensureValidToken()
if err != nil {
return fmt.Errorf("authentication required: %w", err)
}
// Prepare the git pull command with authorization header
authHeader := fmt.Sprintf("Authorization: Bearer %s", token.IDToken)
// Build the git command with auth header and all passed arguments
gitArgs := []string{"-c", fmt.Sprintf("http.extraHeader=%s", authHeader), "pull"}
gitArgs = append(gitArgs, args...)
cmd := exec.Command("git", gitArgs...)
// Set up command output
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
// Execute the git pull command
err = cmd.Run()
if err != nil {
return fmt.Errorf("git pull failed: %w", err)
}
return nil
}
// checkGitInstalled checks if git is available
func checkGitInstalled() error {
_, err := exec.LookPath("git")
if err != nil {
return fmt.Errorf("git is not installed or not in PATH")
}
return nil
}
// gitCredentialHelper implements the git credential helper protocol
func gitCredentialHelper(action string) error {
switch action {
case "get":
return gitCredentialGet()
case "store", "erase":
// These are no-ops for JuliaHub since we manage tokens ourselves
return nil
default:
return fmt.Errorf("unknown credential helper action: %s", action)
}
}
// gitCredentialGet handles the 'get' action for git credential helper
func gitCredentialGet() error {
// Read input from stdin to get the credential request
input, err := readCredentialInput()
if err != nil {
return fmt.Errorf("failed to read credential input: %w", err)
}
// Check if this is a JuliaHub URL
if !isJuliaHubURL(input["host"]) {
// Not a JuliaHub URL, return empty (let other credential helpers handle it)
return nil
}
requestedServer := input["host"]
// Check if we have a stored token and if the server matches
storedToken, err := readStoredToken()
if err != nil || storedToken.Server != requestedServer {
// No stored token or server mismatch - need to authenticate
fmt.Fprintf(os.Stderr, "JuliaHub CLI: Authenticating to %s...\n", requestedServer)
// Normalize the server name
normalizedServer := normalizeServer(requestedServer)
// Perform device flow authentication
token, err := deviceFlow(normalizedServer)
if err != nil {
return fmt.Errorf("authentication to %s failed: %w", requestedServer, err)
}
// Save token and server to config file
if err := writeTokenToConfig(normalizedServer, *token); err != nil {
fmt.Fprintf(os.Stderr, "Warning: Failed to save auth config: %v\n", err)
}
fmt.Fprintf(os.Stderr, "Successfully authenticated to %s!\n", requestedServer)
// Output credentials in the format git expects
fmt.Printf("username=oauth2\n")
fmt.Printf("password=%s\n", token.IDToken)
return nil
}
// Server matches, ensure we have a valid token
token, err := ensureValidToken()
if err != nil {
return fmt.Errorf("authentication required: %w", err)
}
// Output credentials in the format git expects
fmt.Printf("username=oauth2\n")
fmt.Printf("password=%s\n", token.IDToken)
return nil
}
// readCredentialInput reads and parses credential input from stdin
func readCredentialInput() (map[string]string, error) {
input := make(map[string]string)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
break
}
parts := strings.SplitN(line, "=", 2)
if len(parts) == 2 {
input[parts[0]] = parts[1]
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return input, nil
}
// isJuliaHubURL checks if the host is a JuliaHub server
func isJuliaHubURL(host string) bool {
if host == "" {
return false
}
// Check for juliahub.com and its subdomains
if strings.HasSuffix(host, "juliahub.com") {
return true
}
// Check for any host that might be a JuliaHub server
// This is a simple heuristic - in production, you might want to be more specific
if strings.Contains(host, "juliahub") {
return true
}
// Check against configured server
configServer, err := readConfigFile()
if err == nil && host == configServer {
return true
}
return false
}
// gitCredentialSetup configures git to use the JuliaHub credential helper
func gitCredentialSetup() error {
// Check if git is installed
if err := checkGitInstalled(); err != nil {
return err
}
// Get the path to the current executable
execPath, err := os.Executable()
if err != nil {
return fmt.Errorf("failed to get executable path: %w", err)
}
// Set up credential helper for JuliaHub domains
juliaHubDomains := []string{
"juliahub.com",
"*.juliahub.com",
}
// Also check if there's a custom server configured
configServer, err := readConfigFile()
if err == nil && configServer != "" && configServer != "juliahub.com" {
juliaHubDomains = append(juliaHubDomains, configServer)
}
fmt.Println("Configuring Git credential helper for JuliaHub...")
for _, domain := range juliaHubDomains {
credentialKey := fmt.Sprintf("credential.https://%s.helper", domain)
credentialValue := fmt.Sprintf("%s git-credential", execPath)
// Configure git credential helper for this domain
cmd := exec.Command("git", "config", "--global", credentialKey, credentialValue)
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to configure git credential helper for %s: %w", domain, err)
}
fmt.Printf("✓ Configured credential helper for %s\n", domain)
}
fmt.Println("\nGit credential helper setup complete!")
fmt.Println("\nYou can now use standard Git commands with JuliaHub repositories:")
fmt.Println(" git clone https://juliahub.com/git/projects/username/project.git")
fmt.Println(" git push")
fmt.Println(" git pull")
fmt.Println(" git fetch")
fmt.Println("\nThe JuliaHub CLI will automatically provide authentication when needed.")
return nil
}