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 
15 #include "clang-apply-replacements/Tooling/ApplyReplacements.h"
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 
26 using namespace llvm;
27 using namespace clang;
28 using namespace clang::replace;
29 
30 static cl::opt<std::string> Directory(cl::Positional, cl::Required,
31                                       cl::desc("<Search Root Directory>"));
32 
33 static cl::OptionCategory ReplacementCategory("Replacement Options");
34 static cl::OptionCategory FormattingCategory("Formatting Options");
35 
36 const cl::OptionCategory *VisibleCategories[] = {&ReplacementCategory,
37                                                  &FormattingCategory};
38 
39 static 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 
45 static cl::opt<bool> DoFormat(
46     "format",
47     cl::desc("Enable formatting of code changed by applying replacements.\n"
48              "Use -style to choose formatting style.\n"),
49     cl::cat(FormattingCategory));
50 
51 // FIXME: Consider making the default behaviour for finding a style
52 // configuration file to start the search anew for every file being changed to
53 // handle situations where the style is different for different parts of a
54 // project.
55 
56 static cl::opt<std::string> FormatStyleConfig(
57     "style-config",
58     cl::desc("Path to a directory containing a .clang-format file\n"
59              "describing a formatting style to use for formatting\n"
60              "code when -style=file.\n"),
61     cl::init(""), cl::cat(FormattingCategory));
62 
63 static cl::opt<std::string>
64     FormatStyleOpt("style", cl::desc(format::StyleOptionHelpDescription),
65                    cl::init("LLVM"), cl::cat(FormattingCategory));
66 
67 namespace {
68 // Helper object to remove the TUReplacement and TUDiagnostic (triggered by
69 // "remove-change-desc-files" command line option) when exiting current scope.
70 class ScopedFileRemover {
71 public:
ScopedFileRemover(const TUReplacementFiles & Files,clang::DiagnosticsEngine & Diagnostics)72   ScopedFileRemover(const TUReplacementFiles &Files,
73                     clang::DiagnosticsEngine &Diagnostics)
74       : TURFiles(Files), Diag(Diagnostics) {}
75 
~ScopedFileRemover()76   ~ScopedFileRemover() { deleteReplacementFiles(TURFiles, Diag); }
77 
78 private:
79   const TUReplacementFiles &TURFiles;
80   clang::DiagnosticsEngine &Diag;
81 };
82 } // namespace
83 
printVersion(raw_ostream & OS)84 static void printVersion(raw_ostream &OS) {
85   OS << "clang-apply-replacements version " CLANG_VERSION_STRING << "\n";
86 }
87 
main(int argc,char ** argv)88 int main(int argc, char **argv) {
89   cl::HideUnrelatedOptions(makeArrayRef(VisibleCategories));
90 
91   cl::SetVersionPrinter(printVersion);
92   cl::ParseCommandLineOptions(argc, argv);
93 
94   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions());
95   DiagnosticsEngine Diagnostics(
96       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), DiagOpts.get());
97 
98   // Determine a formatting style from options.
99   auto FormatStyleOrError = format::getStyle(FormatStyleOpt, FormatStyleConfig,
100                                              format::DefaultFallbackStyle);
101   if (!FormatStyleOrError) {
102     llvm::errs() << llvm::toString(FormatStyleOrError.takeError()) << "\n";
103     return 1;
104   }
105   format::FormatStyle FormatStyle = std::move(*FormatStyleOrError);
106 
107   TUReplacements TURs;
108   TUReplacementFiles TUFiles;
109 
110   std::error_code ErrorCode =
111       collectReplacementsFromDirectory(Directory, TURs, TUFiles, Diagnostics);
112 
113   TUDiagnostics TUDs;
114   TUFiles.clear();
115   ErrorCode =
116       collectReplacementsFromDirectory(Directory, TUDs, TUFiles, Diagnostics);
117 
118   if (ErrorCode) {
119     errs() << "Trouble iterating over directory '" << Directory
120            << "': " << ErrorCode.message() << "\n";
121     return 1;
122   }
123 
124   // Remove the TUReplacementFiles (triggered by "remove-change-desc-files"
125   // command line option) when exiting main().
126   std::unique_ptr<ScopedFileRemover> Remover;
127   if (RemoveTUReplacementFiles)
128     Remover.reset(new ScopedFileRemover(TUFiles, Diagnostics));
129 
130   FileManager Files((FileSystemOptions()));
131   SourceManager SM(Diagnostics, Files);
132 
133   FileToChangesMap Changes;
134   if (!mergeAndDeduplicate(TURs, TUDs, Changes, SM))
135     return 1;
136 
137   tooling::ApplyChangesSpec Spec;
138   Spec.Cleanup = true;
139   Spec.Style = FormatStyle;
140   Spec.Format = DoFormat ? tooling::ApplyChangesSpec::kAll
141                          : tooling::ApplyChangesSpec::kNone;
142 
143   for (const auto &FileChange : Changes) {
144     const FileEntry *Entry = FileChange.first;
145     StringRef FileName = Entry->getName();
146     llvm::Expected<std::string> NewFileData =
147         applyChanges(FileName, FileChange.second, Spec, Diagnostics);
148     if (!NewFileData) {
149       errs() << llvm::toString(NewFileData.takeError()) << "\n";
150       continue;
151     }
152 
153     // Write new file to disk
154     std::error_code EC;
155     llvm::raw_fd_ostream FileStream(FileName, EC, llvm::sys::fs::OF_None);
156     if (EC) {
157       llvm::errs() << "Could not open " << FileName << " for writing\n";
158       continue;
159     }
160     FileStream << *NewFileData;
161   }
162 
163   return 0;
164 }
165