blob: de2f9d7fe76e1c898c359ac8a929ad4a37cf0efc [file] [log] [blame]
djasper7f663602013-03-20 09:53:23 +00001//===-- clang-format/ClangFormat.cpp - Clang format tool ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
adrian78220842018-05-09 01:00:01 +000011/// This file implements a clang-format tool that automatically formats
djasper7f663602013-03-20 09:53:23 +000012/// (fragments of) C++ code.
13///
14//===----------------------------------------------------------------------===//
15
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/DiagnosticOptions.h"
18#include "clang/Basic/FileManager.h"
19#include "clang/Basic/SourceManager.h"
nico436d02f2014-01-07 16:27:35 +000020#include "clang/Basic/Version.h"
djasper7f663602013-03-20 09:53:23 +000021#include "clang/Format/Format.h"
djasper44bf2ae2015-09-30 13:59:29 +000022#include "clang/Rewrite/Core/Rewriter.h"
djasper1e1687b2014-10-29 22:42:53 +000023#include "llvm/Support/CommandLine.h"
djasper7f663602013-03-20 09:53:23 +000024#include "llvm/Support/FileSystem.h"
ruiucdaacac2018-04-13 20:57:57 +000025#include "llvm/Support/InitLLVM.h"
alexfh9b1d30f2018-03-26 13:54:17 +000026#include "llvm/Support/Process.h"
djasper7f663602013-03-20 09:53:23 +000027
28using namespace llvm;
djasper578d2032015-09-23 08:30:47 +000029using clang::tooling::Replacements;
djasper7f663602013-03-20 09:53:23 +000030
31static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
32
alexfh725a9f72013-05-10 18:12:00 +000033// Mark all our options with this category, everything else (except for -version
34// and -help) will be hidden.
alexfhebc16002014-02-05 13:42:43 +000035static cl::OptionCategory ClangFormatCategory("Clang-format options");
djasper7f663602013-03-20 09:53:23 +000036
alexfh725a9f72013-05-10 18:12:00 +000037static cl::list<unsigned>
38 Offsets("offset",
39 cl::desc("Format a range starting at this byte offset.\n"
40 "Multiple ranges can be formatted by specifying\n"
41 "several -offset and -length pairs.\n"
42 "Can only be used with one input file."),
43 cl::cat(ClangFormatCategory));
44static cl::list<unsigned>
45 Lengths("length",
46 cl::desc("Format a range of this length (in bytes).\n"
47 "Multiple ranges can be formatted by specifying\n"
48 "several -offset and -length pairs.\n"
49 "When only a single -offset is specified without\n"
50 "-length, clang-format will format up to the end\n"
51 "of the file.\n"
52 "Can only be used with one input file."),
53 cl::cat(ClangFormatCategory));
alexfh6e701792013-07-18 22:54:56 +000054static cl::list<std::string>
55LineRanges("lines", cl::desc("<start line>:<end line> - format a range of\n"
56 "lines (both 1-based).\n"
57 "Multiple ranges can be formatted by specifying\n"
58 "several -lines arguments.\n"
59 "Can't be used with -offset and -length.\n"
60 "Can only be used with one input file."),
61 cl::cat(ClangFormatCategory));
alexfh725a9f72013-05-10 18:12:00 +000062static cl::opt<std::string>
ioeric66e10572018-06-25 16:29:19 +000063 Style("style", cl::desc(clang::format::StyleOptionHelpDescription),
64 cl::init(clang::format::DefaultFormatStyle),
65 cl::cat(ClangFormatCategory));
alexfh7e0adcf2013-12-02 15:21:38 +000066static cl::opt<std::string>
ioeric66e10572018-06-25 16:29:19 +000067 FallbackStyle("fallback-style",
68 cl::desc("The name of the predefined style used as a\n"
69 "fallback in case clang-format is invoked with\n"
70 "-style=file, but can not find the .clang-format\n"
71 "file to use.\n"
72 "Use -fallback-style=none to skip formatting."),
73 cl::init(clang::format::DefaultFallbackStyle),
74 cl::cat(ClangFormatCategory));
djasper05848282013-09-13 13:40:24 +000075
76static cl::opt<std::string>
djasper262cb332015-09-29 07:53:08 +000077AssumeFileName("assume-filename",
djasper05848282013-09-13 13:40:24 +000078 cl::desc("When reading from stdin, clang-format assumes this\n"
79 "filename to look for a style config file (with\n"
nico92818852014-11-10 16:14:54 +000080 "-style=file) and to determine the language."),
djasper44bf2ae2015-09-30 13:59:29 +000081 cl::init("<stdin>"), cl::cat(ClangFormatCategory));
djasper05848282013-09-13 13:40:24 +000082
alexfh725a9f72013-05-10 18:12:00 +000083static cl::opt<bool> Inplace("i",
84 cl::desc("Inplace edit <file>s, if specified."),
85 cl::cat(ClangFormatCategory));
86
87static cl::opt<bool> OutputXML("output-replacements-xml",
88 cl::desc("Output replacements as XML."),
89 cl::cat(ClangFormatCategory));
alexfh59883452013-05-10 11:56:10 +000090static cl::opt<bool>
91 DumpConfig("dump-config",
alexfh725a9f72013-05-10 18:12:00 +000092 cl::desc("Dump configuration options to stdout and exit.\n"
93 "Can be used with -style option."),
94 cl::cat(ClangFormatCategory));
djasperd0252b72013-05-21 12:21:39 +000095static cl::opt<unsigned>
96 Cursor("cursor",
alexfhb5b43022013-09-02 15:30:26 +000097 cl::desc("The position of the cursor when invoking\n"
98 "clang-format from an editor integration"),
djasperd0252b72013-05-21 12:21:39 +000099 cl::init(0), cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +0000100
djasper71631c22015-11-16 12:38:56 +0000101static cl::opt<bool> SortIncludes(
102 "sort-includes",
103 cl::desc("If set, overrides the include sorting behavior determined by the "
104 "SortIncludes style flag"),
105 cl::cat(ClangFormatCategory));
djasper578d2032015-09-23 08:30:47 +0000106
sylvestrea23fc482017-08-12 15:15:10 +0000107static cl::opt<bool>
108 Verbose("verbose", cl::desc("If set, shows the list of processed files"),
109 cl::cat(ClangFormatCategory));
110
alexfh725a9f72013-05-10 18:12:00 +0000111static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
112 cl::cat(ClangFormatCategory));
djasper7f663602013-03-20 09:53:23 +0000113
114namespace clang {
115namespace format {
116
dblaikieaa159c52014-06-27 17:40:03 +0000117static FileID createInMemoryFile(StringRef FileName, MemoryBuffer *Source,
d0k39bdfea2015-10-06 10:04:08 +0000118 SourceManager &Sources, FileManager &Files,
119 vfs::InMemoryFileSystem *MemFS) {
120 MemFS->addFileNoOwn(FileName, 0, Source);
121 return Sources.createFileID(Files.getFile(FileName), SourceLocation(),
122 SrcMgr::C_User);
djasper7f663602013-03-20 09:53:23 +0000123}
124
alexfh6e701792013-07-18 22:54:56 +0000125// Parses <start line>:<end line> input to a pair of line numbers.
alexfh4df43642013-04-24 12:46:44 +0000126// Returns true on error.
alexfh6e701792013-07-18 22:54:56 +0000127static bool parseLineRange(StringRef Input, unsigned &FromLine,
128 unsigned &ToLine) {
129 std::pair<StringRef, StringRef> LineRange = Input.split(':');
130 return LineRange.first.getAsInteger(0, FromLine) ||
131 LineRange.second.getAsInteger(0, ToLine);
132}
133
djasper578d2032015-09-23 08:30:47 +0000134static bool fillRanges(MemoryBuffer *Code,
135 std::vector<tooling::Range> &Ranges) {
d0k39bdfea2015-10-06 10:04:08 +0000136 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
137 new vfs::InMemoryFileSystem);
138 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
djasper578d2032015-09-23 08:30:47 +0000139 DiagnosticsEngine Diagnostics(
140 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
141 new DiagnosticOptions);
142 SourceManager Sources(Diagnostics, Files);
d0k39bdfea2015-10-06 10:04:08 +0000143 FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files,
144 InMemoryFileSystem.get());
alexfh6e701792013-07-18 22:54:56 +0000145 if (!LineRanges.empty()) {
146 if (!Offsets.empty() || !Lengths.empty()) {
djasper9e191b42015-11-23 08:36:35 +0000147 errs() << "error: cannot use -lines with -offset/-length\n";
alexfh6e701792013-07-18 22:54:56 +0000148 return true;
149 }
150
151 for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
152 unsigned FromLine, ToLine;
153 if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
djasper9e191b42015-11-23 08:36:35 +0000154 errs() << "error: invalid <start line>:<end line> pair\n";
alexfh6e701792013-07-18 22:54:56 +0000155 return true;
156 }
157 if (FromLine > ToLine) {
djasper9e191b42015-11-23 08:36:35 +0000158 errs() << "error: start line should be less than end line\n";
alexfh6e701792013-07-18 22:54:56 +0000159 return true;
160 }
161 SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
162 SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
163 if (Start.isInvalid() || End.isInvalid())
164 return true;
djasper578d2032015-09-23 08:30:47 +0000165 unsigned Offset = Sources.getFileOffset(Start);
166 unsigned Length = Sources.getFileOffset(End) - Offset;
167 Ranges.push_back(tooling::Range(Offset, Length));
alexfh6e701792013-07-18 22:54:56 +0000168 }
169 return false;
djasper7f663602013-03-20 09:53:23 +0000170 }
alexfh6e701792013-07-18 22:54:56 +0000171
djasper7f663602013-03-20 09:53:23 +0000172 if (Offsets.empty())
173 Offsets.push_back(0);
174 if (Offsets.size() != Lengths.size() &&
175 !(Offsets.size() == 1 && Lengths.empty())) {
djasper9e191b42015-11-23 08:36:35 +0000176 errs() << "error: number of -offset and -length arguments must match.\n";
alexfh4df43642013-04-24 12:46:44 +0000177 return true;
djasper7f663602013-03-20 09:53:23 +0000178 }
alexfh4df43642013-04-24 12:46:44 +0000179 for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
180 if (Offsets[i] >= Code->getBufferSize()) {
djasper9e191b42015-11-23 08:36:35 +0000181 errs() << "error: offset " << Offsets[i] << " is outside the file\n";
alexfh4df43642013-04-24 12:46:44 +0000182 return true;
183 }
djasper7f663602013-03-20 09:53:23 +0000184 SourceLocation Start =
185 Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
186 SourceLocation End;
187 if (i < Lengths.size()) {
alexfh4df43642013-04-24 12:46:44 +0000188 if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
djasper9e191b42015-11-23 08:36:35 +0000189 errs() << "error: invalid length " << Lengths[i]
190 << ", offset + length (" << Offsets[i] + Lengths[i]
191 << ") is outside the file.\n";
alexfh4df43642013-04-24 12:46:44 +0000192 return true;
193 }
djasper7f663602013-03-20 09:53:23 +0000194 End = Start.getLocWithOffset(Lengths[i]);
195 } else {
196 End = Sources.getLocForEndOfFile(ID);
197 }
djasper578d2032015-09-23 08:30:47 +0000198 unsigned Offset = Sources.getFileOffset(Start);
199 unsigned Length = Sources.getFileOffset(End) - Offset;
200 Ranges.push_back(tooling::Range(Offset, Length));
djasper7f663602013-03-20 09:53:23 +0000201 }
alexfh6e701792013-07-18 22:54:56 +0000202 return false;
203}
204
klimek82392d72013-12-03 09:46:06 +0000205static void outputReplacementXML(StringRef Text) {
djasperc8a1a082015-10-15 18:39:31 +0000206 // FIXME: When we sort includes, we need to make sure the stream is correct
207 // utf-8.
klimek82392d72013-12-03 09:46:06 +0000208 size_t From = 0;
209 size_t Index;
djasperc8a1a082015-10-15 18:39:31 +0000210 while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) {
djasper9e191b42015-11-23 08:36:35 +0000211 outs() << Text.substr(From, Index - From);
klimek82392d72013-12-03 09:46:06 +0000212 switch (Text[Index]) {
213 case '\n':
djasper9e191b42015-11-23 08:36:35 +0000214 outs() << "&#10;";
klimek82392d72013-12-03 09:46:06 +0000215 break;
216 case '\r':
djasper9e191b42015-11-23 08:36:35 +0000217 outs() << "&#13;";
klimek82392d72013-12-03 09:46:06 +0000218 break;
djasperc8a1a082015-10-15 18:39:31 +0000219 case '<':
djasper9e191b42015-11-23 08:36:35 +0000220 outs() << "&lt;";
djasperc8a1a082015-10-15 18:39:31 +0000221 break;
222 case '&':
djasper9e191b42015-11-23 08:36:35 +0000223 outs() << "&amp;";
djasperc8a1a082015-10-15 18:39:31 +0000224 break;
klimek82392d72013-12-03 09:46:06 +0000225 default:
226 llvm_unreachable("Unexpected character encountered!");
227 }
228 From = Index + 1;
229 }
djasper9e191b42015-11-23 08:36:35 +0000230 outs() << Text.substr(From);
klimek82392d72013-12-03 09:46:06 +0000231}
232
djasper578d2032015-09-23 08:30:47 +0000233static void outputReplacementsXML(const Replacements &Replaces) {
234 for (const auto &R : Replaces) {
235 outs() << "<replacement "
236 << "offset='" << R.getOffset() << "' "
237 << "length='" << R.getLength() << "'>";
238 outputReplacementXML(R.getReplacementText());
239 outs() << "</replacement>\n";
240 }
241}
242
alexfh6e701792013-07-18 22:54:56 +0000243// Returns true on error.
voida14558f2013-11-09 00:23:58 +0000244static bool format(StringRef FileName) {
nicoc09c8de2017-02-27 22:59:58 +0000245 if (!OutputXML && Inplace && FileName == "-") {
246 errs() << "error: cannot use -i when reading from stdin.\n";
247 return false;
248 }
249 // On Windows, overwriting a file with an open file mapping doesn't work,
250 // so read the whole file into memory when formatting in-place.
rafael54c71a82014-07-06 17:43:24 +0000251 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
nicoc09c8de2017-02-27 22:59:58 +0000252 !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName) :
253 MemoryBuffer::getFileOrSTDIN(FileName);
rafael54c71a82014-07-06 17:43:24 +0000254 if (std::error_code EC = CodeOrErr.getError()) {
djasper9e191b42015-11-23 08:36:35 +0000255 errs() << EC.message() << "\n";
alexfh6e701792013-07-18 22:54:56 +0000256 return true;
257 }
rafael54c71a82014-07-06 17:43:24 +0000258 std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
alexfh6e701792013-07-18 22:54:56 +0000259 if (Code->getBufferSize() == 0)
djasper60dad2e2013-10-08 15:54:36 +0000260 return false; // Empty files are formatted correctly.
djasper578d2032015-09-23 08:30:47 +0000261 std::vector<tooling::Range> Ranges;
262 if (fillRanges(Code.get(), Ranges))
alexfh6e701792013-07-18 22:54:56 +0000263 return true;
djasper262cb332015-09-29 07:53:08 +0000264 StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;
amaioranoa7d62362017-01-17 00:12:27 +0000265
266 llvm::Expected<FormatStyle> FormatStyle =
djasper4be7a6c2016-12-12 12:42:29 +0000267 getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer());
amaioranoa7d62362017-01-17 00:12:27 +0000268 if (!FormatStyle) {
269 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
270 return true;
271 }
mprobstf9dd41b2017-01-27 09:09:11 +0000272
djasper71631c22015-11-16 12:38:56 +0000273 if (SortIncludes.getNumOccurrences() != 0)
amaioranoa7d62362017-01-17 00:12:27 +0000274 FormatStyle->SortIncludes = SortIncludes;
djasper9e191b42015-11-23 08:36:35 +0000275 unsigned CursorPosition = Cursor;
amaioranoa7d62362017-01-17 00:12:27 +0000276 Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges,
djasper9e191b42015-11-23 08:36:35 +0000277 AssumedFileName, &CursorPosition);
ioeric2b036d32016-07-11 13:53:12 +0000278 auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
279 if (!ChangedCode) {
280 llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
281 return true;
282 }
ioeric51590652016-08-10 09:32:23 +0000283 // Get new affected ranges after sorting `#includes`.
284 Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges);
krasimir0653eee2017-04-21 14:35:20 +0000285 FormattingAttemptStatus Status;
amaioranoa7d62362017-01-17 00:12:27 +0000286 Replacements FormatChanges = reformat(*FormatStyle, *ChangedCode, Ranges,
krasimir0653eee2017-04-21 14:35:20 +0000287 AssumedFileName, &Status);
ioeric531dffd2016-08-01 10:16:37 +0000288 Replaces = Replaces.merge(FormatChanges);
djasper7f663602013-03-20 09:53:23 +0000289 if (OutputXML) {
djasper9e191b42015-11-23 08:36:35 +0000290 outs() << "<?xml version='1.0'?>\n<replacements "
291 "xml:space='preserve' incomplete_format='"
krasimir0653eee2017-04-21 14:35:20 +0000292 << (Status.FormatComplete ? "false" : "true") << "'";
293 if (!Status.FormatComplete)
ioeric35c8ff02017-11-02 12:48:48 +0000294 outs() << " line='" << Status.Line << "'";
krasimir0653eee2017-04-21 14:35:20 +0000295 outs() << ">\n";
klimekbf977882015-01-09 10:03:47 +0000296 if (Cursor.getNumOccurrences() != 0)
djasper9e191b42015-11-23 08:36:35 +0000297 outs() << "<cursor>"
ioeric531dffd2016-08-01 10:16:37 +0000298 << FormatChanges.getShiftedCodePosition(CursorPosition)
djasper9e191b42015-11-23 08:36:35 +0000299 << "</cursor>\n";
djasper0c6c9472015-05-10 07:47:19 +0000300
ioeric531dffd2016-08-01 10:16:37 +0000301 outputReplacementsXML(Replaces);
djasper9e191b42015-11-23 08:36:35 +0000302 outs() << "</replacements>\n";
djasper7f663602013-03-20 09:53:23 +0000303 } else {
d0k39bdfea2015-10-06 10:04:08 +0000304 IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
305 new vfs::InMemoryFileSystem);
306 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
djasper44bf2ae2015-09-30 13:59:29 +0000307 DiagnosticsEngine Diagnostics(
308 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
309 new DiagnosticOptions);
310 SourceManager Sources(Diagnostics, Files);
d0k39bdfea2015-10-06 10:04:08 +0000311 FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
312 InMemoryFileSystem.get());
djasper44bf2ae2015-09-30 13:59:29 +0000313 Rewriter Rewrite(Sources, LangOptions());
314 tooling::applyAllReplacements(Replaces, Rewrite);
djasper7f663602013-03-20 09:53:23 +0000315 if (Inplace) {
nicoc09c8de2017-02-27 22:59:58 +0000316 if (Rewrite.overwriteChangedFiles())
djasper44bf2ae2015-09-30 13:59:29 +0000317 return true;
djasper7f663602013-03-20 09:53:23 +0000318 } else {
krasimir0653eee2017-04-21 14:35:20 +0000319 if (Cursor.getNumOccurrences() != 0) {
grosser7e070d52015-05-08 21:34:09 +0000320 outs() << "{ \"Cursor\": "
ioeric531dffd2016-08-01 10:16:37 +0000321 << FormatChanges.getShiftedCodePosition(CursorPosition)
djasper0c6c9472015-05-10 07:47:19 +0000322 << ", \"IncompleteFormat\": "
krasimir0653eee2017-04-21 14:35:20 +0000323 << (Status.FormatComplete ? "false" : "true");
324 if (!Status.FormatComplete)
325 outs() << ", \"Line\": " << Status.Line;
326 outs() << " }\n";
327 }
djasper44bf2ae2015-09-30 13:59:29 +0000328 Rewrite.getEditBuffer(ID).write(outs());
djasper7f663602013-03-20 09:53:23 +0000329 }
330 }
alexfh4df43642013-04-24 12:46:44 +0000331 return false;
djasper7f663602013-03-20 09:53:23 +0000332}
333
334} // namespace format
335} // namespace clang
336
dim00bed782017-06-06 21:54:21 +0000337static void PrintVersion(raw_ostream &OS) {
nico436d02f2014-01-07 16:27:35 +0000338 OS << clang::getClangToolFullVersion("clang-format") << '\n';
339}
340
djasper7f663602013-03-20 09:53:23 +0000341int main(int argc, const char **argv) {
ruiucdaacac2018-04-13 20:57:57 +0000342 llvm::InitLLVM X(argc, argv);
alexfh9b1d30f2018-03-26 13:54:17 +0000343
cbienemanc9f3db62015-01-21 23:26:11 +0000344 cl::HideUnrelatedOptions(ClangFormatCategory);
alexfh725a9f72013-05-10 18:12:00 +0000345
nico436d02f2014-01-07 16:27:35 +0000346 cl::SetVersionPrinter(PrintVersion);
djasper7f663602013-03-20 09:53:23 +0000347 cl::ParseCommandLineOptions(
ruiucdaacac2018-04-13 20:57:57 +0000348 argc, argv,
nico636f8552015-10-19 01:03:19 +0000349 "A tool to format C/C++/Java/JavaScript/Objective-C/Protobuf code.\n\n"
djasper7f663602013-03-20 09:53:23 +0000350 "If no arguments are specified, it formats the code from standard input\n"
351 "and writes the result to the standard output.\n"
alexfhb5b43022013-09-02 15:30:26 +0000352 "If <file>s are given, it reformats the files. If -i is specified\n"
353 "together with <file>s, the files are edited in-place. Otherwise, the\n"
alexfh4df43642013-04-24 12:46:44 +0000354 "result is written to the standard output.\n");
355
rafaelf94a89d2017-09-08 00:01:26 +0000356 if (Help) {
djasper7f663602013-03-20 09:53:23 +0000357 cl::PrintHelpMessage();
rafaelf94a89d2017-09-08 00:01:26 +0000358 return 0;
359 }
alexfh4df43642013-04-24 12:46:44 +0000360
alexfh59883452013-05-10 11:56:10 +0000361 if (DumpConfig) {
benhamilton3597d092018-01-29 17:36:43 +0000362 StringRef FileName;
363 std::unique_ptr<llvm::MemoryBuffer> Code;
364 if (FileNames.empty()) {
365 // We can't read the code to detect the language if there's no
366 // file name, so leave Code empty here.
367 FileName = AssumeFileName;
368 } else {
369 // Read in the code in case the filename alone isn't enough to
370 // detect the language.
371 ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
372 MemoryBuffer::getFileOrSTDIN(FileNames[0]);
373 if (std::error_code EC = CodeOrErr.getError()) {
374 llvm::errs() << EC.message() << "\n";
375 return 1;
376 }
377 FileName = (FileNames[0] == "-") ? AssumeFileName : FileNames[0];
378 Code = std::move(CodeOrErr.get());
379 }
amaioranoa7d62362017-01-17 00:12:27 +0000380 llvm::Expected<clang::format::FormatStyle> FormatStyle =
benhamilton3597d092018-01-29 17:36:43 +0000381 clang::format::getStyle(Style, FileName, FallbackStyle,
382 Code ? Code->getBuffer() : "");
amaioranoa7d62362017-01-17 00:12:27 +0000383 if (!FormatStyle) {
384 llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
385 return 1;
386 }
387 std::string Config = clang::format::configurationAsText(*FormatStyle);
djasper9e191b42015-11-23 08:36:35 +0000388 outs() << Config << "\n";
alexfh59883452013-05-10 11:56:10 +0000389 return 0;
390 }
391
alexfh4df43642013-04-24 12:46:44 +0000392 bool Error = false;
sylvestrea23fc482017-08-12 15:15:10 +0000393 if (FileNames.empty()) {
alexfh4df43642013-04-24 12:46:44 +0000394 Error = clang::format::format("-");
sylvestrea23fc482017-08-12 15:15:10 +0000395 return Error ? 1 : 0;
396 }
397 if (FileNames.size() != 1 && (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty())) {
398 errs() << "error: -offset, -length and -lines can only be used for "
399 "single file.\n";
400 return 1;
401 }
402 for (const auto &FileName : FileNames) {
403 if (Verbose)
404 errs() << "Formatting " << FileName << "\n";
405 Error |= clang::format::format(FileName);
alexfh4df43642013-04-24 12:46:44 +0000406 }
407 return Error ? 1 : 0;
djasper7f663602013-03-20 09:53:23 +0000408}