Unable runTest For cat-file command

I’m stuck on Stage #yt5.

I’ve tried to parse the escape character and i work’s fine for most of the test cases but on Writing file “/tmp/quz/f\n48” it’s not passing the file writing part .

Here are my logs:

[your-program] $ cat "/tmp/quz/f\n48" "/tmp/quz/f\20" "/tmp/quz/f'\'69"
[your-program] cat: /tmp/quz/fn48: No such file or directory
[tester::#YT5] Output does not match expected value.
[tester::#YT5] Expected: "pear strawberry.mango orange.strawberry pineapple."
[tester::#YT5] Received: "cat: /tmp/quz/fn48: No such file or directory"
[your-program] cat: /tmp/quz/f20: No such file or directory
[your-program] cat: /tmp/quz/f''69: No such file or directory
[your-program] $
[tester::#YT5] Assertion failed.
[tester::#YT5] Test failed

And here’s a snippet of my code:

func executeCommand(input string) {
	input = strings.ReplaceAll(input, "\\\n", "")

	commands := strings.Trim(input, "\r\n")

	args, err := parseArgs(commands)
.
.
.
}

func parseArgs(input string) ([]string, error) {
	var args []string
	var currentArg strings.Builder
	currentArg.Grow(len(input))
	inSingleQuote := false
	inDoubleQuote := false

	for i := 0; i < len(input); i++ {
		char := input[i]

		switch char {

		case '\'':
			if inDoubleQuote {
				currentArg.WriteByte(char)
			} else {
				inSingleQuote = !inSingleQuote
			}
		case '"':
			if inSingleQuote {
				currentArg.WriteByte(char)
			} else {
				inDoubleQuote = !inDoubleQuote
			}
		case ' ':
			if inSingleQuote || inDoubleQuote {
				currentArg.WriteByte(char)
			} else if currentArg.Len() > 0 {
				args = append(args, currentArg.String())
				currentArg.Reset()
			}
		case '\\':
			if i+1 < len(input) {
				nextChar := input[i+1]
				if nextChar == ' ' {
					currentArg.WriteByte(' ')
				} else {

					currentArg.WriteByte(nextChar)
				}
				i++
			} else {
				currentArg.WriteByte(char)
			}

		default:
			currentArg.WriteByte(char)

		}
	}

	if currentArg.Len() > 0 {
		args = append(args, currentArg.String())
	}

	if inSingleQuote || inDoubleQuote {
		return nil, fmt.Errorf("unmatched quote")
	}

	return args, nil

}

Hi @amanuell2, it seems the current code doesn’t differentiate between being inside and outside of quotes:

$ cat “/tmp/quz/f\n48” “/tmp/quz/f\20” “/tmp/quz/f’'69”
cat: /tmp/quz/fn48: No such file or directory

Suggestions:

  1. Try to differentiate inside and outside.
  2. Don’t remove \ inside quotes.
case '\\':
// this if case was the thing i missed (big thanks to @andy1li 
			if inDoubleQuote || inSingleQuote {
				currentArg.WriteByte(char)
			}
			if i+1 < len(input) {
				nextChar := input[i+1]
				if nextChar == ' ' {
					currentArg.WriteByte(' ')
				} else {
					currentArg.WriteByte(nextChar)
				}
				i++
			}
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.