static void outputReplacementsXML(const Replacements &Replaces) { for (const auto &R : Replaces) { outs() << "<replacement " << "offset='" << R.getOffset() << "' " << "length='" << R.getLength() << "'>"; outputReplacementXML(R.getReplacementText()); outs() << "</replacement>\n"; } }
// Returns true on error. static bool format(StringRef FileName) { FileManager Files((FileSystemOptions())); DiagnosticsEngine Diagnostics( IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), new DiagnosticOptions); SourceManager Sources(Diagnostics, Files); std::unique_ptr<MemoryBuffer> Code; if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) { llvm::errs() << ec.message() << "\n"; return true; } if (Code->getBufferSize() == 0) return false; // Empty files are formatted correctly. FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files); std::vector<CharSourceRange> Ranges; if (fillRanges(Sources, ID, Code.get(), Ranges)) return true; FormatStyle FormatStyle = getStyle( Style, (FileName == "-") ? AssumeFilename : FileName, FallbackStyle); Lexer Lex(ID, Sources.getBuffer(ID), Sources, getFormattingLangOpts(FormatStyle.Standard)); tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges); if (OutputXML) { llvm::outs() << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n"; for (tooling::Replacements::const_iterator I = Replaces.begin(), E = Replaces.end(); I != E; ++I) { llvm::outs() << "<replacement " << "offset='" << I->getOffset() << "' " << "length='" << I->getLength() << "'>"; outputReplacementXML(I->getReplacementText()); llvm::outs() << "</replacement>\n"; } llvm::outs() << "</replacements>\n"; } else { Rewriter Rewrite(Sources, LangOptions()); tooling::applyAllReplacements(Replaces, Rewrite); if (Inplace) { if (Rewrite.overwriteChangedFiles()) return true; } else { if (Cursor.getNumOccurrences() != 0) outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(Replaces, Cursor) << " }\n"; Rewrite.getEditBuffer(ID).write(outs()); } } return false; }