Skip to content

Instantly share code, notes, and snippets.

@purplenoodlesoop
Last active May 11, 2022 21:46
Show Gist options
  • Save purplenoodlesoop/a003e81dcaf8aae28a9a2b3f95b141e2 to your computer and use it in GitHub Desktop.
Save purplenoodlesoop/a003e81dcaf8aae28a9a2b3f95b141e2 to your computer and use it in GitHub Desktop.
Visual Studio Code snippet generator
import 'dart:convert';
import 'dart:io';
import 'package:pure/pure.dart';
import 'package:stream_transform/stream_transform.dart';
typedef Json = Map<String, Object?>;
extension on Directory {
String get scope => uri.pathSegments.elementAt(1);
}
extension on File {
String get name => uri.pathSegments.last;
}
extension on String {
String uppercased() => this[0].toUpperCase() + substring(1);
String followedBy(String other) => this + other;
}
class SnippetInfo {
final String scope;
final String filename;
final String contents;
const SnippetInfo({
required this.scope,
required this.filename,
required this.contents,
});
String get name => filename
.split('.')
.first
.split('_')
.join(' ')
.uppercased()
.followedBy(' (${scope.uppercased()})');
Json get json {
final json = jsonDecode(contents) as Json;
if (scope.isEmpty || scope == 'global') return json;
json['scope'] = scope;
return json;
}
}
Future<SnippetInfo> extractInfo(String scope, File file) async => SnippetInfo(
scope: scope,
filename: file.name,
contents: await file.readAsString(),
);
bool isJson(File file) => file.path.endsWith('.json');
Stream<SnippetInfo> extractAllSnippets(Directory scopedDirectory) =>
scopedDirectory
.list(recursive: true)
.whereType<File>()
.where(isJson)
.concurrentAsyncMap(extractInfo.curry(scopedDirectory.scope));
Json appendSnippet(Json result, SnippetInfo info) => {
...result,
info.name: info.json,
};
File get snippetsFile => File('global.code-snippets');
Future<void> writeResult(Json result) =>
jsonEncode(result).pipe(snippetsFile.writeAsString);
void main(List<String> arguments) => Directory(arguments.first)
.list()
.whereType<Directory>()
.concurrentAsyncExpand(extractAllSnippets)
.fold<Json>(const {}, appendSnippet).then(writeResult);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment