Home | History | Annotate | Download | only in deptools
      1 // Copyright 2014 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 
     15 package deptools
     16 
     17 import (
     18 	"fmt"
     19 	"os"
     20 	"strings"
     21 )
     22 
     23 var (
     24 	pathEscaper = strings.NewReplacer(
     25 		`\`, `\\`,
     26 		` `, `\ `,
     27 		`#`, `\#`,
     28 		`*`, `\*`,
     29 		`[`, `\[`,
     30 		`|`, `\|`)
     31 )
     32 
     33 // WriteDepFile creates a new gcc-style depfile and populates it with content
     34 // indicating that target depends on deps.
     35 func WriteDepFile(filename, target string, deps []string) error {
     36 	f, err := os.Create(filename)
     37 	if err != nil {
     38 		return err
     39 	}
     40 	defer f.Close()
     41 
     42 	var escapedDeps []string
     43 
     44 	for _, dep := range deps {
     45 		escapedDeps = append(escapedDeps, pathEscaper.Replace(dep))
     46 	}
     47 
     48 	_, err = fmt.Fprintf(f, "%s: \\\n %s\n", target,
     49 		strings.Join(escapedDeps, " \\\n "))
     50 	if err != nil {
     51 		return err
     52 	}
     53 
     54 	return nil
     55 }
     56