...

Source file src/github.com/miekg/pkcs11/const_generate.go

Documentation: github.com/miekg/pkcs11

     1  //go:build ignore
     2  // +build ignore
     3  
     4  // const_generate.go parses pkcs11t.h and generates zconst.go.
     5  // zconst.go is meant to be checked into git.
     6  
     7  package main
     8  
     9  import (
    10  	"bufio"
    11  	"bytes"
    12  	"fmt"
    13  	"go/format"
    14  	"log"
    15  	"os"
    16  	"strings"
    17  )
    18  
    19  func main() {
    20  	file, err := os.Open("pkcs11t.h")
    21  	if err != nil {
    22  		log.Fatal(err)
    23  	}
    24  	defer file.Close()
    25  
    26  	out := &bytes.Buffer{}
    27  	fmt.Fprintf(out, header)
    28  
    29  	scanner := bufio.NewScanner(file)
    30  	fmt.Fprintln(out, "const (")
    31  	for scanner.Scan() {
    32  		// Fairly simple parsing, any line starting with '#define' will output
    33  		// $2 = $3 and drop any UL (unsigned long) suffixes
    34  		fields := strings.Fields(scanner.Text())
    35  		if len(fields) < 3 {
    36  			continue
    37  		}
    38  		if fields[0] != "#define" {
    39  			continue
    40  		}
    41  		// fields[1] (const name) needs to be 3 chars, starting with CK
    42  		if !strings.HasPrefix(fields[1], "CK") {
    43  			continue
    44  		}
    45  		value := strings.TrimSuffix(fields[2], "UL")
    46  		// special case for things like: (CKF_ARRAY_ATTRIBUTE|0x00000211UL)
    47  		if strings.HasSuffix(value, "UL)") {
    48  			value = strings.Replace(value, "UL)", ")", 1)
    49  		}
    50  		// CK_UNAVAILABLE_INFORMATION is encoded as (~0) (with UL) removed, this needs to be ^uint(0) in Go.
    51  		// Special case that here.
    52  		if value == "(~0)" {
    53  			value = "^uint(0)"
    54  		}
    55  
    56  		// check for /* deprecated */ comment
    57  		if len(fields) == 6 && fields[4] == "Deprecated" {
    58  			fmt.Fprintln(out, fields[1], " = ", value, "// Deprecated")
    59  			continue
    60  		}
    61  
    62  		fmt.Fprintln(out, fields[1], " = ", value)
    63  	}
    64  
    65  	if err := scanner.Err(); err != nil {
    66  		log.Fatal(err)
    67  	}
    68  	fmt.Fprintln(out, ")")
    69  	res, err := format.Source(out.Bytes())
    70  	if err != nil {
    71  		fmt.Fprintf(os.Stderr, out.String())
    72  		log.Fatal(err)
    73  	}
    74  	f, err := os.Create("zconst.go")
    75  	if err != nil {
    76  		log.Fatal(err)
    77  	}
    78  	f.Write(res)
    79  
    80  }
    81  
    82  const header = `// Copyright 2013 Miek Gieben. All rights reserved.
    83  // Use of this source code is governed by a BSD-style
    84  // license that can be found in the LICENSE file.
    85  
    86  // Code generated by "go run const_generate.go"; DO NOT EDIT.
    87  
    88  
    89  package pkcs11
    90  
    91  `
    92  

View as plain text