-
-
Notifications
You must be signed in to change notification settings - Fork 241
/
docpad.coffee
executable file
·2026 lines (1625 loc) · 46.8 KB
/
docpad.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# =====================================
# Requires
# Necessary
pathUtil = require('path')
_ = require('underscore')
caterpillar = require('caterpillar')
queryEngine = require('query-engine')
CSON = require('cson')
balUtil = require('bal-util')
EventSystem = balUtil.EventSystem
airbrake = null
# Local
PluginLoader = require(__dirname+'/plugin-loader')
BasePlugin = require(__dirname+'/plugin')
require(__dirname+'/prototypes')
# =====================================
# DocPad
###
The DocPad Class
It extends the EventSystem from bal-util to provide system events
It allows us to support multiple instances of docpad at the same time
###
class DocPad extends EventSystem
# =================================
# Variables
# ---------------------------------
# DocPad
# DocPad's version number
version: null
# The express server instance bound to docpad
server: null
# The caterpillar instance bound to docpad
logger: null
# ---------------------------------
# Models
# File Model
FileModel: require(__dirname+'/models/file')
# Document Model
DocumentModel: require(__dirname+'/models/document')
# ---------------------------------
# Collections
# Query Collection
QueryCollection: require(__dirname+'/base').QueryCollection
# Elements Collection
ElementsCollection: require(__dirname+'/collections/elements')
# Scripts Collection
ScriptsCollection: require(__dirname+'/collections/scripts')
# Styles Collection
StylesCollection: require(__dirname+'/collections/styles')
# Blocks
blocks: null
### {
# A collection of meta elements
meta: null # Elements Collection
# A collection of script elements
scripts: null # Scripts Collection
# Collection of style elements
styles: null # Styles Collection
} ###
# Collections
collections: null
### {
# Documents collection
documents: null # QueryEngine Collection
# Files collection
files: null # QueryEngine Collection
# Layouts collection
layouts: null # QueryEngine Collection
} ###
# Database collection
database: null # QueryEngine Collection
# Documents collection
# only here for b/c
documents: null # QueryEngine Collection
# ---------------------------------
# Plugins
# Plugins that are loading really slow
slowPlugins: null # {}
# Plugins which DocPad have found
foundPlugins: null # {}
# Loaded plugins indexed by name
loadedPlugins: null # {}
# A listing of all the available extensions for DocPad
exchange: null # {}
# -----------------------------
# Paths
# The DocPad directory
corePath: pathUtil.join(__dirname, '..')
# The DocPad library directory
libPath: __dirname
# The main DocPad file
mainPath: pathUtil.join(__dirname, 'docpad')
# The DocPad package.json path
packagePath: pathUtil.join(__dirname, '..', 'package.json')
# The DocPad local NPM path
npmPath: pathUtil.join(__dirname, '..', 'node_modules', 'npm', 'bin', 'npm-cli.js')
# -----------------------------
# Configuration
###
Instance Configuration
Loaded from:
- the passed instanceConfiguration when creating a new DocPad instance
- the detected websiteConfiguration inside ./docpad.cson>docpad
- the following configuration
###
config:
# -----------------------------
# Plugins
# Force re-install of all plugin dependencies
force: false
# Whether or not we should enable plugins that have not been listed or not
enableUnlistedPlugins: true
# Plugins which should be enabled or not pluginName: pluginEnabled
enabledPlugins: null # {}
# Whether or not we should skip unsupported plugins
skipUnsupportedPlugins: true
# Configuration to pass to any plugins pluginName: pluginConfiguration
plugins: null # {}
# Plugin directories to load
pluginPaths: null # []
# The website's plugins directory
pluginsPaths: null # ['node_modules','plugins']
# Where to fetch the exchange information from
exchangeUrl: 'https://raw.github.com/bevry/docpad-extras/docpad-5.x/exchange.json'
# -----------------------------
# Website Paths
# The website directory
rootPath: '.'
# The website's package.json path
packagePath: 'package.json'
# The website's docpad.cson path
configPath: 'docpad.cson'
# The website's out directory
outPath: 'out'
# The website's src directory
srcPath: 'src'
# The website's documents directory
documentsPath: pathUtil.join('src', 'documents')
# The website's files directory
filesPath: pathUtil.join('src', 'files')
# The website's layouts directory
layoutsPath: pathUtil.join('src', 'layouts')
# -----------------------------
# Server
# Server
# A express server that we want docpad to use
server: null
# Extend Server
# Whether or not we should extend the server with extra middleware and routing
extendServer: true
# Port
# The port that the server should use
port: 9778
# Max Age
# The caching time limit that is sent to the client
maxAge: false
# -----------------------------
# Logging
# Log Level
# Which level of logging should we actually output
logLevel: (if process.argv.has('-d') then 7 else 6)
# Logger
# A caterpillar instance if we already have one
logger: null
# Growl
# Whether or not to send notifications to growl when we have them
growl: true
# -----------------------------
# Other
# Node Path
# The location of our node executable
nodePath: if /node$/.test(process.execPath) then process.execPath else 'node'
# Git Path
# The location of our git executable
gitPath: if /^win/.test(process.platform) then 'git.cmd' else 'git'
# Template Data
# What data would you like to expose to your templates
templateData: null
# Report Errors
# Whether or not we should report our errors back to DocPad
reportErrors: true
# Check Version
# Whether or not to check for newer versions of DocPad
checkVersion: true
# Collections
# A hash of functions that create collections
collections: null
# =================================
# Initialization Functions
# Construct DocPad
# next(err)
constructor: (config={},next) ->
# Prepare
docpad = @
# Ensure certain functions always have the scope of this instance
_.bindAll(@, 'createDocument', 'createFile')
# Allow DocPad to have unlimited event listeners
@setMaxListeners(0)
# Initialize a default logger
@logger = new caterpillar.Logger
transports:
formatter: module: module
@setLogLevel(6)
logger = @logger
# Bind the error handler, so we don't crash on errors
process.setMaxListeners(0)
process.on 'uncaughtException', (err) ->
docpad.error(err)
# Initialize advanced variables
@slowPlugins = {}
@foundPlugins = {}
@loadedPlugins = {}
@exchange = {}
@collections = {}
@blocks = {}
# Initialize the collections
@database = new @QueryCollection()
# Apply configuration
@loadConfiguration config, {}, (err) =>
# Error?
return @error(err) if err
# Collections
@collections.documents = @database.createLiveChildCollection().setQuery('isDocument', fullPath: $beginsWith: @config.documentsPath)
@collections.files = @database.createLiveChildCollection().setQuery('isFile', fullPath: $beginsWith: @config.filesPath)
@collections.layouts = @database.createLiveChildCollection().setQuery('isLayout', fullPath: $beginsWith: @config.layoutsPath)
@documents = @collections.documents # only here for b/c
# Blocks
@blocks.meta = new @ElementsCollection()
@blocks.scripts = new @ScriptsCollection()
@blocks.styles = new @StylesCollection()
@blocks.meta.add([
'<meta http-equiv="X-Powered-By" content="DocPad"/>'
])
# Load Airbrake if we want to reportErrors
if @config.reportErrors and /win/.test(process.platform) is false
airbrake = require('airbrake').createClient('e7374dd1c5a346efe3895b9b0c1c0325')
# Version Check
@compareVersion()
# Log
logger.log 'debug', 'DocPad loaded succesfully'
logger.log 'debug', 'Loaded the following plugins:', _.keys(@loadedPlugins).sort().join(', ')
# Next
return next?()
# =================================
# Configuration
# Clean
clean: ->
# Perform a complete clean of our collections
@database.reset([])
@blocks.meta.reset([])
@blocks.scripts.reset([])
@blocks.styles.reset([])
# Chain
@
# Load a configuration url
# next(err,parsedData)
loadConfigUrl: (configUrl,next) ->
# Log
@logger.log 'debug', "Loading configuration url: #{configUrl}"
# Read the url using balUtil
balUtil.readPath configUrl, (err,data) ->
return next(err) if err
# Read the string using CSON
CSON.parse(data.toString(),next)
# Chain
@
# Load a configuration file
# CSON supports CSON and JSON
# next(err,parsedData)
loadConfigPath: (configPath,next) ->
# Log
@logger.log 'debug', "Loading configuration path: #{configPath}"
# Check that it exists
pathUtil.exists configPath, (exists) ->
return next?(null,null) unless exists
# Read the path using CSON
CSON.parseFile(configPath, next)
# Chain
@
# Load collections
loadCollections: (next) ->
# Prepare
docpad = @
database = @database
collections = @collections
@config.collections or= {}
# Group
tasks = new balUtil.Group (err) =>
docpad.error(err) if err
return next?()
# Cycle
_.each @config.collections, (fn,name) ->
tasks.push (complete) ->
if fn.length is 2 # callback
fn database, (err,collection) ->
docpad.error(err) if err
if collection
collection.live(true) # make it a live collection
collections[name] = collection # apply the collection
complete()
else
collection = fn(database)
if collection
collection.live(true) # make it a live collection
collections[name] = collection # apply the collection
complete()
# Run
tasks.async()
# Chain
@
# Load Configuration
loadConfiguration: (instanceConfig={},options={},next) ->
# Prepare
docpad = @
logger = @logger
# Options
options.blocking ?= true
# Exits
fatal = (err) ->
docpad.fatal(err,next)
complete = (err) ->
nextStep = ->
docpad.finish 'loading', (lockError) ->
return fatal(lockError) if lockError
return next?(err)
if options.blocking
docpad.unblock 'generating, watching, serving', (lockError) ->
return fatal(lockError) if lockError
nextStep()
else
nextStep()
# Define loading
startLoading = =>
# Start loading
docpad.start 'loading', (lockError) =>
return fatal(lockError) if lockError
# Prepare
instanceConfig.rootPath or= process.cwd()
instanceConfig.packagePath or= @config.packagePath
instanceConfig.configPath or= @config.configPath
docpadPackagePath = @packagePath
websitePackagePath = pathUtil.resolve(instanceConfig.rootPath, instanceConfig.packagePath) # only here for b/c
websiteConfigPath = pathUtil.resolve(instanceConfig.rootPath, instanceConfig.configPath)
websitePackageConfig = {}
websiteConfig = {}
# Async
tasks = new balUtil.Group (err) =>
return fatal(err) if err
# Merge Configuration (not deep!)
config = _.extend(
{}
@config
websitePackageConfig # only here for b/c
websiteConfig
instanceConfig
)
# Merge enabled plugins
config.enabledPlugins = _.extend(
{}
@config.enabledPlugins or {}
websiteConfig.enabledPlugins or {}
instanceConfig.enabledPlugins or {}
)
# Ensure advanced variables
config.plugins or= {}
config.pluginPaths or= []
config.pluginsPaths or= ['node_modules','plugins']
# Apply merged configuration
@config = config
# Options
@server = @config.server if @config.server
# Noramlize and resolve the configuration paths
@config.rootPath = pathUtil.normalize(@config.rootPath or process.cwd())
@config.outPath = pathUtil.resolve @config.rootPath, @config.outPath
@config.srcPath = pathUtil.resolve @config.rootPath, @config.srcPath
@config.documentsPath = pathUtil.resolve @config.rootPath, @config.documentsPath
@config.filesPath = pathUtil.resolve @config.rootPath, @config.filesPath
@config.layoutsPath = pathUtil.resolve @config.rootPath, @config.layoutsPath
for pluginsPath,index in @config.pluginsPaths
@config.pluginsPaths[index] = pathUtil.resolve(@config.rootPath, pluginsPath)
# Other
@config.templateData or= {}
# Logger
@logger = @config.logger if @config.logger
@setLogLevel(@config.logLevel)
# Async
postTasks = new balUtil.Group (err) =>
return fatal(err) if err
return complete()
postTasks.total = 2
# Load collections
@loadCollections(postTasks.completer())
# Initialize
@loadPlugins(postTasks.completer())
# Prepare configuration loading
tasks.total = 3
# Load DocPad Configuration
@loadConfigPath docpadPackagePath, (err,data) ->
return tasks.complete(err) if err
data or= {}
# Version
docpad.version = data.version
airbrake.appVersion = docpad.version if airbrake
# Compelte the loading
tasks.complete()
# Load Website Package Configuration
# only here for b/c
@loadConfigPath websitePackagePath, (err,data) ->
return tasks.complete(err) if err
data or= {}
# Apply data to parent scope
websitePackageConfig = data.docpad or {}
# Compelte the loading
tasks.complete()
# Load Website Configuration
@loadConfigPath websiteConfigPath, (err,data) ->
return tasks.complete(err) if err
data or= {}
# Apply data to parent scope
websiteConfig = data
# Compelte the loading
tasks.complete()
# Block other events
if options.blocking
docpad.block 'generating, watching, serving', (lockError) =>
return fatal(lockError) if lockError
startLoading()
else
startLoading()
# Chain
@
# Init Node Modules
# next(err,results)
initNodeModules: (opts={}) ->
# Prepare
opts.npmPath = @npmPath
opts.nodePath = @config.nodePath
opts.force = @config.force
# Forward
balUtil.initNodeModules(opts)
# Chain
@
# =================================
# Logging
# Set Log Level
setLogLevel: (level) ->
@logger.setLevel(level)
@
# Are we debugging?
getLogLevel: ->
return @config.logLevel
# Are we debugging?
getDebugging: ->
return @getLogLevel() is 7
# Handle a fatal error
fatal: (err) ->
return @ unless err
@error err, 'err', ->
process.exit(-1)
# Handle an error
error: (err,type='err',next) ->
# Prepare
docpad = @
logger = @logger
# Check
if !err or err.logged
next?()
return @
# Log the error only if it hasn't been logged already
err.logged = true
err = new Error(err) unless err instanceof Error
err.logged = true
logger.log type, 'An error occured:', err.message, err.stack
# Report the error back to DocPad using airbrake
if docpad.config.reportErrors and airbrake
err.params =
docpadVersion: @version
docpadConfig: @config
airbrake.notify err, (airbrakeErr,airbrakeUrl) ->
console.log(airbrakeErr) if airbrakeErr
console.log('Error has been logged to:', airbrakeUrl)
next?()
else
next?()
# Chain
@
# Handle a warning
warn: (message,err,next) ->
# Prepare
docpad = @
logger = @logger
# Log
logger.log('warn', message)
docpad.error(err, 'warn', next)
# Chain
@
# Perform a growl notification
notify: (args...) =>
# Check if we want to use growl
return @ unless @config.growl
# Try
try
# Load growl
growl = require('growl')
# Use growl
growl.apply(growl,args)
# Catch
catch err
# Ignore
# Chain
@
# =================================
# Models
# Instantiate a File
createFile: (data={},options={}) ->
# Prepare
options = _.extend(
logger: @logger
outDirPath: @config.outPath
,options)
# Create and return
file = new @FileModel(data,options)
# Return
return file
# Instantiate a Document
createDocument: (data={},options={}) ->
# Prepare
docpad = @
options = _.extend(
logger: @logger
outDirPath: @config.outPath
layouts: @collections.layouts
,options)
# Create and return
document = new @DocumentModel(data,options)
# Bubble
document.on 'render', (args...) ->
docpad.emitSync 'render', args...
document.on 'renderDocument', (args...) ->
docpad.emitSync 'renderDocument', args...
# Return
return document
# =================================
# Plugins
# Get a plugin by it's name
getPlugin: (pluginName) ->
@loadedPlugins[pluginName]
# Check if we have any plugins
hasPlugins: ->
return _.isEmpty(@loadedPlugins) is false
# Load Plugins
loadPlugins: (next) ->
# Prepare
docpad = @
logger = @logger
@slowPlugins = {}
snore = @createSnore ->
logger.log 'notice', "We're preparing your plugins, this may take a while the first time. Waiting on the plugins: #{_.keys(docpad.slowPlugins).join(', ')}"
# Async
tasks = new balUtil.Group (err) ->
docpad.slowPlugins = {}
snore.clear()
return next?(err)
# Load website plugins
_.each @config.pluginsPaths or [], (pluginsPath) =>
exists = pathUtil.existsSync(pluginsPath)
if exists
tasks.push (complete) =>
@loadPluginsIn(pluginsPath, complete)
# Load specific plugins
_.each @config.pluginPaths or [], (pluginPath) =>
exists = pathUtil.existsSync(pluginPath)
if exists
tasks.push (complete) =>
@loadPlugin(pluginPath, complete)
# Execute the loading asynchronously
tasks.async()
# Chain
@
# Loaded Plugin
# Checks if a plugin was loaded succesfully
# next(err,loaded)
loadedPlugin: (pluginName,next) ->
# Prepare
docpad = @
# Once loading has finished
docpad.onceFinished 'loading', (err) ->
return next(err) if err
loaded = docpad.loadedPlugins[pluginName]?
return next(null,loaded)
# Load PLugin
# next(err)
loadPlugin: (fileFullPath,_next) ->
# Prepare
docpad = @
logger = @logger
config = @config
next = (err) ->
# Remove from slow plugins
delete docpad.slowPlugins[pluginName]
# Forward
return _next(err)
# Prepare variables
loader = new PluginLoader(
dirPath: fileFullPath
docpad: docpad
BasePlugin: BasePlugin
)
pluginName = loader.pluginName
enabled = (
(config.enableUnlistedPlugins and config.enabledPlugins[pluginName]? is false) or
config.enabledPlugins[pluginName] is true
)
# Check if we already exist
if docpad.foundPlugins[pluginName]?
return _next()
# Add to loading stores
docpad.slowPlugins[pluginName] = true
docpad.foundPlugins[pluginName] = true
# Check
unless enabled
# Skip
logger.log 'debug', "Skipped plugin: #{pluginName}"
return next()
else
# Load
logger.log 'debug', "Loading plugin: #{pluginName}"
loader.exists (err,exists) ->
return next(err) if err or not exists
loader.unsupported (err,unsupported) ->
return next(err) if err
if unsupported
if unsupported is 'version' and docpad.config.skipUnsupportedPlugins is false
logger.log 'warn', "Continuing with the unsupported plugin: #{pluginName}"
else
if unsupported is 'type'
logger.log 'debug', "Skipped the unsupported plugin: #{pluginName} due to #{unsupported}"
else
logger.log 'warn', "Skipped the unsupported plugin: #{pluginName} due to #{unsupported}"
return next()
loader.install (err) ->
return next(err) if err
loader.load (err) ->
return next(err) if err
loader.create {}, (err,pluginInstance) ->
return next(err) if err
# Add to plugin stores
docpad.loadedPlugins[loader.pluginName] = pluginInstance
# Log completion
logger.log 'debug', "Loaded plugin: #{pluginName}"
# Forward
return next()
# Load Plugins
loadPluginsIn: (pluginsPath, next) ->
# Prepare
docpad = @
logger = @logger
# Load Plugins
logger.log 'debug', "Plugins loading for: #{pluginsPath}"
balUtil.scandir(
# Path
path: pluginsPath
# Ignore common patterns
ignorePatterns: true
# Skip files
fileAction: false
# Handle directories
dirAction: (fileFullPath,fileRelativePath,_nextFile) ->
# Prepare
pluginName = pathUtil.basename(fileFullPath)
return _nextFile(null,false) if fileFullPath is pluginsPath
nextFile = (err,skip) ->
if err
docpad.warn("Failed to load the plugin: #{pluginName} at #{fileFullPath}. The error follows:",err)
return _nextFile(null,skip)
# Forward
docpad.loadPlugin fileFullPath, (err) ->
return nextFile(err,true)
# Next
next: (err) ->
logger.log 'debug', "Plugins loaded for: #{pluginsPath}"
return next?(err)
)
# Chain
@
# =================================
# Utilities
# ---------------------------------
# Utilities: Misc
# Create snore
createSnore: (message) ->
# Prepare
logger = @logger
# Create snore object
snore =
snoring: false
timer: setTimeout(
->
snore.clear()
snore.snoring = true
if _.isFunction(message)
message()
else
logger.log 'notice', message
5000
)
clear: ->
if snore.timer
clearTimeout(snore.timer)
snore.timer = false
# Compare current DocPad version to the latest
compareVersion: ->
return @ unless @config.checkVersion
# Prepare
docpad = @
notify = @notify
logger = @logger
# Check
balUtil.packageCompare
local: pathUtil.join(docpad.corePath, 'package.json')
remote: 'https://raw.github.com/bevry/docpad/master/package.json'
newVersionCallback: (details) ->
docpad.notify "There is a new version of #{details.local.name} available"
docpad.logger.log 'notice', """
There is a new version of #{details.local.name} available, you should probably upgrade...
current version: #{details.local.version}
new version: #{details.remote.version}
grab it here: #{details.remote.homepage}
"""
@
# ---------------------------------
# Utilities: Rendering
# Get Template Data
getTemplateData: (userData) ->
# Prepare
userData or= {}
docpad = @
# Initial merge
templateData = _.extend({
require: require
include: (subRelativePath) ->
fullRelativePath = @document.relativeDirPath+'/'+subRelativePath
result = docpad.database.findOne(relativePath: fullRelativePath)
if result
return result.get('contentRendered') or result.get('content')
else
warn = "The file #{relativeBase} was not found..."
docpad.warn(warn)
return warn
docpad: @
database: @database
collections: @collections
document: null
site: {}
blocks: @blocks
}, @config.templateData, userData)
# Add site data
templateData.site.date or= new Date()
templateData.site.keywords or= []
if _.isString(templateData.site.keywords)
templateData.site.keywords = templateData.site.keywords.split(/,\s*/g)
# Return
return templateData
# Render a document
# next(err,document)
render: (document,templateData,next) ->
templateData = _.extend({},templateData)
templateData.document = document.toJSON()
templateData.documentModel = document
document.render templateData, (err) =>
@error(err) if err
return next?(err,document)
# Chain
@
# Render a document
# next(err,document)
prepareAndRender: (document,templateData,next) ->
# Prepare
docpad = @
# Normalize the document
document.normalize (err) ->