blob: d465405440ea27d35d3a62244cd4638607da7125 [file] [log] [blame]
lakshmanae1409172018-02-22 15:09:01 -08001/*
2 * Copyright (c) 2018, Google Inc.
3 * All rights reserved.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "perf_to_profile_lib.h"
9
10#include <sys/stat.h>
11#include <sstream>
12
13bool FileExists(const string& path) {
14 struct stat file_stat;
15 return stat(path.c_str(), &file_stat) != -1;
16}
17
18string ReadFileToString(const string& path) {
19 std::ifstream perf_file(path);
20 if (!perf_file.is_open()) {
21 LOG(FATAL) << "Failed to open file: " << path;
22 }
23 std::ostringstream ss;
24 ss << perf_file.rdbuf();
25 return ss.str();
26}
27
28void CreateFile(const string& path, std::ofstream* file, bool overwriteOutput) {
29 if (!overwriteOutput && FileExists(path)) {
30 LOG(FATAL) << "File already exists: " << path;
31 }
32 file->open(path, std::ios_base::trunc);
33 if (!file->is_open()) {
34 LOG(FATAL) << "Failed to open file: " << path;
35 }
36}
37
38void PrintUsage() {
39 LOG(INFO) << "Usage:";
40 LOG(INFO) << "perf_to_profile -i <input perf data> -o <output profile> [-f]";
41 LOG(INFO) << "If the -f option is given, overwrite the existing output "
42 << "profile.";
43}
44
45bool ParseArguments(int argc, const char* argv[], string* input, string* output,
46 bool* overwriteOutput) {
47 *input = "";
48 *output = "";
49 *overwriteOutput = false;
50 int opt;
51 while ((opt = getopt(argc, const_cast<char* const*>(argv), ":fi:o:")) != -1) {
52 switch (opt) {
53 case 'i':
54 *input = optarg;
55 break;
56 case 'o':
57 *output = optarg;
58 break;
59 case 'f':
60 *overwriteOutput = true;
61 break;
62 case ':':
63 LOG(ERROR) << "Must provide arguments for flags -i and -o";
64 return false;
65 case '?':
66 LOG(ERROR) << "Invalid option: " << static_cast<char>(optopt);
67 return false;
68 default:
69 LOG(ERROR) << "Invalid option: " << static_cast<char>(opt);
70 return false;
71 }
72 }
73 return !input->empty() && !output->empty();
74}