Skip to content

Commit

Permalink
サイトマップ生成 locだけよお
Browse files Browse the repository at this point in the history
  • Loading branch information
garypippi committed May 4, 2024
1 parent 6da6c42 commit 19a18b9
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 4 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ jobs:
npm ci
npm run build
npm run export
npm run build:cli
HOST_URL="${{ vars.HOST_URL }}" node ./cli/index.mjs sitemap
mkdir -m 700 ~/.ssh
echo "${{ secrets.SSH_KEY }}" > ~/.ssh/id_rsa
echo "${{ secrets.SSH_KNOWN_HOSTS }}" > ~/.ssh/known_hosts
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/node_modules
/public
/cli/index.js
/cli/**/*.mjs
/out
/.next
/.env.local
1 change: 1 addition & 0 deletions cli/cmds/index.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './sitemap.mjs'
39 changes: 39 additions & 0 deletions cli/cmds/sitemap.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { join } from 'path'
import { existsSync, readdirSync, createWriteStream } from 'fs'

const outDir = join(process.cwd(), 'out')
const ignore = [/^_next$/, /^404\.html/, /^tags$/, /^sitemap\.xml$/, /^index\.html$/]
const output = join(outDir, 'sitemap.xml')

const hostURL = process.env.HOST_URL

export const sitemap = () => {
if (!hostURL) {
throw new Error('Please provide HOST_URL environment variable')
}
if (!existsSync(outDir)) {
throw new Error(`Directory ${outDir} does not exist.`)
}

const handle = createWriteStream(output, {
encoding: 'utf8',
})

handle.write('<?xml version="1.0" encoding="UTF-8"?>\n')
handle.write('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n')

handle.write('<url>\n')
handle.write(` <loc>${hostURL}/</loc>\n`)
handle.write('</url>\n')

readdirSync(outDir)
.filter(file => !ignore.some(re => re.test(file)))
.forEach(file => {
handle.write('<url>\n')
handle.write(` <loc>${hostURL}/${file.replace(/^([^.]+)\.html$/, '$1')}</loc>\n`)
handle.write('</url>\n')
})

handle.write('</urlset>')
handle.close()
}
7 changes: 4 additions & 3 deletions cli/index.ts → cli/index.mts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
/**
* command line utilities
*/
import cli from 'commander'
import * as cmd from './cmds/index.mjs'
import { join } from 'path'
import { randomBytes } from 'crypto'
import { mkdir, writeFile } from 'fs'
Expand Down Expand Up @@ -37,5 +35,8 @@ cli.command('add <dir>')
})
})

cli.command('sitemap')
.action(cmd.sitemap)

// parse arguments and run
cli.parse(process.argv)

0 comments on commit 19a18b9

Please sign in to comment.