github.com/aitjcize/Overlord@v0.0.0-20240314041920-104a804cf5e8/overlord/utils.go (about)

     1  // Copyright 2015 The Chromium OS Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style license that can be
     3  // found in the LICENSE file.
     4  
     5  package overlord
     6  
     7  import (
     8  	"crypto/sha1"
     9  	"encoding/hex"
    10  	"errors"
    11  	"fmt"
    12  	"io"
    13  	"os"
    14  	"runtime"
    15  	"strconv"
    16  	"strings"
    17  	"syscall"
    18  )
    19  
    20  // ToVTNewLine replace the newline character to VT100 newline control.
    21  func ToVTNewLine(text string) string {
    22  	return strings.Replace(text, "\n", "\r\n", -1)
    23  }
    24  
    25  // GetPlatformString returns machine platform string.
    26  // Platform stream has the format of GOOS.GOARCH
    27  func GetPlatformString() string {
    28  	return fmt.Sprintf("%s.%s", runtime.GOOS, runtime.GOARCH)
    29  }
    30  
    31  // GetFileSha1 return the sha1sum of a file.
    32  func GetFileSha1(filename string) (string, error) {
    33  	f, err := os.Open(filename)
    34  	if err != nil {
    35  		return "", err
    36  	}
    37  	defer f.Close()
    38  
    39  	h := sha1.New()
    40  	if _, err = io.Copy(h, f); err != nil {
    41  		return "", err
    42  	}
    43  	return hex.EncodeToString(h.Sum(nil)), nil
    44  }
    45  
    46  // PollableProcess is a os.Process which supports the polling for it's status.
    47  type PollableProcess os.Process
    48  
    49  // Poll polls the process for it's execution status.
    50  func (p *PollableProcess) Poll() (uint32, error) {
    51  	var wstatus syscall.WaitStatus
    52  	pid, err := syscall.Wait4(p.Pid, &wstatus, syscall.WNOHANG, nil)
    53  	if err == nil && p.Pid == pid {
    54  		return uint32(wstatus), nil
    55  	}
    56  	return 0, errors.New("Wait4 failed")
    57  }
    58  
    59  // GetenvInt parse an integer from environment variable, and return default
    60  // value when error.
    61  func GetenvInt(key string, defaultValue int) int {
    62  	env := os.Getenv(key)
    63  	value, err := strconv.Atoi(env)
    64  	if err != nil {
    65  		return defaultValue
    66  	}
    67  	return value
    68  }