github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/utils/hasher/main.go (about)

     1  // Copyright 2023 Dolthub, Inc.
     2  //
     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  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package main
    16  
    17  import (
    18  	"fmt"
    19  	"os"
    20  	"strconv"
    21  
    22  	"github.com/dolthub/dolt/go/store/hash"
    23  )
    24  
    25  // hasher is a simple utility for converting between dolt base32 hashes and raw bytes. If you give it one argument,
    26  // the assumption is that it's a hash:
    27  //
    28  // $ hasher 201orjntip8jb6annkfsmiue9h4309k9
    29  // [16 3 141 206 253 150 81 53 153 87 189 31 203 75 206 76 72 48 38 137]
    30  //
    31  // If you give it multiple arguments, the assumption is that they're bytes. if you only specify a few bytes, the
    32  // tail will be 0s:
    33  //
    34  // $ hasher 16 3 141 206 253 150
    35  // 201orjnt000000000000000000000000
    36  //
    37  // Why? When you are looking at a byte array in the debugger and you need to know if it's a specific hash this
    38  // can help. base32 conversion in your head no longer required, which is what aaron always does.
    39  
    40  func main() {
    41  	if len(os.Args) == 1 {
    42  		fmt.Println("Usage: hasher <hash> OR hasher <uint8> <uint8> ...")
    43  		return
    44  	}
    45  
    46  	if len(os.Args) == 2 {
    47  		hashStr := os.Args[1]
    48  		if !hash.IsValid(hashStr) {
    49  			fmt.Println("Invalid hash")
    50  			return
    51  		}
    52  		h := hash.Parse(hashStr)
    53  		fmt.Printf("%v\n", h[:])
    54  	} else {
    55  		var raw hash.Hash
    56  
    57  		bytesGiven := len(os.Args) - 1
    58  
    59  		if bytesGiven > hash.ByteLen {
    60  			fmt.Println("Too many bytes given.")
    61  			return
    62  		}
    63  
    64  		for i := 1; i < bytesGiven; i++ {
    65  			val, err := strconv.ParseUint(os.Args[i], 10, 8)
    66  			if err != nil {
    67  				fmt.Println(err)
    68  				return
    69  			}
    70  			raw[i-1] = uint8(val)
    71  		}
    72  
    73  		fmt.Printf("%v\n", raw)
    74  	}
    75  }