main.go (7527B)
1 package main 2 3 import ( 4 "bufio" 5 "bytes" 6 "flag" 7 "fmt" 8 "io" 9 "os" 10 "path/filepath" 11 "regexp" 12 "strconv" 13 "strings" 14 "time" 15 ) 16 17 // config holds strict key-value records from config.kv 18 type Config map[string]string 19 20 var configKeyPattern = regexp.MustCompile(`^[A-Z][A-Z0-9_]*$`) 21 var featureNamePattern = regexp.MustCompile(`^FEATURE_[A-Z][A-Z0-9_]*$`) 22 23 func parseConfigKv(path string) (Config, error) { 24 f, err := os.Open(path) 25 if err != nil { 26 return nil, err 27 } 28 defer f.Close() 29 30 cfg := make(Config) 31 sc := bufio.NewScanner(f) 32 lineNo := 0 33 for sc.Scan() { 34 lineNo++ 35 line := strings.TrimSpace(sc.Text()) 36 if line == "" || strings.HasPrefix(line, "#") { 37 continue 38 } 39 40 eq := strings.IndexByte(line, '=') 41 if eq < 0 { 42 return nil, fmt.Errorf("line %d: missing =", lineNo) 43 } 44 key := strings.TrimSpace(line[:eq]) 45 if !configKeyPattern.MatchString(key) { 46 return nil, fmt.Errorf("line %d: invalid key %q", lineNo, key) 47 } 48 if strings.HasPrefix(key, "FEATURE") && !featureNamePattern.MatchString(key) { 49 return nil, fmt.Errorf("line %d: invalid feature name %q", lineNo, key) 50 } 51 if _, ok := cfg[key]; ok { 52 return nil, fmt.Errorf("line %d: duplicate key %q", lineNo, key) 53 } 54 55 raw := strings.TrimSpace(line[eq+1:]) 56 value, err := strconv.Unquote(raw) 57 if err != nil { 58 return nil, fmt.Errorf("line %d: invalid quoted value for %s: %w", lineNo, key, err) 59 } 60 cfg[key] = value 61 } 62 if err := sc.Err(); err != nil { 63 return nil, err 64 } 65 66 return cfg, nil 67 } 68 69 func (cfg Config) isEnabled(key string) bool { 70 return cfg[key] == "1" 71 } 72 73 // preprocessor condition stack for nested feature blocks 74 type ifFrame struct { 75 active bool 76 seen bool 77 elseSeen bool 78 } 79 80 type ifStack struct { 81 frames []ifFrame 82 } 83 84 func (s *ifStack) push(active, seen bool) { 85 s.frames = append(s.frames, ifFrame{active: active, seen: seen}) 86 } 87 88 func (s *ifStack) pop() { 89 if len(s.frames) > 0 { 90 s.frames = s.frames[:len(s.frames)-1] 91 } 92 } 93 94 func (s *ifStack) parentActive() bool { 95 for i := 0; i < len(s.frames)-1; i++ { 96 if !s.frames[i].active { 97 return false 98 } 99 } 100 return true 101 } 102 103 func (s *ifStack) globallyActive() bool { 104 for _, f := range s.frames { 105 if !f.active { 106 return false 107 } 108 } 109 return true 110 } 111 112 func (s *ifStack) top() *ifFrame { 113 if len(s.frames) == 0 { 114 return nil 115 } 116 return &s.frames[len(s.frames)-1] 117 } 118 119 var conditionPattern = regexp.MustCompile(`^(?:(!?)defined\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)|(!?)([A-Za-z_][A-Za-z0-9_]*)(?:\s*(==|!=)\s*([01]))?)$`) 120 121 func validateConditionalName(name string) error { 122 if strings.HasPrefix(name, "FEATURE") && !featureNamePattern.MatchString(name) { 123 return fmt.Errorf("invalid feature name %q", name) 124 } 125 return nil 126 } 127 128 func evalCondition(expr string, cfg Config) (bool, error) { 129 expr = strings.TrimSpace(expr) 130 alternatives := strings.Split(expr, "||") 131 result := false 132 for _, alternative := range alternatives { 133 terms := strings.Split(alternative, "&&") 134 termResult := true 135 for _, term := range terms { 136 value, err := evalConditionAtom(term, cfg) 137 if err != nil { 138 return false, err 139 } 140 termResult = termResult && value 141 } 142 result = result || termResult 143 } 144 return result, nil 145 } 146 147 func evalConditionAtom(expr string, cfg Config) (bool, error) { 148 match := conditionPattern.FindStringSubmatch(strings.TrimSpace(expr)) 149 if match == nil { 150 return false, fmt.Errorf("unsupported preprocessor condition %q", expr) 151 } 152 153 not := match[1] != "" 154 definedName := match[2] 155 plainNot := match[3] != "" 156 plainName := match[4] 157 operator := match[5] 158 value := match[6] 159 160 if definedName != "" { 161 if err := validateConditionalName(definedName); err != nil { 162 return false, err 163 } 164 _, ok := cfg[definedName] 165 return ok != not, nil 166 } 167 if err := validateConditionalName(plainName); err != nil { 168 return false, err 169 } 170 if operator == "" { 171 return cfg[plainName] == "1" != plainNot, nil 172 } 173 result := cfg[plainName] == value 174 if operator == "!=" { 175 result = !result 176 } 177 return result, nil 178 } 179 180 // section inference from file path 181 func inferSection(path string) int { 182 parts := strings.Split(filepath.ToSlash(path), "/") 183 if len(parts) < 3 { 184 return 1 185 } 186 switch parts[1] { 187 case "linux", "net", "xsi": 188 return 8 189 default: 190 return 1 191 } 192 } 193 194 func validateSourcePath(path string) error { 195 if filepath.IsAbs(path) || filepath.Clean(path) != path || strings.Contains(path, "\\") { 196 return fmt.Errorf("source path must be a clean relative path") 197 } 198 base := filepath.Base(path) 199 if filepath.Ext(base) != ".c" || !manNamePattern.MatchString(strings.TrimSuffix(base, ".c")) { 200 return fmt.Errorf("invalid generated path %q", path) 201 } 202 return nil 203 } 204 205 // a renderer turns a parsed page into one output format 206 type Renderer interface { 207 Render() error 208 } 209 210 func newRenderer(format string, page *Page, w io.Writer) (Renderer, error) { 211 switch strings.ToLower(format) { 212 case "", "mdoc": 213 return NewMdocRenderer(page, w), nil 214 case "txt": 215 return NewTxtRenderer(page, w), nil 216 default: 217 return nil, fmt.Errorf("unknown format %q (want mdoc or txt)", format) 218 } 219 } 220 221 func main() { 222 os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) 223 } 224 225 func run(args []string, stdout, stderr io.Writer) int { 226 flags := flag.NewFlagSet("mkman", flag.ContinueOnError) 227 flags.SetOutput(stderr) 228 configPath := flags.String("config", "scripts/mk/config.kv", "path to config.kv") 229 sectionFlag := flags.Int("section", 0, "man section override (0 = infer from path)") 230 dateFlag := flags.String("date", "", "date string for TH line (default: current month/year)") 231 formatFlag := flags.String("fmt", "mdoc", "output format: mdoc or txt") 232 outputPath := flags.String("out", "", "write output to this path instead of standard output") 233 if err := flags.Parse(args); err != nil { 234 return 1 235 } 236 237 if flags.NArg() != 1 { 238 fmt.Fprintln(stderr, "usage: mkman [-config scripts/mk/config.kv] [-section N] [-fmt mdoc|txt] [-out file] file.c") 239 return 1 240 } 241 cfile := flags.Arg(0) 242 if err := validateSourcePath(cfile); err != nil { 243 fmt.Fprintf(stderr, "mkman: %v\n", err) 244 return 1 245 } 246 247 cfg, err := parseConfigKv(*configPath) 248 if err != nil { 249 fmt.Fprintf(stderr, "mkman: config: %v\n", err) 250 return 1 251 } 252 253 section := *sectionFlag 254 if section == 0 { 255 section = inferSection(cfile) 256 } 257 if section != 1 && section != 8 { 258 fmt.Fprintf(stderr, "mkman: invalid man section %d\n", section) 259 return 1 260 } 261 262 date := *dateFlag 263 if date == "" { 264 date = time.Now().Format("January 2, 2006") 265 } 266 267 page, err := ParsePage(cfile, cfg, section, date) 268 if err != nil { 269 fmt.Fprintf(stderr, "mkman: scan: %v\n", err) 270 return 1 271 } 272 if page == nil { 273 fmt.Fprintf(stderr, "mkman: %s: no ?man comments found\n", cfile) 274 return 0 275 } 276 277 var output bytes.Buffer 278 renderer, err := newRenderer(*formatFlag, page, &output) 279 if err != nil { 280 fmt.Fprintf(stderr, "mkman: %v\n", err) 281 return 1 282 } 283 if err := renderer.Render(); err != nil { 284 fmt.Fprintf(stderr, "mkman: render: %v\n", err) 285 return 1 286 } 287 288 outProvided := false 289 flags.Visit(func(f *flag.Flag) { 290 if f.Name == "out" { 291 outProvided = true 292 } 293 }) 294 if outProvided { 295 if strings.TrimSpace(*outputPath) == "" { 296 fmt.Fprintln(stderr, "mkman: output path must not be empty") 297 return 1 298 } 299 if err := os.WriteFile(*outputPath, output.Bytes(), 0666); err != nil { 300 fmt.Fprintf(stderr, "mkman: write %s: %v\n", *outputPath, err) 301 return 1 302 } 303 return 0 304 } 305 306 n, err := stdout.Write(output.Bytes()) 307 if err == nil && n != output.Len() { 308 err = io.ErrShortWrite 309 } 310 if err != nil { 311 fmt.Fprintf(stderr, "mkman: write stdout: %v\n", err) 312 return 1 313 } 314 return 0 315 }