sync method

Future<void> sync({
  1. bool skipBackup = false,
})

Implementation

Future<void> sync({bool skipBackup = false}) async {
  try {
    if (!(await _fileStorage.exists())) {
      await _fileStorage.writeAsString('');
    }

    final String localContent = await _fileStorage.readAsString();

    final localHash = _calculateFileHash(localContent);

    final syncResponse = await _client.syncDev(
      projectId: int.parse(_options.projectId),
      figmaFileHash: _lastKnownHash ?? localHash,
    );

    final patchesJson = syncResponse['patches'] as List;
    final serverHash = syncResponse['figmaFileHash'] as String;

    if (patchesJson.isEmpty) {
      _lastKnownHash = serverHash;
      return;
    }

    final dmp = DiffMatchPatch();
    final patches = patchesJson.map<Patch>((patchJson) {
      return _patchFromJson(patchJson as Map<String, dynamic>);
    }).toList();

    if (!skipBackup && localContent.isNotEmpty) {
      await _fileStorage.createBackup();
    }

    String newContent = localContent;
    final patchResults = dmp.patch_apply(patches, newContent);
    newContent = patchResults[0] as String;

    await _fileStorage.writeAsString(newContent);

    _lastKnownHash = serverHash;
  } catch (e) {
    if (e is! MorphrCloudException) {
      throw MorphrCloudException('Error while syncing: $e');
    }
    rethrow;
  }
}