<commit_before>/* Copyright 2016 The Bazel Authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Command gazelle is a BUILD file generator for Go projects.
// See "gazelle --help" for more details.
package main

import (
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"

	bzl "github.com/bazelbuild/buildifier/build"
	"github.com/bazelbuild/rules_go/go/tools/gazelle/generator"
	"github.com/bazelbuild/rules_go/go/tools/gazelle/merger"
	"github.com/bazelbuild/rules_go/go/tools/gazelle/rules"
	"github.com/bazelbuild/rules_go/go/tools/gazelle/wspace"
)

var (
	buildFileName  = flag.String("build_file_name", "BUILD", "name of output build files to generate.")
	buildTags      = flag.String("build_tags", "", "comma-separated list of build tags. If not specified, GOOS and GOARCH are used.")
	external       = flag.String("external", "external", "external: resolve external packages with new_go_repository\n\tvendored: resolve external packages as packages in vendor/")
	goPrefix       = flag.String("go_prefix", "", "go_prefix of the target workspace")
	repoRoot       = flag.String("repo_root", "", "path to a directory which corresponds to go_prefix, otherwise gazelle searches for it.")
	mode           = flag.String("mode", "fix", "print: prints all of the updated BUILD files\n\tfix: rewrites all of the BUILD files in place\n\tdiff: computes the rewrite but then just does a diff")
	buildFileNames = []string{"BUILD.bazel", "BUILD"}
)

func init() {
	// See also #135.
	// TODO(yugui): Remove this flag when we drop support of Bazel 0.3.2
	flag.StringVar(&generator.GoRulesBzl, "go_rules_bzl_only_for_internal_use", "@io_bazel_rules_go//go:def.bzl", "hacky flag to build rules_go repository itself")
}

var externalResolverFromName = map[string]rules.ExternalResolver{
	"external": rules.External,
	"vendored": rules.Vendored,
}

var modeFromName = map[string]func(*bzl.File) error{
	"print": printFile,
	"fix":   fixFile,
	"diff":  diffFile,
}

func isValidBuildFileName(buildFileName string) bool {
	for _, bfn := range buildFileNames {
		if buildFileName == bfn {
			return true
		}
	}
	return false
}

func run(dirs []string, emit func(*bzl.File) error, external rules.ExternalResolver) error {
	g, err := generator.New(*repoRoot, *goPrefix, *buildFileName, *buildTags, external)
	if err != nil {
		return err
	}

	for _, d := range dirs {
		files, err := g.Generate(d)
		if err != nil {
			return err
		}
		for _, f := range files {
			f.Path = filepath.Join(*repoRoot, f.Path)
			existingFilePath, err := findBuildFile(filepath.Dir(f.Path))
			if os.IsNotExist(err) {
				// No existing file, so write a new one
				bzl.Rewrite(f, nil) // have buildifier 'format' our rules.
				if err := emit(f); err != nil {
					return err
				}
				continue
			}
			if err != nil {
				// An unexpected error
				return err
			}
			// Existing file, so merge and maybe remove the old one
			if f, err = merger.MergeWithExisting(f, existingFilePath); err != nil {
				if _, ok := err.(merger.GazelleIgnoreError); ok {
					// found gazelle:ignore comment. Do not rewrite.
					continue
				}
				return err
			}
			bzl.Rewrite(f, nil) // have buildifier 'format' our rules.
			if err := emit(f); err != nil {
				return err
			}
			if f.Path != existingFilePath {
				if err := os.Remove(existingFilePath); err != nil {
					return err
				}
			}
		}
	}
	return nil
}<commit_msg>gazelle: only rename BUILD files in "fix" mode (#343)<commit_after>/* Copyright 2016 The Bazel Authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Command gazelle is a BUILD file generator for Go projects.
// See "gazelle --help" for more details.
package main

import (
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"

	bzl "github.com/bazelbuild/buildifier/build"
	"github.com/bazelbuild/rules_go/go/tools/gazelle/generator"
	"github.com/bazelbuild/rules_go/go/tools/gazelle/merger"
	"github.com/bazelbuild/rules_go/go/tools/gazelle/rules"
	"github.com/bazelbuild/rules_go/go/tools/gazelle/wspace"
)

var (
	buildFileName  = flag.String("build_file_name", "BUILD", "name of output build files to generate.")
	buildTags      = flag.String("build_tags", "", "comma-separated list of build tags. If not specified, GOOS and GOARCH are used.")
	external       = flag.String("external", "external", "external: resolve external packages with new_go_repository\n\tvendored: resolve external packages as packages in vendor/")
	goPrefix       = flag.String("go_prefix", "", "go_prefix of the target workspace")
	repoRoot       = flag.String("repo_root", "", "path to a directory which corresponds to go_prefix, otherwise gazelle searches for it.")
	mode           = flag.String("mode", "fix", "print: prints all of the updated BUILD files\n\tfix: rewrites all of the BUILD files in place\n\tdiff: computes the rewrite but then just does a diff")
	buildFileNames = []string{"BUILD.bazel", "BUILD"}
)

func init() {
	// See also #135.
	// TODO(yugui): Remove this flag when we drop support of Bazel 0.3.2
	flag.StringVar(&generator.GoRulesBzl, "go_rules_bzl_only_for_internal_use", "@io_bazel_rules_go//go:def.bzl", "hacky flag to build rules_go repository itself")
}

var externalResolverFromName = map[string]rules.ExternalResolver{
	"external": rules.External,
	"vendored": rules.Vendored,
}

var modeFromName = map[string]func(*bzl.File) error{
	"print": printFile,
	"fix":   fixFile,
	"diff":  diffFile,
}

func isValidBuildFileName(buildFileName string) bool {
	for _, bfn := range buildFileNames {
		if buildFileName == bfn {
			return true
		}
	}
	return false
}

func run(dirs []string, emit func(*bzl.File) error, external rules.ExternalResolver) error {
	g, err := generator.New(*repoRoot, *goPrefix, *buildFileName, *buildTags, external)
	if err != nil {
		return err
	}

	for _, d := range dirs {
		files, err := g.Generate(d)
		if err != nil {
			return err
		}
		for _, f := range files {
			f.Path = filepath.Join(*repoRoot, f.Path)
			existingFilePath, err := findBuildFile(filepath.Dir(f.Path))
			if os.IsNotExist(err) {
				// No existing file, so write a new one
				bzl.Rewrite(f, nil) // have buildifier 'format' our rules.
				if err := emit(f); err != nil {
					return err
				}
				continue
			}
			if err != nil {
				// An unexpected error
				return err
			}
			// Existing file, so merge and maybe remove the old one
			if f, err = merger.MergeWithExisting(f, existingFilePath); err != nil {
				if _, ok := err.(merger.GazelleIgnoreError); ok {
					// found gazelle:ignore comment. Do not rewrite.
					continue
				}
				return err
			}
			bzl.Rewrite(f, nil) // have buildifier 'format' our rules.
			if err := emit(f); err != nil {
				return err
			}
			if *mode == "fix" && f.Path != existingFilePath {
				if err := os.Remove(existingFilePath); err != nil {
					return err
				}
			}
		}
	}
	return nil
}
{'fraction_non_alphanumeric': 0.11698352344740177, 'fraction_numerical': 0.0039290240811153355, 'mean_word_length': 3.6390358612580833, 'pattern_counts': {'":': 10, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3845697', 'n_tokens_mistral': 2806, 'n_tokens_neox': 2531, 'n_words': 820}