@@ -357,8 +357,12 @@ esp_err_t esp_spiffs_info(const char* partition_label, size_t *total_bytes, size
357357
358358esp_err_t esp_spiffs_format (const char * partition_label )
359359{
360- bool mount_on_success = false;
360+ bool partition_was_mounted = false;
361361 int index ;
362+ /* If the partition is not mounted, need to create SPIFFS structures
363+ * and mount the partition, unmount, format, delete SPIFFS structures.
364+ * See SPIFFS wiki for the reason why.
365+ */
362366 esp_err_t err = esp_spiffs_by_label (partition_label , & index );
363367 if (err != ESP_OK ) {
364368 esp_vfs_spiffs_conf_t conf = {
@@ -371,23 +375,28 @@ esp_err_t esp_spiffs_format(const char* partition_label)
371375 return err ;
372376 }
373377 err = esp_spiffs_by_label (partition_label , & index );
374- if (err != ESP_OK ) {
375- return err ;
376- }
377- esp_spiffs_free (& _efs [index ]);
378- return ESP_OK ;
378+ assert (err == ESP_OK && "failed to get index of the partition just mounted" );
379379 } else if (SPIFFS_mounted (_efs [index ]-> fs )) {
380- SPIFFS_unmount (_efs [index ]-> fs );
381- mount_on_success = true;
380+ partition_was_mounted = true;
382381 }
382+
383+ SPIFFS_unmount (_efs [index ]-> fs );
384+
383385 s32_t res = SPIFFS_format (_efs [index ]-> fs );
384386 if (res != SPIFFS_OK ) {
385387 ESP_LOGE (TAG , "format failed, %i" , SPIFFS_errno (_efs [index ]-> fs ));
386388 SPIFFS_clearerr (_efs [index ]-> fs );
389+ /* If the partition was previously mounted, but format failed, don't
390+ * try to mount the partition back (it will probably fail). On the
391+ * other hand, if it was not mounted, need to clean up.
392+ */
393+ if (!partition_was_mounted ) {
394+ esp_spiffs_free (& _efs [index ]);
395+ }
387396 return ESP_FAIL ;
388397 }
389398
390- if (mount_on_success ) {
399+ if (partition_was_mounted ) {
391400 res = SPIFFS_mount (_efs [index ]-> fs , & _efs [index ]-> cfg , _efs [index ]-> work ,
392401 _efs [index ]-> fds , _efs [index ]-> fds_sz , _efs [index ]-> cache ,
393402 _efs [index ]-> cache_sz , spiffs_api_check );
@@ -396,6 +405,8 @@ esp_err_t esp_spiffs_format(const char* partition_label)
396405 SPIFFS_clearerr (_efs [index ]-> fs );
397406 return ESP_FAIL ;
398407 }
408+ } else {
409+ esp_spiffs_free (& _efs [index ]);
399410 }
400411 return ESP_OK ;
401412}
0 commit comments