食谱:使用 Bash

分享此
分享此

GitHub 上的许多项目都使用 Travis 在每次构建时自动执行某些脚本。在这些脚本中,有一个绝对是最有名的,它被称为 Bash。自动化你的 shell 命令,添加 env vars,并提高你的工作流程,再加上 Bash 的灵活性带来的无限可能。关键是 - Bash 在大多数情况下对于 Travis CI 构建至关重要。

Bash 入门(gh-pages 示例)

如果你想在 Bash 中自动化流程,你可能有一些目标,例如在 gpages_build.sh 脚本中使用 TRAVIS_REPO_SLUG 自动化 GH_REF 值。

为了使 GH_REF 变量自动执行,避免每次都使用进程加载,Travis CI 为我们提供了 TRAVIS_REPO_SLUG,你可能在 React 等语言中见过它。SLUG 变量本质上是你在 GitHub 上工作的任何仓库的用户名/仓库名。你可以这样写:GH_REF="github.com/${TRAVIS_REPO_SLUG}"

下面是一个示例脚本,它演示了我上面解释的内容,我们可以假设这个 Bash 脚本名为 pages.sh

# This script pushes a demo-friendly version of your element and its
# dependencies to gh-pages.

# usage gp Polymer core-item [branch]
# Run in a clean directory passing in a GitHub org and repo name

#!/bin/bash

GH_REF="github.com/${TRAVIS_REPO_SLUG}"

org=`echo ${TRAVIS_REPO_SLUG} | cut -f 1 -d /`
repo=`echo ${TRAVIS_REPO_SLUG} | cut -f 2 -d /`

name="Montana"
email="[email protected]"
branch=${3:-"master"} # default to master, when branch isn't specified

mkdir temp && cd temp # make temp dir 

# make folder (same as input, no checking!)
mkdir $repo
git clone "https://${GH_TOKEN}@${GH_REF}" --single-branch # you can theoretically as Montana likes to do, 'git stash pop' here

# switch to gh-pages branch
pushd $repo >/dev/null
git checkout --orphan gh-pages

# remove all content
git rm -rf -q .

# use bower to install runtime deployment
bower cache clean $repo # ensure we're getting the latest from the desired branch.
git show ${branch}:bower.json > bower.json
echo "{
  \"directory\": \"components\"
}
" > .bowerrc
bower install
bower install $org/$repo#$branch
git checkout ${branch} -- demo
rm -rf components/$repo/demo
mv demo components/$repo/

# redirect by default to the component folder
echo "<META http-equiv="refresh" content=\"0;URL=components/$repo/\">" >index.html

git config user.name $name
git config user.email $email

# send it all to github
git add -A .
git commit -am 'Deploy to GitHub Pages'
git push --force --quiet -u "https://${GH_TOKEN}@${GH_REF}" gh-pages > /dev/null 2>&1

popd >/dev/null

在你的 .travis.yml 中实现它

以下是我创建的 travis.yml 文件,假设你将脚本命名为 pages.sh,你的 .travis.yml 文件将如下所示

language: bash

sudo: required

script:
    - chmod u+x bash pages.sh

就这样,你现在已经在 Travis CI 中成功使用了 Bash。你也可以做一些更简单的操作 - 只是为了测试你是否掌握了步骤,也许创建一个名为 test.sh 的 Bash 程序,并让它读取

#!/bin/bash

echo "Hello Travis"

然后让你的 .travis.yml 文件读取以下内容

language: bash

script: chmod u+x test.sh

然后,你应该会在运行构建时看到 Travis 打印出 Hello Travis。你现在知道如何在 Travis CI 中成功使用 Bash 了。

© 版权所有 2024,保留所有权利
© 版权所有 2024,保留所有权利
© 版权所有 2024,保留所有权利