@@ -196,30 +196,36 @@ void RestProfile::save_to_file(const bool overwrite) {
196196 // If the file already exists, load it into a json object.
197197 json data;
198198 if (std::filesystem::exists (filepath_)) {
199- // Read the file into the json object.
200- data = read_file (filepath_);
201-
202- // If the file is outdated, throw an error. This behavior will evolve.
203- if (data[" version" ] < version_) {
199+ try {
200+ // If the file is empty, treat it as a new json object.
201+ if (std::filesystem::file_size (filepath_) == 0 ) {
202+ data = json::object ();
203+ } else {
204+ data = read_file (filepath_);
205+ }
206+ } catch (const std::filesystem::filesystem_error& e) {
204207 throw RestProfileException (
205- " The version of your local profile.json file is out of date. " );
208+ " Failed to access profile file: " + std::string (e. what ()) );
206209 }
207210
208- // Check that this profile hasn't already been saved.
209- if (data.contains (name_)) {
210- if (overwrite) {
211- // If a profile of the given name exists, remove it.
212- auto it = data.find (name_);
213- if (it != data.end ()) {
214- data.erase (it);
215- }
216- } else {
217- // If the user doesn't want to overwrite, throw an error.
211+ if (data.empty ()) {
212+ data[" version" ] = version_;
213+ } else {
214+ if (data[" version" ] < version_) {
215+ throw RestProfileException (
216+ " The version of your local profile.json file is out of date." );
217+ }
218+
219+ if (data.contains (name_) && !overwrite) {
218220 throw RestProfileException (
219221 " Failed to save '" + name_ +
220222 " '; This profile has already been saved "
221223 " and must be explicitly removed in order to be replaced." );
222224 }
225+
226+ if (overwrite) {
227+ data.erase (name_);
228+ }
223229 }
224230 } else {
225231 // Write the version number iff this is the first time opening the file.
0 commit comments