1# Copyright (C) 2007-2012, Parrot Foundation. 2 3=head1 DESCRIPTION 4 5Provides a simple wrapper to read and write JSON config files. 6 7=cut 8 9.namespace [ 'Config' ; 'JSON' ] 10 11=head2 ReadConfig(filename) 12 13Given a filename, parse the file containing valid JSON and return a 14PMC containing the data. 15 16If the data is not valid, an exception will be thrown. 17 18=cut 19 20.sub 'ReadConfig' 21 .param string filename 22 23 # Slurp in the file 24 .local string text 25 .local pmc fh 26 27 fh = new ['FileHandle'] 28 fh.'open'(filename, 'r') 29 if fh goto slurp_file 30 $P0 = new 'Exception' 31 $S0 = concat "Can't open file: ", filename 32 $P0 = $S0 33 throw $P0 34 35 slurp_file: 36 fh.'encoding'('utf8') 37 text = fh.'readall'() 38 39 # Convert the text to an object and return it. 40 .local pmc json, code 41 load_language 'data_json' 42 json = compreg 'data_json' 43 code = json.'compile'(text) 44 .tailcall code() 45.end 46 47=head2 WriteConfig(config, filename, ?:compact) 48 49Given a PMC and a filename, render the pmc as JSON and store the contents 50into the named file, overwriting the existing contents. 51 52Any exceptions generated by the conversion or writing to the file will 53be passed through. 54 55If a true value is passed for the optional named parameter 'compact', then 56the rendered JSON will not be formatted. The default is false. 57 58=cut 59 60.sub 'WriteConfig' 61 .param pmc config 62 .param string filename 63 .param int compact :optional :named('compact') 64 .param int has_compact :opt_flag 65 66 if has_compact goto done_options 67 compact = 0 68 69 done_options: 70 .local int expanded 71 expanded = not compact 72 73 # render the object as a string. 74 load_bytecode 'JSON.pbc' 75 .local string output 76 output = _json( config, expanded ) 77 78 # write out the file.. 79 $P1 = new ['FileHandle'] 80 $P1.'open'(filename, 'w') 81 print $P1, output 82 print $P1, "\n" 83 $P1.'close'() 84 85.end 86 87# Local Variables: 88# mode: pir 89# fill-column: 100 90# End: 91# vim: expandtab shiftwidth=4 ft=pir: 92