github.com/distbuild/reclient@v0.0.0-20240401075343-3de72e395564/internal/pkg/inputprocessor/action/headerabi/flagsparser.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 headerabi
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  
    21  	"github.com/bazelbuild/reclient/internal/pkg/inputprocessor/args"
    22  	"github.com/bazelbuild/reclient/internal/pkg/inputprocessor/clangparser"
    23  	"github.com/bazelbuild/reclient/internal/pkg/inputprocessor/flags"
    24  )
    25  
    26  // Parser parses clang command args to produce a CommandFlags object.
    27  type Parser struct{}
    28  
    29  var (
    30  	abiFlags map[string]int
    31  )
    32  
    33  func init() {
    34  	abiFlags = clangparser.ClangOptions
    35  	abiFlags["--root-dir"] = 1
    36  }
    37  
    38  // ParseFlags is used to translate the given action command into clang compiler
    39  // options, so that they can be used during input processing.
    40  // Android build, throw error for unsupported flags.
    41  func (h Parser) ParseFlags(ctx context.Context, command []string, workingDir, execRoot string) (*flags.CommandFlags, error) {
    42  	numArgs := len(command)
    43  	if numArgs < 2 {
    44  		return nil, fmt.Errorf("insufficient number of arguments in command: %v", command)
    45  	}
    46  
    47  	res := &flags.CommandFlags{
    48  		ExecutablePath:   command[0],
    49  		TargetFilePaths:  []string{},
    50  		WorkingDirectory: workingDir,
    51  		ExecRoot:         execRoot,
    52  	}
    53  	var state clangparser.State
    54  	s := args.Scanner{
    55  		Args:       command[1:],
    56  		Flags:      abiFlags,
    57  		Joined:     clangparser.ClangPrefixes,
    58  		Normalized: clangparser.ClangNormalizedFlags,
    59  	}
    60  	defer state.Finalize(res)
    61  	for s.HasNext() {
    62  		nr := s.ReadNextFlag()
    63  		if nr.NormalizedKey == "root-dir" || nr.OriginalKey == "--" {
    64  			continue
    65  		}
    66  		if err := state.HandleClangFlags(nr, res, false); err != nil {
    67  			return res, err
    68  		}
    69  	}
    70  	return res, nil
    71  }