|
| 1 | +const {appendFile, exists, readFile, writeFile} = require('fs-extra'); |
| 2 | + |
| 3 | +const HEADER_COMMENT = `## Created with gatsby-transformer-versions-yaml`; |
| 4 | + |
| 5 | +// Patterned after the 'gatsby-plugin-netlify' plug-in: |
| 6 | +// https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-plugin-netlify/src/create-redirects.js |
| 7 | +module.exports = async function writeRedirectsFile( |
| 8 | + redirects, |
| 9 | + redirectsFilePath, |
| 10 | +) { |
| 11 | + if (!redirects.length) { |
| 12 | + return null; |
| 13 | + } |
| 14 | + |
| 15 | + // Map redirect data to the format Netlify expects |
| 16 | + // https://www.netlify.com/docs/redirects/ |
| 17 | + redirects = redirects.map(redirect => { |
| 18 | + const { |
| 19 | + fromPath, |
| 20 | + isPermanent, |
| 21 | + redirectInBrowser, // eslint-disable-line no-unused-vars |
| 22 | + toPath, |
| 23 | + ...rest |
| 24 | + } = redirect; |
| 25 | + |
| 26 | + // The order of these parameters is significant. |
| 27 | + const pieces = [ |
| 28 | + fromPath, |
| 29 | + toPath, |
| 30 | + isPermanent ? 301 : 302, // Status |
| 31 | + ]; |
| 32 | + |
| 33 | + for (let key in rest) { |
| 34 | + const value = rest[key]; |
| 35 | + |
| 36 | + if (typeof value === `string` && value.indexOf(` `) >= 0) { |
| 37 | + console.warn( |
| 38 | + `Invalid redirect value "${value}" specified for key "${key}". ` + |
| 39 | + `Values should not contain spaces.`, |
| 40 | + ); |
| 41 | + } else { |
| 42 | + pieces.push(`${key}=${value}`); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + return pieces.join(` `); |
| 47 | + }); |
| 48 | + |
| 49 | + let appendToFile = false; |
| 50 | + |
| 51 | + // Websites may also have statically defined redirects |
| 52 | + // In that case we should append to them (not overwrite) |
| 53 | + // Make sure we aren't just looking at previous build results though |
| 54 | + const fileExists = await exists(redirectsFilePath); |
| 55 | + if (fileExists) { |
| 56 | + const fileContents = await readFile(redirectsFilePath); |
| 57 | + if (fileContents.indexOf(HEADER_COMMENT) < 0) { |
| 58 | + appendToFile = true; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + const data = `${HEADER_COMMENT}\n\n${redirects.join(`\n`)}`; |
| 63 | + |
| 64 | + return appendToFile |
| 65 | + ? appendFile(redirectsFilePath, `\n\n${data}`) |
| 66 | + : writeFile(redirectsFilePath, data); |
| 67 | +}; |
0 commit comments