1 #include "format.h"
2 #include "json.h"
3
4 #include "getpost.h"
5
6 #if defined(_MSC_VER)
7 #include <io.h>
8 #else
9 #include <unistd.h>
10 #endif
11 #include <cstdlib>
12 #include <fstream>
13 #include <map>
14 #include <sstream>
15 #include <string>
16
17 #if defined(_WIN32)
erase_char(std::string & s,const char & c)18 static void erase_char( std::string &s, const char &c )
19 {
20 s.erase( std::remove( s.begin(), s.end(), c ), s.end() );
21 }
22 #endif
23
main(int argc,char * argv[])24 int main( int argc, char *argv[] )
25 {
26 std::stringstream in;
27 std::stringstream out;
28 std::string filename;
29 std::string header;
30
31 char *gateway_var = getenv( "GATEWAY_INTERFACE" );
32 if( gateway_var == nullptr ) {
33 // Expect a single filename for now.
34 if( argc == 2 ) {
35 filename = argv[1];
36 } else if( argc != 1 ) {
37 std::cout << "Supply a filename to style or no arguments." << std::endl;
38 exit( EXIT_FAILURE );
39 }
40
41 if( filename.empty() ) {
42 in << std::cin.rdbuf();
43 } else {
44 std::ifstream fin( filename, std::ios::binary );
45 if( !fin.good() ) {
46 std::cout << "Failed to open " << filename << std::endl;
47 exit( EXIT_FAILURE );
48 }
49 in << fin.rdbuf();
50 fin.close();
51 }
52 } else {
53 std::map<std::string, std::string> params;
54 initializePost( params );
55 std::string data = params[ "data" ];
56 if( data.empty() ) {
57 exit( -255 );
58 }
59 in.str( data );
60 header = "Content-type: application/json\n\n";
61 }
62
63 if( in.str().empty() ) {
64 std::cout << "Error, input empty." << std::endl;
65 exit( EXIT_FAILURE );
66 }
67 JsonOut jsout( out, true );
68 JsonIn jsin( in );
69
70 formatter::format( jsin, jsout );
71
72 out << std::endl;
73
74 if( filename.empty() ) {
75 std::cout << header;
76 std::cout << out.str();
77 } else {
78 std::string in_str = in.str();
79 #if defined(_WIN32)
80 erase_char( in_str, '\r' );
81 #endif
82
83 #if defined(_MSC_VER)
84 bool supports_color = _isatty( _fileno( stdout ) );
85 #else
86 bool supports_color = isatty( STDOUT_FILENO );
87 #endif
88 std::string color_bad = supports_color ? "\x1b[31m" : std::string();
89 std::string color_end = supports_color ? "\x1b[0m" : std::string();
90 if( in_str == out.str() ) {
91 exit( EXIT_SUCCESS );
92 } else {
93 std::ofstream fout( filename, std::ios::binary | std::ios::trunc );
94 fout << out.str();
95 fout.close();
96 std::cout << color_bad << "Needs linting : " << color_end << filename << std::endl;
97 std::cout << "Please read doc/JSON_STYLE.md" << std::endl;
98 exit( EXIT_FAILURE );
99 }
100 }
101 }
102