This repository has been archived by the owner on Apr 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
playlists.js
66 lines (57 loc) · 1.82 KB
/
playlists.js
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
const config = require('./config.js')
const path = require('path')
/**
* Metalsmith plugin.
* Make global playlists object.
* Usage:
* Metalsmith.use(playlists({
* collections: ['python', 'scratch']
* }))
*/
module.exports = function (opts) {
opts = opts || {}
opts.collections = opts.collections || []
return function (files, metalsmith, done) {
const metadata = metalsmith.metadata()
metadata.playlists = {}
// for each collection
opts.collections.map((collection) => {
// /course\/playlists\/[^\/]+txt$/
const re = new RegExp([collection, config.playlistFolder,
'[^', ']+txt$'].join('\\' + path.sep))
// [ course/playlists/learn_python.txt, ...]
const playlists = Object.keys(files).filter((file) => {
return file.search(re) === 0
})
metadata.playlists[collection] = []
for (let file of playlists) {
const playlist = {}
playlist.name = playlistName(file)
playlist.id = playlistId(playlist.name)
let lessons = files[file].contents.toString('utf8')
lessons = lessons.match(/[^\r\n]+/g) // read lines
playlist.lessons = lessons.map((file) => {
const key = path.normalize(path.join(collection, ...file.split('/')))
if (!files[key]) {
console.warn('playlist: file not found')
console.warn(key + ' in ' + file)
}
return files[key]
})
metadata.playlists[collection].push(playlist)
}
})
done()
}
}
function playlistName (filename) {
return path.basename(filename).replace('.txt', '').replace(/_/g, ' ')
}
/**
* replace chars in playlist-name, so that it can be used as id or class
*/
function playlistId (name) {
var id = name.replace(/ /g, '_')
id = id.replace(/[\,\.\-\?]/g, '')
return id
}