Created
March 23, 2021 21:15
-
-
Save ramyak-mehra/802d60811914dd0b6472b4e11880d564 to your computer and use it in GitHub Desktop.
Script to validate dart packages pubspec yaml that can it be converted to json or not
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:yaml/yaml.dart'; | |
import 'dart:io'; | |
import 'package:tar/tar.dart'; | |
import 'package:http/http.dart' as http; | |
void main(List<String> args) async { | |
final httpClient = http.Client(); | |
var packageUrl = ''; | |
var pubspecContent; | |
var validJson = false; | |
try { | |
pubspecContent = | |
await _readPubspecFile(_downloadFile(httpClient, packageUrl)); | |
} catch (e) { | |
//Log the error | |
print(e); | |
} | |
try { | |
validJson = _validateYaml(pubspecContent, 'packageName'); | |
} on InvalidYamlException catch (e) { | |
//log the error. | |
print(e); | |
} catch (e) { | |
//Log the error | |
print(e); | |
} | |
//TODO Wrtie to file | |
} | |
bool _validateYaml(String pubspecContent, String packageName) { | |
try { | |
final map = loadYaml(pubspecContent) as Map; | |
json.decode(json.encode(map)) as Map<String, dynamic>; | |
return true; | |
} on JsonUnsupportedObjectError catch (e) { | |
throw InvalidYamlException( | |
errorMessage: e.toString(), packageName: packageName); | |
} catch (e) { | |
throw AssertionError('Unable to parse pubspec yaml'); | |
} | |
} | |
Stream<List<int>> _downloadFile(http.Client client, String url) async* { | |
try { | |
final request = await client.get(Uri.parse(url)); | |
yield request.bodyBytes; | |
} catch (e) { | |
print(e); | |
} | |
} | |
Future<String> _readPubspecFile(Stream<List<int>> fileStream) async { | |
final reader = TarReader(fileStream.transform(gzip.decoder)); | |
try { | |
while (await reader.moveNext()) { | |
var maxLength = 0; | |
final entry = reader.current; | |
if (entry.name != 'pubspec.yaml') continue; | |
final builder = BytesBuilder(); | |
await for (final chunk in entry.contents) { | |
builder.add(chunk); | |
} | |
var content = utf8.decode(builder.toBytes(), allowMalformed: true); | |
if (maxLength > 0 && content.length > maxLength) { | |
content = content.substring(0, maxLength) + '[...]\n\n'; | |
} | |
return content; | |
} | |
} finally { | |
await reader.cancel(); | |
} | |
throw AssertionError('Unable to read the file'); | |
} | |
class InvalidYamlException implements Exception { | |
String errorMessage; | |
String packageName; | |
InvalidYamlException({this.packageName, this.errorMessage}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment