Skip to content

Commit

Permalink
Now, we return original content in case of error
Browse files Browse the repository at this point in the history
  • Loading branch information
metal3d committed Apr 19, 2022
1 parent 7f6cdb4 commit 1e53790
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 13 deletions.
28 changes: 15 additions & 13 deletions ordering/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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))
Expand Down
15 changes: 15 additions & 0 deletions ordering/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit 1e53790

Please sign in to comment.