1// Copyright 2015 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// bpglob is the command line tool that checks if the list of files matching a glob has
16// changed, and only updates the output file list if it has changed.  It is used to optimize
17// out build.ninja regenerations when non-matching files are added.  See
18// github.com/google/blueprint/bootstrap/glob.go for a longer description.
19package main
20
21import (
22	"flag"
23	"fmt"
24	"io/ioutil"
25	"os"
26	"time"
27
28	"github.com/google/blueprint/pathtools"
29)
30
31var (
32	out = flag.String("o", "", "file to write list of files that match glob")
33
34	excludes multiArg
35)
36
37func init() {
38	flag.Var(&excludes, "e", "pattern to exclude from results")
39}
40
41type multiArg []string
42
43func (m *multiArg) String() string {
44	return `""`
45}
46
47func (m *multiArg) Set(s string) error {
48	*m = append(*m, s)
49	return nil
50}
51
52func (m *multiArg) Get() interface{} {
53	return m
54}
55
56func usage() {
57	fmt.Fprintln(os.Stderr, "usage: bpglob -o out glob")
58	flag.PrintDefaults()
59	os.Exit(2)
60}
61
62func main() {
63	flag.Parse()
64
65	if *out == "" {
66		fmt.Fprintln(os.Stderr, "error: -o is required")
67		usage()
68	}
69
70	if flag.NArg() != 1 {
71		usage()
72	}
73
74	_, err := pathtools.GlobWithDepFile(flag.Arg(0), *out, *out+".d", excludes)
75	if err != nil {
76		// Globs here were already run in the primary builder without error.  The only errors here should be if the glob
77		// pattern was made invalid by a change in the pathtools glob implementation, in which case the primary builder
78		// needs to be rerun anyways.  Update the output file with something that will always cause the primary builder
79		// to rerun.
80		s := fmt.Sprintf("%s: error: %s\n", time.Now().Format(time.StampNano), err.Error())
81		err := ioutil.WriteFile(*out, []byte(s), 0666)
82		if err != nil {
83			fmt.Fprintf(os.Stderr, "error: %s\n", err.Error())
84			os.Exit(1)
85		}
86	}
87}
88