Skip to content

Commit 3bdb843

Browse files
Merge pull request #77 from diegopereiraeng/main
scan match enhancement
2 parents 08acfd2 + 211f5d6 commit 3bdb843

File tree

2 files changed

+112
-145
lines changed

2 files changed

+112
-145
lines changed

README.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ This plugin is designed to run SonarQube scans and handle the results and conver
99
- Quality Gate status reporting + Metrics
1010
- Skip Scan and only check for quality Gate Status of a specific analysisId or last analysis
1111

12+
Obs: USe branch and pr_key params for accuracy results matches when skiping the scan
13+
1214
<img src="https://github.com/drone-plugins/sonarqube-scanner/blob/main/sonar-result-v2.png" alt="Results" width="800"/>
1315

1416
### Simple Pipeline example
@@ -109,7 +111,7 @@ spec:
109111
- Example: `"token": "your-sonarqube-token"`
110112
- `ver`: The version of the project.
111113
- Example: `"ver": "1.0.0"`
112-
- `branch`: The branch of the project.
114+
- `branch`: The branch of the project. This parameter is used to specify the branch of your codebase that the results should be matched with. If you're working on multiple branches, it's important to specify the correct branch to ensure that you're looking at the correct set of results.
113115
- Example: `"branch": "master"`
114116
- `timeout`: The timeout for the Sonar scanner.
115117
- Example: `"timeout": "300"`
@@ -157,8 +159,8 @@ spec:
157159
- Example: `"tests": "/path/to/tests"`
158160
- `java_test`: Java Test.
159161
- Example: `"java_test": "/path/to/java/test"`
160-
- `pr_key`: PR Key.
161-
- Example: `"pr_key": "your-pr-key"`
162+
- `pr_key`: Pull Request Key.
163+
- Example: `"pr_key": "123"`
162164
- `pr_branch`: PR Branch.
163165
- Example: `"pr_branch": "your-pr-branch"`
164166
- `pr_base`: PR Base.

plugin.go

Lines changed: 107 additions & 142 deletions
Original file line numberDiff line numberDiff line change
@@ -154,13 +154,6 @@ type (
154154
ActualValue string `json:"actualValue"`
155155
}
156156

157-
// type Period struct {
158-
// Index int `json:"index"`
159-
// Mode string `json:"mode"`
160-
// Date string `json:"date"`
161-
// Parameter string `json:"parameter,omitempty"` // this might not always be present
162-
// }
163-
164157
Testsuites struct {
165158
XMLName xml.Name `xml:"testsuites"`
166159
Text string `xml:",chardata"`
@@ -273,20 +266,6 @@ func displaySummary(total, passed, failed int, errors int, newErrors int, projec
273266
fmt.Println("Error writing to .env file:", err)
274267
// return
275268
}
276-
// file, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
277-
// if err != nil {
278-
// fmt.Println("Error opening/creating .env file:", err)
279-
// // return
280-
// }
281-
282-
// for key, value := range vars {
283-
// fmt.Println("Writing to .env file:", key, value)
284-
// _, err = file.WriteString(fmt.Sprintf("%s=%s\n", key, value))
285-
// if err != nil {
286-
// fmt.Println("Error writing to .env file:", err)
287-
// // return
288-
// }
289-
// }
290269

291270
fmt.Println("Successfully wrote to .env file")
292271
// defer file.Close()
@@ -398,6 +377,34 @@ func GetProjectKey(key string) string {
398377
return projectKey
399378
}
400379

380+
func logConfigInfo(configType, configValue string) {
381+
fmt.Printf("==> %s: %s\n", configType, configValue)
382+
}
383+
384+
func PreFlightGetLatestTaskID(config Config) (string, error) {
385+
var statusID string
386+
var err error
387+
388+
if config.PRKey != "" {
389+
logConfigInfo("PR Key", config.PRKey)
390+
statusID, err = getStatusV2("pr", config.PRKey, config.Host, config.Key)
391+
} else if config.Branch != "" {
392+
logConfigInfo("Branch", config.Branch)
393+
statusID, err = getStatusV2("branch", config.Branch, config.Host, config.Key)
394+
} else {
395+
logConfigInfo("Project Key", config.Key)
396+
statusID, err = getStatusID(config.TaskId, config.Host, config.Key)
397+
}
398+
399+
if err != nil {
400+
fmt.Printf("\n\n==> Error getting the latest scanID\n\n")
401+
fmt.Printf("Error: %s", err.Error())
402+
return "", err
403+
}
404+
405+
return statusID, nil
406+
}
407+
401408
func (p Plugin) Exec() error {
402409
// Initial values
403410
args := []string{
@@ -471,113 +478,6 @@ func (p Plugin) Exec() error {
471478
fmt.Printf("\n\n==> Sonar Java Plugin Jacoco Path configured!\n\n")
472479
}
473480

474-
// args := []string{
475-
// "-Dsonar.host.url=" + p.Config.Host,
476-
// "-Dsonar.login=" + p.Config.Token,
477-
// }
478-
// projectFinalKey := p.Config.Key
479-
480-
// if len(p.Config.Verbose) >= 1 {
481-
// args = append(args, "-X")
482-
// }
483-
484-
// if !p.Config.UsingProperties {
485-
// argsParameter := []string{
486-
// "-Dsonar.projectKey=" + projectFinalKey,
487-
// "-Dsonar.projectName=" + p.Config.Name,
488-
// "-Dsonar.projectVersion=" + p.Config.Version,
489-
// "-Dsonar.sources=" + p.Config.Sources,
490-
// "-Dsonar.ws.timeout=" + p.Config.Timeout,
491-
// "-Dsonar.inclusions=" + p.Config.Inclusions,
492-
// "-Dsonar.exclusions=" + p.Config.Exclusions,
493-
// "-Dsonar.log.level=" + p.Config.Level,
494-
// "-Dsonar.showProfiling=" + p.Config.ShowProfiling,
495-
// "-Dsonar.scm.provider=git",
496-
// "-Dsonar.java.binaries=" + p.Config.Binaries,
497-
// }
498-
// args = append(args, argsParameter...)
499-
// }
500-
// if p.Config.BranchAnalysis {
501-
// args = append(args, "-Dsonar.branch.name="+p.Config.Branch)
502-
// }
503-
// if p.Config.QualityEnabled == "true" {
504-
// args = append(args, "-Dsonar.qualitygate.wait="+p.Config.QualityEnabled)
505-
// args = append(args, "-Dsonar.qualitygate.timeout="+p.Config.QualityTimeout)
506-
// }
507-
// if len(p.Config.JavascitptIcovReport) >= 1 {
508-
// args = append(args, "-Dsonar.javascript.lcov.reportPaths="+p.Config.JavascitptIcovReport)
509-
// }
510-
// if len(p.Config.JacocoReportPath) >= 1 {
511-
// args = append(args, "-Dsonar.coverage.jacoco.xmlReportPaths="+p.Config.JacocoReportPath)
512-
// fmt.Printf("\n\n==> Sonar Java Plugin Jacoco configured!\n\n")
513-
// fmt.Printf("\n\n==> -Dsonar.coverage.jacoco.xmlReportPaths=" + p.Config.JacocoReportPath + "\n\n")
514-
// }
515-
// if len(p.Config.JavaCoveragePlugin) >= 1 {
516-
// args = append(args, "-Dsonar.java.coveragePlugin="+p.Config.JavaCoveragePlugin)
517-
// fmt.Printf("\n\n==> Sonar Java Plugin Jacoco Path configured!\n\n")
518-
// }
519-
// if len(p.Config.JunitReportPaths) >= 1 {
520-
// args = append(args, "-Dsonar.junit.reportPaths="+p.Config.JunitReportPaths)
521-
// }
522-
// if len(p.Config.SourceEncoding) >= 1 {
523-
// args = append(args, "-Dsonar.sourceEncoding="+p.Config.SourceEncoding)
524-
// }
525-
// if len(p.Config.SonarTests) >= 1 {
526-
// args = append(args, "-Dsonar.tests="+p.Config.SonarTests)
527-
// }
528-
// if len(p.Config.JavaTest) >= 1 {
529-
// args = append(args, "-Dsonar.java.test.binaries="+p.Config.JavaTest)
530-
// }
531-
// if len(p.Config.CoverageExclusion) >= 1 {
532-
// args = append(args, "-Dsonar.coverage.exclusions="+p.Config.CoverageExclusion)
533-
// }
534-
// if len(p.Config.JavaSource) >= 1 {
535-
// args = append(args, "-Dsonar.java.source="+p.Config.JavaSource)
536-
// }
537-
// if len(p.Config.JavaLibraries) >= 1 {
538-
// args = append(args, "-Dsonar.java.libraries="+p.Config.JavaLibraries)
539-
// }
540-
// if len(p.Config.SurefireReportsPath) >= 1 {
541-
// args = append(args, "-Dsonar.surefire.reportsPath="+p.Config.SurefireReportsPath)
542-
// }
543-
// if len(p.Config.TypescriptLcovReportPaths) >= 1 {
544-
// args = append(args, "-Dsonar.sonar.typescript.lcov.reportPaths="+p.Config.TypescriptLcovReportPaths)
545-
// }
546-
// if len(p.Config.Verbose) >= 1 {
547-
// args = append(args, "-Dsonar.verbose="+p.Config.Verbose)
548-
// }
549-
550-
// if len(p.Config.CustomJvmParams) >= 1 {
551-
552-
// params := strings.Split(p.Config.CustomJvmParams, ",")
553-
554-
// for _, param := range params {
555-
// //fmt.Println(i, param)
556-
// args = append(args, param)
557-
// }
558-
559-
// }
560-
561-
// if len(p.Config.PRKey) >= 1 {
562-
// args = append(args, "-Dsonar.pullrequest.key="+p.Config.PRKey)
563-
// }
564-
565-
// if len(p.Config.PRBranch) >= 1 {
566-
// args = append(args, "-Dsonar.pullrequest.branch="+p.Config.PRBranch)
567-
// }
568-
569-
// if len(p.Config.PRBase) >= 1 {
570-
// args = append(args, "-Dsonar.pullrequest.base="+p.Config.PRBase)
571-
// }
572-
573-
// if len(p.Config.SSLKeyStorePassword) >= 1 {
574-
// args = append(args, "-Djavax.net.ssl.trustStorePassword="+p.Config.SSLKeyStorePassword)
575-
// }
576-
577-
// if len(p.Config.CacertsLocation) >= 1 {
578-
// args = append(args, "-Djavax.net.ssl.trustStore="+p.Config.CacertsLocation)
579-
// }
580-
581481
os.Setenv("SONAR_USER_HOME", ".sonar")
582482

583483
fmt.Printf("\n\n")
@@ -599,13 +499,13 @@ func (p Plugin) Exec() error {
599499
fmt.Printf("#######################################\n")
600500
fmt.Printf("Waiting for quality gate validation...\n")
601501
fmt.Printf("#######################################\n")
602-
statusID, err := getStatusID(p.Config.TaskId, p.Config.Host, p.Config.Key)
502+
var err error
503+
status, err = PreFlightGetLatestTaskID(p.Config)
603504
if err != nil {
604505
fmt.Printf("\n\n==> Error getting the latest scanID\n\n")
605-
fmt.Printf("Error: %s", err.Error())
506+
logConfigInfo("Error", err.Error())
606507
return err
607508
}
608-
status = statusID
609509
} else {
610510
fmt.Printf("Starting Analisys")
611511
fmt.Printf("\n")
@@ -615,7 +515,7 @@ func (p Plugin) Exec() error {
615515
err := cmd.Run()
616516
if err != nil {
617517
fmt.Printf("\n\n==> Error in Analysis\n\n")
618-
fmt.Printf("Error: %s", err.Error())
518+
logConfigInfo("Error", err.Error())
619519
//return err
620520
}
621521
fmt.Printf("\n==> Sonar Analysis Finished!\n\n")
@@ -834,6 +734,7 @@ func getStatus(task *TaskResponse, report *SonarReport) string {
834734

835735
func getStatusID(taskIDOld string, sonarHost string, projectSlug string) (string, error) {
836736
// token := os.Getenv("PLUGIN_SONAR_TOKEN")
737+
837738
taskID, err := GetLatestTaskID(sonarHost, projectSlug)
838739
if err != nil {
839740
fmt.Println("Failed to get the latest task ID:", err)
@@ -851,16 +752,80 @@ func getStatusID(taskIDOld string, sonarHost string, projectSlug string) (string
851752
fmt.Printf("analysisId:" + taskID)
852753
fmt.Printf("\n")
853754

854-
// projectRequest, err := http.NewRequest("GET", sonarHost+"/api/qualitygates/project_status?"+reportRequest.Encode(), nil)
855-
// projectRequest.Header.Add("Authorization", basicAuth+token)
856-
// projectResponse, err := netClient.Do(projectRequest)
857-
// if err != nil {
858-
// logrus.WithFields(logrus.Fields{
859-
// "error": err,
860-
// }).Fatal("Failed get status")
861-
// return "", err
862-
// }
863-
// buf, _ := ioutil.ReadAll(projectResponse.Body)
755+
buf, err := GetProjectStatus(sonarHost, reportRequest.Encode(), projectSlug)
756+
757+
if err != nil {
758+
logrus.WithFields(logrus.Fields{
759+
"error": err,
760+
}).Error("Failed to get project status")
761+
}
762+
763+
project := ProjectStatusResponse{}
764+
if err := json.Unmarshal(buf, &project); err != nil {
765+
logrus.WithFields(logrus.Fields{
766+
"error": err,
767+
}).Fatal("Failed")
768+
return "", nil
769+
}
770+
771+
fmt.Printf("==> Report Result:\n")
772+
fmt.Printf(string(buf))
773+
774+
// JUNUT
775+
junitReport := ""
776+
junitReport = string(buf) // returns a string of what was written to it
777+
fmt.Printf("\n---------------------> JUNIT Exporter <---------------------\n")
778+
bytesReport := []byte(junitReport)
779+
var projectReport Project
780+
err = json.Unmarshal(bytesReport, &projectReport)
781+
if err != nil {
782+
panic(err)
783+
}
784+
785+
fmt.Printf("%+v", projectReport)
786+
fmt.Printf("\n")
787+
result := ParseJunit(projectReport, "BankingApp")
788+
file, _ := xml.MarshalIndent(result, "", " ")
789+
_ = ioutil.WriteFile("sonarResults.xml", file, 0644)
790+
791+
fmt.Printf("\n")
792+
fmt.Printf("\n======> JUNIT Exporter <======\n")
793+
794+
//JUNIT
795+
fmt.Printf("\n======> Harness Drone/CIE SonarQube Plugin <======\n\n====> Results:")
796+
797+
return project.ProjectStatus.Status, nil
798+
}
799+
800+
func getStatusV2(scanType string, scanValue string, sonarHost string, projectSlug string) (string, error) {
801+
// token := os.Getenv("PLUGIN_SONAR_TOKEN")
802+
803+
fmt.Println("Searchng last analysis")
804+
805+
var reportRequest url.Values
806+
807+
if scanType == "branch" {
808+
fmt.Println("Searchng last analysis by branch")
809+
reportRequest = url.Values{
810+
"branch": {scanValue},
811+
"projectKey": {projectSlug},
812+
}
813+
} else {
814+
fmt.Println("Searchng last analysis by pull request")
815+
reportRequest = url.Values{
816+
"pullRequest": {scanValue},
817+
"projectKey": {projectSlug},
818+
}
819+
}
820+
821+
fmt.Printf("==> Job Status Request:\n")
822+
fmt.Printf(sonarHost + "/api/qualitygates/project_status?" + reportRequest.Encode())
823+
fmt.Printf("\n")
824+
fmt.Printf("\n")
825+
fmt.Printf("scanType:" + scanType)
826+
fmt.Printf("scanValue:" + scanValue)
827+
fmt.Printf("\n")
828+
864829
buf, err := GetProjectStatus(sonarHost, reportRequest.Encode(), projectSlug)
865830

866831
if err != nil {

0 commit comments

Comments
 (0)