diff --git a/ordering/main.go b/ordering/main.go index 8e6488d..9849314 100644 --- a/ordering/main.go +++ b/ordering/main.go @@ -186,11 +186,24 @@ func GetTypeComments(d *ast.GenDecl) []string { func ReorderSource(filename, formatCommand string, reorderStructs bool, src interface{}) (string, error) { methods, constructors, structs, err := Parse(filename, formatCommand, src) + // in all cases, we must return the original source code if an error occurs + // get the content of the file + var content []byte + if src == nil { + var err error + content, err = ioutil.ReadFile(filename) + if err != nil { + return "", err + } + } else { + content = src.([]byte) + } + if err != nil { - return "", err + return string(content), err } if len(structs) == 0 { - return "", errors.New("No structs found in " + filename + ", cannot reorder") + return string(content), errors.New("No structs found in " + filename + ", cannot reorder") } // sort methods by name @@ -213,17 +226,6 @@ func ReorderSource(filename, formatCommand string, reorderStructs bool, src inte if reorderStructs { sort.Strings(structNames) } - // get the content of the file - var content []byte - if src == nil { - var err error - content, err = ioutil.ReadFile(filename) - if err != nil { - return "", err - } - } else { - content = src.([]byte) - } // Get the source code signature sign := fmt.Sprintf("%x", sha256.Sum256(content)) diff --git a/ordering/main_test.go b/ordering/main_test.go index 6af5737..b3272f2 100644 --- a/ordering/main_test.go +++ b/ordering/main_test.go @@ -120,3 +120,18 @@ func TestReorder(t *testing.T) { } } + +func TestNoStruct(t *testing.T) { + const source = `package main + func main() { + fmt.Println("nothing") + } + ` + content, err := ReorderSource(source, "gofmt", true, []byte(source)) + if err == nil { + t.Error("Expected error") + } + if content != source { + t.Errorf("Expected:\n%s\nGot:\n%s\n", source, content) + } +}