Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improving error handling in a more go way #9

Merged
merged 5 commits into from
Oct 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 23 additions & 26 deletions build/make.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,13 @@ var deployDir = filepath.Join(deploy, report)

func main() {
flag.Parse()
if *install {
switch {
case *install:
updatePluginInstallPrefix()
installPlugin(*pluginInstallPrefix)
} else if *distro {
case *distro:
createPluginDistro(*allPlatforms)
} else {
default:
compile()
}
}
Expand Down Expand Up @@ -147,7 +148,7 @@ func mirrorFile(src, dst string) error {

func mirrorDir(src, dst string) error {
fmt.Printf("Copying '%s' -> '%s'\n", src, dst)
err := filepath.Walk(src, func(path string, fi os.FileInfo, err error) error {
return filepath.Walk(src, func(path string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
Expand All @@ -160,13 +161,11 @@ func mirrorDir(src, dst string) error {
}
return mirrorFile(path, filepath.Join(dst, suffix))
})
return err
}

func set(envName, envValue string) {
fmt.Printf("%s = %s\n", envName, envValue)
err := os.Setenv(envName, envValue)
if err != nil {
if err := os.Setenv(envName, envValue); err != nil {
panic(err)
}
}
Expand All @@ -176,8 +175,7 @@ func runProcess(command string, arg ...string) {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
fmt.Printf("Execute %v\n", cmd.Args)
err := cmd.Run()
if err != nil {
if err := cmd.Run(); err != nil {
panic(err)
}
}
Expand Down Expand Up @@ -322,20 +320,22 @@ func installPlugin(installPrefix string) {
}

func updatePluginInstallPrefix() {
if *pluginInstallPrefix == "" {
if runtime.GOOS == "windows" {
*pluginInstallPrefix = os.Getenv("APPDATA")
if *pluginInstallPrefix == "" {
panic(fmt.Errorf("Failed to find AppData directory"))
}
*pluginInstallPrefix = filepath.Join(*pluginInstallPrefix, gauge, plugins)
} else {
userHome := getUserHome()
if userHome == "" {
panic(fmt.Errorf("Failed to find User Home directory"))
}
*pluginInstallPrefix = filepath.Join(userHome, dotGauge, plugins)
if *pluginInstallPrefix != "" {
return
}
switch runtime.GOOS {
case "windows":
*pluginInstallPrefix = os.Getenv("APPDATA")
if *pluginInstallPrefix == "" {
panic(fmt.Errorf("Failed to find AppData directory"))
}
*pluginInstallPrefix = filepath.Join(*pluginInstallPrefix, gauge, plugins)
default:
userHome := getUserHome()
if userHome == "" {
panic(fmt.Errorf("Failed to find User Home directory"))
}
*pluginInstallPrefix = filepath.Join(userHome, dotGauge, plugins)
}
}

Expand All @@ -344,8 +344,7 @@ func getUserHome() string {
}

func getArch() string {
arch := getGOARCH()
if arch == x86 {
if arch := getGOARCH(); arch == x86 {
return "x86"
}
return "x86_64"
Expand All @@ -355,7 +354,6 @@ func getGOARCH() string {
goArch := os.Getenv(GOARCH)
if goArch == "" {
return runtime.GOARCH

}
return goArch
}
Expand All @@ -364,7 +362,6 @@ func getGOOS() string {
os := os.Getenv(goOS)
if os == "" {
return runtime.GOOS

}
return os
}
55 changes: 26 additions & 29 deletions listener/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,34 +55,32 @@ func (listener *Listener) Start() {
func (listener *Listener) ProcessMessages(buffer *bytes.Buffer) {
for {
messageLength, bytesRead := proto.DecodeVarint(buffer.Bytes())
if messageLength > 0 && messageLength < uint64(buffer.Len()) {
message := &gauge_messages.Message{}
messageBoundary := int(messageLength) + bytesRead
messageBytes := buffer.Bytes()[bytesRead:messageBoundary]
err := proto.Unmarshal(messageBytes, message)
if messageLength <= 0 || messageLength >= uint64(buffer.Len()) {
return
}
message := &gauge_messages.Message{}
messageBoundary := int(messageLength) + bytesRead
messageBytes := buffer.Bytes()[bytesRead:messageBoundary]
if err := proto.Unmarshal(messageBytes, message); err != nil {
logger.Warnf("Failed to read proto message: %s\n", err.Error())
logger.Warnf("Message : %s\n", string(messageBytes))
continue
}
switch message.MessageType {
case gauge_messages.Message_KillProcessRequest:
logger.Debug("Received Kill Message, exiting...")
listener.onKillProcessRequestHandler(message.GetKillProcessRequest())
err := listener.connection.Close()
if err != nil {
logger.Warnf("Failed to read proto message: %s\n", err.Error())
logger.Warnf("Message : %s\n", string(messageBytes))
} else {
switch message.MessageType {
case gauge_messages.Message_KillProcessRequest:
logger.Debug("Received Kill Message, exiting...")
listener.onKillProcessRequestHandler(message.GetKillProcessRequest())
err := listener.connection.Close()
if err != nil {
logger.Debug("Failed to close the listener connection.")
}
os.Exit(0)
case gauge_messages.Message_SuiteExecutionResult:
go listener.sendPings()
listener.onResultHandler(message.GetSuiteExecutionResult())
}
buffer.Next(messageBoundary)
if buffer.Len() == 0 {
return
}
logger.Debug("Failed to close the listener connection.")
}
} else {
os.Exit(0)
case gauge_messages.Message_SuiteExecutionResult:
go listener.sendPings()
listener.onResultHandler(message.GetSuiteExecutionResult())
}
buffer.Next(messageBoundary)
if buffer.Len() == 0 {
return
}
}
Expand All @@ -102,13 +100,12 @@ func (listener *Listener) sendPings() {
ping := func(b []byte, c net.Conn) {
logger.Debug("reportserver sending a keep-alive ping")
l := proto.EncodeVarint(uint64(len(b)))
_, err := c.Write(append(l, b...))
if err != nil {
if _, err := c.Write(append(l, b...)); err != nil {
logger.Debugf("Unable to send ping message, %s", err.Error())
}
}
ticker := time.NewTicker(interval())
defer func() { ticker.Stop() }()
defer ticker.Stop()

for {
select {
Expand Down
8 changes: 3 additions & 5 deletions reportserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,7 @@ func ReadLogsFile(logsFilePath string) (logLineExists bool) {
return
}
start := stat.Size() - 512
_, err = file.ReadAt(buf, start)
if err == nil {
if _, err = file.ReadAt(buf, start); err == nil {
logLineExists = strings.Contains(string(buf), logLine)
}
return
Expand Down Expand Up @@ -136,9 +135,8 @@ func SendReport(stop chan bool) {
return
}
reportPath := env.GetReportServerUrl()
err := sender.SendArchive(reportPath, ArchiveDestination())
if err != nil {
logger.Infof("Could not send the archive from '%s' to '%s'\n%s\n", ArchiveDestination(), reportPath, err.Error())
if err := sender.SendArchive(reportPath, ArchiveDestination()); err != nil {
logger.Infof("Could not send the archive from '%s' to '%s'\n%s\n", ArchiveDestination(), reportPath, err)
} else {
logger.Infof("Successfully sent html-report to reportserver => %s\n", filepath.Join(reportPath, "report.html"))
}
Expand Down
15 changes: 5 additions & 10 deletions sender/sender.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,11 @@ func SendArchive(url, filePath string) (err error) {
writer := multipart.NewWriter(&b)
// Add your image file
file, err := os.Open(filePath)
defer func() {
err := file.Close()
if err != nil {
return
}
}()
if err != nil {
return fmt.Errorf("error opening the file '%s'", filePath)
}
defer file.Close()

fileStat, err := file.Stat()
if err != nil {
return fmt.Errorf("could not get file information")
Expand All @@ -32,14 +28,14 @@ func SendArchive(url, filePath string) (err error) {
if err != nil {
return fmt.Errorf("error create a form writer")
}
if _, err = io.Copy(formWriter, file); err != nil {
if _, err := io.Copy(formWriter, file); err != nil {
return fmt.Errorf("error copying file '%s' to form writer", file.Name())
}
// add auto unzip param to request
_ = writer.WriteField("unzip", "true")
writer.WriteField("unzip", "true")
// close the multipart writer.
// If you don't close it, your request will be missing the terminating boundary.
if err = writer.Close(); err != nil {
if err := writer.Close(); err != nil {
return err
}
// Now that you have a form, you can submit it to your handler.
Expand All @@ -55,7 +51,6 @@ func SendArchive(url, filePath string) (err error) {
if err != nil {
return err
}

// Check the response
if res.StatusCode != http.StatusOK {
return fmt.Errorf("bad status: %s", res.Status)
Expand Down
20 changes: 4 additions & 16 deletions zipper/zipper.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
)

func ZipDir(source, target string) error {

// check if sourceDir exists
if _, err := os.Stat(source); os.IsNotExist(err) {
return fmt.Errorf("source directory '%s' does not exist", source)
Expand All @@ -22,29 +21,19 @@ func ZipDir(source, target string) error {
}
// create a zip file at target
zipFile, err := os.Create(target)
defer func() {
err := zipFile.Close()
if err != nil {
return
}
}()
defer zipFile.Close()
if err != nil {
return fmt.Errorf("could not create the target archive at '%s'", target)
}
// create a new writer for writing into zip
archive := zip.NewWriter(zipFile)
defer func() {
err := archive.Close()
if err != nil {
return
}
}()
defer archive.Close()
// list of files to ignore when adding to zip
ignoreFiles := []string{
"html-report",
".DS_Store",
}
err = filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
if err := filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
Expand Down Expand Up @@ -85,8 +74,7 @@ func ZipDir(source, target string) error {
}
_, err = io.Copy(writer, file)
return err
})
if err != nil {
}); err != nil {
return err
}
if err = archive.Flush(); err != nil {
Expand Down