github.com/rcowham/go-libgitfastimport@v0.1.6/util.go (about)

     1  // Copyright (C) 2017, 2021  Luke Shumaker <lukeshu@lukeshu.com>
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as published by
     5  // the Free Software Foundation, either version 3 of the License, or
     6  // (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <https://www.gnu.org/licenses/>.
    15  
    16  package libfastimport
    17  
    18  import (
    19  	"fmt"
    20  	"strconv"
    21  	"strings"
    22  
    23  	"github.com/pkg/errors"
    24  )
    25  
    26  func trimLinePrefix(line string, prefix string) string {
    27  	if !strings.HasPrefix(line, prefix) {
    28  		n := 80
    29  		if len(line) < n {
    30  			n = len(line)
    31  		}
    32  		panic(fmt.Sprintf("line didn't have prefix: %s", line[:n]))
    33  	}
    34  	if !strings.HasSuffix(line, "\n") {
    35  		panic("line didn't have LF")
    36  	}
    37  	return strings.TrimSuffix(strings.TrimPrefix(line, prefix), "\n")
    38  }
    39  
    40  func parse_data(line string) (data string, err error) {
    41  	nl := strings.IndexByte(line, '\n')
    42  	if nl < 0 {
    43  		return "", errors.Errorf("data: expected newline: %q", data)
    44  	}
    45  	head := line[:nl+1]
    46  	rest := line[nl+1:]
    47  	if !strings.HasPrefix(head, "data ") {
    48  		return "", errors.Errorf("data: could not parse: %q", data)
    49  	}
    50  	if strings.HasPrefix(head, "data <<") {
    51  		// Delimited format
    52  		delim := trimLinePrefix(head, "data <<")
    53  		suffix := "\n" + delim + "\n"
    54  		if !strings.HasSuffix(rest, suffix) {
    55  			return "", errors.Errorf("data: did not find suffix: %q", suffix)
    56  		}
    57  		data = strings.TrimSuffix(rest, suffix)
    58  	} else {
    59  		// Exact byte count format
    60  		size, err := strconv.Atoi(trimLinePrefix(head, "data "))
    61  		if err != nil {
    62  			return "", err
    63  		}
    64  		if size != len(rest) {
    65  			panic("FIReader should not have let this happen")
    66  		}
    67  		data = rest
    68  	}
    69  	return
    70  }