blob: e8ff4b2c9541fa78b7407e83602b073a23aff085 [file] [log] [blame]
Colin Crossfd708b52021-03-23 14:16:05 -07001// Copyright 2021 Google Inc. All rights reserved.
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
15package response
16
17import (
18 "io"
19 "io/ioutil"
20 "unicode"
21)
22
23const noQuote = '\x00'
24
25// ReadRspFile reads a file in Ninja's response file format and returns its contents.
26func ReadRspFile(r io.Reader) ([]string, error) {
27 var files []string
28 var file []byte
29
30 buf, err := ioutil.ReadAll(r)
31 if err != nil {
32 return nil, err
33 }
34
35 isEscaping := false
36 quotingStart := byte(noQuote)
37 for _, c := range buf {
38 switch {
39 case isEscaping:
40 if quotingStart == '"' {
41 if !(c == '"' || c == '\\') {
42 // '\"' or '\\' will be escaped under double quoting.
43 file = append(file, '\\')
44 }
45 }
46 file = append(file, c)
47 isEscaping = false
48 case c == '\\' && quotingStart != '\'':
49 isEscaping = true
50 case quotingStart == noQuote && (c == '\'' || c == '"'):
51 quotingStart = c
52 case quotingStart != noQuote && c == quotingStart:
53 quotingStart = noQuote
54 case quotingStart == noQuote && unicode.IsSpace(rune(c)):
55 // Current character is a space outside quotes
56 if len(file) != 0 {
57 files = append(files, string(file))
58 }
59 file = file[:0]
60 default:
61 file = append(file, c)
62 }
63 }
64
65 if len(file) != 0 {
66 files = append(files, string(file))
67 }
68
69 return files, nil
70}