Skip to content

Commit

Permalink
test non-svg knitr dev output
Browse files Browse the repository at this point in the history
  • Loading branch information
dmca-glasgow committed May 11, 2022
1 parent ddd2b16 commit 5a54b6e
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 30 deletions.
2 changes: 1 addition & 1 deletion compiler/src/course/__test__/load-course.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ describe('loadCourse', () => {
const courseYaml = path.join('fixtures', 'basic', 'course.yaml');

try {
await fixtureTestProcessor('basic', { week: 2 });
await fixtureTestProcessor('basic', { week: 2, shouldFail: true });
} catch (err) {
expect(err).toContain(`Week 2 not found in ${courseYaml}`);
}
Expand Down
19 changes: 16 additions & 3 deletions compiler/src/knitr/__test__/knitr.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,11 +78,24 @@ describe('knitr', () => {
`,
{ noEmbedAssets: false }
);
expect(html).toContain('<svg xmlns="http://www.w3.org/2000/svg"');
});

it('should output a graph as png', async () => {
const { html } = await testProcessor(
`
\`\`\`{r, dev='png'}
x <- rnorm(100)
hist(x)
\`\`\`
`,
{ noEmbedAssets: false }
);

const match =
html.match(/<svg alt="plot of chunk unnamed-chunk-2"/) || [];
expect(html).toContain('<img src="data:image/png;base64');

expect(match.length).toBe(1);
// testing fig.retina=2 in knitr.R
expect(html).toContain('style="max-width: 1008px"');
});

it('should ignore tab whitespace', async () => {
Expand Down
3 changes: 2 additions & 1 deletion compiler/src/knitr/knitr.R
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ knitr::opts_knit$set(root.dir=baseDir)
knitr::opts_chunk$set(
dev='svglite',
class.output='knitr-output',
fig.path=cacheDir
fig.path=cacheDir,
fig.retina=2
)

knitr::knit(
Expand Down
69 changes: 47 additions & 22 deletions compiler/src/knitr/knitr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { mkdir, rmFile, writeFile } from '../utils/utils';

export async function knitr(unit: Unit, ctx: Context) {
const parentFile = await createParentFile(unit, ctx);
// console.log(parentFile.value);

const result = await execKnitr(parentFile, ctx, unit.unitPath);
// console.log(result);
Expand Down Expand Up @@ -61,7 +62,6 @@ async function createParentFile(unit: Unit, ctx: Context) {
return file;
}

// TODO: see what can be done with output when "quiet" in knitr.R is turned off
async function execKnitr(file: VFile, ctx: Context, unitPath: string) {
const md = file.value as string;
const uniqueId = getUniqueId(md);
Expand Down Expand Up @@ -105,6 +105,10 @@ function createKnitrCommand(
const baseDir = path.parse(unitPath).dir;
const cachedFile = path.join(ctx.cacheDir, `${uniqueId}.Rmd`);
const cacheDir = path.join(ctx.cacheDir, uniqueId);

// spawn args
// return [rFile, cachedFile, baseDir, cacheDir];

return `Rscript "${rFile}" "${cachedFile}" "${baseDir}" "${cacheDir}"`;
}

Expand Down Expand Up @@ -233,24 +237,45 @@ function findLanguageForOutput(prev: string[]) {
return match[1];
}

// attempt at changing knitr output. doesn't completely work
// const hooks = `
// knit_hooks$set(
// source = function(x, options) {
// paste(c("\`\`\`r", x, "\`\`\`"), collapse = "\n")
// },
// output = function(x, options) {
// paste(c("\`\`\`", x, "\`\`\`"), collapse = "\n")
// },
// error = function(x, options) {
// paste(
// c(
// "\`\`\`plaintext error",
// gsub("## Error", "\#\# Error", x),
// "\`\`\`"
// ),
// collapse = "\n"
// )
// }
// )
// `;
// experimental streaming output
// async function spawnKnitr(file: VFile, ctx: Context, unitPath: string) {
// const md = file.value as string;
// const uniqueId = getUniqueId(md);
// const cachedFile = path.join(ctx.cacheDir, `${uniqueId}.Rmd`);
// const cacheDir = path.join(ctx.cacheDir, uniqueId);
// await mkdir(cacheDir);
// await writeFile(cachedFile, md);

// return new Promise<string>((resolve, reject) => {
// const args = createKnitrCommand(ctx, uniqueId, unitPath);
// const knitr = spawn('Rscript', args);
// const result: string[] = [];

// knitr.stdout.on('data', (data) => {
// const str = data.toString();
// console.log(str);
// result.push(str);
// });

// knitr.stdout.on('end', () => {
// console.log('STDOUT END');
// const end = result.join('');
// console.log('END', end);
// reportErrors(end, file);
// resolve(formatResponse(end));
// });

// knitr.stdout.on('error', (err) => {
// console.log('STDOUT ERROR', err, err.toString());
// reject();
// });

// knitr.stderr.on('data', (data) => {
// const str = data.toString();
// console.log('STDERR ERROR', str);
// });
// }).then(async (result) => {
// await rmFile(cachedFile);
// return result;
// });
// }
2 changes: 1 addition & 1 deletion compiler/src/mdast/images.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ function template(node: Image, count: number) {
],
};

if (node.data?.width) {
if (node.data?.width && /^\d+px/.test(String(node.data.width))) {
image.properties = {
...image.properties,
style: `width: ${node.data.width};`,
Expand Down
8 changes: 6 additions & 2 deletions compiler/src/test-utils/fixture-test-processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,15 @@ export async function fixtureTestProcessor(

exec(cmd, (err, response, stdErr) => {
if (stdErr) {
console.log(stdErr);
if (!options.shouldFail) {
console.log(stdErr);
}
reject(stdErr);
}
if (err) {
console.error(err);
if (!options.shouldFail) {
console.error(err);
}
reject(err);
}
resolve(response);
Expand Down

0 comments on commit 5a54b6e

Please sign in to comment.