@@ -20,6 +20,17 @@ import path from 'node:path'
2020import minimist from './libs/minimist.cjs'
2121import slugify from './libs/slugify.cjs'
2222
23+ const ID_LENGTH = 4 ;
24+ const ID_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789' ;
25+
26+ function generateShortId ( length ) {
27+ let result = '' ;
28+ for ( let i = 0 ; i < length ; i ++ ) {
29+ result += ID_CHARS . charAt ( Math . floor ( Math . random ( ) * ID_CHARS . length ) ) ;
30+ }
31+ return result ;
32+ }
33+
2334function getDate ( ) {
2435 const date = new Date ( )
2536 const year = date . getFullYear ( )
@@ -54,6 +65,28 @@ Example:
5465`
5566const TARGET_DIR = 'src/content/blog/'
5667
68+ function getExistingSlugs ( ) {
69+ const existingSlugs = new Set ( ) ;
70+ const files = fs . readdirSync ( TARGET_DIR ) ;
71+
72+ for ( const file of files ) {
73+ if ( file . endsWith ( '.md' ) || file . endsWith ( '.mdx' ) ) {
74+ const filePath = path . join ( TARGET_DIR , file ) ;
75+ const content = fs . readFileSync ( filePath , 'utf8' ) ;
76+ const frontmatterMatch = content . match ( / ^ - - - \n ( [ \s \S ] * ?) \n - - - / ) ;
77+
78+ if ( frontmatterMatch && frontmatterMatch [ 1 ] ) {
79+ const frontmatter = frontmatterMatch [ 1 ] ;
80+ const slugMatch = frontmatter . match ( / ^ s l u g : \s * ( .* ) $ / m) ;
81+ if ( slugMatch && slugMatch [ 1 ] ) {
82+ existingSlugs . add ( slugMatch [ 1 ] . trim ( ) ) ;
83+ }
84+ }
85+ }
86+ }
87+ return existingSlugs ;
88+ }
89+
5790export default function main ( args ) {
5891 const parsedArgs = minimist ( args , {
5992 string : [ 'lang' ] ,
@@ -93,19 +126,21 @@ export default function main(args) {
93126 process . exit ( 1 )
94127 }
95128
96- let content = `---
97- title: ${ postTitle }
98- description: 'Write your description here.'
99- publishDate: ${ getDate ( ) }
100- `
129+ let slug = generateShortId ( ID_LENGTH ) ;
130+ const existingSlugs = getExistingSlugs ( ) ;
131+
132+ while ( existingSlugs . has ( slug ) ) {
133+ slug = generateShortId ( ID_LENGTH ) ;
134+ }
135+
136+ let content = `---\ntitle: ${ postTitle } \ndescription: 'Write your description here.'\npublishDate: ${ getDate ( ) } \nslug: ${ slug } \n`
101137 content += parsedArgs . draft ? 'draft: true\n' : ''
102138 content += parsedArgs . lang ? `lang: ${ parsedArgs . lang } \n` : ''
103- content += `tags: ['tag1', 'tag2']
104- ---
105-
106- Write your content here.
139+ content += `tags: ['tag1', 'tag2']\n---\n\nWrite your content here.
107140`
108141
109142 fs . writeFileSync ( fullPath , content )
110143 console . log ( `Post "${ postTitle } " created at ${ fullPath } ` )
111144}
145+
146+ main ( process . argv . slice ( 2 ) ) ;
0 commit comments