Refactor writeProtoFile function for better error handling

Streamlined the writeProtoFile function in desc_source.go file. Simplified path calculations and improved error messages for file-creation functions, making it easier to trace the exact point of failure and enhance the debugging process.
This commit is contained in:
Eitol 2024-07-12 01:00:54 -04:00
parent 0bb9027957
commit 9901b7affc
1 changed files with 7 additions and 10 deletions

View File

@ -320,22 +320,19 @@ func WriteProtoFiles(outProtoDirPath string, descSource DescriptorSource, symbol
} }
func writeProtoFile(outProtoDirPath string, fd *desc.FileDescriptor, pr *protoprint.Printer) error { func writeProtoFile(outProtoDirPath string, fd *desc.FileDescriptor, pr *protoprint.Printer) error {
fdFQName := fd.GetFullyQualifiedName() outFile := filepath.Join(outProtoDirPath, fd.GetFullyQualifiedName())
dirPath := filepath.Dir(fdFQName) outDir := filepath.Dir(outFile)
outFilepath := filepath.Join(outProtoDirPath, dirPath) if err := os.MkdirAll(outDir, 0777); err != nil {
if err := os.MkdirAll(outFilepath, 0755); err != nil { return fmt.Errorf("failed to create directory %q: %w", outDir, err)
return fmt.Errorf("failed to create directory %q: %v", outFilepath, err)
} }
fileName := filepath.Base(fdFQName)
filePath := filepath.Join(outFilepath, fileName)
f, err := os.Create(filePath) f, err := os.Create(outFile)
if err != nil { if err != nil {
return fmt.Errorf("failed to create proto file: %v", err) return fmt.Errorf("failed to create proto file %q: %w", outFile, err)
} }
defer f.Close() defer f.Close()
if err := pr.PrintProtoFile(fd, f); err != nil { if err := pr.PrintProtoFile(fd, f); err != nil {
return fmt.Errorf("failed to write proto file: %v", err) return fmt.Errorf("failed to write proto file %q: %w", outFile, err)
} }
return nil return nil
} }