move-songs.js

import fs from 'fs';
import path from 'path';

const directoryPath = '/home/jsbisht/workspace/site/rhythm-guitar/src/pages';

function fromDir(startPath) {
	if (!fs.existsSync(startPath)) {
		console.log(`${startPath} is not a valid path`);
		return;
	}
	const metas = [];
	const directories = fs.readdirSync(startPath);
	for (var i = 0; i < directories.length; i++) {
		const directory = directories[i];
		const directoryName = path.join(startPath, directory);
		const stat = fs.lstatSync(directoryName);
		if (stat.isDirectory() && directory !== 'about') {
			console.log('-- found:', directory.substring(11));
			const filename = path.join(directoryName, 'index.md');
			const content = fs.readFileSync(filename, 'utf8');
			const { slug, meta, lyrics } = getMeta(content);
			metas.push(meta);
			writeFile(slug, lyrics);
		}
	}
	writeJsonFile(metas);
}

function writeJsonFile(data) {
	const directoryPath = 'rhythm-guitar-svelte/src/data';
	const filename = path.join(directoryPath, 'meta.json');
	const content = JSON.stringify(data, null, 2);
	fs.writeFileSync(filename, content);
}

function writeFile(slug, lyrics) {
	const directoryPath = 'rhythm-guitar-svelte/src/data';
	const filename = path.join(directoryPath, `${slug}.js`);
	if (fs.existsSync(filename)) return;
	const content = 'export default `' + lyrics + '`;';
	fs.writeFileSync(filename, content);
}

function getMeta(content) {
	const meta = {
		instrument: 'Guitar',
		capo: null,
		metronome: null,
		difficulty: null
	};
	const lines = content.split(/\r?\n/);
	let lyrics = '';
	let isReadingLyrics = false;
	for (let line of lines) {
		let text = '';
		if (line.includes('path:')) {
			meta['slug'] = line.slice(0, -1).substr('8');
		} else if (line.includes('Song')) {
			meta['title'] = line.slice(0, -6).substring(8);
		} else if (line.includes('Movie')) {
			meta['movie'] = line.slice(0, -6).substring(9);
		} else if (line.includes('Artist')) {
			text = line
				.slice(0, -6)
				.substring(10)
				.split(',')
				.map((x) => x.trim());
			meta['artists'] = text;
		} else if (line.includes('Released')) {
			meta['year'] = line.slice(0, -2).substring(12);
		} else if (line.includes('Strumming Pattern:')) {
			const patterns = line.slice(0, -7).substring(22);
			meta['strumming'] =
				patterns.split('|').map((x) => x.trim()) ||
				patterns.split(',').map((x) => x.trim()) ||
				patterns.split('or').map((x) => x.trim()) ||
				patterns.split('and').map((x) => x.trim()) ||
				patterns;
		} else if (line.includes('Capo Used:')) {
			text = line.includes('No Capo') ? null : line.slice(0, -7).substring(14).slice(0, 1);
			meta['capo'] = text ? parseInt(text) : null;
		} else if (line.includes('```')) {
			isReadingLyrics = !isReadingLyrics;
		} else if (isReadingLyrics) {
			lyrics += line + '\n';
		}
	}
	const { slug } = meta;
	return {
		slug,
		meta,
		lyrics
	};
}

fromDir(directoryPath);