|
| 1 | +package generator |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "path/filepath" |
| 6 | + "slices" |
| 7 | +) |
| 8 | + |
| 9 | +type InputSource interface { |
| 10 | + Args() []string |
| 11 | +} |
| 12 | + |
| 13 | +type RequestImpl struct { |
| 14 | + command, |
| 15 | + pattern, |
| 16 | + difficulty string |
| 17 | + data DocsTemplateData |
| 18 | +} |
| 19 | + |
| 20 | +func NewRequest( |
| 21 | + source InputSource, |
| 22 | +) (RequestImpl, error) { |
| 23 | + args := source.Args() |
| 24 | + if err := validate(args); err != nil { |
| 25 | + return RequestImpl{}, err |
| 26 | + } |
| 27 | + |
| 28 | + result := RequestImpl{ |
| 29 | + args[0], |
| 30 | + args[1], |
| 31 | + args[2], |
| 32 | + NewDocsTemplateData(args[3]), |
| 33 | + } |
| 34 | + return result, nil |
| 35 | +} |
| 36 | + |
| 37 | +func validate(args []string) error { |
| 38 | + doValidate := func(attr string, member string, list []string) error { |
| 39 | + if !slices.Contains(list, member) { |
| 40 | + return fmt.Errorf("invalid %s: %s, allowed: %v", attr, member, list) |
| 41 | + } |
| 42 | + return nil |
| 43 | + } |
| 44 | + |
| 45 | + if len(args) != 4 { |
| 46 | + return fmt.Errorf("missing command, pattern, difficulty and title") |
| 47 | + } |
| 48 | + |
| 49 | + if err := doValidate( |
| 50 | + "command", |
| 51 | + args[0], |
| 52 | + []string{"create", "delete"}, |
| 53 | + ); err != nil { |
| 54 | + return err |
| 55 | + } |
| 56 | + |
| 57 | + if err := doValidate( |
| 58 | + "pattern", |
| 59 | + args[1], |
| 60 | + []string{"arrays", "bit-manipulation", "stack"}, |
| 61 | + ); err != nil { |
| 62 | + return err |
| 63 | + } |
| 64 | + |
| 65 | + if err := doValidate( |
| 66 | + "difficulty", |
| 67 | + args[2], |
| 68 | + []string{"easy", "medium", "hard"}, |
| 69 | + ); err != nil { |
| 70 | + return err |
| 71 | + } |
| 72 | + |
| 73 | + return nil |
| 74 | +} |
| 75 | + |
| 76 | +func (r RequestImpl) Create() bool { |
| 77 | + return r.command == "create" |
| 78 | +} |
| 79 | + |
| 80 | +func (r RequestImpl) TemplateData() DocsTemplateData { |
| 81 | + return r.data |
| 82 | +} |
| 83 | + |
| 84 | +func (r RequestImpl) TargetPath(root string) string { |
| 85 | + return filepath.Join( |
| 86 | + root, |
| 87 | + r.pattern, |
| 88 | + r.difficulty, |
| 89 | + r.data.SmallTitle, |
| 90 | + ) |
| 91 | +} |
0 commit comments