github.com/distbuild/reclient@v0.0.0-20240401075343-3de72e395564/pkg/inputprocessor/fake/executor.go (about)

     1  // Copyright 2023 Google LLC
     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  
    15  // Package fake defines fakes to be used for testing integration with the input processor.
    16  package fake
    17  
    18  import (
    19  	"context"
    20  	"fmt"
    21  
    22  	"github.com/bazelbuild/remote-apis-sdks/go/pkg/command"
    23  )
    24  
    25  // ClangExecutor is a fake executor used to replace actual execution of clang in the process of
    26  // determining inputs.
    27  type ClangExecutor struct {
    28  	InputFiles     []string
    29  	ToolchainFiles []string
    30  	Err            error
    31  }
    32  
    33  // Execute fakes execution of a command and returns outputs predefined in the ClangExecutor.
    34  func (e *ClangExecutor) Execute(ctx context.Context, cmd *command.Command) (string, string, error) {
    35  	for _, arg := range cmd.Args {
    36  		if arg == "-M" {
    37  			return e.clangInputFiles(), "", e.Err
    38  		} else if arg == "strace" {
    39  			return e.clangStraceFiles(), "", e.Err
    40  		}
    41  	}
    42  	return "", "", e.Err
    43  }
    44  
    45  func (e *ClangExecutor) clangInputFiles() string {
    46  	out := ""
    47  	seps := []string{"\n", " ", ":", "\r"}
    48  	idx := 0
    49  	for _, i := range e.InputFiles {
    50  		out += i + seps[idx]
    51  		idx = (idx + 1) % len(seps)
    52  	}
    53  	return out
    54  }
    55  
    56  func (e *ClangExecutor) clangStraceFiles() string {
    57  	out := ""
    58  	pfx := []string{"\n", " ", ":", "\r"}
    59  	idx := 0
    60  	for _, i := range e.ToolchainFiles {
    61  		out += fmt.Sprintf("%v%q, \"O_RDONLY|O_CLOEXEC\") = 0", pfx[idx], i)
    62  		idx = (idx + 1) % len(pfx)
    63  	}
    64  	return out
    65  }