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