Skip to content

Instantly share code, notes, and snippets.

@bantya
Last active June 5, 2024 19:45
Show Gist options
  • Save bantya/eb758d251e0bdb37b15c02dac0d8a77b to your computer and use it in GitHub Desktop.
Save bantya/eb758d251e0bdb37b15c02dac0d8a77b to your computer and use it in GitHub Desktop.
Convert sublime snippets to vscode.
<?php
$directory = $argv[1];
$directory = str_replace(['.', '/', '\\', '_', ' '], '', $directory);
$files = getFiles('./' . $directory . '/');
$output = [];
foreach ($files as $file) {
$content = getContent($file, $directory);
$output[$content['description']] = [
'prefix' => $content['trigger'],
'body' => $content['snippet'],
'description' => $content['description'],
];
}
saveContent($directory . '.json', $output);
function getContent(string $file, string $directory)
{
$content = simplexml_load_file('./' . $directory . '/' . $file, 'SimpleXMLElement', LIBXML_NOCDATA);
$snippet = explode("\n", $content->content);
array_shift($snippet);
array_pop($snippet);
$description = getName($file, $directory);
$trigger = $content->tabTrigger->__toString();
return [
'description' => $description,
'trigger' => $trigger,
'snippet' => $snippet,
];
}
function getName(string $name, string $directory)
{
$name = explode('.', $name);
$name = $name[0];
$name = preg_replace('/[^\_\-\s\pN\pL]+/u', '', $name);
$name = trim(preg_replace('/[\_\-\s]+/', ' ', $name), '-');
$name = $directory . ' ' . trim(str_replace($directory, '', $name));
return $name;
}
function saveContent($name, $output)
{
$output = json_encode($output, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
if (false !== file_put_contents('./' . $name, $output)) {
echo "\e[42mDone!\e[0m";
} else {
echo "\e[41mError!\e[0m";
}
}
function getFiles(string $directory)
{
return array_values(
array_filter(
array_map(
function ($file) {
if ($file === '.' || $file === '..') {
return false;
}
return $file;
},
scandir($directory)
)
)
);
}
php snippets.php [SNIPPETS_DIRECTORY]
e.g. php snippets.php vue
SNIPPETS_DIRECTORY: Assuming that the snippets are categorized in directories (preferably by languages) and snippet directories and the script have the same parent directory.
e.g.
/snippets
|
+--- snippets.php
|
+--- /php
| ...
+--- /sass
| ...
+--- /vue
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment