github.com/goplus/gox@v1.14.13-0.20240308130321-6ff7f61cfae8/cpackages/pubfile.go (about)

     1  /*
     2   Copyright 2022 The GoPlus Authors (goplus.org)
     3   Licensed under the Apache License, Version 2.0 (the "License");
     4   you may not use this file except in compliance with the License.
     5   You may obtain a copy of the License at
     6       http://www.apache.org/licenses/LICENSE-2.0
     7   Unless required by applicable law or agreed to in writing, software
     8   distributed under the License is distributed on an "AS IS" BASIS,
     9   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    10   See the License for the specific language governing permissions and
    11   limitations under the License.
    12  */
    13  
    14  package cpackages
    15  
    16  import (
    17  	"fmt"
    18  	"os"
    19  	"sort"
    20  	"strings"
    21  )
    22  
    23  // ----------------------------------------------------------------------------
    24  
    25  func ReadPubFile(pubfile string) (ret map[string]string, err error) {
    26  	b, err := os.ReadFile(pubfile)
    27  	if err != nil {
    28  		if os.IsNotExist(err) {
    29  			return make(map[string]string), nil
    30  		}
    31  		return
    32  	}
    33  
    34  	text := string(b)
    35  	lines := strings.Split(text, "\n")
    36  	ret = make(map[string]string, len(lines))
    37  	for i, line := range lines {
    38  		flds := strings.Fields(line)
    39  		goName := ""
    40  		switch len(flds) {
    41  		case 1:
    42  		case 2:
    43  			goName = flds[1]
    44  		case 0:
    45  			continue
    46  		default:
    47  			err = fmt.Errorf("%s:%d: too many fields", pubfile, i+1)
    48  			return
    49  		}
    50  		ret[flds[0]] = goName
    51  	}
    52  	return
    53  }
    54  
    55  // ----------------------------------------------------------------------------
    56  
    57  func WritePubFile(file string, public map[string]string) (err error) {
    58  	if len(public) == 0 {
    59  		return
    60  	}
    61  	f, err := os.Create(file)
    62  	if err != nil {
    63  		return
    64  	}
    65  	defer f.Close()
    66  	ret := make([]string, 0, len(public))
    67  	for name, goName := range public {
    68  		if goName == "" {
    69  			ret = append(ret, name)
    70  		} else {
    71  			ret = append(ret, name+" "+goName)
    72  		}
    73  	}
    74  	sort.Strings(ret)
    75  	_, err = f.WriteString(strings.Join(ret, "\n"))
    76  	return
    77  }
    78  
    79  // ----------------------------------------------------------------------------