-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
215 lines (187 loc) · 7.13 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
const fs = require('fs-extra')
const path = require('path')
const { logger, globby, sort } = require('@vuepress/shared-utils')
const convertRouterLinkPlugin = require('./lib/link')
const { generateVersionedPath, snapshotSidebar, updateSidebarConfig } = require('./lib/util')
const versionManager = require('./lib/version-manager')
module.exports = (options, context) => {
const pluginName = 'titanium/versioning'
const versionedSourceDir = options.versionedSourceDir || path.resolve(context.sourceDir, '..', 'website', 'versioned_docs')
const pagesSourceDir = options.pagesSourceDir || path.resolve(context.sourceDir, '..', 'website', 'pages')
const versionsFilePath = path.join(context.sourceDir, '.vuepress', 'versions.json')
versionManager.loadVersions(versionsFilePath)
const versions = versionManager.versions
const defaultPluginOptions = {
name: pluginName,
/**
* Reads in the snaphotted sidebar configs and rewrites them to be versioned
*/
ready () {
if (versions.length === 0) {
return
}
updateSidebarConfig(context.themeConfig, 'next')
const currentVersion = versions[0]
context.themeConfig.versionedSidebar = {}
for (const version of versions) {
const versionSidebarConfigPath = path.join(versionedSourceDir, version, 'sidebar.config.json')
if (!fs.existsSync(versionSidebarConfigPath)) {
continue
}
const sidebarConfig = JSON.parse(fs.readFileSync(versionSidebarConfigPath).toString())
if (version !== currentVersion) {
updateSidebarConfig(sidebarConfig, version)
}
context.themeConfig.versionedSidebar[version] = sidebarConfig
}
},
/**
* Extends the cli with new commands to manage versions
*/
extendCli (cli) {
cli
.command('version <targetDir> <version>', 'Draft a new version')
.allowUnknownOptions()
.action(async (dir, version) => {
if (versions.includes(version)) {
logger.error(`Version ${version} already exists in version.json. Please use a different version.`)
return
}
logger.wait(`Creating new version ${version} ...`)
const versionDestPath = path.join(versionedSourceDir, version)
await fs.copy(context.sourceDir, versionDestPath, {
filter: (src, dest) => {
if (src === context.vuepressDir) {
return false
}
return true
}
})
await snapshotSidebar(context.siteConfig, versionDestPath)
if (typeof options.onNewVersion === 'function') {
await options.onNewVersion(version, versionDestPath)
}
versions.unshift(version)
await fs.writeFile(versionsFilePath, JSON.stringify(versions, null, 2))
logger.success(`Snapshotted your current docs as version ${version}`)
logger.tip(`You can find them under ${versionDestPath}`)
})
},
/**
* Adds additional pages from versioned docs as well as unversioned extra pages.
*/
async additionalPages () {
const patterns = ['**/*.md', '**/*.vue', '!.vuepress', '!node_modules']
const addPages = (pageFiles, basePath) => {
const pages = []
pageFiles.map(relative => {
const filePath = path.resolve(basePath, relative)
pages.push({
filePath,
relative
})
})
return pages
}
let versionedPages = []
if (await fs.exists(versionedSourceDir)) {
const versionedPageFiles = sort(await globby(patterns, { cwd: versionedSourceDir }))
versionedPages = addPages(versionedPageFiles, versionedSourceDir)
}
let pages = []
if (await fs.exists(pagesSourceDir)) {
const pageFiles = sort(await globby(patterns, { cwd: pagesSourceDir }))
pages = addPages(pageFiles, pagesSourceDir)
}
return [...versionedPages, ...pages]
},
/**
* Marks unversioned pages from the pageSourceDir
*
* @param {Object} page VuePress page object
*/
extendPageData (page) {
if (!page._filePath) {
return
}
if (page._filePath.startsWith(pagesSourceDir)) {
page.unversioned = true
}
}
}
if (versions.length === 0) {
return defaultPluginOptions
}
return Object.assign(defaultPluginOptions, {
/**
* Extends and updates a page with additional information for versioning support.
*/
extendPageData (page) {
const currentVersion = versions[0]
if (!page._filePath) {
return
}
if (page._filePath.startsWith(versionedSourceDir)) {
const version = page._filePath.substring(versionedSourceDir.length + 1, page._filePath.indexOf('/', versionedSourceDir.length + 1))
page.version = version
page.originalRegularPath = page.regularPath
const pathWithoutLeadingVersion = page.path.replace(new RegExp(`^/${version}`), '')
if (version === currentVersion) {
page.path = page.regularPath = pathWithoutLeadingVersion
} else {
page.path = page.regularPath = generateVersionedPath(pathWithoutLeadingVersion, page.version, page._localePath)
}
page.originalRelativePath = page.relativePath
page.relativePath = path.relative(versionedSourceDir, page._filePath).replace(/\\/g, '/')
} else if (page._filePath.startsWith(pagesSourceDir)) {
page.unversioned = true
page.originalRelativePath = page.relativePath
page.relativePath = path.relative(pagesSourceDir, page._filePath).replace(/\\/g, '/')
} else if (page._filePath.startsWith(context.sourceDir)) {
page.version = 'next'
page.originalRegularPath = page.regularPath
page.path = page.regularPath = generateVersionedPath(page.path, page.version, page._localePath)
}
},
/**
* Enhances the app with a globally accessible list of available versions.
*
* @fixme ideally this should go into siteData but that is not extendable
* right now so store versions as a computed property on Vue
*/
enhanceAppFiles: [{
name: 'versions-site-data',
content: `export default ({ Vue }) => {
Vue.mixin({
computed: {
$versions: () => ${JSON.stringify(versions)}
}
})
}`
}],
/**
* Replaces the default convert-router-link plugin from VuePress with a
* modified one that knows how to properly handle relative links for the
* rewritten paths of versioned pages.
*
* @param {*} config
*/
chainMarkdown (config) {
config.plugins.delete('convert-router-link')
const { externalLinks } = context.siteConfig.markdown || {}
config
.plugin('convert-router-link-versioned')
.use(convertRouterLinkPlugin, [{
externalAttrs: Object.assign({
target: '_blank',
rel: 'noopener noreferrer'
}, externalLinks),
sourceDir: context.sourceDir,
versionedSourceDir,
pagesSourceDir,
locales: Object.keys(context.siteConfig.locales || {}).filter(l => l !== '/')
}])
.end()
}
})
}