github.com/khulnasoft/codebase@v0.0.0-20231214144635-a707781cbb24/service/github/githubutils/utils.go (about) 1 package githubutils 2 3 import ( 4 "fmt" 5 "net/url" 6 "os" 7 8 "github.com/khulnasoft/codebase/proto/rdf" 9 ) 10 11 // LinkedMarkdownDiagnostic returns Markdown string which contains a link to the 12 // location in the diagnostic and the diagnostic content itself. 13 func LinkedMarkdownDiagnostic(owner, repo, sha string, d *rdf.Diagnostic) string { 14 path := d.GetLocation().GetPath() 15 msg := d.GetMessage() 16 if path == "" { 17 return msg 18 } 19 loc := BasicLocationFormat(d) 20 line := int(d.GetLocation().GetRange().GetStart().GetLine()) 21 link, err := PathLink(owner, repo, sha, path, line) 22 if err != nil { 23 return fmt.Sprintf("%s %s", loc, msg) 24 } 25 return fmt.Sprintf("[%s](%s) %s", loc, link, msg) 26 } 27 28 // PathLink build a link to GitHub path to given sha, file, and line. 29 func PathLink(owner, repo, sha, path string, line int) (string, error) { 30 serverURL, err := githubServerURL() 31 if err != nil { 32 return "", err 33 } 34 35 if sha == "" { 36 sha = "master" 37 } 38 fragment := "" 39 if line > 0 { 40 fragment = fmt.Sprintf("#L%d", line) 41 } 42 43 result := fmt.Sprintf("%s/%s/%s/blob/%s/%s%s", 44 serverURL.String(), owner, repo, sha, path, fragment) 45 46 return result, nil 47 } 48 49 // BasicLocationFormat format a diagnostic to %f|%l col %c| errorformat. 50 func BasicLocationFormat(d *rdf.Diagnostic) string { 51 loc := d.GetLocation() 52 out := loc.GetPath() + "|" 53 lnum := int(loc.GetRange().GetStart().GetLine()) 54 col := int(loc.GetRange().GetStart().GetColumn()) 55 if lnum != 0 { 56 out = fmt.Sprintf("%s%d", out, lnum) 57 if col != 0 { 58 out = fmt.Sprintf("%s col %d", out, col) 59 } 60 } 61 return out + "|" 62 } 63 64 const defaultGitHubServerURL = "https://github.com" 65 66 func githubServerURL() (*url.URL, error) { 67 // get GitHub server URL from GitHub Actions' default environment variable GITHUB_SERVER_URL 68 // ref: https://docs.github.com/en/actions/reference/environment-variables#default-environment-variables 69 if baseURL := os.Getenv("GITHUB_SERVER_URL"); baseURL != "" { 70 u, err := url.Parse(baseURL) 71 if err != nil { 72 return nil, fmt.Errorf("GitHub server URL from GITHUB_SERVER_URL is invalid: %v, %w", baseURL, err) 73 } 74 return u, nil 75 } 76 u, err := url.Parse(defaultGitHubServerURL) 77 if err != nil { 78 return nil, fmt.Errorf("GitHub server URL from codebase default is invalid: %v, %w", defaultGitHubServerURL, err) 79 } 80 return u, nil 81 }