clang-tools 19.0.0git
ClangApplyReplacementsMain.cpp
Go to the documentation of this file.
1//===-- ClangApplyReplacementsMain.cpp - Main file for the tool -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file provides the main function for the
11/// clang-apply-replacements tool.
12///
13//===----------------------------------------------------------------------===//
14
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/DiagnosticOptions.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/Version.h"
20#include "clang/Format/Format.h"
21#include "clang/Rewrite/Core/Rewriter.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/StringSet.h"
24#include "llvm/Support/CommandLine.h"
25
26using namespace llvm;
27using namespace clang;
28using namespace clang::replace;
29
30static cl::opt<std::string> Directory(cl::Positional, cl::Required,
31 cl::desc("<Search Root Directory>"));
32
33static cl::OptionCategory ReplacementCategory("Replacement Options");
34static cl::OptionCategory FormattingCategory("Formatting Options");
35
36const cl::OptionCategory *VisibleCategories[] = {&ReplacementCategory,
38
39static cl::opt<bool> RemoveTUReplacementFiles(
40 "remove-change-desc-files",
41 cl::desc("Remove the change description files regardless of successful\n"
42 "merging/replacing."),
43 cl::init(false), cl::cat(ReplacementCategory));
44
45static cl::opt<bool> IgnoreInsertConflict(
46 "ignore-insert-conflict",
47 cl::desc("Ignore insert conflict and keep running to fix."),
48 cl::init(false), cl::cat(ReplacementCategory));
49
50static cl::opt<bool> DoFormat(
51 "format",
52 cl::desc("Enable formatting of code changed by applying replacements.\n"
53 "Use -style to choose formatting style.\n"),
54 cl::cat(FormattingCategory));
55
56// FIXME: Consider making the default behaviour for finding a style
57// configuration file to start the search anew for every file being changed to
58// handle situations where the style is different for different parts of a
59// project.
60
61static cl::opt<std::string> FormatStyleConfig(
62 "style-config",
63 cl::desc("Path to a directory containing a .clang-format file\n"
64 "describing a formatting style to use for formatting\n"
65 "code when -style=file.\n"),
66 cl::init(""), cl::cat(FormattingCategory));
67
68static cl::opt<std::string>
69 FormatStyleOpt("style", cl::desc(format::StyleOptionHelpDescription),
70 cl::init("LLVM"), cl::cat(FormattingCategory));
71
72namespace {
73// Helper object to remove the TUReplacement and TUDiagnostic (triggered by
74// "remove-change-desc-files" command line option) when exiting current scope.
75class ScopedFileRemover {
76public:
77 ScopedFileRemover(const TUReplacementFiles &Files,
78 clang::DiagnosticsEngine &Diagnostics)
79 : TURFiles(Files), Diag(Diagnostics) {}
80
81 ~ScopedFileRemover() { deleteReplacementFiles(TURFiles, Diag); }
82
83private:
84 const TUReplacementFiles &TURFiles;
85 clang::DiagnosticsEngine &Diag;
86};
87} // namespace
88
89static void printVersion(raw_ostream &OS) {
90 OS << "clang-apply-replacements version " CLANG_VERSION_STRING << "\n";
91}
92
93int main(int argc, char **argv) {
94 cl::HideUnrelatedOptions(ArrayRef(VisibleCategories));
95
96 cl::SetVersionPrinter(printVersion);
97 cl::ParseCommandLineOptions(argc, argv);
98
99 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions());
100 DiagnosticsEngine Diagnostics(
101 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), DiagOpts.get());
102
103 // Determine a formatting style from options.
104 auto FormatStyleOrError = format::getStyle(FormatStyleOpt, FormatStyleConfig,
105 format::DefaultFallbackStyle);
106 if (!FormatStyleOrError) {
107 llvm::errs() << llvm::toString(FormatStyleOrError.takeError()) << "\n";
108 return 1;
109 }
110 format::FormatStyle FormatStyle = std::move(*FormatStyleOrError);
111
112 TUReplacements TURs;
113 TUReplacementFiles TUFiles;
114
115 std::error_code ErrorCode =
117
118 TUDiagnostics TUDs;
119 TUFiles.clear();
120 ErrorCode =
122
123 if (ErrorCode) {
124 errs() << "Trouble iterating over directory '" << Directory
125 << "': " << ErrorCode.message() << "\n";
126 return 1;
127 }
128
129 // Remove the TUReplacementFiles (triggered by "remove-change-desc-files"
130 // command line option) when exiting main().
131 std::unique_ptr<ScopedFileRemover> Remover;
133 Remover.reset(new ScopedFileRemover(TUFiles, Diagnostics));
134
135 FileManager Files((FileSystemOptions()));
136 SourceManager SM(Diagnostics, Files);
137
139 if (!mergeAndDeduplicate(TURs, TUDs, Changes, SM, IgnoreInsertConflict))
140 return 1;
141
142 tooling::ApplyChangesSpec Spec;
143 Spec.Cleanup = true;
144 Spec.Format = DoFormat ? tooling::ApplyChangesSpec::kAll
145 : tooling::ApplyChangesSpec::kNone;
146 Spec.Style = DoFormat ? FormatStyle : format::getNoStyle();
147
148 for (const auto &FileChange : Changes) {
149 FileEntryRef Entry = FileChange.first;
150 StringRef FileName = Entry.getName();
151 llvm::Expected<std::string> NewFileData =
152 applyChanges(FileName, FileChange.second, Spec, Diagnostics);
153 if (!NewFileData) {
154 errs() << llvm::toString(NewFileData.takeError()) << "\n";
155 continue;
156 }
157
158 // Write new file to disk
159 std::error_code EC;
160 llvm::raw_fd_ostream FileStream(FileName, EC, llvm::sys::fs::OF_None);
161 if (EC) {
162 llvm::errs() << "Could not open " << FileName << " for writing\n";
163 continue;
164 }
165 FileStream << *NewFileData;
166 }
167
168 return 0;
169}
This file provides the interface for deduplicating, detecting conflicts in, and applying collections ...
static cl::OptionCategory FormattingCategory("Formatting Options")
const cl::OptionCategory * VisibleCategories[]
static cl::opt< std::string > FormatStyleOpt("style", cl::desc(format::StyleOptionHelpDescription), cl::init("LLVM"), cl::cat(FormattingCategory))
int main(int argc, char **argv)
static cl::opt< bool > DoFormat("format", cl::desc("Enable formatting of code changed by applying replacements.\n" "Use -style to choose formatting style.\n"), cl::cat(FormattingCategory))
static cl::opt< std::string > FormatStyleConfig("style-config", cl::desc("Path to a directory containing a .clang-format file\n" "describing a formatting style to use for formatting\n" "code when -style=file.\n"), cl::init(""), cl::cat(FormattingCategory))
static void printVersion(raw_ostream &OS)
static cl::opt< bool > IgnoreInsertConflict("ignore-insert-conflict", cl::desc("Ignore insert conflict and keep running to fix."), cl::init(false), cl::cat(ReplacementCategory))
static cl::OptionCategory ReplacementCategory("Replacement Options")
static cl::opt< bool > RemoveTUReplacementFiles("remove-change-desc-files", cl::desc("Remove the change description files regardless of successful\n" "merging/replacing."), cl::init(false), cl::cat(ReplacementCategory))
static cl::opt< std::string > FormatStyle("format-style", desc(R"( Style for formatting code around applied fixes: - 'none' (default) turns off formatting - 'file' (literally 'file', not a placeholder) uses .clang-format file in the closest parent directory - '{ <json> }' specifies options inline, e.g. -format-style='{BasedOnStyle: llvm, IndentWidth: 8}' - 'llvm', 'google', 'webkit', 'mozilla' See clang-format documentation for the up-to-date information about formatting styles and options. This option overrides the 'FormatStyle` option in .clang-tidy file, if any. )"), cl::init("none"), cl::cat(ClangTidyCategory))
tooling::Replacements Changes
Definition: Format.cpp:109
StringRef FileName
llvm::StringRef Directory
WantDiagnostics Diagnostics
llvm::raw_string_ostream OS
Definition: TraceTests.cpp:160
llvm::DenseMap< clang::FileEntryRef, std::vector< tooling::AtomicChange > > FileToChangesMap
Map mapping file name to a set of AtomicChange targeting that file.
bool mergeAndDeduplicate(const TUReplacements &TUs, const TUDiagnostics &TUDs, FileToChangesMap &FileChanges, clang::SourceManager &SM, bool IgnoreInsertConflict=false)
Deduplicate, check for conflicts, and extract all Replacements stored in TUs.
bool deleteReplacementFiles(const TUReplacementFiles &Files, clang::DiagnosticsEngine &Diagnostics)
Delete the replacement files.
std::error_code collectReplacementsFromDirectory(const llvm::StringRef Directory, TranslationUnits &TUs, TUReplacementFiles &TUFiles, clang::DiagnosticsEngine &Diagnostics)=delete
Recursively descends through a directory structure rooted at Directory and attempts to deserialize *....
std::vector< clang::tooling::TranslationUnitReplacements > TUReplacements
Collection of TranslationUnitReplacements.
std::vector< std::string > TUReplacementFiles
Collection of TranslationUnitReplacement files.
llvm::Expected< std::string > applyChanges(StringRef File, const std::vector< tooling::AtomicChange > &Changes, const tooling::ApplyChangesSpec &Spec, DiagnosticsEngine &Diagnostics)
Apply AtomicChange on File and rewrite it.
std::vector< clang::tooling::TranslationUnitDiagnostics > TUDiagnostics
Collection of TranslationUniDiagnostics.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Some operations such as code completion produce a set of candidates.