Skip to content

Instantly share code, notes, and snippets.

@jakebathman
Created January 29, 2021 19:31
Show Gist options
  • Save jakebathman/ca1ae34c087b885897b7068f7cc2d55d to your computer and use it in GitHub Desktop.
Save jakebathman/ca1ae34c087b885897b7068f7cc2d55d to your computer and use it in GitHub Desktop.
Convert TextExpander exported CSV file to an Alfred 4 snippets import file
<?php
$input = $argv[1] ?? 'snippets.csv';
$file = fopen($input, 'r');
$outputDir = pathinfo($input, PATHINFO_FILENAME);
$snippetFiles = [];
// Make the temp output directory
if (! file_exists($outputDir)) {
mkdir($outputDir, 0777, true);
}
// Read the CSV file and render a single JSON output per snippet
while (($line = fgetcsv($file)) !== false) {
// Create a 15-character UID
$uid = substr(sha1(microtime(true) . mt_rand(10000, 90000)), 0, 15);
$filename = $line[0] . " [{$uid}].json";
$snippetFiles[] = $filename;
$keyword = str_replace(';', '', $line[0]);
$output = [
'alfredsnippet' => [
'snippet' => $line[1],
'uid' => $uid,
'keyword' => $keyword,
'name' => $keyword,
'dontautoexpand' => false,
],
];
file_put_contents($outputDir . '/' . $filename, json_encode($output, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
}
// Add info.plist
$plist = '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>snippetkeywordprefix</key>
<string>;</string>
<key>snippetkeywordsuffix</key>
<string></string>
</dict>
</plist>
';
file_put_contents($outputDir . '/info.plist', $plist);
fclose($file);
// Zip output files together
$zip = new ZipArchive;
$zipFilename = "{$outputDir}.alfredsnippets";
try {
unlink($zipFilename);
} catch (\Throwable $th) {
}
// Create ZIP archive file
$zip->open($zipFilename, ZipArchive::CREATE);
// Add plist and json files
$zip->addFile($outputDir . '/info.plist', 'info.plist');
foreach ($snippetFiles as $f) {
$zip->addFile($outputDir . '/' . $f, $f);
}
echo 'numfiles: ' . $zip->numFiles . "\n";
echo 'status:' . $zip->status . "\n";
$zip->close();
// Delete temp folder
array_map('unlink', glob("$outputDir/*.*"));
rmdir($outputDir);
echo "\nFinished creating {$outputDir}.alfredsnippets";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment