Refactor proto file writing into separate function

The file writing process for protobuf files has been extracted into a new function called writeProtoFile(). This refactoring simplifies the main function. The code is cleaner and more manageable this way, improving maintainability and readability.
This commit is contained in:
Eitol 2024-07-10 23:30:04 -04:00
parent 21c947e107
commit 0bb9027957
1 changed files with 26 additions and 20 deletions

View File

@ -305,13 +305,21 @@ func WriteProtoFiles(outProtoDirPath string, descSource DescriptorSource, symbol
// now expand that to include transitive dependencies in topologically sorted // now expand that to include transitive dependencies in topologically sorted
// order (such that file always appears after its dependencies) // order (such that file always appears after its dependencies)
expandedFiles := make(map[string]struct{}, len(fds)) expandedFiles := make(map[string]struct{}, len(fds))
allFilesSlice := make([]*desc.FileDescriptor, 0, len(fds)) allFileDescriptors := make([]*desc.FileDescriptor, 0, len(fds))
for _, filename := range filenames { for _, filename := range filenames {
allFilesSlice = addFilesToFileDescriptorList(allFilesSlice, expandedFiles, fds[filename]) allFileDescriptors = addFilesToFileDescriptorList(allFileDescriptors, expandedFiles, fds[filename])
} }
pr := protoprint.Printer{} pr := protoprint.Printer{}
// now we can serialize to files // now we can serialize to files
for _, fd := range allFilesSlice { for i := range allFileDescriptors {
if err := writeProtoFile(outProtoDirPath, allFileDescriptors[i], &pr); err != nil {
return err
}
}
return nil
}
func writeProtoFile(outProtoDirPath string, fd *desc.FileDescriptor, pr *protoprint.Printer) error {
fdFQName := fd.GetFullyQualifiedName() fdFQName := fd.GetFullyQualifiedName()
dirPath := filepath.Dir(fdFQName) dirPath := filepath.Dir(fdFQName)
outFilepath := filepath.Join(outProtoDirPath, dirPath) outFilepath := filepath.Join(outProtoDirPath, dirPath)
@ -320,16 +328,14 @@ func WriteProtoFiles(outProtoDirPath string, descSource DescriptorSource, symbol
} }
fileName := filepath.Base(fdFQName) fileName := filepath.Base(fdFQName)
filePath := filepath.Join(outFilepath, fileName) filePath := filepath.Join(outFilepath, fileName)
f, err := os.Create(filePath) f, err := os.Create(filePath)
if err != nil { if err != nil {
return fmt.Errorf("failed to create file %q: %v", filePath, err) return fmt.Errorf("failed to create proto file: %v", err)
}
err = pr.PrintProtoFile(fd, f)
if err == nil {
_ = f.Close()
} else {
return fmt.Errorf("failed to write file %q: %v", filePath, err)
} }
defer f.Close()
if err := pr.PrintProtoFile(fd, f); err != nil {
return fmt.Errorf("failed to write proto file: %v", err)
} }
return nil return nil
} }