cmd/hopp-generate: Add code generator command
This commit is contained in:
		
							parent
							
								
									2e28cf7c06
								
							
						
					
					
						commit
						69f3d4973b
					
				
							
								
								
									
										58
									
								
								cmd/hopp-generate/main.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										58
									
								
								cmd/hopp-generate/main.go
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,58 @@ | ||||
| package main | ||||
| 
 | ||||
| import "os" | ||||
| import "fmt" | ||||
| import "strings" | ||||
| import "path/filepath" | ||||
| import "git.tebibyte.media/sashakoshka/hopp/generate" | ||||
| 
 | ||||
| func main() { | ||||
| 	name := os.Args[0] | ||||
| 	if len(os.Args) != 3 { | ||||
| 		fmt.Fprintf(os.Stderr, "Usage: %s SOURCE DESTINATION\n", name) | ||||
| 		os.Exit(2) | ||||
| 	} | ||||
| 	source      := os.Args[1] | ||||
| 	destination := os.Args[2] | ||||
| 
 | ||||
| 	input, err := os.Open(source) | ||||
| 	handleErr(1, err) | ||||
| 	defer input.Close() | ||||
| 	protocol, err := generate.ParseReader(input) | ||||
| 	handleErr(1, err) | ||||
| 
 | ||||
| 	absDestination, err := filepath.Abs(destination) | ||||
| 	handleErr(1, err) | ||||
| 	packageName := cleanPackageName(strings.ReplaceAll( | ||||
| 		strings.ToLower(filepath.Base(absDestination)), | ||||
| 		" ", "_")) | ||||
| 	destination = filepath.Join(os.Args[2], "generated.go") | ||||
| 
 | ||||
| 	output, err := os.Create(destination) | ||||
| 	handleErr(1, err) | ||||
| 	err = protocol.Generate(output, packageName) | ||||
| 	handleErr(1, err) | ||||
| 	fmt.Fprintf(os.Stderr, "%s: OK\n", name) | ||||
| } | ||||
| 
 | ||||
| func handleErr(code int, err error) { | ||||
| 	if err != nil { | ||||
| 		fmt.Fprintf(os.Stderr, "%s: %v\n", os.Args[0], err) | ||||
| 		os.Exit(code) | ||||
| 	} | ||||
| } | ||||
| 
 | ||||
| func cleanPackageName(str string) string { | ||||
| 	buffer := []byte(str) | ||||
| 	j := 0 | ||||
| 	for _, b := range buffer { | ||||
| 		if ('a' <= b && b <= 'z') || | ||||
| 			('A' <= b && b <= 'Z') || | ||||
| 			('0' <= b && b <= '9') || | ||||
| 			b == '_' || b == ' ' { | ||||
| 			buffer[j] = b | ||||
| 			j++ | ||||
| 		} | ||||
| 	} | ||||
| 	return string(buffer[:j]) | ||||
| } | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user