gitlab wiki 页面中的 Javascript/html?

sw_*_*ddy 3 javascript wiki gitlab

恐怕我真的不知道如何做到这一点 - 我想在 Gitlab Wiki 页面中使用变量。这完全可以使用 html 吗?我可以在页面上运行脚本吗?

例如,这个关于在 html 中使用 javascript 变量的问题- 这样的事情可能吗?

对于我的具体示例,我想要一个带有表格的页面,其中第一列是数字,并且我想取最大值并将其显示在页面顶部。例如,该表可能有如下行:

1   X
22  Y
15  Z
Run Code Online (Sandbox Code Playgroud)

所以在页面的顶部我会显示“最大的数字是 22”。这有意义吗?

ble*_*lex 5

您的 Wikipage 中不能有脚本,因为它们会清理 HTML(在此处查看它们允许的内容)。要执行您想要的操作,您可以在 Gitlab-CI 中生成该页面作为项目部署管道的一部分,使用任何渲染引擎并将该变量放入其中,然后使用Gitlab 的 Wiki API自动更新它。

如何

我在这里创建了一个演示 NodeJS 项目,当我推送到master分支时,它会自动生成Wiki 页面。您可以查看代码以了解其工作原理。

这个示例应用程序公开了一个函数来获取水果列表和库存数量。我们会自动将这些数据添加到 Wiki 中。

步骤 1 - 创建页面模板

您可以将模板添加到您的 Wiki 页面的项目中。在我的示例中,我使用了MustacheJS。我将所有内容都放在一个wiki文件夹中(请参阅第 5 步末尾的文件夹结构)。您的模板可能如下所示:

维基/模板/home.mst

# Welcome to the supermarket

The biggest quantity we have in stock is for **{{topProduct.label}}**,
with a total of **{{topProduct.stock}}**!

|   Fruit   |   Quantity   |
|-----------|--------------|
{{#inventory}}
| {{label}} | {{stock}} |
{{/inventory}}
Run Code Online (Sandbox Code Playgroud)

在本例中,数据将来自项目代码本身。

第 2 步 - 构建您的页面

注意:我作为演示编写的脚本axios用于向 Gitlab API 发出请求、mustache呈现页面以及qs在将数据发布到 Gitlab 之前将数据格式化为查询字符串。您可以使用其他的或将它们安装为开发依赖项: npm install --save-dev axios mustache qs

创建一个 js 文件,它将从您的应用程序中获取数据,并将模板渲染到一个build目录中。像这样的东西:

维基/build.js

const fs = require('fs');
const Mustache = require('mustache');
const myApp = require('../src/index.js');
const inventory = myApp.getInventory();

// Get the Mustache template
const homeTemplate = fs.readFileSync(__dirname + '/templates/home.mst', 'utf-8');

// Get the fruit with the highest quantity
const topProduct = inventory.reduce((acc, curr) => {
  if (acc === null || curr.stock > acc.stock) {
    return curr;
  } else {
    return acc;
  }
}, null);

// Render the page using your variables
const homeContent = Mustache.render(homeTemplate, { inventory, topProduct });

// Write the file in a build directory
const buildDir = __dirname + '/../build';
if (!fs.existsSync(buildDir)) {
  fs.mkdirSync(buildDir);
}

fs.writeFileSync(buildDir + '/home.md', homeContent);
Run Code Online (Sandbox Code Playgroud)

在您的 中package.json,添加一个命令来运行该脚本:

"scripts": {
    // ...
    "wiki:build": "node wiki/build.js"
  }
Run Code Online (Sandbox Code Playgroud)

第 3 步 - 部署您的 Wiki 页面

创建一个脚本,将页面上传到您的 Wiki。如果您还使用 NodeJS,这可以按原样工作,无需太多修改。

维基/部署.js

const fs = require('fs');
const Axios = require('axios');
const qs = require('qs');

const config = {
  gitlabBaseUrl: 'https://gitlab.com', // Update this if you're on a private Gitlab
  projectId: process.env.CI_PROJECT_ID, // Provided by Gitlab-CI
  privateToken: process.env.WIKI_DEPLOY_TOKEN, // Added through Gitlab interface
  buildDir: __dirname + '/../build'
};

const axios = Axios.create({
  baseURL: config.gitlabBaseUrl,
  headers: { 'Private-Token': config.privateToken, Accept: 'application/json' }
});

(async function deploy() {
  const existingPages = await getExistingWikiPages();
  const updatedPages = getUpdatedPages();
  // Pages which existed but are no longer in the build (obsolete)
  const pagesToDelete = existingPages.filter(p1 => updatedPages.every(p2 => p2.slug !== p1.slug));
  // Pages which didn't exist before
  const pagesToCreate = updatedPages.filter(p1 => existingPages.every(p2 => p2.slug !== p1.slug));
  // Pages which already exist
  const pagesToUpdate = updatedPages.filter(p1 => existingPages.some(p2 => p2.slug === p1.slug));

  console.log(
    `Found ${pagesToDelete.length} pages to delete, ${pagesToCreate.length} pages to create, ${pagesToUpdate.length} pages to update.`
  );
  for (let page of pagesToDelete) {
    await deletePage(page);
  }
  for (let page of pagesToCreate) {
    await createPage(page);
  }
  for (let page of pagesToUpdate) {
    await updatePage(page);
  }
  console.log('Deploy complete!');
})();

function getExistingWikiPages() {
  return axios.get(`/api/v4/projects/${config.projectId}/wikis`).then(res => res.data);
}

function getUpdatedPages() {
  const files = fs.readdirSync(config.buildDir);
  return files.map(file => {
    const name = file // Remove the file extension
      .split('.')
      .slice(0, -1)
      .join('.');
    return {
      format: 'markdown', // You could make this depend on the file extension
      slug: name,
      title: name,
      content: fs.readFileSync(`${config.buildDir}/${file}`, 'utf-8')
    };
  });
}

function deletePage(page) {
  console.log(`Deleting ${page.slug}...`);
  return axios.delete(`/api/v4/projects/${config.projectId}/wikis/${page.slug}`);
}

function createPage(page) {
  console.log(`Creating ${page.slug}...`);
  return axios.post(`/api/v4/projects/${config.projectId}/wikis`, qs.stringify(page));
}

function updatePage(page) {
  console.log(`Updating ${page.slug}...`);
  return axios.put(`/api/v4/projects/${config.projectId}/wikis/${page.slug}`, qs.stringify(page));
}
Run Code Online (Sandbox Code Playgroud)

config顶部,您需要指定 Gitlab 使用的 URL。CI_PROJECT_ID将由 Gitlab-CI 本身作为环境变量提供。WIKI_DEPLOY_TOKEN,然而,不会。在步骤 4 中进行设置。

在您的 中package.json,添加一个命令来运行该脚本:

"scripts": {
    // ...
    "wiki:build": "node wiki/build.js",
    "wiki:deploy": "node wiki/deploy.js"
  }
Run Code Online (Sandbox Code Playgroud)

注意:此示例将删除过时的页面,并根据在构建文件夹中找到的文件和 Wiki 已包含的文件更新或创建新页面。如果您还想拥有附件(图像),则还需要使用此 API

第 4 步 - 设置私人令牌 WIKI_DEPLOY_TOKEN

为此,您需要点击右上角的个人资料图片 >设置。然后在左侧菜单中,访问令牌,并创建一个具有api范围的令牌。名称无关紧要。现在复制这个令牌,因为它只会显示一次。

然后,转到您的项目。在左侧菜单中,单击Settings > CI/CD。展开Variables部分,并使用之前复制的标记创建一个名为 的变量WIKI_DEPLOY_TOKEN,将其设置为Masked以便它不会出现在任何日志中,然后保存变量

在此处输入图片说明

这将使该令牌仅在您的管道中可用,作为环境变量。

第 5 步 - 创建您的管道

如果您还没有管道,您需要做的就是.gitlab-ci.yml在项目的根目录下创建一个文件。声明一个generate_wiki阶段:

.gitlab-ci.yml

stages:
  # - tests
  # - deploy
  # ...
  - generate_wiki

generate_wiki:
  image: node:10
  stage: generate_wiki
  script:
    - npm install
    - npm run wiki:build  # build the wiki in a directory
    - npm run wiki:deploy # update it in Gitlab
  only:
    - master # Only when merging or pushing to master branch


# ... rest of your pipeline ...
Run Code Online (Sandbox Code Playgroud)

如您所见,我们使用了在步骤 2 和 3 中声明的命令wiki:buildwiki:deploy

现在,您的项目结构应如下所示:

/
????src
?    ??? index.js
????wiki
?    ??? templates
?    ?    ??? home.mst
?    ??? build.js
?    ??? deploy.js
??? .gitlab-ci.yml
??? package.json
Run Code Online (Sandbox Code Playgroud)

第 6 步 - 推动掌握,并享受魔力

推送后,如果一切顺利,您可以单击左侧菜单中的CI/CD,您应该会看到您的管道正在运行:

在此处输入图片说明

如果单击小圆圈,您应该会看到日志:

在此处输入图片说明

如果您访问您的 Wiki 页面,它们应该会自动更新:

在此处输入图片说明