github.com/krzko/gosh@v0.0.0-20241128233202-5abd4ef06633/internal/shell/parser/parser.go (about)

     1  // internal/shell/parser/parser.go
     2  package parser
     3  
     4  import (
     5  	"errors"
     6  	"strings"
     7  
     8  	"github.com/krzko/gosh/internal/shell/executor"
     9  )
    10  
    11  type Parser struct{}
    12  
    13  func New() *Parser {
    14  	return &Parser{}
    15  }
    16  
    17  func (p *Parser) Parse(input string) (*executor.Command, error) {
    18  	if input == "" {
    19  		return nil, errors.New("empty input")
    20  	}
    21  
    22  	// Handle ".." as "cd .."
    23  	if input == ".." {
    24  		return &executor.Command{
    25  			Name: "cd",
    26  			Args: []string{".."},
    27  		}, nil
    28  	}
    29  
    30  	// Split the input into pipeline segments
    31  	pipeSegments := strings.Split(input, "|")
    32  	var currentCommand *executor.Command
    33  	var firstCommand *executor.Command
    34  
    35  	for i, segment := range pipeSegments {
    36  		// Trim spaces and split into command and args
    37  		parts := splitCommand(strings.TrimSpace(segment))
    38  		if len(parts) == 0 {
    39  			continue
    40  		}
    41  
    42  		command := &executor.Command{
    43  			Name: parts[0],
    44  			Args: parts[1:],
    45  		}
    46  
    47  		if i == 0 {
    48  			firstCommand = command
    49  			currentCommand = command
    50  		} else {
    51  			currentCommand.Pipe = command
    52  			currentCommand = command
    53  		}
    54  	}
    55  
    56  	return firstCommand, nil
    57  }
    58  
    59  // splitCommand splits a command string into command and arguments,
    60  // handling quoted strings and escaping
    61  func splitCommand(input string) []string {
    62  	var parts []string
    63  	var current strings.Builder
    64  	inQuotes := false
    65  	escapeNext := false
    66  
    67  	for _, char := range input {
    68  		if escapeNext {
    69  			current.WriteRune(char)
    70  			escapeNext = false
    71  			continue
    72  		}
    73  
    74  		switch char {
    75  		case '\\':
    76  			escapeNext = true
    77  		case '"':
    78  			inQuotes = !inQuotes
    79  		case ' ':
    80  			if !inQuotes {
    81  				if current.Len() > 0 {
    82  					parts = append(parts, current.String())
    83  					current.Reset()
    84  				}
    85  			} else {
    86  				current.WriteRune(char)
    87  			}
    88  		default:
    89  			current.WriteRune(char)
    90  		}
    91  	}
    92  
    93  	if current.Len() > 0 {
    94  		parts = append(parts, current.String())
    95  	}
    96  
    97  	return parts
    98  }