forked from arve0/codeclub_lesson_builder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplaylist.js
81 lines (65 loc) · 2.19 KB
/
playlist.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
var fs = require('fs');
var path = require('path');
var yaml = require('yaml-front-matter');
var _ = require('lodash');
/*
* export
*/
module.exports = function(collectionRoot, playlistFolder){
// return playlists found in collectionRoot/playlistFolder
var playlistRoot = path.join(collectionRoot, playlistFolder);
if (!fs.existsSync(playlistRoot)) {
return [];
}
// create a list of playlists
var playlistFiles = fs.readdirSync(playlistRoot);
playlistFiles = _.map(playlistFiles, withPath, {root: playlistRoot});
playlistFiles = _.filter(playlistFiles, isPlaylist);
var playlists = _.map(playlistFiles, getPlaylist, {root: collectionRoot});
return playlists;
};
/*
* helper functions
*/
function withPath(filename) {
// add path to filename
return path.join(this.root, filename);
}
function isPlaylist(filename) {
// if not directory and ends with .txt
return filename.match(/\.txt$/) &&
!fs.statSync(filename).isDirectory();
}
function playlistId(name){
// replace chars in playlist-name, so that it can be used as id or class
var id = name.replace(/ /g, '_');
id = id.replace(/[\,\.\-\?]/g, '');
return id;
}
function getLink(root, filename) {
var link = filename.replace('.md', '.html');
link = path.relative(root, link);
link = path.join(path.basename(root), link);
return link;
}
function getPlaylist(filename) {
var lessonFiles = fs.readFileSync(filename, {encoding: 'utf8'})
.replace(/\r/g, '')
.split('\n');
lessonFiles = _.compact(lessonFiles); // omit empty lines
lessonFiles = _.map(lessonFiles, withPath, {root: this.root});
var playlist = {};
playlist.name = path.basename(filename).replace('.txt', '').replace(/_/g, ' ');
playlist.id = playlistId(playlist.name);
playlist.lessons = _.map(lessonFiles, getFrontMatter, {root: this.root});
return playlist;
}
function getFrontMatter(filename){
// return front matter of file, its filename and link
var content = fs.readFileSync(filename);
var frontMatter = yaml.loadFront(content);
frontMatter = _.omit(frontMatter, '__content');
frontMatter.filename = filename;
frontMatter.link = getLink(this.root, filename);
return frontMatter;
}