diff --git a/src/__tests__/index.js b/src/__tests__/index.js index 6ee4faf..c761bec 100644 --- a/src/__tests__/index.js +++ b/src/__tests__/index.js @@ -3,6 +3,7 @@ jest.mock(`fs`, () => { existsSync: jest.fn(), readdirSync: jest.fn(), readFileSync: jest.fn(), + lstatSync: jest.fn(), }; }); @@ -28,6 +29,7 @@ describe('gatsby-remark-embedded-codesandbox', () => { fs.existsSync.mockReset(); fs.readdirSync.mockReset(); fs.readFileSync.mockReset(); + fs.lstatSync.mockReset(); fs.existsSync.mockReturnValue(true); fs.readdirSync.mockReturnValue(['index.html', 'index.js', 'package.json']); @@ -35,6 +37,11 @@ describe('gatsby-remark-embedded-codesandbox', () => { .mockReturnValueOnce('') .mockReturnValueOnce('const foo = "bar";') .mockReturnValueOnce('{ "name": "example" }'); + fs.lstatSync.mockReturnValue({ + isDirectory: function() { + return false; + }, + }); }); it(`generates an embedded sandbox for the specified example folder`, async () => { diff --git a/src/index.js b/src/index.js index f8fb78c..5fd9324 100644 --- a/src/index.js +++ b/src/index.js @@ -21,6 +21,18 @@ const compress = string => .replace(/\//g, `_`) // Convert '/' to '_' .replace(/=+$/, ``); // Remove ending '=' +const getFiles = (baseDir, dir, files) => { + fs.readdirSync(dir).forEach(function(file) { + var subDir = path.join(dir, file); + if (fs.lstatSync(subDir).isDirectory()) { + getFiles(baseDir, subDir, files); + } else { + let filePath = path.join(dir, file); + files.push(filePath.replace(`${baseDir}/`, '')); + } + }); +}; + module.exports = ( { markdownAST }, { @@ -46,18 +58,21 @@ module.exports = ( const getFilesList = directory => { let packageJsonFound = false; - const folderFiles = fs.readdirSync(directory); - const sandboxFiles = folderFiles + const folderFiles = []; + const sandboxFiles = []; + getFiles(directory, directory, folderFiles); + + folderFiles // we ignore the package.json file as it will // be handled separately .filter(file => file !== 'package.json') .map(file => { const fullFilePath = path.resolve(directory, file); const content = fs.readFileSync(fullFilePath, 'utf-8'); - return { + sandboxFiles.push({ name: file, content, - }; + }); }); let workingDir = directory;