license import { execFileSync } from 'child_process' ; import * as fs from 'fs' ; import * as path from 'path' ; import { URL } from 'url' ; const mwcRepoRoot = path . resolve ( __dirname , '..' , '..' ) ; const githubRaw = `https://raw.githubusercontent.com/material-components/material-components-web-components` ; const markdownImageRegexp = /(\!\[.*?\]\()([^) ]+)(.*?\))/g ; const htmlImageRegexp = /(<img .*?src=['"])(.+?)(['"])/g ; function isUrl ( str ) { try { new URL ( str ) ; } catch ( e ) { return false ; } return true ; } function main ( ) { const fileNames = process . argv . slice ( 2 ) ; if ( fileNames . length === 0 ) { throw new Error ( 'Expected at least one markdown file argument.' ) ; } const sha = execFileSync ( 'git' , [ 'rev-parse' , '--verify' , 'master' ] , { encoding : 'utf8' } ) . trim ( ) ; for ( const fileName of fileNames ) { const markdown = fs . readFileSync ( fileName , 'utf8' ) ; const replacer = ( _ , prefix , oldUrl , suffix ) => { if ( isUrl ( oldUrl ) ) { return prefix + oldUrl + suffix ; } const absFilePath = path . resolve ( path . dirname ( fileName ) , oldUrl ) ; if ( ! fs . existsSync ( absFilePath ) ) { throw new Error ( `Image file does not exist: ${ absFilePath }` ) ; } const relUrlPath = path . relative ( mwcRepoRoot , absFilePath ) . replace ( path . win32 . sep , '/' ) ; const newUrl = `${ githubRaw }/${ sha }/${ relUrlPath }` ; return prefix + newUrl + suffix ; } ; const updated = markdown . replace ( markdownImageRegexp , replacer ) . replace ( htmlImageRegexp , replacer ) ; fs . writeFileSync ( fileName , updated , 'utf8' ) ; } } main ( ) ;