...

Source file src/edge-infra.dev/pkg/tools/vset/path.go

Documentation: edge-infra.dev/pkg/tools/vset

     1  package vset
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"strings"
     7  )
     8  
     9  // The Path interface contains two functions: Validate() and Update().
    10  // Validate() validates the input path from Start().
    11  // Once validated, the path is passed to Update() to check if the .vscode directory and settings.json file exist.
    12  // If either of those items don't exist, Update() creates and adds them to the path.
    13  // The updated path is returned to Start().
    14  type Path interface {
    15  	Update(path string) string
    16  	Validate(path string)
    17  }
    18  
    19  func Update(path string) (string, error) {
    20  	// Assert that the path ends with a /.
    21  	if !strings.HasSuffix(path, "/") {
    22  		path = path + "/"
    23  	}
    24  
    25  	if err := Validate(path); err != nil {
    26  		return "", err
    27  	}
    28  	goLintPath = path
    29  	path = path + ".vscode"
    30  
    31  	// Check if .vscode directory exists and create it if it doesn't.
    32  	_, err := os.Stat(path)
    33  	if os.IsNotExist(err) {
    34  		err = os.MkdirAll(path, 0755)
    35  		if err != nil {
    36  			return "", fmt.Errorf("failed to create .vscode dir: %w", err)
    37  		}
    38  	}
    39  
    40  	path = path + "/settings.json"
    41  	_, err = os.ReadFile(path)
    42  
    43  	// If a user does not have a settings.json file, an empty one is created for configuration.
    44  	if err != nil {
    45  		err = os.WriteFile(path, []byte(`{}`), 0644)
    46  		if err != nil {
    47  			return "", fmt.Errorf("failed to create settings.json: %w", err)
    48  		}
    49  	}
    50  	return path, nil
    51  }
    52  
    53  func Validate(path string) error {
    54  	// Validate the path.
    55  	_, err := os.Stat(path)
    56  	if os.IsNotExist(err) {
    57  		return fmt.Errorf("invalid path: %w", err)
    58  	}
    59  	return nil
    60  }
    61  

View as plain text