1
+ const path = require ( 'path' ) ;
2
+ const mkdirp = require ( 'mkdirp' ) ;
3
+ const fs = require ( 'fs' ) ;
4
+
5
+ function plugin ( opts ) {
6
+
7
+ return function ( files , metalsmith , done ) {
8
+ const meta = metalsmith . metadata ( ) ;
9
+ const sourcePath = metalsmith . source ( ) ;
10
+
11
+ // set global information about the available locales
12
+ const defaultLocale = meta . defaultLocale = opts . defaultLocale ;
13
+ const locales = meta . locales = opts . locales ;
14
+ const pattern = ( locales ) => {
15
+ if ( ! Array . isArray ( locales ) ) {
16
+ locales = [ locales ]
17
+ }
18
+
19
+ return new RegExp ( `.*\\/(?:${ locales . join ( '|' ) } )\\/(.+)(\\..+)` )
20
+ } ;
21
+
22
+ const requiredFiles = Object . keys ( files )
23
+ . filter ( file => file . match ( pattern ( defaultLocale ) ) )
24
+ . map ( file => {
25
+ return file . replace ( `${ path . sep } ${ defaultLocale } ${ path . sep } ` , `${ path . sep } {LOCALE}${ path . sep } ` ) ;
26
+ } ) ;
27
+ const otherLocales = locales . filter ( l => l !== defaultLocale ) ;
28
+
29
+ otherLocales . forEach ( ( locale ) => {
30
+ requiredFiles . forEach ( ( file ) => {
31
+ const new_file = file . replace ( '{LOCALE}' , locale ) ;
32
+ const dir = path . dirname ( file ) ;
33
+ mkdirp ( dir , ( err ) => {
34
+ if ( err ) throw err ;
35
+ const exists = fs . existsSync ( new_file ) ;
36
+ if ( ! exists ) {
37
+ fs . writeFileSync ( new_file , files [ file . replace ( '{LOCALE}' , defaultLocale ) ] . contents , ( ) => {
38
+ console . log ( 'Written new file at ' , new_file )
39
+ } )
40
+ }
41
+ } )
42
+ } )
43
+ } ) ;
44
+ console . log ( otherLocales , requiredFiles )
45
+ // console.log(path.resolve(sourcePath, defaultLocale));
46
+
47
+
48
+ // done();
49
+ }
50
+ }
51
+
52
+ module . exports = plugin ;
0 commit comments