Merge pull request #11 from LCTT/master

Update 2018415
This commit is contained in:
zyk 2018-04-15 19:04:33 +08:00 committed by GitHub
commit 8f1ddef16d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 284 additions and 286 deletions

View File

@ -1,100 +0,0 @@
translating by MZqk
11 awesome vi tips and tricks
======
![](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/keyboaord_enter_writing_documentation.jpg?itok=kKrnXc5h)
The [vi editor][1] is one of the most popular text editors on Unix and Unix-like systems, such as Linux. Whether you're new to vi or just looking for a refresher, these 11 tips will enhance how you use it.
### Editing
Editing a long script can be tedious, especially when you need to edit a line so far down that it would take hours to scroll to it. Here's a faster way.
1. The command `:set number` numbers each line down the left side.
![](https://opensource.com/sites/default/files/styles/panopoly_image_original/public/u128651/setnum.png?itok=sFVA97mG)
You can directly reach line number 26 by opening the file and entering this command on the CLI: `vi +26 sample.txt`. To edit line 26 (for example), the command `:26` will take you directly to it.
![](https://opensource.com/sites/default/files/styles/panopoly_image_original/public/u128651/number.png?itok=d7FE0LL3)
### Fast navigation
2. `i` changes your mode from "command" to "insert" and starts inserting text at the current cursor position.
3. `a` does the same, except it starts just after the current cursor position.
4. `o` starts the cursor position from the line below the current cursor position.
### Delete
If you notice an error or typo, being able to make a quick fix is important. Good thing vi has it all figured out.
Understanding vi's delete function so you don't accidentally press a key and permanently remove a line, paragraph, or more, is critical.
5. `x` deletes the character under the cursor.
6. `dd` deletes the current line. (Yes, the whole line!)
Here's the scary part: `30dd` would delete 30 lines starting with the current line! Proceed with caution when using this command.
### Search
You can search for keywords from the "command" mode rather than manually navigating and looking for a specific word in a plethora of text.
7. `:/<keyword>` searches for the word mentioned in the `< >` space and takes your cursor to the first match.
8. To navigate to the next instance of that word, type `n`, and keep pressing it until you get to the match you're looking for.
For example, in the image below I searched for `ssh`, and vi highlighted the beginning of the first result.
![](https://opensource.com/sites/default/files/styles/panopoly_image_original/public/u128651/ssh-search.png?itok=tJ-7FujH)
After I pressed `n`, vi highlighted the next instance.
![](https://opensource.com/sites/default/files/styles/panopoly_image_original/public/u128651/n-search.png?itok=wU-u3LiI)
### Save and exit
Developers (and others) will probably find this next command useful.
9. `:x` saves your work and exits vi.
![](https://opensource.com/sites/default/files/styles/panopoly_image_original/public/u128651/x.png?itok=kfoHx84m)
10. If you think every nanosecond is worth saving, here's a faster way to shift to terminal mode in vi. Instead of pressing `Shift+:` on the keyboard, you can press `Shift+q` (or Q, in caps) to access [Ex mode][2], but this doesn't really make any difference if you just want to save and quit by typing `x` (as shown above).
### Substitution
Here is a neat trick if you want to substitute every occurrence of one word with another. For example, if you want to substitute "desktop" with "laptop" in a large file, it would be monotonous and waste time to search for each occurrence of "desktop," delete it, and type "laptop."
11. The command `:%s/desktop/laptop/g` would replace each occurrence of "desktop" with "laptop" throughout the file; it works just like the Linux `sed` command.
In this example, I replaced "root" with "user":
![](https://opensource.com/sites/default/files/styles/panopoly_image_original/public/u128651/subs-command.png?itok=M8MN72sp)
![](https://opensource.com/sites/default/files/styles/panopoly_image_original/public/u128651/subs-result.png?itok=34zzVdUt)
These tricks should help anyone get started using vi. Are there other neat tips I missed? Share them in the comments.
--------------------------------------------------------------------------------
via: https://opensource.com/article/18/1/top-11-vi-tips-and-tricks
作者:[Archit Modi][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://opensource.com/users/architmodi
[1]:http://ex-vi.sourceforge.net/
[2]:https://en.wikibooks.org/wiki/Learning_the_vi_Editor/Vim/Modes#Ex-mode

View File

@ -1,186 +0,0 @@
translating by kimii
Do continuous deployment with Github and Python
======
![](https://fedoramagazine.org/wp-content/uploads/2018/03/cd-github-python-945x400.jpg)
Developers can create many useful services using Githubs webhooks. From triggering a CI job on a Jenkins instance to provisioning machines in the cloud, the possibilities are almost limitless. This tutorial shows how to use Python and the Flask framework to build a simple continuous deployment service.
The continuous deployment service in this example is a simple Flask application with a REST endpoint that will receive Githubs webhook requests. After validating each request to check that it comes from the correct Github repository, the service pulls changes to the local copy of the repository. That way every time a new commit is pushed to the remote Github repository, the local repository is automatically updated.
### Flask web service
It is easy to build a small web service with Flask. Heres a look at the project structure.
```
├── app
│   ├── __init__.py
│   └── webhooks.py
├── requirements.txt
└── wsgi.py
```
First, create the application. The application code goes under the app directory.
Two files ( __init__.py and webhooks.py) compose the Flask application. The former has the code needed to create the Flask application and add configuration to it. The latter has the endpoints logic. This is where the app receives the data from the Github request.
Here is the app/__init__.py content:
```
import os
from flask import Flask
from .webhooks import webhook
def create_app():
""" Create, configure and return the Flask application """
app = Flask(__name__)
app.config['GITHUB_SECRET'] = os.environ.get('GITHUB_SECRET')
app.config['REPO_PATH'] = os.environ.get('REPO_PATH')
app.register_blueprint(webhook)
return(app)
```
The function creates two configuration variables:
* **GITHUB_SECRET** holds a secret passphrase, used to authenticate the Github requests.
* **REPO_PATH** holds the path of the repository to automatically update.
This code uses [Flask Blueprints][1] to organize the application endpoints. Using blueprints allows logical grouping of APIs, making applications easier to maintain. It is generally considered a good practice.
Here is the content of app/webhooks.py:
```
import hmac
from flask import request, Blueprint, jsonify, current_app
from git import Repo
webhook = Blueprint('webhook', __name__, url_prefix='')
@webhook.route('/github', methods=['POST'])
def handle_github_hook():
""" Entry point for github webhook """
signature = request.headers.get('X-Hub-Signature')
sha, signature = signature.split('=')
secret = str.encode(current_app.config.get('GITHUB_SECRET'))
hashhex = hmac.new(secret, request.data, digestmod='sha1').hexdigest()
if hmac.compare_digest(hashhex, signature):
repo = Repo(current_app.config.get('REPO_PATH'))
origin = repo.remotes.origin
origin.pull('--rebase')
commit = request.json['after'][0:6]
print('Repository updated with commit {}'.format(commit))
return jsonify({}), 200
```
First the code creates a new Blueprint webhook. Then it adds a new endpoint to the Blueprint using a Flask route. This route will be called by any POST request on the /github URL endpoint.
#### Verifying the request
When the service receives a request on this endpoint, it must first verify that the request comes from Github and from the correct repository. Github gives a signature in the request header X-Hub-Signature. This signature is generated using a secret (GITHUB_SECRET), the [HMAC][2] hex digest of the request body, and then hashed using the sha1 hash function.
To verify the request the service needs to calculate locally the signature and compare it to the signature received in the request header. This is done by the hmac.compare_digest function.
#### Custom hook logic
After validating the request, it can now be processd. This tutorial uses the [GitPython][3] module to interface with a git repository. From the GitPython module the Repo object is used to access the remote repository called origin. The service pulls the latest changes locally from the origin repository, also using the rebase option to avoid issues with merges.
A debug print statement displays the short commit hash received from the request body. This example shows how to use the request body. For more details about the data available in the body, check [githubs documentation][4].
Finally the service returns a empty JSON string and a 200 status code. This tells Githubs webhook server the request was received.
### Deploying the service
To run the service, this example uses the [gunicorn][5] web server. First install the service dependencies. On a supported Fedora server, use this command with [sudo][6]:
```
sudo dnf install python3-gunicorn python3-flask python3-GitPython
```
Now edit the wsgi.py file used by gunicorn to run the service:
```
from app import create_app
application = create_app()
```
To deploy this service, clone this git [repository][7] or use your own git repository with this command:
```
git clone https://github.com/cverna/github_hook_deployment.git /opt/
```
The next step is to configure the environment variables needed by the service. Run these commands:
```
export GITHUB_SECRET=asecretpassphraseusebygithubwebhook
export REPO_PATH=/opt/github_hook_deployment/
```
This tutorial uses the webhook service Github repository, but you could use a different repository if you wish. Finally, start the webserver with these commands:
```
cd /opt/github_hook_deployment/
gunicorn --bind 0.0.0.0 wsgi:application --reload
```
These options bind the web server to the 0.0.0.0 ip address, meaning it will accept requests coming from any host. The reload option ensures the web server restarts when the code changes. This is where the continuous deployment magic happens. Every Github request received pulls the latest change in the repository, and gunicorn detects these changes and automatically restarts the application.
**Note: **In order to receive the requests from github, the web service must be deployed on a server with a public IP address. An easy way to do this is to use your favorite cloud provider such as DigitalOcean, AWS, Linode, etc.
### Configure Github
The last part of this tutorial configures Github to send the webhook request to the web service. This is key to continuous deployment.
From your Github repository settings, select the Webhook menu and click on Add Webhook. Enter the following information:
* **Payload URL:** The URL of the service, for example <http://public\_ip\_address:8000/github>
* **Content type:** Select application/json
* **Secret:** The **GITHUB_SECRET** environment variable defined earlier
Then click the Add Webhook button.
![][8]
Github will now send a request to the service every time a push event happens on this repository.
### Conclusion
This tutorial has shown you how to write a Flask based web service that receives requests from a Github webhook and does continuous deployment. You should now be able to build your own useful services using this tutorial as a starting base.
#### Like this:
Like
Loading...
--------------------------------------------------------------------------------
via: https://fedoramagazine.org/continuous-deployment-github-python/
作者:[Author Archive;Author Website;Clément Verna][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
选题:[lujun9972](https://github.com/lujun9972)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://fedoramagazine.org
[1]:http://flask.pocoo.org/docs/0.12/blueprints/
[2]:https://en.wikipedia.org/wiki/HMAC
[3]:https://gitpython.readthedocs.io/en/stable/index.html
[4]:https://developer.github.com/v3/activity/events/types/#webhook-payload-example-26
[5]:http://gunicorn.org/
[6]:https://fedoramagazine.org/howto-use-sudo/
[7]:https://github.com/cverna/github_hook_deployment.git
[8]:https://fedoramagazine.org/wp-content/uploads/2018/03/Screenshot-2018-3-26-cverna-github_hook_deployment1.png

View File

@ -1,3 +1,5 @@
translated by hopefully2333
Awesome GNOME extensions for developers
======

View File

@ -1,3 +1,5 @@
Translating by MjSeven
3 password managers for the Linux command line
======

View File

@ -0,0 +1,95 @@
11 个超棒的 vi 技巧和窍门
======
![](https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/keyboaord_enter_writing_documentation.jpg?itok=kKrnXc5h)
[vi][1] 编辑器是 Linux 最流行的编辑器之一,默认安装在 Unix 和类 Uinux 系统中。无论您是 vi 新手还是想进修,这些技巧都对您有用。
### 编辑
编辑长文本时可能很难受,特别是编辑其中某一行时,需要移动许久才能到这行。这有个很快的方法:
1. `:set number` 这个命令可是在编辑器左边显示行号。
![](https://opensource.com/sites/default/files/styles/panopoly_image_original/public/u128651/setnum.png?itok=sFVA97mG)
您可以在命令行中输入 `vi +26 samp.txt` 命令直接打开文件到达 26 行,在 vi 编辑器中也可以输入 `:26` 跳转到 26 行。
![](https://opensource.com/sites/default/files/styles/panopoly_image_original/public/u128651/number.png?itok=d7FE0LL3)
### 快速导航
2. `i` 将工作方式从“命令模式”更改为“输入模式”,并在当前光标位置开始插入内容。
3. `a` 除了是光标之后开始插入年内容,与上面的效果是一样的。
4. `o` 在光标的下一行位置开始插入内容。
### 删除
如果您发现错误或错别字,能快速的修正是很重要的。好在 vi 都事先想好了。
了解 vi 的删除功能,保证你不会意外按下某个键并永久删除一行或多段内容,这点至关重要。
5. `x` 删除当前光标的字符。
6. `dd` 删除当前行 (是的,整行内容!)
下面看可怕的部分:`30dd` 从当前行开始删除以下 30 行!使用此命令请慎重。
### 搜索
您可以在“命令模式”搜索关键字,而不用在大量文本内容中手动导航查找特定的单词或内容。
7. `:/<keyword>` 搜索 `< >` 中的单词并将光标移动到第一个匹配项。
8. 导航到该单词的下一个匹配项,请输入 `n` 并继续按下, 直到找到您要找的内容。
例如,在这个图像中我要搜索包含 `ssh` 的内容, vi 光标就会突出第一个结果的开始位置。
![](https://opensource.com/sites/default/files/styles/panopoly_image_original/public/u128651/ssh-search.png?itok=tJ-7FujH)
按下 n 之后, vi 光标就会突出下一个匹配项。
![](https://opensource.com/sites/default/files/styles/panopoly_image_original/public/u128651/n-search.png?itok=wU-u3LiI)
### 保存并退出
开发人员 (或其他人) 可能会发现这个命令很有用。
9. `:x` 保存您的工作空间并退出 vi 。
![](https://opensource.com/sites/default/files/styles/panopoly_image_original/public/u128651/x.png?itok=kfoHx84m)
10. 如果你想实时保存,那么这有个更快的方法。你可以按下 `Shift+q` (或者大写字母 Q ) 来进入 [Ex 模式][2] , 而不是在键盘上按 `Shift+:` 。但是如果你只是想按下 `x` 来保存退出,那就没有什么区别(如上所示)。
### 替换
如果您想将文中的某个单词全部替换为一个单词,这有个很巧妙的招式。例如,如果您想在一个大文件中将 "desktop" 替换为 "laptop" ,那么单调的搜索每个出现的 "desktop" 将其删掉,然后再输入 "laotop" ,是很浪费时间的。
11. `:%s/desktop/laptop/g` 这个命令将在整个文件中的 "desktop" 用 "laptop" 替换,他就像 Linux 的 `sed` 命令一样。
这个例子中我用 "user" 替换了 "root"
![](https://opensource.com/sites/default/files/styles/panopoly_image_original/public/u128651/subs-command.png?itok=M8MN72sp)
![](https://opensource.com/sites/default/files/styles/panopoly_image_original/public/u128651/subs-result.png?itok=34zzVdUt)
这些技巧应该能帮组任何想开始学 vi 的人。我有遗漏其他巧妙的提示吗?请在评论中分享他们。
--------------------------------------------------------------------------------
via: https://opensource.com/article/18/1/top-11-vi-tips-and-tricks
作者:[Archit Modi][a]
译者:[MZqk](https://github.com/MZqk)
校对:[校对者 ID](https://github.com/ 校对者 ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux 中国](https://linux.cn/) 荣誉推出
[a]:https://opensource.com/users/architmodi
[1]:http://ex-vi.sourceforge.net/
[2]:https://en.wikibooks.org/wiki/Learning_the_vi_Editor/Vim/Modes#Ex-mode

View File

@ -0,0 +1,185 @@
使用 Github 和 Python 实现持续部署
======
![](https://fedoramagazine.org/wp-content/uploads/2018/03/cd-github-python-945x400.jpg)
借助 Github 的 webhook网络钩子开发者可以创建很多有用的服务。从触发一个 Jenkins 实例上的 CI持续集成 任务到配置云中的机器,几乎有着无限的可能性。这篇教程将展示如何使用 Python 和 Flask 框架来搭建一个简单的持续部署服务。
在这个例子中的持续部署服务是一个简单的 Flask 应用,其带有接受 Github 的 webhook 请求的 REST 端点endpoint。在验证每个请求都来自正确的 Github 仓库后服务器将拉取pull更改到仓库的本地副本。这样每次一个新的提交(commit)推送到远程 Github 仓库,本地仓库就会自动更新。
### Flask web 服务
用 Flask 搭建一个小的 web 服务非常简单。这里可以先看看项目的结构。
```
├── app
│ ├── __init__.py
│ └── webhooks.py
├── requirements.txt
└── wsgi.py
```
首先,创建应用。应用代码在 app 目录下。
两个文件__init__.py 和 webhooks.py构成了 Flask 应用。前者有创建 Flask 应用并为其添加配置的代码。后者有端点endpoint逻辑。这是该应用接收 Github 请求的地方。
这里是 app/__init__.py 的内容:
```
import os
from flask import Flask
from .webhooks import webhook
def create_app():
""" Create, configure and return the Flask application """
app = Flask(__name__)
app.config['GITHUB_SECRET'] = os.environ.get('GITHUB_SECRET')
app.config['REPO_PATH'] = os.environ.get('REPO_PATH')
app.register_blueprint(webhook)
return(app)
```
该函数创建了两个配置变量:
* **GITHUB_SECRET** 保存一个密码,用来认证 Github 请求。
* **REPO_PATH** 保存了自动更新的仓库路径。
这份代码使用[Flask 蓝图Blueprints][1]来组织应用的端点endpoint。使用蓝图可以对 API 进行逻辑分组,使应用程序更易于维护。通常认为这是一种好的做法。
这里是 app/webhooks.py 的内容:
```
import hmac
from flask import request, Blueprint, jsonify, current_app
from git import Repo
webhook = Blueprint('webhook', __name__, url_prefix='')
@webhook.route('/github', methods=['POST'])
def handle_github_hook():
""" Entry point for github webhook """
signature = request.headers.get('X-Hub-Signature')
sha, signature = signature.split('=')
secret = str.encode(current_app.config.get('GITHUB_SECRET'))
hashhex = hmac.new(secret, request.data, digestmod='sha1').hexdigest()
if hmac.compare_digest(hashhex, signature):
repo = Repo(current_app.config.get('REPO_PATH'))
origin = repo.remotes.origin
origin.pull('--rebase')
commit = request.json['after'][0:6]
print('Repository updated with commit {}'.format(commit))
return jsonify({}), 200
```
首先代码创建了一个新的蓝图 webhook。然后它使用 Flask 路由route为蓝图添加了一个端点。任何 URL 为 /Github 的端点的 POST 请求都将调用这个路由。
#### 验证请求
当服务收到该端点的请求时,首先它必须验证该请求是否来自 GitHub 同时来自正确的仓库。Github 在请求头的 X-Hub-Signature 中提供了一个签名。该签名由一个密码GITHUB_SECRET请求体的 HMAC 十六进制摘要和使用 sha1 的哈希生成。
为了验证请求,服务需要在本地计算签名并与请求头中收到的签名做比较。这可以由 hmac.compare_digest 函数完成。
#### 自定义钩子逻辑
在验证请求后,现在可以处理了。这篇教程使用[GitPython][3]模块来与 git 仓库进行交互。GitPython 模块中的 Repo 对象用于访问远程仓库 origin。服务在本地拉取远程仓库的最新更改还用 -rebase 选项来避免合并的问题。
调试打印语句显示了从请求体收到的短提交哈希。这个例子展示了如何使用请求体。更多关于请求体的可用数据的信息,请查询[github 文档][4]。
最后服务返回了一个空的 JSON 字符串和 200 的状态码。这用于告诉 Github 的 webhook 服务已经收到了请求。
### 部署服务
为了运行该服务,这个例子使用 [gunicorn][5] web 服务器。首先安装服务依赖。在支持的 Fedora 服务器上,以[sudo][6]运行这条命令:
```
sudo dnf install python3-gunicorn python3-flask python3-GitPython
```
现在编辑 gunicorn 使用的 wsgi.py 文件来运行服务:
```
from app import create_app
application = create_app()
```
为了部署服务,使用以下命令克隆这个 git [仓库][7]或者使用你自己的 git 仓库:
```
git clone https://github.com/cverna/github_hook_deployment.git /opt/
```
下一步是配置服务所需的环境变量。运行这些命令:
```
export GITHUB_SECRET=asecretpassphraseusebygithubwebhook
export REPO_PATH=/opt/github_hook_deployment/
```
这篇教程使用 webhook 服务的 Github 仓库,但你可以使用你想要的不同仓库。最后,使用这些命令开启 该 web 服务:
```
cd /opt/github_hook_deployment/
gunicorn --bind 0.0.0.0 wsgi:application --reload
```
这些选项中绑定了 web 服务的 ip 地址为 0.0.0.0,意味着它将接收来自任何的主机的请求。选项 -reload 确保了当代码更改时重启 web 服务。这就是持续部署的魔力所在。每次接收到 Github 请求时将拉取仓库的最近更新,同时 gunicore 检测这些更改并且自动重启服务。
**注意: **为了能接收到 Github 请求web 服务必须部署到具有公有 IP 地址的服务器上。做到这点的简单方法就是使用你最喜欢的云提供商比如 DigitalOceanAWSLinode等。
### 配置 Github
这篇教程的最后一部分是配置 Github 来发送 webhook 请求到 web 服务上。这是持续部署的关键。
从你的 Github 仓库的设置中,选择 Webhook 菜单,并且点击添加 Webhook。输入以下信息
* **Payload URL:** 服务的 URL比如<http://public\_ip\_address:8000/github>
* **Content type:** 选择 application/json
* **Secret:** 前面定义的 **GITHUB_SECRET** 环境变量
然后点击添加 Webhook 按钮。
![][8]
现在每当该仓库发生 push(推送)事件时Github 将向服务发送请求。
### 总结
这篇教程向你展示了如何写一个基于 Flask 的用于接收 Github 的 webhook 请求和实现持续集成的 web 服务。现在你应该能以本教程作为起点来搭建对自己有用的服务。
#### 像这样:
加载中...
--------------------------------------------------------------------------------
via: https://fedoramagazine.org/continuous-deployment-github-python/
作者:[Author Archive;Author Website;Clément Verna][a]
译者:[kimii](https://github.com/kimii)
校对:[校对者ID](https://github.com/校对者ID)
选题:[lujun9972](https://github.com/lujun9972)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]:https://fedoramagazine.org
[1]:http://flask.pocoo.org/docs/0.12/blueprints/
[2]:https://en.wikipedia.org/wiki/HMAC
[3]:https://gitpython.readthedocs.io/en/stable/index.html
[4]:https://developer.github.com/v3/activity/events/types/#webhook-payload-example-26
[5]:http://gunicorn.org/
[6]:https://fedoramagazine.org/howto-use-sudo/
[7]:https://github.com/cverna/github_hook_deployment.git
[8]:https://fedoramagazine.org/wp-content/uploads/2018/03/Screenshot-2018-3-26-cverna-github_hook_deployment1.png