import fs from 'fs' ; import path from 'path' ; import childProcess from 'child_process' ; import clipboardy from 'clipboardy' ; import helper from './helpers' ; import { fuzzyProcess } from './fuzzy-list' ; const HOME = process . env . HOME ?? '~' ; const EDITOR = process . env . EDITOR ?? 'vim' ; const snippetsRoot = path . join ( HOME , '.snips' ) ; const _listSnips = ( ) => { try { return fs . readdirSync ( snippetsRoot ) ; } catch { helper . error ( 'snippets root folder not found' ) ; throw new Error ( 'snippets root folder not found' ) ; } } ; const _editSnip = ( snippetName ) => { const fileName = path . join ( snippetsRoot , snippetName ) ; childProcess . spawn ( EDITOR , [ fileName ] , { stdio : 'inherit' , } ) ; } ; const _copySnip = ( snippetName ) => { const fileName = path . join ( snippetsRoot , snippetName ) ; if ( ! fs . existsSync ( fileName ) ) { throw new Error ( 'Snippet with given name does not exist' ) ; } const text = fs . readFileSync ( fileName ) . toString ( ) ; clipboardy . writeSync ( text ) ; } ; function createSnippet ( snippetName ) { const fileName = path . join ( snippetsRoot , snippetName ) ; const template = '---\ntags: []\nlanguage:\n---\n\n' ; fs . writeFileSync ( fileName , template ) ; childProcess . spawn ( EDITOR , [ fileName ] , { stdio : 'inherit' , } ) ; } function listSnippets ( ) { _listSnips ( ) . forEach ( item => console . log ( item ) ) ; } function editSnippet ( snippetName ) { if ( snippetName ) { _editSnip ( snippetName ) ; } else { fuzzyProcess ( _editSnip , _listSnips ( ) ) ; } } function copySnippet ( snippetName ) { if ( snippetName ) { _copySnip ( snippetName ) ; } else { fuzzyProcess ( _copySnip , _listSnips ( ) ) ; } } function checkFiles ( ) { try { fs . mkdirSync ( snippetsRoot ) ; } catch ( e ) { if ( e . code !== 'EEXIST' ) { throw e ; } } } export default { createSnippet , editSnippet , listSnippets , copySnippet , checkFiles , } ;