mirror of
https://github.com/arcan1s/arcanis.me.git
synced 2025-04-24 07:17:17 +00:00
move html papers to md
This commit is contained in:
parent
28dd83b280
commit
4c9ff17bf0
@ -21,7 +21,7 @@ markdown: redcarpet
|
||||
markdown_ext: markdown,mkd,mkdn,md
|
||||
textile_ext: textile
|
||||
|
||||
excerpt_separator: "\n\n"
|
||||
excerpt_separator: "<!--more-->"
|
||||
|
||||
safe: false
|
||||
host: 0.0.0.0
|
||||
|
@ -49,7 +49,5 @@ layout: default
|
||||
<section>
|
||||
|
||||
<h1><a href="#" class="anchor" id="title"><span class="octicon octicon-link"></span></a>{{ page.title }}</h1>
|
||||
<p>{{ page.description }}</p>
|
||||
<br>
|
||||
|
||||
{{ content }}
|
||||
|
@ -6,32 +6,37 @@ hastr: true
|
||||
tags: zshrc, configuration, linux
|
||||
title: About zshrc
|
||||
short: about-zshrc
|
||||
description: It is first paper in my blog (I think I need something here for tests =)). There are many similar articles, and I'll not be an exception. I just want to show my <code>.zshrc</code> and explain what it does and why it is needed. Also any comments or additions are welcome. It is a translated paper from Russian (<a href="//archlinux.org.ru/forum/topic/12752/" title="Forum thread">original</a>).
|
||||
---
|
||||
<h2><a href="#prepare" class="anchor" id="prepare"><span class="octicon octicon-link"></span></a>Prepare</h2>
|
||||
<p>First install recommended minima:</p>
|
||||
It is first paper in my blog (I think I need something here for tests =)). There are many similar articles, and I'll not be an exception. I just want to show my `.zshrc` and explain what it does and why it is needed. Also any comments or additions are welcome. It is a translated paper from Russian ([original](//archlinux.org.ru/forum/topic/12752/ "Forum thread")).
|
||||
|
||||
{% highlight bash %}
|
||||
<!--more-->
|
||||
|
||||
## <a href="#prepare" class="anchor" id="prepare"><span class="octicon octicon-link"></span></a>Prepare
|
||||
|
||||
First install recommended minima:
|
||||
|
||||
```bash
|
||||
pacman -Sy pkgfile zsh zsh-completions zsh-syntax-highlighting
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p><a href="//www.archlinux.org/packages/pkgfile/" title="Archlinux package">pkgfile</a> is a very useful utility. Also this command will install shell, additional completion and syntax highlighting.</p>
|
||||
[pkgfile](//www.archlinux.org/packages/pkgfile/ "Archlinux package") is a very useful utility. Also this command will install shell, additional completion and syntax highlighting.
|
||||
|
||||
<h2><a href="#configuration" class="anchor" id="configuration"><span class="octicon octicon-link"></span></a>Shell configuration</h2>
|
||||
<p>All options are avaible <a href="//zsh.sourceforge.net/Doc/Release/Options.html" title="zsh documentation">here</a>.</p>
|
||||
## <a href="#configuration" class="anchor" id="configuration"><span class="octicon octicon-link"></span></a>Shell configuration
|
||||
|
||||
<p>Set history file and number of commands in cache of the current session and in the history file:</p>
|
||||
All options are avaible [here](//zsh.sourceforge.net/Doc/Release/Options.html "zsh documentation").
|
||||
|
||||
{% highlight bash %}
|
||||
Set history file and number of commands in cache of the current session and in the history file:
|
||||
|
||||
```bash
|
||||
# history
|
||||
HISTFILE=~/.zsh_history
|
||||
HISTSIZE=500000
|
||||
SAVEHIST=500000
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>I can not remember all <code>Ctrl+</code> combinations so I bind keys to its default usages:</p>
|
||||
I can not remember all `Ctrl+` combinations so I bind keys to its default usages:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# bindkeys
|
||||
bindkey '^[[A' up-line-or-search # up arrow for back-history-search
|
||||
bindkey '^[[B' down-line-or-search # down arrow for fwd-history-search
|
||||
@ -41,106 +46,106 @@ bindkey '\e[3~' delete-char # del
|
||||
bindkey '\e[4~' end-of-line # end
|
||||
bindkey '\e[5~' up-line-or-history # page-up
|
||||
bindkey '\e[6~' down-line-or-history # page-down
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>But in this case <code>Up</code>/<code>Down</code> arrows are used to navigate through the history based on <b>already entered part</b> of a command. And <code>PgUp</code>/<code>PgDown</code> <b>will ignore</b> already entered part of a command.</p>
|
||||
But in this case `Up`/`Down` arrows are used to navigate through the history based on **already entered part** of a command. And `PgUp`/`PgDown` **will ignore** already entered part of a command.
|
||||
|
||||
<p>Command autocomplete:</p>
|
||||
Command autocomplete:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# autocomplete
|
||||
autoload -U compinit
|
||||
compinit
|
||||
zstyle ':completion:*' insert-tab false
|
||||
zstyle ':completion:*' max-errors 2
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Full command autocomplete will be enabled. <code>insert-tab false</code> will enable autocomplete for <b>non-entered</b> commands. <code>max-errors</code> sets maximum number of errors that could be corrected.</p>
|
||||
Full command autocomplete will be enabled. `insert-tab false` will enable autocomplete for **non-entered** commands. `max-errors` sets maximum number of errors that could be corrected.
|
||||
|
||||
<p>Prompt:</p>
|
||||
Prompt:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# promptinit
|
||||
autoload -U promptinit
|
||||
promptinit
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Enable colors:</p>
|
||||
Enable colors:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# colors
|
||||
autoload -U colors
|
||||
colors
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Here are some other options.</p>
|
||||
<p>Change directory without <code>cd</code>:</p>
|
||||
Here are some other options.
|
||||
Change directory without `cd`:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# autocd
|
||||
setopt autocd
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Correcting of typos (and question template):</p>
|
||||
Correcting of typos (and question template):
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# correct
|
||||
setopt CORRECT_ALL
|
||||
SPROMPT="Correct '%R' to '%r' ? ([Y]es/[N]o/[E]dit/[A]bort) "
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Disable f#$%ing beep:</p>
|
||||
Disable f#$%ing beep:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# disable beeps
|
||||
unsetopt beep
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Enable calculator:</p>
|
||||
Enable calculator:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# calc
|
||||
autoload zcalc
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Append history (<b>do not recreate</b> the history file):</p>
|
||||
Append history (**do not recreate** the history file):
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# append history
|
||||
setopt APPEND_HISTORY
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Do not save dups to history file:</p>
|
||||
Do not save dups to history file:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# ignore spaces in history
|
||||
setopt HIST_IGNORE_ALL_DUPS
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>...and additional spaces:</p>
|
||||
...and additional spaces:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# ignore dups in history
|
||||
setopt HIST_IGNORE_SPACE
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>...and blank lines too:</p>
|
||||
...and blank lines too:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# reduce blanks in history
|
||||
setopt HIST_REDUCE_BLANKS
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Enable <code>pkgfile</code>:</p>
|
||||
Enable `pkgfile`:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# pkgfile
|
||||
source /usr/share/doc/pkgfile/command-not-found.zsh
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h2><a href="#highlighting" class="anchor" id="highlighting"><span class="octicon octicon-link"></span></a>Syntax highlighting</h2>
|
||||
## <a href="#highlighting" class="anchor" id="highlighting"><span class="octicon octicon-link"></span></a>Syntax highlighting
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# highlighting
|
||||
source /usr/share/zsh/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
|
||||
ZSH_HIGHLIGHT_HIGHLIGHTERS=(main brackets pattern)
|
||||
@ -185,14 +190,15 @@ ZSH_HIGHLIGHT_STYLES[double-quoted-argument]='fg=yellow'
|
||||
#ZSH_HIGHLIGHT_PATTERNS+=('rm -rf *' 'fg=white,bold,bg=red')
|
||||
# root example
|
||||
#ZSH_HIGHLIGHT_STYLES[root]='bg=red'
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>In first line highlighting is turned on. Next main, brackets and pattern highlighting are turned on. Patterns are set below (<code>rm -rf *</code> in the example). Also <code>root</code> and <code>cursor</code> highlighting may be turned on. Colors syntax is understandable, <code>fg</code> is font color, <code>bg</code> is background color.</p>
|
||||
In first line highlighting is turned on. Next main, brackets and pattern highlighting are turned on. Patterns are set below (`rm -rf *` in the example). Also `root` and `cursor` highlighting may be turned on. Colors syntax is understandable, `fg` is font color, `bg` is background color.
|
||||
|
||||
<h2><a href="#prompt" class="anchor" id="prompt"><span class="octicon octicon-link"></span></a>$PROMPT and $RPROMPT</h2>
|
||||
<p>The general idea is the use single <code>.zshrc</code> for root and normal user:</p>
|
||||
## <a href="#prompt" class="anchor" id="prompt"><span class="octicon octicon-link"></span></a>$PROMPT and $RPROMPT
|
||||
|
||||
{% highlight bash %}
|
||||
The general idea is the use single `.zshrc` for root and normal user:
|
||||
|
||||
```bash
|
||||
# PROMPT && RPROMPT
|
||||
if [[ $EUID == 0 ]]; then
|
||||
# [root@host dir]#
|
||||
@ -211,11 +217,11 @@ else
|
||||
%{$fg_bold[yellow]%}%1/%{$reset_color%}\
|
||||
%{$fg_bold[white]%}]$ %{$reset_color%}"
|
||||
fi
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p><code>fg</code> is font color, <code>bg</code> is background color. <code>_bold</code> and <code>_no_bold</code> regulate the tint. Commands should be in <code>%{ ... %}</code> so they do not appear. Avaible colors are:</p>
|
||||
`fg` is font color, `bg` is background color. `_bold` and `_no_bold` regulate the tint. Commands should be in `%{ ... %}` so they do not appear. Avaible colors are:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
black
|
||||
red
|
||||
green
|
||||
@ -224,11 +230,11 @@ blue
|
||||
magenta
|
||||
cyan
|
||||
white
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Avaible variables are:</p>
|
||||
Avaible variables are:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
%n - the username
|
||||
%m - the computer's hostname (truncated to the first period)
|
||||
%M - the computer's hostname
|
||||
@ -241,11 +247,11 @@ white
|
||||
%d - the current working directory
|
||||
%~ - the same as %d but if in $HOME, this will be replaced by ~
|
||||
%1/ - the same as %d but only last directory
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>RPROMPT (<code>acpi</code> package is necessary):</p>
|
||||
RPROMPT (`acpi` package is necessary):
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
precmd () {
|
||||
# battery charge
|
||||
function batcharge {
|
||||
@ -268,25 +274,26 @@ $(batcharge)\
|
||||
"%{$fg_bold[white]%}[%{$reset_color%}"\
|
||||
$returncode\
|
||||
"%{$fg_bold[white]%}]%{$reset_color%}"
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>My RPROMPT shows current time, battery change and last returned code. <code>precmd()</code> is necessary for automatic updating. The construct <code>$(if.true.false)</code> is conditional statement in <code>zsh</code>.</p>
|
||||
My RPROMPT shows current time, battery change and last returned code. `precmd()` is necessary for automatic updating. The construct `$(if.true.false)` is conditional statement in `zsh`.
|
||||
|
||||
<h2><a href="#aliases" class="anchor" id="aliases"><span class="octicon octicon-link"></span></a>Aliases</h2>
|
||||
<p><b>Copy only those aliases that you need.</b> If any alias uses application that is not installed it will leads to fail of loading of configuration file.</p>
|
||||
## <a href="#aliases" class="anchor" id="aliases"><span class="octicon octicon-link"></span></a>Aliases
|
||||
|
||||
<p>Small useful (or maybe not) function:</p>
|
||||
**Copy only those aliases that you need.** If any alias uses application that is not installed it will leads to fail of loading of configuration file.
|
||||
|
||||
{% highlight bash %}
|
||||
Small useful (or maybe not) function:
|
||||
|
||||
```bash
|
||||
show_which() {
|
||||
OUTPUT=$(which $1 | cut -d " " -f7-)
|
||||
echo "Running '$OUTPUT'" 1>&2
|
||||
}
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Here is the first group of aliases:</p>
|
||||
Here is the first group of aliases:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
## alias
|
||||
# colored grep
|
||||
alias grep='grep --colour=auto'
|
||||
@ -302,11 +309,11 @@ alias du='show_which du && du -k --total --human-readable'
|
||||
# change less and zless to vimpager
|
||||
alias less='vimpager'
|
||||
alias zless='vimpager'
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Here are ls aliases (see <a href="//unixhelp.ed.ac.uk/CGI/man-cgi?ls" title="Man page">man ls</a>):</p>
|
||||
Here are ls aliases (see [man ls](//unixhelp.ed.ac.uk/CGI/man-cgi?ls "Man page")):
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
alias ls='show_which ls && ls --color=auto --group-directories-first'
|
||||
alias ll='show_which ll && ls -l --human-readable'
|
||||
alias lr='show_which lr && ls --recursive'
|
||||
@ -315,11 +322,11 @@ alias lx='show_which lx && ll -X --ignore-backups'
|
||||
alias lz='show_which lz && ll -S --reverse'
|
||||
alias lt='show_which lt && ll -t --reverse'
|
||||
alias lm='show_which lm && la | more'
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Here are aliases to quick file view from console (just type a file name!):</p>
|
||||
Here are aliases to quick file view from console (just type a file name!):
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# alias -s
|
||||
alias -s {avi,mpeg,mpg,mov,m2v,mkv}=mpv
|
||||
alias -s {mp3,flac}=qmmp
|
||||
@ -327,11 +334,11 @@ alias -s {odt,doc,xls,ppt,docx,xlsx,pptx,csv}=libreoffice
|
||||
alias -s {pdf}=okular
|
||||
autoload -U pick-web-browser
|
||||
alias -s {html,htm}=opera
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Here are "sudo" aliases:</p>
|
||||
Here are "sudo" aliases:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# sudo alias
|
||||
if [[ $EUID == 0 ]]; then
|
||||
alias fat32mnt='show_which fat32mnt && mount -t vfat -o codepage=866,iocharset=utf8,umask=000'
|
||||
@ -351,23 +358,24 @@ else
|
||||
alias staging-i686-build='show_which staging-i686-build && sudo staging-i686-build'
|
||||
alias staging-x86_64-build='show_which staging-x86_64-build && sudo staging-x86_64-build'
|
||||
fi
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Here are global aliases. If they are enable the command <code>cat foo g bar</code> will be equivalent the command <code>cat foo | grep bar</code>:</p>
|
||||
Here are global aliases. If they are enable the command `cat foo g bar` will be equivalent the command `cat foo | grep bar`:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# global alias
|
||||
alias -g g="| grep"
|
||||
alias -g l="| less"
|
||||
alias -g t="| tail"
|
||||
alias -g h="| head"
|
||||
alias -g dn="&> /dev/null &"
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h2><a href="#functions" class="anchor" id="functions"><span class="octicon octicon-link"></span></a>Functions</h2>
|
||||
<p>Here is a special function for <code>xrandr</code>:</p>
|
||||
## <a href="#functions" class="anchor" id="functions"><span class="octicon octicon-link"></span></a>Functions
|
||||
|
||||
{% highlight bash %}
|
||||
Here is a special function for `xrandr`:
|
||||
|
||||
```bash
|
||||
# function to contorl xrandr
|
||||
# EXAMPLE: projctl 1024x768
|
||||
projctl () {
|
||||
@ -388,11 +396,11 @@ projctl () {
|
||||
xrandr --output VGA1 --mode 1366x768 --output LVDS1 --mode 1366x768
|
||||
fi
|
||||
}
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Unfortunately I can not remember <code>tar</code> flags thus I use special functions:</p>
|
||||
Unfortunately I can not remember `tar` flags thus I use special functions:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# function to extract archives
|
||||
# EXAMPLE: unpack file
|
||||
unpack () {
|
||||
@ -442,11 +450,11 @@ pack () {
|
||||
echo "'$1' is not a valid file"
|
||||
fi
|
||||
}
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Here is a special function for <code>su</code>:</p>
|
||||
Here is a special function for `su`:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
su () {
|
||||
CHECKSU=0
|
||||
for FLAG in $*; do
|
||||
@ -461,11 +469,11 @@ su () {
|
||||
/usr/bin/su $*
|
||||
fi
|
||||
}
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Function that replaces original <code>rm</code> command. If you type <code>rm</code> it will be equivalent moving to trash an you can easily restore a file:</p>
|
||||
Function that replaces original `rm` command. If you type `rm` it will be equivalent moving to trash an you can easily restore a file:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
rm () {
|
||||
# error check
|
||||
[ $# -eq 0 ] && { echo "Files are not set!"; return 1 }
|
||||
@ -505,11 +513,11 @@ rm () {
|
||||
fi
|
||||
done
|
||||
}
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Functions with automatic rehash after installing/removing packages are:</p>
|
||||
Functions with automatic rehash after installing/removing packages are:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
pacman () {
|
||||
/usr/bin/sudo /usr/bin/pacman $* && echo "$*" | grep -q "S\|R\|U" && rehash
|
||||
}
|
||||
@ -520,14 +528,15 @@ yaourt () {
|
||||
yatest () {
|
||||
/usr/bin/yaourt --config /etc/pactest.conf $* && echo "$*" | grep -q "S\|R\|U" && rehash
|
||||
}
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h2><a href="#variables" class="anchor" id="variables"><span class="octicon octicon-link"></span></a>Variables</h2>
|
||||
<p>It is recommended to set own variables in <code>~/.zshenv</code>. But I have everything stored in the single file.</p>
|
||||
## <a href="#variables" class="anchor" id="variables"><span class="octicon octicon-link"></span></a>Variables
|
||||
|
||||
<p>Here are path, mask of new files, editor and pager:</p>
|
||||
It is recommended to set own variables in `~/.zshenv`. But I have everything stored in the single file.
|
||||
|
||||
{% highlight bash %}
|
||||
Here are path, mask of new files, editor and pager:
|
||||
|
||||
```bash
|
||||
# path
|
||||
export PATH="$PATH:$HOME/.local/bin"
|
||||
# umask
|
||||
@ -535,25 +544,27 @@ umask 022
|
||||
# editor
|
||||
export EDITOR="vim"
|
||||
export PAGER="vimpager"
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Here is hashes. If they are enable the command <code>~global</code> will be equivalent the command <code>/mnt/global</code>:</p>
|
||||
Here is hashes. If they are enable the command `~global` will be equivalent the command `/mnt/global`:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# hash
|
||||
hash -d global=/mnt/global
|
||||
hash -d windows=/mnt/windows
|
||||
hash -d iso=/mnt/iso
|
||||
hash -d u1=/mnt/usbdev1
|
||||
hash -d u2=/mnt/usbdev
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
## <a href="#screenshot" class="anchor" id="screenshot"><span class="octicon octicon-link"></span></a>Screenshot
|
||||
|
||||
<h2><a href="#screenshot" class="anchor" id="screenshot"><span class="octicon octicon-link"></span></a>Screenshot</h2>
|
||||
<div class="thumbnails">
|
||||
{% assign scrdesc = "Zsh demonstation" %}
|
||||
{% assign scrname = "zshrc_demo" %}
|
||||
{% include prj_scr.html %}
|
||||
</div>
|
||||
|
||||
<h2><a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>File</h2>
|
||||
<p><a href="//raw.github.com/arcan1s/dotfiles/master/zshrc" title="GitHub" type="text/plain">Here is</a> my <code>.zshrc</code>.</p>
|
||||
## <a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>File
|
||||
|
||||
[Here is](//raw.github.com/arcan1s/dotfiles/master/zshrc "GitHub") my `.zshrc`.
|
@ -6,37 +6,43 @@ hastr: true
|
||||
tags: archlinux, linux, building, qutim
|
||||
title: Building Qutim using Qt5
|
||||
short: building-qutim-using-qt5
|
||||
description: <a href="//qutim.org" title="Qutim Homepage">Qutim</a> is a multiprotocol and cross platform messenger. It is written on <code>CPP</code> using Qt library. The project is actively developed. In this paper I will say about building this package in Archlinux using Qt5 library (instead of Qt4 which is used in current AUR packages).
|
||||
---
|
||||
<h2><a href="#problems" class="anchor" id="problems"><span class="octicon octicon-link"></span></a>What's wrong?</h2>
|
||||
<p>This package uses <a href="//qt-project.org/wiki/qbs" title="Wiki">qbs</a> for building, which is a bit strange IMHO. A package, which is necessary for building, is <a href="//aur.archlinux.org/packages/qbs-git/" title="AUR">in AUR </a>. I recommend to use git version of the package. When I asked Andrea Scarpino (who maintains KDE and Qt packages into the official repos) about qbs, he told me "we will support it in time". And I agree with him, the project seems to be a little unstable.</p>
|
||||
[Qutim](//qutim.org) is a multiprotocol and cross platform messenger. It is written on `CPP` using Qt library. The project is actively developed. In this paper I will say about building this package in Archlinux using Qt5 library (instead of Qt4 which is used in current AUR packages).
|
||||
|
||||
<h2><a href="#prepare" class="anchor" id="prepare"><span class="octicon octicon-link"></span></a>Prepare</h2>
|
||||
<p>Install dependences. I had used <code>namcap</code>, so maybe I missed something:</p>
|
||||
<!--more-->
|
||||
|
||||
{% highlight bash %}
|
||||
# <a href="#problems" class="anchor" id="problems"><span class="octicon octicon-link"></span></a>What's wrong?
|
||||
|
||||
This package uses [qbs](//qt-project.org/wiki/qbs "Wiki") for building, which is a bit strange IMHO. A package, which is necessary for building, is [in AUR](//aur.archlinux.org/packages/qbs-git/ "AUR") . I recommend to use git version of the package. When I asked Andrea Scarpino (who maintains KDE and Qt packages into the official repos) about qbs, he told me "we will support it in time". And I agree with him, the project seems to be a little unstable.
|
||||
|
||||
# <a href="#prepare" class="anchor" id="prepare"><span class="octicon octicon-link"></span></a>Prepare
|
||||
|
||||
Install dependences. I had used `namcap`, so maybe I missed something:
|
||||
|
||||
```bash
|
||||
pacman -Sy --asdeps clang git libc++abi qt5-quick1 qt5-x11extras
|
||||
yaourt -S --asdeps jreen-git qbs-git
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h3><a href="#qbs" class="anchor" id="qbs"><span class="octicon octicon-link"></span></a>qbs settings</h3>
|
||||
<p>You may read about qbs <a href="//qt-project.org/wiki/qbs" title="Wiki">on the link</a> or see examples which are provides by the package. qbs uses configuration file that firstly you must create and secondly it is stored in your home directory. In theory a configuration file creating ((<code>~/.config/QtProject/qbs.conf</code>)) looks like this:</p>
|
||||
### <a href="#qbs" class="anchor" id="qbs"><span class="octicon octicon-link"></span></a>qbs settings
|
||||
|
||||
{% highlight bash %}
|
||||
You may read about qbs [on the link](//qt-project.org/wiki/qbs "Wiki") or see examples which are provides by the package. qbs uses configuration file that firstly you must create and secondly it is stored in your home directory. In theory a configuration file creating (`~/.config/QtProject/qbs.conf`) looks like this:
|
||||
|
||||
```bash
|
||||
qbs-setup-qt --detect
|
||||
qbs-detect-toolchains
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Firstly we find Qt libraries. Then we find toolchains (such as compilers). And next we must insert a toolchain into Qt profile (for example, we need <code>clang</code> toolchain):</p>
|
||||
Firstly we find Qt libraries. Then we find toolchains (such as compilers). And next we must insert a toolchain into Qt profile (for example, we need `clang` toolchain):
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
sed 's/clang\\/qt-5-2-0\\/g' -i ~/.config/QtProject/qbs.conf
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>And there are other ways. You may edit the file manually or use <code>qbs-config-ui</code> or <code>qbs-config</code>.</p>
|
||||
<p>So, we have created the configuration file and put it into build directory:</p>
|
||||
And there are other ways. You may edit the file manually or use `qbs-config-ui` or `qbs-config`.
|
||||
So, we have created the configuration file and put it into build directory:
|
||||
|
||||
{% highlight ini %}
|
||||
```ini
|
||||
[General]
|
||||
|
||||
[Qt]
|
||||
@ -70,14 +76,15 @@ qutim\cpp\toolchainInstallPath=/usr/bin
|
||||
qutim\qbs\architecture=x86_64
|
||||
qutim\qbs\endianness=little
|
||||
qutim\qbs\toolchain=clang, llvm, gcc
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p><a href="/resources/docs/qutim-qt5-git/qbs-qutim.conf" title="File" type="text/plain">qbs-qutim.conf</a></p>
|
||||
[qbs-qutim.conf](/resources/docs/qutim-qt5-git/qbs-qutim.conf "File")
|
||||
|
||||
<h3><a href="#patch" class="anchor" id="patch"><span class="octicon octicon-link"></span></a>Patch for sources</h3>
|
||||
<p>The first problem is <code>clang</code> (at least in Archlinux):</p>
|
||||
### <a href="#patch" class="anchor" id="patch"><span class="octicon octicon-link"></span></a>Patch for sources
|
||||
|
||||
{% highlight diff %}
|
||||
The first problem is `clang` (at least in Archlinux):
|
||||
|
||||
```diff
|
||||
diff -ruN qutim.orig/core/libqutim.qbs qutim/core/libqutim.qbs
|
||||
--- qutim.orig/core/libqutim.qbs 2014-01-06 15:39:56.000000000 +0400
|
||||
+++ qutim/core/libqutim.qbs 2014-01-06 15:44:54.502175067 +0400
|
||||
@ -90,11 +97,11 @@ diff -ruN qutim.orig/core/libqutim.qbs qutim/core/libqutim.qbs
|
||||
return flags;
|
||||
}
|
||||
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>And the second one is Vk plugin:</p>
|
||||
And the second one is Vk plugin:
|
||||
|
||||
{% highlight diff %}
|
||||
```diff
|
||||
diff -ruN qutim.orig/protocols/vkontakte/vreen/vreen.qbs qutim/protocols/vkontakte/vreen/vreen.qbs
|
||||
--- qutim.orig/protocols/vkontakte/vreen/vreen.qbs 2014-01-06 15:41:42.000000000 +0400
|
||||
+++ qutim/protocols/vkontakte/vreen/vreen.qbs 2014-01-06 15:46:47.142178486 +0400
|
||||
@ -106,13 +113,13 @@ diff -ruN qutim.orig/protocols/vkontakte/vreen/vreen.qbs qutim/protocols/vkontak
|
||||
|
||||
property string vreen_version_major: 1
|
||||
property string vreen_version_minor: 9
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p><a href="/resources/docs/qutim-qt5-git/qutim-qbs-1.1.patch" title="File" type="text/plain">qutim-qbs-1.1.patch</a></p>
|
||||
[qutim-qbs-1.1.patch](/resources/docs/qutim-qt5-git/qutim-qbs-1.1.patch "File")
|
||||
|
||||
<h3><a href="#sources" class="anchor" id="sources"><span class="octicon octicon-link"></span></a>Get sources</h3>
|
||||
### <a href="#sources" class="anchor" id="sources"><span class="octicon octicon-link"></span></a>Get sources
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# clone repo
|
||||
git clone https://github.com/euroelessar/qutim
|
||||
# save qbs.conf
|
||||
@ -126,28 +133,28 @@ git submodule update --init --recursive
|
||||
# patch
|
||||
cd ..
|
||||
patch -p0 -i qutim-qbs-1.1.patch
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h2><a href="#build" class="anchor" id="build"><span class="octicon octicon-link"></span></a>Building</h2>
|
||||
## <a href="#build" class="anchor" id="build"><span class="octicon octicon-link"></span></a>Building
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
cd qutim
|
||||
HOME=$(pwd) qbs -j $(nproc) -d ../build release profile:qutim
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>I want to create a universal recipe for the building, thus we must set <code>$HOME</code> directory. Flag <code>-j</code> means number of jobs, <code>-d</code> means build directory, <code>release</code> means building type (debug, release), <code>profile</code> is used profile, which is described in the configuration file.</p>
|
||||
I want to create a universal recipe for the building, thus we must set `$HOME` directory. Flag `-j` means number of jobs, `-d` means build directory, `release` means building type (debug, release), `profile` is used profile, which is described in the configuration file.
|
||||
|
||||
<h2><a href="#install" class="anchor" id="install"><span class="octicon octicon-link"></span></a>Installation</h2>
|
||||
## <a href="#install" class="anchor" id="install"><span class="octicon octicon-link"></span></a>Installation
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
HOME=$(pwd) sudo qbs install -d ../build --install-root "/usr" profile:qutim
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>We must set root directory (<code>--install-root</code>), because without this option the package will be installed into <code>/</code> (<code>/bin</code> and <code>/lib</code>).</p>
|
||||
We must set root directory (`--install-root`), because without this option the package will be installed into `/` (`/bin` and `/lib`).
|
||||
|
||||
<h2><a href="#pkgbuild" class="anchor" id="pkgbuild"><span class="octicon octicon-link"></span></a>PKGBUILD</h2>
|
||||
## <a href="#pkgbuild" class="anchor" id="pkgbuild"><span class="octicon octicon-link"></span></a>PKGBUILD
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
pkgname=qutim-qt5-git
|
||||
_gitname=qutim
|
||||
pkgver=v0.3.1.967.gc56d61e
|
||||
@ -198,6 +205,6 @@ package() {
|
||||
cd "${srcdir}/${_gitname}"
|
||||
HOME="${srcdir}" qbs install -d ../build --install-root "${pkgdir}/usr" profile:qutim
|
||||
}
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p><a href="/resources/docs/qutim-qt5-git/PKGBUILD" title="File" type="text/plain">PKGBUILD</a></p>
|
||||
[PKGBUILD](/resources/docs/qutim-qt5-git/PKGBUILD "File")
|
@ -1,74 +0,0 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
layout: paper
|
||||
hastr: true
|
||||
tags: site, github pages
|
||||
title: Site changes
|
||||
short: site-changes
|
||||
description: I decided to change my site. You may find short list of changes below.
|
||||
---
|
||||
<h2><a href="#list" class="anchor" id="list"><span class="octicon octicon-link"></span></a>The list of changes:</h2>
|
||||
<ul>
|
||||
<li>I rented a <code>arcanis.me</code> domain. Now I have a normal address, as well as all normal people have it. Small description of how to do it. Firstly, you should rent domain and activate DNS editing (it is called <a href="//www.nic.ru/dns/service/dns_hosting/" title="Service page">DNS-master</a> for Ru-center). I pay about $30 in year. Then you should create CNAME file in your repository; this file has line with your domain name. And finally you should create two DNS records for your domain:
|
||||
|
||||
{% highlight bash %}
|
||||
@ A 192.30.252.153
|
||||
@ A 192.30.252.154
|
||||
# redirection from www.*
|
||||
www CNAME @
|
||||
{% endhighlight %}
|
||||
|
||||
(Symbol <code>@</code> means you root domain.) And next wait for two hours. You may find out the result as follows:
|
||||
|
||||
{% highlight bash %}
|
||||
$ dig domain.name +nostats +nocomments +nocmd
|
||||
; <<>> DiG 9.9.2-P2 <<>> domain.name +nostats +nocomments +nocmd
|
||||
;; global options: +cmd
|
||||
;domain.name. IN A
|
||||
domain.name. 912 IN A 192.30.252.153
|
||||
domain.name. 912 IN A 192.30.252.154
|
||||
...
|
||||
{% endhighlight %}
|
||||
</li>
|
||||
<li>Also I've created <a href="ftp://repo.arcanis.me/repo" title="Repository">my own repo</a>, which will contain some AUR packages that I'm using. Support of both architectures is planned.</li>
|
||||
<li>Since the repo requires ftp protocol, I've changed samba shared folders to ftp. The problem of access has been resolved by using mount options:
|
||||
|
||||
{% highlight bash %}
|
||||
# only read rights
|
||||
/home/arcanis/music /srv/ftp/music ext4 defaults,bind,ro 0 0
|
||||
/home/arcanis/arch/repo /srv/ftp/repo ext4 defaults,bind,ro 0 0
|
||||
# read and write rights (the file has size 2 Gb)
|
||||
/home/arcanis/share.fs /srv/ftp/share ext4 defaults,rw 0 0
|
||||
{% endhighlight %}
|
||||
|
||||
Login on special user and option <code>anon_world_readable_only=YES</code> are used for prevent access to the music directory. Also here is my <code>/etc/vsftpd.conf</code> configuration file:
|
||||
|
||||
{% highlight bash %}
|
||||
anonymous_enable=YES
|
||||
anon_root=/srv/ftp
|
||||
local_enable=YES
|
||||
write_enable=YES
|
||||
local_umask=022
|
||||
anon_upload_enable=YES
|
||||
anon_mkdir_write_enable=YES
|
||||
anon_other_write_enable=YES
|
||||
anon_world_readable_only=YES
|
||||
dirmessage_enable=YES
|
||||
xferlog_enable=YES
|
||||
connect_from_port_20=YES
|
||||
nopriv_user=music
|
||||
ascii_upload_enable=YES
|
||||
ftpd_banner=Welcome to arcanis
|
||||
chroot_local_user=YES
|
||||
local_root=/srv/ftp/music
|
||||
listen=YES
|
||||
{% endhighlight %}
|
||||
Now let's add redirection from <code>repo.arcanis.me</code> to the needed IP address. To do this, add the following entry in DNS:
|
||||
{% highlight bash %}
|
||||
repo A 89.249.170.38
|
||||
{% endhighlight %}
|
||||
|
||||
</li>
|
||||
<li>Also there are plans to buy a server for compiling packages and hosting the repository, filesharing and backups.</li>
|
||||
</ul>
|
76
_posts/2014-03-06-site-changes.md
Normal file
76
_posts/2014-03-06-site-changes.md
Normal file
@ -0,0 +1,76 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
layout: paper
|
||||
hastr: true
|
||||
tags: site, github pages
|
||||
title: Site changes
|
||||
short: site-changes
|
||||
---
|
||||
I decided to change my site. You may find short list of changes below.
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#list" class="anchor" id="list"><span class="octicon octicon-link"></span></a>The list of changes:
|
||||
* I rented a `arcanis.me` domain. Now I have a normal address, as well as all normal people have it. Small description of how to do it. Firstly, you should rent domain and activate DNS editing (it is called [DNS-master](//www.nic.ru/dns/service/dns_hosting/ "Service page") for Ru-center). I pay about $30 in year. Then you should create CNAME file in your repository; this file has line with your domain name. And finally you should create two DNS records for your domain:
|
||||
|
||||
```bash
|
||||
@ A 192.30.252.153
|
||||
@ A 192.30.252.154
|
||||
# redirection from www.*
|
||||
www CNAME @
|
||||
```
|
||||
|
||||
(Symbol `@` means you root domain.) And next wait for two hours. You may find out the result as follows:
|
||||
|
||||
```bash
|
||||
$ dig domain.name +nostats +nocomments +nocmd
|
||||
; <<>> DiG 9.9.2-P2 <<>> domain.name +nostats +nocomments +nocmd
|
||||
;; global options: +cmd
|
||||
;domain.name. IN A
|
||||
domain.name. 912 IN A 192.30.252.153
|
||||
domain.name. 912 IN A 192.30.252.154
|
||||
...
|
||||
```
|
||||
|
||||
* Also I've created [my own repo](ftp://repo.arcanis.me/repo "Repository"), which will contain some AUR packages that I'm using. Support of both architectures is planned.
|
||||
* Since the repo requires ftp protocol, I've changed samba shared folders to ftp. The problem of access has been resolved by using mount options:
|
||||
|
||||
```bash
|
||||
# only read rights
|
||||
/home/arcanis/music /srv/ftp/music ext4 defaults,bind,ro 0 0
|
||||
/home/arcanis/arch/repo /srv/ftp/repo ext4 defaults,bind,ro 0 0
|
||||
# read and write rights (the file has size 2 Gb)
|
||||
/home/arcanis/share.fs /srv/ftp/share ext4 defaults,rw 0 0
|
||||
```
|
||||
|
||||
Login on special user and option `anon_world_readable_only=YES` are used for prevent access to the music directory. Also here is my `/etc/vsftpd.conf` configuration file:
|
||||
|
||||
```bash
|
||||
anonymous_enable=YES
|
||||
anon_root=/srv/ftp
|
||||
local_enable=YES
|
||||
write_enable=YES
|
||||
local_umask=022
|
||||
anon_upload_enable=YES
|
||||
anon_mkdir_write_enable=YES
|
||||
anon_other_write_enable=YES
|
||||
anon_world_readable_only=YES
|
||||
dirmessage_enable=YES
|
||||
xferlog_enable=YES
|
||||
connect_from_port_20=YES
|
||||
nopriv_user=music
|
||||
ascii_upload_enable=YES
|
||||
ftpd_banner=Welcome to arcanis
|
||||
chroot_local_user=YES
|
||||
local_root=/srv/ftp/music
|
||||
listen=YES
|
||||
```
|
||||
|
||||
Now let's add redirection from `repo.arcanis.me` to the needed IP address. To do this, add the following entry in DNS:
|
||||
|
||||
```bash
|
||||
repo A 89.249.170.38
|
||||
```
|
||||
|
||||
* Also there are plans to buy a server for compiling packages and hosting the repository, filesharing and backups.
|
@ -6,20 +6,24 @@ hastr: true
|
||||
tags: archlinux, configuration, linux
|
||||
title: Creating own repository
|
||||
short: creating-custom-repo
|
||||
description: It is a short paper devoted to creation own ArchLinux repository.
|
||||
---
|
||||
<h2><a href="#prepare" class="anchor" id="prepare"><span class="octicon octicon-link"></span></a>Prepare</h2>
|
||||
<p>First find a server and desire to have sex with it. It is recommended to use Archlinux on it, but it is not necessarily - because you may create special root for Archlinux. Also you need two packages, <code>devtools</code> and <code>pacman</code>:</p>
|
||||
It is a short paper devoted to creation own ArchLinux repository.
|
||||
|
||||
{% highlight bash %}
|
||||
<!--more-->
|
||||
|
||||
## <a href="#prepare" class="anchor" id="prepare"><span class="octicon octicon-link"></span></a>Prepare
|
||||
|
||||
First find a server and desire to have sex with it. It is recommended to use Archlinux on it, but it is not necessarily - because you may create special root for Archlinux. Also you need two packages, `devtools` and `pacman`:
|
||||
|
||||
```bash
|
||||
pacman -Sy devtools
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p><a href="//www.archlinux.org/packages/devtools/" title="Archlinux package">devtools</a> is script set for building automation in the clean chroot. I think most of Arch maintainers use it.</p>
|
||||
[devtools](//www.archlinux.org/packages/devtools/ "Archlinux package") is script set for building automation in the clean chroot. I think most of Arch maintainers use it.
|
||||
|
||||
<p>Let's create working directories and set colors:</p>
|
||||
Let's create working directories and set colors:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# colors
|
||||
if [ ${USECOLOR} == "yes" ]; then
|
||||
bblue='\e[1;34m'
|
||||
@ -53,39 +57,40 @@ if [ ! -d "${STAGINGDIR}" ]; then
|
||||
echo -e "${bwhite}[II] ${bblue}Creating directory ${bwhite}'${STAGINGDIR}'${cclose}"
|
||||
mkdir -p "${STAGINGDIR}" || error_mes "unknown"
|
||||
fi
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p><code>${REPODIR}/{i686,x86_64}</code> are directories for repository, <code>${PREPAREDIR}</code> is directory where compiled packages will be stored, <code>${STAGINGDIR}</code> is one where packages will be built.</p>
|
||||
`${REPODIR}/{i686,x86_64}` are directories for repository, `${PREPAREDIR}` is directory where compiled packages will be stored, `${STAGINGDIR}` is one where packages will be built.
|
||||
|
||||
<h2><a href="#theory" class="anchor" id="theory"><span class="octicon octicon-link"></span></a>A bit of theory</h2>
|
||||
<p>Create directory, share it (using <a href="/en/2014/03/06/site-changes/" title="Site changes paper">ftp</a>, for example). It has two subdirectories - <code>i686</code> and <code>x86_64</code> - for each architecture respectively. And fill them with a set of packages.</p>
|
||||
## <a href="#theory" class="anchor" id="theory"><span class="octicon octicon-link"></span></a>A bit of theory
|
||||
|
||||
<p>Updating repository may be split into the following steps:</p>
|
||||
<ol>
|
||||
<li>Creating PKGBUILDs (or updating them from AUR).</li>
|
||||
<li>Packages building for each architecture in clean chroot.</li>
|
||||
<li>Packages signing.</li>
|
||||
<li>Creating the list of packages.</li>
|
||||
<li>Repository update:
|
||||
<ol><li>Removal old packages from repository.</li>
|
||||
<li>Copying new packages</li>
|
||||
<li>Repository update.</li></ol>
|
||||
</li>
|
||||
<li>Cleaning.</li>
|
||||
</ol>
|
||||
Create directory, share it (using [ftp](/en/2014/03/06/site-changes/ "Site changes paper"), for example). It has two subdirectories - `i686` and `x86_64` - for each architecture respectively. And fill them with a set of packages.
|
||||
|
||||
<h3><a href="#pkgbuild" class="anchor" id="pkgbuild"><span class="octicon octicon-link"></span></a>Creating PKGBUILDs</h3>
|
||||
<p>Download source tarballs from AUR:</p>
|
||||
Updating repository may be split into the following steps:
|
||||
|
||||
{% highlight bash %}
|
||||
1. Creating PKGBUILDs (or updating them from AUR).
|
||||
2. Packages building for each architecture in clean chroot.
|
||||
3. Packages signing.
|
||||
4. Creating the list of packages.
|
||||
5. Repository update:
|
||||
1. Removal old packages from repository.
|
||||
2. Copying new packages
|
||||
3. Repository update.
|
||||
6. Cleaning.
|
||||
|
||||
### <a href="#pkgbuild" class="anchor" id="pkgbuild"><span class="octicon octicon-link"></span></a>Creating PKGBUILDs
|
||||
|
||||
Download source tarballs from AUR:
|
||||
|
||||
```bash
|
||||
cd "${STAGINGDIR}"
|
||||
yaourt -G package-name
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h3><a href="#building" class="anchor" id="building"><span class="octicon octicon-link"></span></a>Packages building</h3>
|
||||
<p>Build each package automatically:</p>
|
||||
### <a href="#building" class="anchor" id="building"><span class="octicon octicon-link"></span></a>Packages building
|
||||
|
||||
{% highlight bash %}
|
||||
Build each package automatically:
|
||||
|
||||
```bash
|
||||
func_build() {
|
||||
if [ ${USECOLOR} == "yes" ]; then
|
||||
_bblue='\e[1;34m'
|
||||
@ -121,19 +126,19 @@ export -f func_build
|
||||
echo -e "${bwhite}[II]${cclose} Building packages"
|
||||
cd "${STAGINGDIR}"
|
||||
/usr/bin/find -name 'PKGBUILD' -type f -execdir /usr/bin/bash -c "func_build "${PREPAREDIR}" "${ROOTDIR}"" \;
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>It is recommended to add the following lines to <code>/etc/sudoers</code>:</p>
|
||||
It is recommended to add the following lines to `/etc/sudoers`:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
username ALL=NOPASSWD: /usr/bin/staging-i686-build
|
||||
username ALL=NOPASSWD: /usr/bin/staging-x86_64-build
|
||||
username ALL=NOPASSWD: /usr/bin/multilib-staging-build
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h3><a href="#signing" class="anchor" id="signing"><span class="octicon octicon-link"></span></a>Packages signing</h3>
|
||||
### <a href="#signing" class="anchor" id="signing"><span class="octicon octicon-link"></span></a>Packages signing
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# signing
|
||||
if [ ${USEGPG} == "yes" ]; then
|
||||
echo -e "${bwhite}[II]${cclose} Signing"
|
||||
@ -142,34 +147,35 @@ if [ ${USEGPG} == "yes" ]; then
|
||||
/usr/bin/gpg -b ${PACKAGE}
|
||||
done
|
||||
fi
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>It is recommended to configure <a href="//wiki.archlinux.org/index.php/GPG#gpg-agent" title="ArchWiki">gpg-agent</a>.</p>
|
||||
It is recommended to configure [gpg-agent](//wiki.archlinux.org/index.php/GPG#gpg-agent "ArchWiki").
|
||||
|
||||
<h3><a href="#list" class="anchor" id="list"><span class="octicon octicon-link"></span></a>Creating the list of packages</h3>
|
||||
### <a href="#list" class="anchor" id="list"><span class="octicon octicon-link"></span></a>Creating the list of packages
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# creating packages list
|
||||
cd "${PREPAREDIR}"
|
||||
i686_PACKAGES=$(/usr/bin/find * -name '*-i686.pkg.tar.xz' -o -name '*-any.pkg.tar.xz')
|
||||
x86_64_PACKAGES=$(/usr/bin/find * -name '*-x86_64.pkg.tar.xz' -o -name '*-any.pkg.tar.xz')
|
||||
echo -e "${bwhite}[II] ${bblue}=>${cclose} i686 packages: \n${bwhite}${i686_PACKAGES}${cclose}"
|
||||
echo -e "${bwhite}[II] ${bblue}=>${cclose} x86_64 packages: \n${bwhite}${x86_64_PACKAGES}${cclose}"
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h3><a href="#updating" class="anchor" id="updating"><span class="octicon octicon-link"></span></a>Repository update</h3>
|
||||
<p>Here is a function for removal packages from database and repository:</p>
|
||||
### <a href="#updating" class="anchor" id="updating"><span class="octicon octicon-link"></span></a>Repository update
|
||||
|
||||
{% highlight bash %}
|
||||
Here is a function for removal packages from database and repository:
|
||||
|
||||
```bash
|
||||
func_remove() {
|
||||
_PACKAGE="$1"
|
||||
/usr/bin/rm -f "${_PACKAGE}"{,.sig}
|
||||
}
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p><code>i686</code> repository update:</p>
|
||||
`i686` repository update:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# updating i686 repo
|
||||
echo -e "${bwhite}[II]${cclose} Updating ${bwhite}i686${cclose} repo"
|
||||
cd "${REPODIR}/i686"
|
||||
@ -184,11 +190,11 @@ for PACKAGE in ${i686_PACKAGES}; do
|
||||
/usr/bin/repo-add ${DBNAME}.db.tar.gz "${PACKAGE}"
|
||||
/usr/bin/repo-add --files ${DBNAME}.files.tar.gz "${PACKAGE}"
|
||||
done
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p><code>x86_64</code> repository update:</p>
|
||||
`x86_64` repository update:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# updating x86_64 repo
|
||||
echo -e "${bwhite}[II]${cclose} Updating ${bwhite}x86_64${cclose} repo"
|
||||
cd "${REPODIR}/x86_64"
|
||||
@ -203,22 +209,23 @@ for PACKAGE in ${x86_64_PACKAGES}; do
|
||||
/usr/bin/repo-add ${DBNAME}.db.tar.gz "${PACKAGE}"
|
||||
/usr/bin/repo-add --files ${DBNAME}.files.tar.gz "${PACKAGE}"
|
||||
done
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h3><a href="#clear" class="anchor" id="clear"><span class="octicon octicon-link"></span></a>Cleaning</h3>
|
||||
### <a href="#clear" class="anchor" id="clear"><span class="octicon octicon-link"></span></a>Cleaning
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# clear
|
||||
cd "${PREPAREDIR}"
|
||||
/usr/bin/rm -rf *
|
||||
cd "${STAGINGDIR}"
|
||||
/usr/bin/rm -rf *
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h3><a href="#symlinks" class="anchor" id="symlinks"><span class="octicon octicon-link"></span></a>Creating symlinks</h3>
|
||||
<p>You may want to create a directory, which will contain symlinks on actual packages with names, which does not contain version:</p>
|
||||
### <a href="#symlinks" class="anchor" id="symlinks"><span class="octicon octicon-link"></span></a>Creating symlinks
|
||||
|
||||
{% highlight bash %}
|
||||
You may want to create a directory, which will contain symlinks on actual packages with names, which does not contain version:
|
||||
|
||||
```bash
|
||||
# creating symlinks
|
||||
if [ ${SYMLINK} == "yes" ]; then
|
||||
echo -e "${bwhite}[II]${cclose} Creating symlinks"
|
||||
@ -237,15 +244,17 @@ if [ ${SYMLINK} == "yes" ]; then
|
||||
/usr/bin/ln -sf "../x86_64/${PACKAGE}" "${PKGNAME}-x86_64.pkg.tar.xz"
|
||||
done
|
||||
fi
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h3><a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>File</h3>
|
||||
<p>Here is <a href="//github.com/arcan1s/repo-scripts" title="GitHub">the scripts</a>. Download source tarballs and run script (editing variables if it is necessary).</p>
|
||||
### <a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>File
|
||||
|
||||
<h2><a href="#using" class="anchor" id="using"><span class="octicon octicon-link"></span></a>Repository usage</h2>
|
||||
<p>Just add following lines to <code>/etc/pacman.conf</code>:</p>
|
||||
Here is [the scripts](//github.com/arcan1s/repo-scripts "GitHub"). Download source tarballs and run script (editing variables if it is necessary).
|
||||
|
||||
{% highlight bash %}
|
||||
## <a href="#using" class="anchor" id="using"><span class="octicon octicon-link"></span></a>Repository usage
|
||||
|
||||
Just add following lines to `/etc/pacman.conf`:
|
||||
|
||||
```bash
|
||||
[$REPONAME]
|
||||
Server = ftp://$REPOADDRESS/repo/$arch
|
||||
{% endhighlight %}
|
||||
```
|
@ -1,85 +0,0 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
layout: paper
|
||||
hastr: true
|
||||
tags: настройка, linux, archlinux
|
||||
title: Apps which I use
|
||||
short: my-desktop
|
||||
description: Here is a short paper devoted to the set of applications and extensions that I use everyday on my home computer.
|
||||
---
|
||||
<h2><a href="#apps" class="anchor" id="apps"><span class="octicon octicon-link"></span></a>Applications</h2>
|
||||
<ul>
|
||||
<li><p><b>Shell</b> is zshrc and nothing else. You may find a small description of my settings <a href="/en/2014/01/14/about-zshrc/" title="About zshrc paper">here</a>. It is stored <a href="//raw.githubusercontent.com/arcan1s/dotfiles/master/zshrc" title="File" type="text/plain">here</a> (or <a href="//raw.githubusercontent.com/arcan1s/dotfiles/master/zshrc_server" title="File" type="text/plain">here</a>).</p></li>
|
||||
|
||||
<li><p><b>DE</b> - I use KDE as Desktop Environment. And that's why most of apps are qt-based. Some KDE settings are below.</p></li>
|
||||
|
||||
<li><p><b>Graphic editors</b> - <a href="//kde.org/applications/graphics/gwenview/" title="Gwenview Homepage">gwenview</a> is used for viewing images, <a href="//kde.org/applications/graphics/kolourpaint/" title="Kolourpaint Homepage">kolourpaint</a> is used for simple editing pixel images, <a href="//www.gimp.org/" title="Gimp Homepage">gimp</a> (without plugins, since they are not needed for me) - for editing and <a href="//www.inkscape.org/" title="Inkskape Homepage">inkskape</a> is used as editor of vector graphics.</p></li>
|
||||
|
||||
<li><p><b>Browser</b> - I use Firefox. Some Firefox settings are below. Chromium is used as additional browser, elinks is used as console browser.</p></li>
|
||||
|
||||
<li><p><b>IM client</b> is <a href="//qutim.org" title="Qutim Homepage">qutIM</a>. It is a cross-platform, multiprotocol and full featured client. <a href="//kde.org/applications/internet/kopete/" title="Kopete Homepage">Kopete</a>, which I used before it, crashes, does not work correctly and does not work normally with codepage. Also I don't use a console client since I use a tablet IM. And I use Skype for skype obviously.</p></li>
|
||||
|
||||
<li><p><b>Mail client</b> is <a href="//kde.org/applications/internet/kmail/" title="Kmail Homepage">kmail</a>. It is a full featured client (and I use most of them), looks pretty and it is easy to use. If it will be DE-undepended it will be better.</p></li>
|
||||
|
||||
<li><p><b>IRC client</b> is <a href="//konversation.kde.org/" title="Konversation Homepage">konversation</a>. It is a simple IRC client. Though as far as I remember qutIM also supports IRC protocol, I prefre to use a special IRC client.</p></li>
|
||||
|
||||
<li><p><b>Torrent client</b> is <a href="//www.transmissionbt.com/" title="Transmission Homepage">transmission</a> with Qt5 interface (it has gtk interface too). It is also used for server but without GUI.</p></li>
|
||||
|
||||
<li><p><b>Video player</b> is <a href="//mpv.io/" title="Mpv Homepage">mpv</a>, since mplayer died and mplayer2 was born deadborn. Graphical frontend are not needed.</p></li>
|
||||
|
||||
<li><p><b>Audio player</b> is <a href="//qmmp.ylsoftware.com/" title="Qmmp Homepage">qmmp</a>. It is a good winamp-like player. Flick of the wrist you may make a handy interface for it (simpleui).</p></li>
|
||||
|
||||
<li><p><b>Audio/video editors</b>: <a href="//kde-apps.org/content/show.php?content=29024" title="Kdenlive Homepage">kdenlive</a> is used as video editor, <a href="//kde-apps.org/content/show.php?content=29024">soundkonverter</a> is used as audio editor, <a href="//wiki.gnome.org/Apps/EasyTAG" title="Easytag Homepage">easytag</a> is used for editing audio tags (unfortunately, it is a gtk-based, but I didn't find a better tool for it). And command line and scripts written on bash are used too.</p></li>
|
||||
|
||||
<li><p><b>Office</b>: <a href="//wps-community.org/" title="KO Homepage">Kingsoft Office</a> is used as alternative of Microsoft Office; it has no any feature, but it looks normally, it is qt-based and it is said that it has a good support for standart formats. (Linux version has an alfa stage.) <a href="//kile.sourceforge.net/" title="Kile Homepage">Kile</a> is used as LaTeX frontend. <a href="//kde.org/applications/graphics/okular/" title="Okular Homepage">Okular</a> is used as document viewer. And I use <a href="//goldendict.org/" title="GoldenDict Homepage">GoldenDict</a> as dictionary.</p></li>
|
||||
|
||||
<li><p><b>Editors</b>: <a href="//www.kde.org/applications/utilities/kwrite/" title="Kwrite Homepage">kwrite</a> is used as a simple text editor, <a href="//www.kde.org/applications/utilities/kate/" title="Kate Homepage">kate</a> (and <a href="//zaufi.github.io/kate-cpp-helper-plugin.html" title="Plugin Homepage">cpp-helper</a> plugin) is used as advanced text editor. And of course I use vim in console.</p></li>
|
||||
|
||||
<li><p><b>Scientific soft</b>. Chemical visualizers are <a href="//www.ks.uiuc.edu/Research/vmd/" title="VMD Homepage">vmd</a>, <a href="//www.cgl.ucsf.edu/chimera/" title="Chimera Homepage">chimera</a> and <a href="//pymol.org/" title="Pymol Homepage">pymol</a>. Physics simulator is <a href="//kde.org/applications/education/step/" title="Step Homepage">step</a>. Calculator is <a href="//kde.org/applications/education/kalgebra/" title="Kalgebra Homepage">kalgebra</a> and console <a href="//ipython.org/" title="ipython Homepage">ipython</a>. <a href="//qtiplot.com/" title="Qtiplot Homepage">Qtiplot</a> is used for drawing graphs and data analysis (scidavis, which is its fork, unfortunately, is half-dead), <a href="//plasma-gate.weizmann.ac.il/Grace/" title="Grace Homepage">grace</a> is used for only drawing graphs. <a href="//ruby.chemie.uni-freiburg.de/~martin/chemtool/chemtool.html" title="Chemtool Homepage">Chemtool</a> is used as alternative of ChemDraw.</p></li>
|
||||
|
||||
<li><p><b>System applications</b>. File manager is <a href="//kde.org/applications/system/dolphin/" title="Dolphin Homepage">dolphin</a>, <a href="//doublecmd.sourceforge.net/" title="Doublecmd Homepage">doublecmd</a> is used as twin-panel manager. Terminal emulators are <a href="//yakuake.kde.org/" title="Yakuake Homepage">yakuake</a> and <a href="//software.schmorp.de/pkg/rxvt-unicode.html" title="Urxvt Homepage">urxvt</a> (as windowed emulator). Archiver graphical interface is <a href="//kde.org/applications/utilities/ark/" title="Ark Homepage">ark</a>.</p></li>
|
||||
</ul>
|
||||
|
||||
|
||||
<h2><a href="#kde" class="anchor" id="kde"><span class="octicon octicon-link"></span></a>KDE settings</h2>
|
||||
<div class="thumbnails">
|
||||
{% assign scrdesc = "KDE screenshot" %}
|
||||
{% assign scrname = "kde" %}
|
||||
{% include prj_scr.html %}
|
||||
</div>
|
||||
|
||||
<p>QtCurve is used as Qt style, its settings may be found <a href="//github.com/arcan1s/dotfiles/tree/master/qtcurve" title="GitHub">here</a>, window decorations are presented by QtCurve too. Cursor theme is <a href="//kde-look.org/content/show.php/Ecliz?content=110340" title="Cursor Homepage">ecliz-small</a>. Plasma theme is <a href="//kde-look.org/content/show.php/Volatile?content=128110" title="Theme Homepage">volatile</a>. Icon pack is <a href="//nitrux.in/" title="Nitrux Homepage">compass</a>. I use fonts which are based on Liberation.</p>
|
||||
|
||||
<p><b>Used widgets</b> (from left to right, top to bottom) are: <a href="//launchpad.net/plasma-widget-menubar" title="Widget Homepage">menubar</a>, <a href="//userbase.kde.org/Homerun" title="Widget Homepage">homerun</a> with transparent icon, <a href="//kde-apps.org/content/show.php?content=144808" title="Widget Homepage">icontask</a>, <a href="/projects/netctl-gui/" title="Widget Homepage">netctl</a>, default KDE tray, <a href="//agateau.com/projects/colibri/" title="Widget Homepage">colibri</a> for notifications, <a href="/projects/awesome-widgets" title="Widget Homepage">Awesome Widgets</a>.</p>
|
||||
|
||||
<p>As a bonus material <a href="//github.com/arcan1s/dotfiles/blob/master/themes/yakuake/My%20color.colorscheme" title="GitHub">here</a> is a settings for konsole bright colors.</p>
|
||||
<div class="thumbnails">
|
||||
{% assign scrdesc = "Zsh demonstation" %}
|
||||
{% assign scrname = "zshrc_demo" %}
|
||||
{% include prj_scr.html %}
|
||||
</div>
|
||||
|
||||
<h2><a href="#firefox" class="anchor" id="firefox"><span class="octicon octicon-link"></span></a>Firefox settings</h2>
|
||||
<p>I do not use a special settings, thus I get you a list of used add-ons:</p>
|
||||
<ul>
|
||||
<li><p><b>Adblock plus</b>.</p></li>
|
||||
<li><p><b>Add to search bar</b> is used for custom searchs.</p></li>
|
||||
<li><p><b>Auto Refresh</b> is used for auto update pages.</p></li>
|
||||
<li><p><b>Clone tab</b> adds "Clone tab" function.</p></li>
|
||||
<li><p><b>Close tab by double click</b>.</p></li>
|
||||
<li><p><b>New scrollbars</b> is used for customizing scrollbars, because original ones look horrible in Qt environment.</p></li>
|
||||
<li><p><b>NoScript</b> is used for I2P and Tor, for example.</p></li>
|
||||
<li><p><b>PrivateTab</b> adds private tab (not the window).</p></li>
|
||||
<li><p><b>Proxy Selector</b> adds an ability to use multiple proxies.</p></li>
|
||||
<li><p><b>QuickJava</b> is used with the same goal as NoScript.</p></li>
|
||||
<li><p><b>RSS icon in url bar</b>.</p></li>
|
||||
<li><p><b>Dictionaries for spellchecking</b> (eng/rus).</p></li>
|
||||
<li><p><b>Space Next</b>. If I tap a space at the bottom of a page, it will be perceived as pushing the "Next" button.</p></li>
|
||||
<li><p><b>Speed Dial</b> is a simple express panel.</p></li>
|
||||
<li><p><b>Status-4-Evar</b> is a normal status bar.</p></li>
|
||||
<li><p><b>tab delabelifier</b> minimizes inactive tabs.</p></li>
|
||||
<li><p><b>Tab Scope + Tab Scope Tweaker</b> is tab tooltip.</p></li>
|
||||
<li><p><b>accessKey</b> does not work now. But it is needed for easy navigation from keyboard (opera-like).</p></li>
|
||||
<li><p><b>FXOpera</b> is a normal minimalistic appearance.</p></li>
|
||||
</ul>
|
75
_posts/2014-05-07-my-desktop.md
Normal file
75
_posts/2014-05-07-my-desktop.md
Normal file
@ -0,0 +1,75 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
layout: paper
|
||||
hastr: true
|
||||
tags: настройка, linux, archlinux
|
||||
title: Apps which I use
|
||||
short: my-desktop
|
||||
---
|
||||
Here is a short paper devoted to the set of applications and extensions that I use everyday on my home computer.
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#apps" class="anchor" id="apps"><span class="octicon octicon-link"></span></a>Applications
|
||||
|
||||
* **Shell** is zshrc and nothing else. You may find a small description of my settings [here](/en/2014/01/14/about-zshrc/ "About zshrc paper"). It is stored [here](//raw.githubusercontent.com/arcan1s/dotfiles/master/zshrc "File") (or [here](//raw.githubusercontent.com/arcan1s/dotfiles/master/zshrc_server "File")).
|
||||
* **DE** - I use KDE as Desktop Environment. And that's why most of apps are qt-based. Some KDE settings are below.
|
||||
* **Graphic editors** - [gwenview](//kde.org/applications/graphics/gwenview/ "Gwenview Homepage") is used for viewing images, [kolourpaint](//kde.org/applications/graphics/kolourpaint/ "Kolourpaint Homepage") is used for simple editing pixel images, [gimp](//www.gimp.org/ "Gimp Homepage") (without plugins, since they are not needed for me) - for editing and [inkskape](//www.inkscape.org/ "Inkskape Homepage") is used as editor of vector graphics.
|
||||
* **Browser** - I use Firefox. Some Firefox settings are below. Chromium is used as additional browser, elinks is used as console browser.
|
||||
* **IM client** is [qutIM](//qutim.org "Qutim Homepage"). It is a cross-platform, multiprotocol and full featured client. [Kopete](//kde.org/applications/internet/kopete/ "Kopete Homepage"), which I used before it, crashes, does not work correctly and does not work normally with codepage. Also I don't use a console client since I use a tablet IM. And I use Skype for skype obviously.
|
||||
* **Mail client** is [kmail](//kde.org/applications/internet/kmail/ "Kmail Homepage"). It is a full featured client (and I use most of them), looks pretty and it is easy to use. If it will be DE-undepended it will be better.
|
||||
* **IRC client** is [konversation](//konversation.kde.org/ "Konversation Homepage"). It is a simple IRC client. Though as far as I remember qutIM also supports IRC protocol, I prefre to use a special IRC client.
|
||||
* **Torrent client** is [transmission](//www.transmissionbt.com/ "Transmission Homepage") with Qt5 interface (it has gtk interface too). It is also used for server but without GUI.
|
||||
* **Video player** is [mpv](//mpv.io/ "Mpv Homepage"), since mplayer died and mplayer2 was born deadborn. Graphical frontend are not needed.
|
||||
* **Audio player** is [qmmp](//qmmp.ylsoftware.com/ "Qmmp Homepage"). It is a good winamp-like player. Flick of the wrist you may make a handy interface for it (simpleui).
|
||||
* **Audio/video editors**: [kdenlive](//kde-apps.org/content/show.php?content=29024 "Kdenlive Homepage") is used as video editor, [soundkonverter](//kde-apps.org/content/show.php?content=29024) is used as audio editor, [easytag](//wiki.gnome.org/Apps/EasyTAG "Easytag Homepage") is used for editing audio tags (unfortunately, it is a gtk-based, but I didn't find a better tool for it). And command line and scripts written on bash are used too.
|
||||
* **Office**: [Kingsoft Office](//wps-community.org/ "KO Homepage") is used as alternative of Microsoft Office; it has no any feature, but it looks normally, it is qt-based and it is said that it has a good support for standart formats. (Linux version has an alfa stage.) [Kile](//kile.sourceforge.net/ "Kile Homepage") is used as LaTeX frontend. [Okular](//kde.org/applications/graphics/okular/ "Okular Homepage") is used as document viewer. And I use [GoldenDict](//goldendict.org/ "GoldenDict Homepage") as dictionary.
|
||||
* **Editors**: [kwrite](//www.kde.org/applications/utilities/kwrite/ "Kwrite Homepage") is used as a simple text editor, [kate](//www.kde.org/applications/utilities/kate/ "Kate Homepage") (and [cpp-helper](//zaufi.github.io/kate-cpp-helper-plugin.html "Plugin Homepage") plugin) is used as advanced text editor. And of course I use vim in console.
|
||||
* **Scientific soft**. Chemical visualizers are [vmd](//www.ks.uiuc.edu/Research/vmd/ "VMD Homepage"), [chimera](//www.cgl.ucsf.edu/chimera/ "Chimera Homepage") and [pymol](//pymol.org/ "Pymol Homepage"). Physics simulator is [step](//kde.org/applications/education/step/ "Step Homepage"). Calculator is [kalgebra](//kde.org/applications/education/kalgebra/ "Kalgebra Homepage") and console [ipython](//ipython.org/ "ipython Homepage"). [Qtiplot](//qtiplot.com/ "Qtiplot Homepage") is used for drawing graphs and data analysis (scidavis, which is its fork, unfortunately, is half-dead), [grace](//plasma-gate.weizmann.ac.il/Grace/ "Grace Homepage") is used for only drawing graphs. [Chemtool](//ruby.chemie.uni-freiburg.de/~martin/chemtool/chemtool.html "Chemtool Homepage") is used as alternative of ChemDraw.
|
||||
* **System applications**. File manager is [dolphin](//kde.org/applications/system/dolphin/ "Dolphin Homepage"), [doublecmd](//doublecmd.sourceforge.net/ "Doublecmd Homepage") is used as twin-panel manager. Terminal emulators are [yakuake](//yakuake.kde.org/ "Yakuake Homepage") and [urxvt](//software.schmorp.de/pkg/rxvt-unicode.html "Urxvt Homepage") (as windowed emulator). Archiver graphical interface is [ark](//kde.org/applications/utilities/ark/ "Ark Homepage").
|
||||
|
||||
## <a href="#kde" class="anchor" id="kde"><span class="octicon octicon-link"></span></a>KDE settings
|
||||
|
||||
<div class="thumbnails">
|
||||
{% assign scrdesc = "KDE screenshot" %}
|
||||
{% assign scrname = "kde" %}
|
||||
{% include prj_scr.html %}
|
||||
</div>
|
||||
|
||||
QtCurve is used as Qt style, its settings may be found [here](//github.com/arcan1s/dotfiles/tree/master/qtcurve "GitHub"), window decorations are presented by QtCurve too. Cursor theme is [ecliz-small](//kde-look.org/content/show.php/Ecliz?content=110340 "Cursor Homepage"). Plasma theme is [volatile](//kde-look.org/content/show.php/Volatile?content=128110 "Theme Homepage"). Icon pack is [compass](//nitrux.in/ "Nitrux Homepage"). I use fonts which are based on Liberation.
|
||||
|
||||
**Used widgets** (from left to right, top to bottom) are: [menubar](//launchpad.net/plasma-widget-menubar "Widget Homepage"), [homerun](//userbase.kde.org/Homerun "Widget Homepage") with transparent icon, [icontask](//kde-apps.org/content/show.php?content=144808 "Widget Homepage"), [netctl](/projects/netctl-gui/ "Widget Homepage"), default KDE tray, [colibri](//agateau.com/projects/colibri/ "Widget Homepage") for notifications, [Awesome Widgets](/projects/awesome-widgets "Widget Homepage").
|
||||
|
||||
As a bonus material [here](//github.com/arcan1s/dotfiles/blob/master/themes/yakuake/My%20color.colorscheme "GitHub") is a settings for konsole bright colors.
|
||||
|
||||
<div class="thumbnails">
|
||||
{% assign scrdesc = "Zsh demonstation" %}
|
||||
{% assign scrname = "zshrc_demo" %}
|
||||
{% include prj_scr.html %}
|
||||
</div>
|
||||
|
||||
## <a href="#firefox" class="anchor" id="firefox"><span class="octicon octicon-link"></span></a>Firefox settings
|
||||
|
||||
I do not use a special settings, thus I get you a list of used add-ons:
|
||||
|
||||
* **Adblock plus**.
|
||||
* **Add to search bar** is used for custom searchs.
|
||||
* **Auto Refresh** is used for auto update pages.
|
||||
* **Clone tab** adds "Clone tab" function.
|
||||
* **Close tab by double click**.
|
||||
* **New scrollbars** is used for customizing scrollbars, because original ones look horrible in Qt environment.
|
||||
* **NoScript** is used for I2P and Tor, for example.
|
||||
* **PrivateTab** adds private tab (not the window).
|
||||
* **Proxy Selector** adds an ability to use multiple proxies.
|
||||
* **QuickJava** is used with the same goal as NoScript.
|
||||
* **RSS icon in url bar**.
|
||||
* **Dictionaries for spellchecking** (eng/rus).
|
||||
* **Space Next**. If I tap a space at the bottom of a page, it will be perceived as pushing the "Next" button.
|
||||
* **Speed Dial** is a simple express panel.
|
||||
* **Status-4-Evar** is a normal status bar.
|
||||
* **tab delabelifier** minimizes inactive tabs.
|
||||
* **Tab Scope + Tab Scope Tweaker** is tab tooltip.
|
||||
* **accessKey** does not work now. But it is needed for easy navigation from keyboard (opera-like).
|
||||
* **FXOpera** is a normal minimalistic appearance.
|
||||
|
@ -1,41 +0,0 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
layout: paper
|
||||
hastr: true
|
||||
tags: linux, archlinux, building
|
||||
title: Disabling baloo, gentoo-way
|
||||
short: disabling-baloo
|
||||
description: Paper, which describes how to remove the dependency on baloo in your system.
|
||||
---
|
||||
<h2><a href="#disclaimer" class="anchor" id="disclaimer"><span class="octicon octicon-link"></span></a>Disclaimer</h2>
|
||||
<p>I do not use this patch, since I prefer less destructive methods. However, apparently all works fine, because there is no any claims. Since this patch was created in a few minutes, it removes all baloo's calls from source files (maybe I'll create a normal patch sometime).</p>
|
||||
|
||||
<p>On other hand, I highly recommend to people, who do not use baloo for some reason, disable it from the settings menu (it was added it 4.13.1) or read this <a href="//blog.andreascarpino.it/disabling-baloo-the-arch-way/" title="Scarpino's blog">article</a>.</p>
|
||||
|
||||
<h2><a href="#intro" class="anchor" id="intro"><span class="octicon octicon-link"></span></a>Introduction</h2>
|
||||
<p>In Archlinux <b>gwenview</b> and <b>kdepim</b> (and <b>baloo-widgets</b>) depend on baloo currently (2014-05-18). In the version 4.13.0 <b>kactivities</b> depends on baloo too (and I don't know why); but this dependency was not required explicitly, so it was enough just to rebuild the package by removing baloo from the list of dependencies.</p>
|
||||
|
||||
<h2><a href="#gwenview" class="anchor" id="gwenview"><span class="octicon octicon-link"></span></a>gwenview</h2>
|
||||
<p>It's all quite simple. Developers have taken care of the wishes of ordinary users and added a special flag:</p>
|
||||
|
||||
{% highlight cmake %}
|
||||
//Semantic info backend for Gwenview (Baloo/Fake/None)
|
||||
GWENVIEW_SEMANTICINFO_BACKEND:STRING=Baloo
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Thus, we add requred cmake flag to the build script:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
cmake ../gwenview-${pkgver} \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DKDE4_BUILD_TESTS=OFF \
|
||||
-DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DGWENVIEW_SEMANTICINFO_BACKEND=None
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#kdepim" class="anchor" id="kdepim"><span class="octicon octicon-link"></span></a>kdepim</h2>
|
||||
<p>Since everything was done in a hurry, I prefer to look at the source code using grep and to find all references to baloo. Needed strings (they are links to ballo in CMakeLists.txt, baloo's function calls and header declarations) were commented (I added some fake calls to the source code). You may find the patch <a href="//gist.github.com/arcan1s/b698bb586faef627b3bb" title="Gist">here</a> (4.13.3). Download the patch, apply it to the source code and recompile kdepim.</p>
|
||||
|
||||
<h2><a href="#packages" class="anchor" id="packages"><span class="octicon octicon-link"></span></a>Packages</h2>
|
||||
<p>All Archlinux packages for both architectures may be found in <a href="//wiki.archlinux.org/index.php/Unofficial_user_repositories#arcanisrepo" title="ArchWiki">my repository</a>.</p>
|
49
_posts/2014-05-18-disabling-baloo.md
Normal file
49
_posts/2014-05-18-disabling-baloo.md
Normal file
@ -0,0 +1,49 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
layout: paper
|
||||
hastr: true
|
||||
tags: linux, archlinux, building
|
||||
title: Disabling baloo, gentoo-way
|
||||
short: disabling-baloo
|
||||
---
|
||||
Paper, which describes how to remove the dependency on baloo in your system.
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#disclaimer" class="anchor" id="disclaimer"><span class="octicon octicon-link"></span></a>Disclaimer
|
||||
|
||||
I do not use this patch, since I prefer less destructive methods. However, apparently all works fine, because there is no any claims. Since this patch was created in a few minutes, it removes all baloo's calls from source files (maybe I'll create a normal patch sometime).
|
||||
|
||||
On other hand, I highly recommend to people, who do not use baloo for some reason, disable it from the settings menu (it was added it 4.13.1) or read this [article](//blog.andreascarpino.it/disabling-baloo-the-arch-way/ "Scarpino's blog").
|
||||
|
||||
## <a href="#intro" class="anchor" id="intro"><span class="octicon octicon-link"></span></a>Introduction
|
||||
|
||||
In Archlinux **gwenview** and **kdepim** (and **baloo-widgets**) depend on baloo currently (2014-05-18). In the version 4.13.0 **kactivities** depends on baloo too (and I don't know why); but this dependency was not required explicitly, so it was enough just to rebuild the package by removing baloo from the list of dependencies.
|
||||
|
||||
## <a href="#gwenview" class="anchor" id="gwenview"><span class="octicon octicon-link"></span></a>gwenview
|
||||
|
||||
It's all quite simple. Developers have taken care of the wishes of ordinary users and added a special flag:
|
||||
|
||||
```cmake
|
||||
//Semantic info backend for Gwenview (Baloo/Fake/None)
|
||||
GWENVIEW_SEMANTICINFO_BACKEND:STRING=Baloo
|
||||
```
|
||||
|
||||
Thus, we add requred cmake flag to the build script:
|
||||
|
||||
```bash
|
||||
cmake ../gwenview-${pkgver} \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DKDE4_BUILD_TESTS=OFF \
|
||||
-DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DGWENVIEW_SEMANTICINFO_BACKEND=None
|
||||
```
|
||||
|
||||
## <a href="#kdepim" class="anchor" id="kdepim"><span class="octicon octicon-link"></span></a>kdepim
|
||||
|
||||
Since everything was done in a hurry, I prefer to look at the source code using grep and to find all references to baloo. Needed strings (they are links to ballo in CMakeLists.txt, baloo's function calls and header declarations) were commented (I added some fake calls to the source code). You may find the patch [here](//gist.github.com/arcan1s/b698bb586faef627b3bb "Gist") (4.13.3). Download the patch, apply it to the source code and recompile kdepim.
|
||||
|
||||
## <a href="#packages" class="anchor" id="packages"><span class="octicon octicon-link"></span></a>Packages
|
||||
|
||||
All Archlinux packages for both architectures may be found in [my repository](//wiki.archlinux.org/index.php/Unofficial_user_repositories#arcanisrepo "ArchWiki").
|
@ -1,143 +0,0 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: linux, development
|
||||
title: Writting own Shell completions. Zsh
|
||||
short: writting-own-completions-p1
|
||||
description: <figure class="img"><img src="/resources/papers/zsh_completion.png" alt="bash_completion"></figure> Some basics of creating a completion files for own application are described in these articles.
|
||||
---
|
||||
<h2><a href="#preamble" class="anchor" id="preamble"><span class="octicon octicon-link"></span></a>Preamble</h2>
|
||||
<p>While developing <a href="/ru/projects/netctl-gui" title="Netctl-gui project page">one of my projects</a> I have wanted to add completion files. I have already tried to create these files, but I was too lazy to read some manuals about it.</p>
|
||||
|
||||
<h2><a href="#introduction" class="anchor" id="introduction"><span class="octicon octicon-link"></span></a>Introduction</h2>
|
||||
<p>There are some possible ways to create zsh completion file. In this article I will describe only one of them, which provides a lot of opportunities, but does not require a lot of costs (such as regular expressions).</p>
|
||||
|
||||
<p>Lets consider the example of my application, which has a part of help message that looks like this:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
netctl-gui [ -h | --help ] [ -e ESSID | --essid ESSID ] [ -с FILE | --config FILE ]
|
||||
[ -o PROFILE | --open PROFILE ] [ -t NUM | --tab NUM ] [ --set-opts OPTIONS ]
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Here is a flag list:</p>
|
||||
<ul>
|
||||
<li>flags <code>-h</code> and <code>--help</code> do not require any arguments;</li>
|
||||
<li>flags <code>-e</code> and <code>--essid</code> require a string argument without completion;</li>
|
||||
<li>flags <code>-c</code> and <code>--config</code> require a string argument, which is a file;</li>
|
||||
<li>flags <code>-o</code> and <code>--open</code> require a string argument, there is a completion from files in the specified directory;</li>
|
||||
<li>flags <code>-t</code> and <code>--tab</code> require a string argument, there is a completion from the specified array;</li>
|
||||
<li>flag <code>--set-opts</code> requires a string argument, there is a completion from the specified array comma separated;</li>
|
||||
</ul>
|
||||
|
||||
<h2><a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>The file pattern</h2>
|
||||
<p>It must be specified in the header that it is a completion file and application for which it will complete (may be string if this file provides completions for several applications):</p>
|
||||
|
||||
{% highlight bash %}
|
||||
#compdef netctl-gui
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Next there is flags, additional functions and variables declarations. It should be noted that all functions and variables, which will be used for completions, <b>should return arrays</b>. In my case this scheme looks like this (I left empty these functions in this chapter):</p>
|
||||
|
||||
{% highlight bash %}
|
||||
# variables
|
||||
_netctl_gui_arglist=()
|
||||
_netctl_gui_settings=()
|
||||
_netctl_gui_tabs=()
|
||||
_netctl_profiles() {}
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Then there are main functions, which will be called for completion of specific application. In my case this there is only one applications, so there is only one function:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
# work block
|
||||
_netctl-gui() {}
|
||||
{% endhighlight %}
|
||||
|
||||
<p>And finally <b>without isolation in a separate function</b> there is a small shamanism, which declares a dependence "application-function":</p>
|
||||
|
||||
{% highlight bash %}
|
||||
case "$service" in
|
||||
netctl-gui)
|
||||
_netctl-gui "$@" && return 0
|
||||
;;
|
||||
esac
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#flags" class="anchor" id="flags"><span class="octicon octicon-link"></span></a>Flags</h2>
|
||||
<p>As it was said above, there are some different ways to create these files. In particular they differ in the flag declaration and their further processing. In my case I will use <code>_arguments</code> command, which require a specific format of variables: <code>FLAG[description]:MESSAGE:ACTION</code>. The last two fields are not required and, as you will see below, are not needed in some cases. If you want to add two flags for an action (short and long format), then the format is a little bit complicated: <code>{(FLAG_2)FLAG_1,(FLAG_1)FLAG_2}[description]:MESSAGE:ACTION</code>. It should be noted that if you want to create completions for two flags but some flags have not a second format. you will should to add following line: <code>{FLAG,FLAG}[description]:MESSAGE:ACTION</code>. <code>MESSAGE</code> is a message which will be shown, <code>ACTION</code> is an action which will be performed after this flag. In this tutorial <code>ACTION</code> will be following: <code>->STATE</code>.</p>
|
||||
|
||||
<p>So, according to our requirements, flags declaration will be following:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl_gui_arglist=(
|
||||
{'(--help)-h','(-h)--help'}'[show help and exit]'
|
||||
{'(--essid)-e','(-e)--essid'}'[select ESSID]:type ESSID:->essid'
|
||||
{'(--config)-c','(-c)--config'}'[read configuration from this file]:select file:->files'
|
||||
{'(--open)-o','(-o)--open'}'[open profile]:select profile:->profiles'
|
||||
{'(--tab)-t','(-t)--tab'}'[open a tab with specified number]:select tab:->tab'
|
||||
{'--set-opts','--set-opts'}'[set options for this run, comma separated]:comma separated:->settings'
|
||||
)
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#variables" class="anchor" id="variables"><span class="octicon octicon-link"></span></a>Arrays of variables</h2>
|
||||
<p>In my case there are two static arrays (which will not be changed):</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl_gui_settings=(
|
||||
'CTRL_DIR'
|
||||
'CTRL_GROUP'
|
||||
)
|
||||
|
||||
_netctl_gui_tabs=(
|
||||
'1'
|
||||
'2'
|
||||
)
|
||||
{% endhighlight %}
|
||||
|
||||
<p>And there is a dynamic array, which should be generated each time. In my case it is a list of files in the specified directory (by the way it may be done by means of zsh):</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl_profiles() {
|
||||
print $(find /etc/netctl -maxdepth 1 -type f -printf "%f\n")
|
||||
}
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#body" class="anchor" id="body"><span class="octicon octicon-link"></span></a>Function</h2>
|
||||
<p>Remember, there was something about a state above? It is stored in the variable <code>$state</code> and in this function we will check what it is to choose the appropriate action. At the beginning of the function we should call <code>_arguments</code> with our flags.</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl-gui() {
|
||||
_arguments $_netctl_gui_arglist
|
||||
case "$state" in
|
||||
essid)
|
||||
# do not completion, wait for string
|
||||
;;
|
||||
files)
|
||||
# completion from files in this directory
|
||||
_files
|
||||
;;
|
||||
profiles)
|
||||
# completion from function
|
||||
# first variable is a description
|
||||
# second variable is a completion array
|
||||
_values 'profiles' $(_netctl_profiles)
|
||||
;;
|
||||
tab)
|
||||
# completion from array
|
||||
_values 'tab' $_netctl_gui_tabs
|
||||
;;
|
||||
settings)
|
||||
# completion from array
|
||||
# flag -s sets separator and enables multi-selection
|
||||
_values -s ',' 'settings' $_netctl_gui_settings
|
||||
;;
|
||||
esac
|
||||
}
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#conclusion" class="anchor" id="conclusion"><span class="octicon octicon-link"></span></a>Conclusion</h2>
|
||||
<p>File should be places to <code>/usr/share/zsh/site-functions/</code> with any name (it is recommended to set prefix to <code>_</code>). You may found the example <a href="//raw.githubusercontent.com/arcan1s/netctl-gui/master/sources/gui/zsh-completions" title="File" type="text/plain">in my repository</a>.</p>
|
||||
|
||||
<p>The additional information may be found in <a href="//github.com/zsh-users/zsh-completions" title="GitHub">zsh-completions</a> repository. For example there is this <a href="//github.com/zsh-users/zsh-completions/blob/master/zsh-completions-howto.org" title="Tutorial">How-To</a>. And also there are a lot of examples.</p>
|
151
_posts/2014-07-17-writting-own-completions-p1.md
Normal file
151
_posts/2014-07-17-writting-own-completions-p1.md
Normal file
@ -0,0 +1,151 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: linux, development
|
||||
title: Writting own Shell completions. Zsh
|
||||
short: writting-own-completions-p1
|
||||
---
|
||||
<figure class="img"></figure> Some basics of creating a completion files for own application are described in these articles.
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#preamble" class="anchor" id="preamble"><span class="octicon octicon-link"></span></a>Preamble
|
||||
|
||||
While developing [one of my projects](/ru/projects/netctl-gui "Netctl-gui project page") I have wanted to add completion files. I have already tried to create these files, but I was too lazy to read some manuals about it.
|
||||
|
||||
## <a href="#introduction" class="anchor" id="introduction"><span class="octicon octicon-link"></span></a>Introduction
|
||||
|
||||
There are some possible ways to create zsh completion file. In this article I will describe only one of them, which provides a lot of opportunities, but does not require a lot of costs (such as regular expressions).
|
||||
|
||||
Lets consider the example of my application, which has a part of help message that looks like this:
|
||||
|
||||
```bash
|
||||
netctl-gui [ -h | --help ] [ -e ESSID | --essid ESSID ] [ -с FILE | --config FILE ]
|
||||
[ -o PROFILE | --open PROFILE ] [ -t NUM | --tab NUM ] [ --set-opts OPTIONS ]
|
||||
```
|
||||
|
||||
Here is a flag list:
|
||||
* flags `-h` and `--help` do not require any arguments;
|
||||
* flags `-e` and `--essid` require a string argument without completion;
|
||||
* flags `-c` and `--config` require a string argument, which is a file;
|
||||
* flags `-o` and `--open` require a string argument, there is a completion from files in the specified directory;
|
||||
* flags `-t` and `--tab` require a string argument, there is a completion from the specified array;
|
||||
* flag `--set-opts` requires a string argument, there is a completion from the specified array comma separated;
|
||||
|
||||
## <a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>The file pattern
|
||||
|
||||
It must be specified in the header that it is a completion file and application for which it will complete (may be string if this file provides completions for several applications):
|
||||
|
||||
```bash
|
||||
#compdef netctl-gui
|
||||
```
|
||||
|
||||
Next there is flags, additional functions and variables declarations. It should be noted that all functions and variables, which will be used for completions, **should return arrays**. In my case this scheme looks like this (I left empty these functions in this chapter):
|
||||
|
||||
```bash
|
||||
# variables
|
||||
_netctl_gui_arglist=()
|
||||
_netctl_gui_settings=()
|
||||
_netctl_gui_tabs=()
|
||||
_netctl_profiles() {}
|
||||
```
|
||||
|
||||
Then there are main functions, which will be called for completion of specific application. In my case this there is only one applications, so there is only one function:
|
||||
|
||||
```bash
|
||||
# work block
|
||||
_netctl-gui() {}
|
||||
```
|
||||
|
||||
And finally **without isolation in a separate function** there is a small shamanism, which declares a dependence "application-function":
|
||||
|
||||
```bash
|
||||
case "$service" in
|
||||
netctl-gui)
|
||||
_netctl-gui "$@" && return 0
|
||||
;;
|
||||
esac
|
||||
```
|
||||
|
||||
## <a href="#flags" class="anchor" id="flags"><span class="octicon octicon-link"></span></a>Flags
|
||||
|
||||
As it was said above, there are some different ways to create these files. In particular they differ in the flag declaration and their further processing. In my case I will use `_arguments` command, which require a specific format of variables: `FLAG[description]:MESSAGE:ACTION`. The last two fields are not required and, as you will see below, are not needed in some cases. If you want to add two flags for an action (short and long format), then the format is a little bit complicated: `{(FLAG_2)FLAG_1,(FLAG_1)FLAG_2}[description]:MESSAGE:ACTION`. It should be noted that if you want to create completions for two flags but some flags have not a second format. you will should to add following line: `{FLAG,FLAG}[description]:MESSAGE:ACTION`. `MESSAGE` is a message which will be shown, `ACTION` is an action which will be performed after this flag. In this tutorial `ACTION` will be following: `->STATE`.
|
||||
|
||||
So, according to our requirements, flags declaration will be following:
|
||||
|
||||
```bash
|
||||
_netctl_gui_arglist=(
|
||||
{'(--help)-h','(-h)--help'}'[show help and exit]'
|
||||
{'(--essid)-e','(-e)--essid'}'[select ESSID]:type ESSID:->essid'
|
||||
{'(--config)-c','(-c)--config'}'[read configuration from this file]:select file:->files'
|
||||
{'(--open)-o','(-o)--open'}'[open profile]:select profile:->profiles'
|
||||
{'(--tab)-t','(-t)--tab'}'[open a tab with specified number]:select tab:->tab'
|
||||
{'--set-opts','--set-opts'}'[set options for this run, comma separated]:comma separated:->settings'
|
||||
)
|
||||
```
|
||||
|
||||
## <a href="#variables" class="anchor" id="variables"><span class="octicon octicon-link"></span></a>Arrays of variables
|
||||
|
||||
In my case there are two static arrays (which will not be changed):
|
||||
|
||||
```bash
|
||||
_netctl_gui_settings=(
|
||||
'CTRL_DIR'
|
||||
'CTRL_GROUP'
|
||||
)
|
||||
|
||||
_netctl_gui_tabs=(
|
||||
'1'
|
||||
'2'
|
||||
)
|
||||
```
|
||||
|
||||
And there is a dynamic array, which should be generated each time. In my case it is a list of files in the specified directory (by the way it may be done by means of zsh):
|
||||
|
||||
```bash
|
||||
_netctl_profiles() {
|
||||
print $(find /etc/netctl -maxdepth 1 -type f -printf "%f\n")
|
||||
}
|
||||
```
|
||||
|
||||
## <a href="#body" class="anchor" id="body"><span class="octicon octicon-link"></span></a>Function
|
||||
|
||||
Remember, there was something about a state above? It is stored in the variable `$state` and in this function we will check what it is to choose the appropriate action. At the beginning of the function we should call `_arguments` with our flags.
|
||||
|
||||
```bash
|
||||
_netctl-gui() {
|
||||
_arguments $_netctl_gui_arglist
|
||||
case "$state" in
|
||||
essid)
|
||||
# do not completion, wait for string
|
||||
;;
|
||||
files)
|
||||
# completion from files in this directory
|
||||
_files
|
||||
;;
|
||||
profiles)
|
||||
# completion from function
|
||||
# first variable is a description
|
||||
# second variable is a completion array
|
||||
_values 'profiles' $(_netctl_profiles)
|
||||
;;
|
||||
tab)
|
||||
# completion from array
|
||||
_values 'tab' $_netctl_gui_tabs
|
||||
;;
|
||||
settings)
|
||||
# completion from array
|
||||
# flag -s sets separator and enables multi-selection
|
||||
_values -s ',' 'settings' $_netctl_gui_settings
|
||||
;;
|
||||
esac
|
||||
}
|
||||
```
|
||||
|
||||
## <a href="#conclusion" class="anchor" id="conclusion"><span class="octicon octicon-link"></span></a>Conclusion
|
||||
|
||||
File should be places to `/usr/share/zsh/site-functions/` with any name (it is recommended to set prefix to `_`). You may found the example [in my repository](//raw.githubusercontent.com/arcan1s/netctl-gui/master/sources/gui/zsh-completions "File").
|
||||
|
||||
The additional information may be found in [zsh-completions](//github.com/zsh-users/zsh-completions "GitHub") repository. For example there is this [How-To](//github.com/zsh-users/zsh-completions/blob/master/zsh-completions-howto.org "Tutorial"). And also there are a lot of examples.
|
@ -1,136 +0,0 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: linux, development
|
||||
title: Writting own Shell completions. Bash
|
||||
short: writting-own-completions-p2
|
||||
description: <figure class="img"><img src="/resources/papers/bash_completion.png" alt="bash_completion"></figure> Some basics of creating a completion files for own application are described in these articles.
|
||||
---
|
||||
<h2><a href="#preamble" class="anchor" id="preamble"><span class="octicon octicon-link"></span></a>Preamble</h2>
|
||||
<p>While developing <a href="/ru/projects/netctl-gui" title="Netctl-gui project page">one of my projects</a> I have wanted to add completion files. I have already tried to create these files, but I was too lazy to read some manuals about it.</p>
|
||||
|
||||
<h2><a href="#introduction" class="anchor" id="introduction"><span class="octicon octicon-link"></span></a>Introduction</h2>
|
||||
<p>Bash, <a href="/ru/2014/07/17/writting-own-completions-p1" title="Zsh completions paper">unlike zsh</a>, demands some dirty workarounds for completions. Cursory have Googled, I have not found a more or less normal tutorials, so it is based on the available <code>pacman</code> completion files in my system.</p>
|
||||
|
||||
<p>Lets consider the example of the same my application. I remind you that a part of help message is as follows:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
netctl-gui [ -h | --help ] [ -e ESSID | --essid ESSID ] [ -с FILE | --config FILE ]
|
||||
[ -o PROFILE | --open PROFILE ] [ -t NUM | --tab NUM ] [ --set-opts OPTIONS ]
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Here is a flag list:</p>
|
||||
<ul>
|
||||
<li>flags <code>-h</code> and <code>--help</code> do not require any arguments;</li>
|
||||
<li>flags <code>-e</code> and <code>--essid</code> require a string argument without completion;</li>
|
||||
<li>flags <code>-c</code> and <code>--config</code> require a string argument, which is a file;</li>
|
||||
<li>flags <code>-o</code> and <code>--open</code> require a string argument, there is a completion from files in the specified directory;</li>
|
||||
<li>flags <code>-t</code> and <code>--tab</code> require a string argument, there is a completion from the specified array;</li>
|
||||
<li>flag <code>--set-opts</code> requires a string argument, there is a completion from the specified array comma separated;</li>
|
||||
</ul>
|
||||
|
||||
<h2><a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>The file pattern</h2>
|
||||
<p>Here <b>all</b> variables must return an array. And there no specific formats. First we declare the flags and then we describe all other variables. As I am not going to describe the functions in more detail below I remind you that <code>_netctl_profiles()</code> should be generated each time:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
# variables
|
||||
_netctl_gui_arglist=()
|
||||
_netctl_gui_settings=()
|
||||
_netctl_gui_tabs=()
|
||||
_netctl_profiles() {}
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Then there are main functions, which will be called for completion of specific application. In my case this there is only one applications, so there is only one function:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
# work block
|
||||
_netctl-gui() {}
|
||||
{% endhighlight %}
|
||||
|
||||
<p>And finally again <b>without isolation in a separate function</b> we create a dependence "function-application":</p>
|
||||
|
||||
{% highlight bash %}
|
||||
complete -F _netctl_gui netctl-gui
|
||||
{% endhighlight %}
|
||||
|
||||
|
||||
<h2><a href="#flags" class="anchor" id="flags"><span class="octicon octicon-link"></span></a>Flags</h2>
|
||||
<p>As it was said above there is no specific format, so all available flags declare by array:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl_gui_arglist=(
|
||||
'-h'
|
||||
'--help'
|
||||
'-e'
|
||||
'--essid'
|
||||
'-c'
|
||||
'--config'
|
||||
'-o'
|
||||
'--open'
|
||||
'-t'
|
||||
'--tab'
|
||||
'--set-opts'
|
||||
)
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#variables" class="anchor" id="variables"><span class="octicon octicon-link"></span></a>Arrays of variables</h2>
|
||||
<p>I just give a function that looked like this in zsh:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl_profiles() {
|
||||
print $(find /etc/netctl -maxdepth 1 -type f -printf "%f\n")
|
||||
}
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Bash does not allow to do so, so this function should be a little changed:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl_profiles() {
|
||||
echo $(find /etc/netctl -maxdepth 1 -type f -printf "%f\n")
|
||||
}
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#body" class="anchor" id="body"><span class="octicon octicon-link"></span></a>Function</h2>
|
||||
<p>The variable <code>COMPREPLY</code> responds for completion in Bash. To keep track of the current state function <code>_get_comp_words_by_ref</code> must be called with parameters <code>cur</code> (current flag) and <code>prev</code> (previous flag, it is the state). Also some point for case are needed (variables <code>want*</code>). Function <code>compgen</code> is used for completion generation. A list of words is given after flag <code>-W</code>. (Also there is flag <code>-F</code> which requires a function as argument, but it gives warning for me.) The last argument is a current string to which you want to generate completion.</p>
|
||||
|
||||
<p>So, here is our function:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl_gui() {
|
||||
COMPREPLY=()
|
||||
wantfiles='-@(c|-config)'
|
||||
wantprofiles='-@(o|-open|s|-select)'
|
||||
wantsettings='-@(-set-opts)'
|
||||
|
||||
wanttabs='-@(t|-tab)'
|
||||
_get_comp_words_by_ref cur prev
|
||||
|
||||
if [[ $prev = $wantstring ]]; then
|
||||
# do not completion, wait for string
|
||||
COMPREPLY=()
|
||||
elif [[ $prev = $wantfiles ]]; then
|
||||
# completion from files in this directory
|
||||
_filedir
|
||||
elif [[ $prev = $wantprofiles ]]; then
|
||||
# completion from function
|
||||
COMPREPLY=($(compgen -W '${_netctl_profiles[@]}' -- "$cur"))
|
||||
elif [[ $prev = $wanttabs ]]; then
|
||||
# completion from array
|
||||
COMPREPLY=($(compgen -W '${_netctl_gui_tabs[@]}' -- "$cur"))
|
||||
elif [[ $prev = $wantsettings ]]; then
|
||||
# completion from array
|
||||
# flag -S add a comma after completion, but does not enable multi-selection =(
|
||||
COMPREPLY=($(compgen -S ',' -W '${_netctl_gui_settings[@]}' -- "$cur"))
|
||||
else
|
||||
# show all available flags
|
||||
COMPREPLY=($(compgen -W '${_netctl_gui_arglist[@]}' -- "$cur"))
|
||||
fi
|
||||
|
||||
true
|
||||
}
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#conclusion" class="anchor" id="conclusion"><span class="octicon octicon-link"></span></a>Conclusion</h2>
|
||||
<p>File should be places to <code>/usr/share/bash-completion/completions/</code> with any name. You may found the example <a href="//raw.githubusercontent.com/arcan1s/netctl-gui/master/sources/gui/bash-completions" title="File" type="text/plain">in my repository</a>.</p>
|
143
_posts/2014-07-17-writting-own-completions-p2.md
Normal file
143
_posts/2014-07-17-writting-own-completions-p2.md
Normal file
@ -0,0 +1,143 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: linux, development
|
||||
title: Writting own Shell completions. Bash
|
||||
short: writting-own-completions-p2
|
||||
---
|
||||
<figure class="img"></figure> Some basics of creating a completion files for own application are described in these articles.
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#preamble" class="anchor" id="preamble"><span class="octicon octicon-link"></span></a>Preamble
|
||||
|
||||
While developing [one of my projects](/ru/projects/netctl-gui "Netctl-gui project page") I have wanted to add completion files. I have already tried to create these files, but I was too lazy to read some manuals about it.
|
||||
|
||||
## <a href="#introduction" class="anchor" id="introduction"><span class="octicon octicon-link"></span></a>Introduction
|
||||
|
||||
Bash, [unlike zsh](/ru/2014/07/17/writting-own-completions-p1 "Zsh completions paper"), demands some dirty workarounds for completions. Cursory have Googled, I have not found a more or less normal tutorials, so it is based on the available `pacman` completion files in my system.
|
||||
|
||||
Lets consider the example of the same my application. I remind you that a part of help message is as follows:
|
||||
|
||||
```bash
|
||||
netctl-gui [ -h | --help ] [ -e ESSID | --essid ESSID ] [ -с FILE | --config FILE ]
|
||||
[ -o PROFILE | --open PROFILE ] [ -t NUM | --tab NUM ] [ --set-opts OPTIONS ]
|
||||
```
|
||||
|
||||
Here is a flag list:
|
||||
* flags `-h` and `--help` do not require any arguments;
|
||||
* flags `-e` and `--essid` require a string argument without completion;
|
||||
* flags `-c` and `--config` require a string argument, which is a file;
|
||||
* flags `-o` and `--open` require a string argument, there is a completion from files in the specified directory;
|
||||
* flags `-t` and `--tab` require a string argument, there is a completion from the specified array;
|
||||
* flag `--set-opts` requires a string argument, there is a completion from the specified array comma separated;
|
||||
|
||||
## <a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>The file pattern
|
||||
|
||||
Here **all** variables must return an array. And there no specific formats. First we declare the flags and then we describe all other variables. As I am not going to describe the functions in more detail below I remind you that `_netctl_profiles()` should be generated each time:
|
||||
|
||||
```bash
|
||||
# variables
|
||||
_netctl_gui_arglist=()
|
||||
_netctl_gui_settings=()
|
||||
_netctl_gui_tabs=()
|
||||
_netctl_profiles() {}
|
||||
```
|
||||
|
||||
Then there are main functions, which will be called for completion of specific application. In my case this there is only one applications, so there is only one function:
|
||||
|
||||
```bash
|
||||
# work block
|
||||
_netctl-gui() {}
|
||||
```
|
||||
|
||||
And finally again **without isolation in a separate function** we create a dependence "function-application":
|
||||
|
||||
```bash
|
||||
complete -F _netctl_gui netctl-gui
|
||||
```
|
||||
|
||||
## <a href="#flags" class="anchor" id="flags"><span class="octicon octicon-link"></span></a>Flags
|
||||
|
||||
As it was said above there is no specific format, so all available flags declare by array:
|
||||
|
||||
```bash
|
||||
_netctl_gui_arglist=(
|
||||
'-h'
|
||||
'--help'
|
||||
'-e'
|
||||
'--essid'
|
||||
'-c'
|
||||
'--config'
|
||||
'-o'
|
||||
'--open'
|
||||
'-t'
|
||||
'--tab'
|
||||
'--set-opts'
|
||||
)
|
||||
```
|
||||
|
||||
## <a href="#variables" class="anchor" id="variables"><span class="octicon octicon-link"></span></a>Arrays of variables
|
||||
|
||||
I just give a function that looked like this in zsh:
|
||||
|
||||
```bash
|
||||
_netctl_profiles() {
|
||||
print $(find /etc/netctl -maxdepth 1 -type f -printf "%f\n")
|
||||
}
|
||||
```
|
||||
|
||||
Bash does not allow to do so, so this function should be a little changed:
|
||||
|
||||
```bash
|
||||
_netctl_profiles() {
|
||||
echo $(find /etc/netctl -maxdepth 1 -type f -printf "%f\n")
|
||||
}
|
||||
```
|
||||
|
||||
## <a href="#body" class="anchor" id="body"><span class="octicon octicon-link"></span></a>Function
|
||||
|
||||
The variable `COMPREPLY` responds for completion in Bash. To keep track of the current state function `_get_comp_words_by_ref` must be called with parameters `cur` (current flag) and `prev` (previous flag, it is the state). Also some point for case are needed (variables `want*`). Function `compgen` is used for completion generation. A list of words is given after flag `-W`. (Also there is flag `-F` which requires a function as argument, but it gives warning for me.) The last argument is a current string to which you want to generate completion.
|
||||
|
||||
So, here is our function:
|
||||
|
||||
```bash
|
||||
_netctl_gui() {
|
||||
COMPREPLY=()
|
||||
wantfiles='-@(c|-config)'
|
||||
wantprofiles='-@(o|-open|s|-select)'
|
||||
wantsettings='-@(-set-opts)'
|
||||
|
||||
wanttabs='-@(t|-tab)'
|
||||
_get_comp_words_by_ref cur prev
|
||||
|
||||
if [[ $prev = $wantstring ]]; then
|
||||
# do not completion, wait for string
|
||||
COMPREPLY=()
|
||||
elif [[ $prev = $wantfiles ]]; then
|
||||
# completion from files in this directory
|
||||
_filedir
|
||||
elif [[ $prev = $wantprofiles ]]; then
|
||||
# completion from function
|
||||
COMPREPLY=($(compgen -W '${_netctl_profiles[@]}' -- "$cur"))
|
||||
elif [[ $prev = $wanttabs ]]; then
|
||||
# completion from array
|
||||
COMPREPLY=($(compgen -W '${_netctl_gui_tabs[@]}' -- "$cur"))
|
||||
elif [[ $prev = $wantsettings ]]; then
|
||||
# completion from array
|
||||
# flag -S add a comma after completion, but does not enable multi-selection =(
|
||||
COMPREPLY=($(compgen -S ',' -W '${_netctl_gui_settings[@]}' -- "$cur"))
|
||||
else
|
||||
# show all available flags
|
||||
COMPREPLY=($(compgen -W '${_netctl_gui_arglist[@]}' -- "$cur"))
|
||||
fi
|
||||
|
||||
true
|
||||
}
|
||||
```
|
||||
|
||||
## <a href="#conclusion" class="anchor" id="conclusion"><span class="octicon octicon-link"></span></a>Conclusion
|
||||
|
||||
File should be places to `/usr/share/bash-completion/completions/` with any name. You may found the example [in my repository](//raw.githubusercontent.com/arcan1s/netctl-gui/master/sources/gui/bash-completions "File").
|
@ -1,38 +0,0 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: awesome-widgets, pytextmonitor
|
||||
title: Migration Awesome Widgets (ex-PyTextMonitor) to version 2.0
|
||||
short: migration-to-v2
|
||||
description: <figure class="img"><img src="/resources/papers/broken-computer.jpg" alt="broken-computer"></figure>Some significant changes occur in the version 2.0 (really, I didn't do anything which can break your desktop!) and user API was rewritten. This paper should help to migrate from older PyTextMonitor versions (<1.11.0) to new one (>2.0).
|
||||
---
|
||||
<h2><a href="#new" class="anchor" id="new"><span class="octicon octicon-link"></span></a>New features</h2>
|
||||
<p>Firstly, a series of new features, including:</p>
|
||||
|
||||
<ul>
|
||||
<li>New widget - <b>Desktop panel</b>. It shows desktop list and select the active one. It can switch to the selected desktop by mouse clicking. Also it may set selected panels hidden.</li>
|
||||
<li>New tags - <code>hddfreemb</code>, <code>hddfreegb</code>, <code>memusedmb</code>, <code>memusedgb</code>, <code>memfreemb</code>, <code>memfreegb</code>, <code>swapfreemb</code>, <code>swapfreegb</code>. And there are new tags related to new features - <code>desktop</code>, <code>ndesktop</code>, <code>tdesktops</code>.</li>
|
||||
<li>New graphical tooltip - battery. It is twin colour (the colour depends on AC status).</li>
|
||||
</ul>
|
||||
|
||||
<h2><a href="#changes" class="anchor" id="changes"><span class="octicon octicon-link"></span></a>Significant changes</h2>
|
||||
<p>Secondly, there are some changes because of which the old settings <b>will not</b> more work. They are:</p>
|
||||
|
||||
<ul>
|
||||
<li>The main widget was rewritten to <code>С++</code>, so the project was renamed to <b>Awesome Widgets</b>, and the main widget was done to <b>Awesome Widget</b></li>
|
||||
<li>Configuration of battery and AC files <b>was moved to DataEngine</b>.</li>
|
||||
<li><b>The labels was removed</b>. Now the widget is a single label. You may set up text in the special browser.</li>
|
||||
<li>According to removal of the label, tooltip <b>should be configured separately</b>.</li>
|
||||
<li>Align of text now can be configured only by using HTML tags.</li>
|
||||
<li>According to fields combining several tags were renamed:
|
||||
<ul>
|
||||
<li><code>custom</code> (time) -> <code>ctime</code></li>
|
||||
<li><code>custom</code> (uptime) -> <code>cuptime</code></li>
|
||||
<li><code>time</code> (player) -> <code>duration</code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<p>On any issues related to the migration, feel free to leave a comment here.</p>
|
36
_posts/2014-09-04-migration-to-v2.md
Normal file
36
_posts/2014-09-04-migration-to-v2.md
Normal file
@ -0,0 +1,36 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: awesome-widgets, pytextmonitor
|
||||
title: Migration Awesome Widgets (ex-PyTextMonitor) to version 2.0
|
||||
short: migration-to-v2
|
||||
---
|
||||
<figure class="img"></figure>Some significant changes occur in the version 2.0 (really, I didn't do anything which can break your desktop!) and user API was rewritten. This paper should help to migrate from older PyTextMonitor versions (<1.11.0) to new one (>2.0).
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#new" class="anchor" id="new"><span class="octicon octicon-link"></span></a>New features
|
||||
|
||||
Firstly, a series of new features, including:
|
||||
|
||||
* New widget - **Desktop panel**. It shows desktop list and select the active one. It can switch to the selected desktop by mouse clicking. Also it may set selected panels hidden.
|
||||
* New tags - `hddfreemb`, `hddfreegb`, `memusedmb`, `memusedgb`, `memfreemb`, `memfreegb`, `swapfreemb`, `swapfreegb`. And there are new tags related to new features - `desktop`, `ndesktop`, `tdesktops`.
|
||||
* New graphical tooltip - battery. It is twin colour (the colour depends on AC status).
|
||||
|
||||
## <a href="#changes" class="anchor" id="changes"><span class="octicon octicon-link"></span></a>Significant changes
|
||||
|
||||
Secondly, there are some changes because of which the old settings **will not** more work. They are:
|
||||
|
||||
* The main widget was rewritten to `С++`, so the project was renamed to **Awesome Widgets**, and the main widget was done to **Awesome Widget**
|
||||
* Configuration of battery and AC files **was moved to DataEngine**.
|
||||
* **The labels was removed**. Now the widget is a single label. You may set up text in the special browser.
|
||||
* According to removal of the label, tooltip **should be configured separately**.
|
||||
* Align of text now can be configured only by using HTML tags.
|
||||
* According to fields combining several tags were renamed:
|
||||
* `custom` (time) -> `ctime`
|
||||
* `custom` (uptime) -> `cuptime`
|
||||
* `time` (player) -> `duration`
|
||||
|
||||
On any issues related to the migration, feel free to leave a comment here.
|
@ -1,173 +0,0 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: linux, systemd, ecryptfs
|
||||
title: How to encrypt home directory. For dummies
|
||||
short: ecnryption-home-directory
|
||||
description: <figure class="img"><img src="/resources/papers/single-door.jpg" alt="single-door"></figure>This paper is about encryption home directory using ecryptfs and automount settins using systemd and key on flash card.
|
||||
---
|
||||
<h2><a href="#preparation" class="anchor" id="preparation"><span class="octicon octicon-link"></span></a>Step 0: Preparation</h2>
|
||||
<ol>
|
||||
<li>Logout as user.</li>
|
||||
<li>Login as root on tty. The following actions should be done as root.</li>
|
||||
<li>Move your home directory and create empty directory (<code>s/$USER/user name/</code>):
|
||||
|
||||
{% highlight bash %}
|
||||
mv /home/{$USER,$USER-org}
|
||||
mkdir /home/$USER
|
||||
chmod 700 /home/$USER
|
||||
chown $USER:users /home/$USER
|
||||
{% endhighlight %}
|
||||
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<h2><a href="#step1" class="anchor" id="step1"><span class="octicon octicon-link"></span></a>Step 1: Encryption</h2>
|
||||
<p>The widespread solution in the Internet is to use automatic utilities to do it. However in our case they are not suitable, since we need to import key / password signature, which is not possible in this case.</p>
|
||||
|
||||
<p>The encryption can be done by the following command (lol):</p>
|
||||
|
||||
{% highlight bash %}
|
||||
mount -t ecryptfs /home/$USER /home/$USER
|
||||
{% endhighlight %}
|
||||
|
||||
<p>While process it asks some question (I suggest to do first mounting in the interactive mode). The answers may be like following (see the comments),
|
||||
please note that if you change something, it will be changed in some lines below too:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
# key or certificate. The second one is more reliable while you don't lose it %)
|
||||
Select key type to use for newly created files:
|
||||
1) passphrase
|
||||
2) openssl
|
||||
Selection: 1
|
||||
# password
|
||||
Passphrase:
|
||||
# cipher, select default
|
||||
Select cipher:
|
||||
1) aes: blocksize = 16; min keysize = 16; max keysize = 32
|
||||
2) blowfish: blocksize = 8; min keysize = 16; max keysize = 56
|
||||
3) des3_ede: blocksize = 8; min keysize = 24; max keysize = 24
|
||||
4) twofish: blocksize = 16; min keysize = 16; max keysize = 32
|
||||
5) cast6: blocksize = 16; min keysize = 16; max keysize = 32
|
||||
6) cast5: blocksize = 8; min keysize = 5; max keysize = 16
|
||||
Selection [aes]: 1
|
||||
# key size, select default
|
||||
Select key bytes:
|
||||
1) 16
|
||||
2) 32
|
||||
3) 24
|
||||
Selection [16]: 1
|
||||
# enable reading/writing to the non-encrypted files
|
||||
Enable plaintext passthrough (y/n) [n]: n
|
||||
# enable filename encryption
|
||||
Enable filename encryption (y/n) [n]: y
|
||||
Filename Encryption Key (FNEK) Signature [XXXXX]:
|
||||
# toolongdontread
|
||||
Attempting to mount with the following options:
|
||||
ecryptfs_unlink_sigs
|
||||
ecryptfs_fnek_sig=XXXXX
|
||||
ecryptfs_key_bytes=16
|
||||
ecryptfs_cipher=aes
|
||||
ecryptfs_sig=XXXXX
|
||||
WARNING: Based on the contents of [/root/.ecryptfs/sig-cache.txt],
|
||||
it looks like you have never mounted with this key
|
||||
before. This could mean that you have typed your
|
||||
passphrase wrong.
|
||||
|
||||
# accept, quit
|
||||
Would you like to proceed with the mount (yes/no)? : yes
|
||||
Would you like to append sig [XXXXX] to
|
||||
[/root/.ecryptfs/sig-cache.txt]
|
||||
in order to avoid this warning in the future (yes/no)? : yes
|
||||
Successfully appended new sig to user sig cache file
|
||||
Mounted eCryptfs
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Then copy files from home directory to encrypted one:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
cp -a /home/$USER-org/. /home/$USER
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#step2" class="anchor" id="step2"><span class="octicon octicon-link"></span></a>Step 2: systemd automounting</h2>
|
||||
<p>Create file on flash card (I've used microSD) with the following text (you should insert your password):</p>
|
||||
|
||||
{% highlight bash %}
|
||||
passphrase_passwd=someverystronguniqpassword
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Add card automount (mount point is <code>/mnt/key</code>) to <code>fstab</code> with option <code>ro</code>, for example:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
UUID=dc3ecb41-bc40-400a-b6bf-65c5beeb01d7 /mnt/key ext2 ro,defaults 0 0
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Let's configure home directory mounting. The mount options can be found in the following output:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
mount | grep ecryptfs
|
||||
{% endhighlight %}
|
||||
|
||||
<p>I should note that there are not all options there, you need add <code>key</code>, <code>no_sig_cache</code>, <code>ecryptfs_passthrough</code> too. Thus systemd mount-unit should be like the following (if you are systemd-hater you can write the own daemon, because it doesn't work over <code>fstab</code> without modification (see below)).</p>
|
||||
|
||||
{% highlight bash %}
|
||||
# cat /etc/systemd/system/home-$USER.mount
|
||||
[Unit]
|
||||
Before=local-fs.target
|
||||
After=mnt-key.mount
|
||||
|
||||
[Mount]
|
||||
What=/home/$USER
|
||||
Where=/home/$USER
|
||||
Type=ecryptfs
|
||||
Options=rw,nosuid,nodev,relatime,key=passphrase:passphrase_passwd_file=/mnt/key/keyfile,no_sig_cache,ecryptfs_fnek_sig=XXXXX,ecryptfs_sig=XXXXX,ecryptfs_cipher=aes,ecryptfs_key_bytes=16,ecryptfs_passthrough=n,ecryptfs_unlink_sigs
|
||||
|
||||
[Install]
|
||||
WantedBy=local-fs.target
|
||||
{% endhighlight %}
|
||||
|
||||
<p><code>XXXXX</code> should be replaced to signature from options with which directory are currently mounting. Also you need to insert user name and edit path to file with password (and unit name) if it is needed. Autoload:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
systemctl enable home-$USER.mount
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Here is a service to unmount flash card when it will be unneeded:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
# cat /etc/systemd/system/umount-key.service
|
||||
[Unit]
|
||||
Description=Unmount key card
|
||||
Before=local-fs.target
|
||||
After=home-arcanis.mount
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/umount /mnt/key
|
||||
|
||||
[Install]
|
||||
WantedBy=local-fs.target
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Enable:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
systemctl enable umount-key.service
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Reboot. Remove backups if all is ok. If not then you did a mistake, resurrect system from emergency mode.</p>
|
||||
|
||||
<h2><a href="#whynotfstab" class="anchor" id="whynotfstab"><span class="octicon octicon-link"></span></a>Why not fstab?</h2>
|
||||
<p>In my case I could not to make flash mounting before home decryption. Thus I saw emergency mode on load in which I should just continue loading. There are two solutions in the Internet:</p>
|
||||
|
||||
<ul>
|
||||
<li>Create entry with noauto option and then mount using the special command in <code>rc.local</code>.</li>
|
||||
<li>Create entry with nofail option and then remount all partitions in <code>rc.local</code>.</li>
|
||||
</ul>
|
||||
|
||||
<p>In my opinion both of them are workarounds too much.</p>
|
||||
|
||||
<h2><a href="#whynotpam" class="anchor" id="whynotpam"><span class="octicon octicon-link"></span></a>Why not pam?</h2>
|
||||
<p>Other solution is to mount using pam entry. In my case I have authentication without password on fingerprint so it doesn't work for me.</p>
|
175
_posts/2014-12-12-encryption-home-directory.md
Normal file
175
_posts/2014-12-12-encryption-home-directory.md
Normal file
@ -0,0 +1,175 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: linux, systemd, ecryptfs
|
||||
title: How to encrypt home directory. For dummies
|
||||
short: ecnryption-home-directory
|
||||
---
|
||||
<figure class="img"></figure>This paper is about encryption home directory using ecryptfs and automount settins using systemd and key on flash card.
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#preparation" class="anchor" id="preparation"><span class="octicon octicon-link"></span></a>Step 0: Preparation
|
||||
|
||||
1. Logout as user.
|
||||
2. Login as root on tty. The following actions should be done as root.
|
||||
3. Move your home directory and create empty directory (`s/$USER/user name/`):
|
||||
|
||||
```bash
|
||||
mv /home/{$USER,$USER-org}
|
||||
mkdir /home/$USER
|
||||
chmod 700 /home/$USER
|
||||
chown $USER:users /home/$USER
|
||||
```
|
||||
|
||||
## <a href="#step1" class="anchor" id="step1"><span class="octicon octicon-link"></span></a>Step 1: Encryption
|
||||
|
||||
The widespread solution in the Internet is to use automatic utilities to do it. However in our case they are not suitable, since we need to import key / password signature, which is not possible in this case.
|
||||
|
||||
The encryption can be done by the following command (lol):
|
||||
|
||||
```bash
|
||||
mount -t ecryptfs /home/$USER /home/$USER
|
||||
```
|
||||
|
||||
While process it asks some question (I suggest to do first mounting in the interactive mode). The answers may be like following (see the comments),
|
||||
please note that if you change something, it will be changed in some lines below too:
|
||||
|
||||
```bash
|
||||
# key or certificate. The second one is more reliable while you don't lose it %)
|
||||
Select key type to use for newly created files:
|
||||
1) passphrase
|
||||
2) openssl
|
||||
Selection: 1
|
||||
# password
|
||||
Passphrase:
|
||||
# cipher, select default
|
||||
Select cipher:
|
||||
1) aes: blocksize = 16; min keysize = 16; max keysize = 32
|
||||
2) blowfish: blocksize = 8; min keysize = 16; max keysize = 56
|
||||
3) des3_ede: blocksize = 8; min keysize = 24; max keysize = 24
|
||||
4) twofish: blocksize = 16; min keysize = 16; max keysize = 32
|
||||
5) cast6: blocksize = 16; min keysize = 16; max keysize = 32
|
||||
6) cast5: blocksize = 8; min keysize = 5; max keysize = 16
|
||||
Selection [aes]: 1
|
||||
# key size, select default
|
||||
Select key bytes:
|
||||
1) 16
|
||||
2) 32
|
||||
3) 24
|
||||
Selection [16]: 1
|
||||
# enable reading/writing to the non-encrypted files
|
||||
Enable plaintext passthrough (y/n) [n]: n
|
||||
# enable filename encryption
|
||||
Enable filename encryption (y/n) [n]: y
|
||||
Filename Encryption Key (FNEK) Signature [XXXXX]:
|
||||
# toolongdontread
|
||||
Attempting to mount with the following options:
|
||||
ecryptfs_unlink_sigs
|
||||
ecryptfs_fnek_sig=XXXXX
|
||||
ecryptfs_key_bytes=16
|
||||
ecryptfs_cipher=aes
|
||||
ecryptfs_sig=XXXXX
|
||||
WARNING: Based on the contents of [/root/.ecryptfs/sig-cache.txt],
|
||||
it looks like you have never mounted with this key
|
||||
before. This could mean that you have typed your
|
||||
passphrase wrong.
|
||||
|
||||
# accept, quit
|
||||
Would you like to proceed with the mount (yes/no)? : yes
|
||||
Would you like to append sig [XXXXX] to
|
||||
[/root/.ecryptfs/sig-cache.txt]
|
||||
in order to avoid this warning in the future (yes/no)? : yes
|
||||
Successfully appended new sig to user sig cache file
|
||||
Mounted eCryptfs
|
||||
```
|
||||
|
||||
Then copy files from home directory to encrypted one:
|
||||
|
||||
```bash
|
||||
cp -a /home/$USER-org/. /home/$USER
|
||||
```
|
||||
|
||||
## <a href="#step2" class="anchor" id="step2"><span class="octicon octicon-link"></span></a>Step 2: systemd automounting
|
||||
|
||||
Create file on flash card (I've used microSD) with the following text (you should insert your password):
|
||||
|
||||
```bash
|
||||
passphrase_passwd=someverystronguniqpassword
|
||||
```
|
||||
|
||||
Add card automount (mount point is `/mnt/key`) to `fstab` with option `ro`, for example:
|
||||
|
||||
```bash
|
||||
UUID=dc3ecb41-bc40-400a-b6bf-65c5beeb01d7 /mnt/key ext2 ro,defaults 0 0
|
||||
```
|
||||
|
||||
Let's configure home directory mounting. The mount options can be found in the following output:
|
||||
|
||||
```bash
|
||||
mount | grep ecryptfs
|
||||
```
|
||||
|
||||
I should note that there are not all options there, you need add `key`, `no_sig_cache`, `ecryptfs_passthrough` too. Thus systemd mount-unit should be like the following (if you are systemd-hater you can write the own daemon, because it doesn't work over `fstab` without modification (see below)).
|
||||
|
||||
```bash
|
||||
# cat /etc/systemd/system/home-$USER.mount
|
||||
[Unit]
|
||||
Before=local-fs.target
|
||||
After=mnt-key.mount
|
||||
|
||||
[Mount]
|
||||
What=/home/$USER
|
||||
Where=/home/$USER
|
||||
Type=ecryptfs
|
||||
Options=rw,nosuid,nodev,relatime,key=passphrase:passphrase_passwd_file=/mnt/key/keyfile,no_sig_cache,ecryptfs_fnek_sig=XXXXX,ecryptfs_sig=XXXXX,ecryptfs_cipher=aes,ecryptfs_key_bytes=16,ecryptfs_passthrough=n,ecryptfs_unlink_sigs
|
||||
|
||||
[Install]
|
||||
WantedBy=local-fs.target
|
||||
```
|
||||
|
||||
`XXXXX` should be replaced to signature from options with which directory are currently mounting. Also you need to insert user name and edit path to file with password (and unit name) if it is needed. Autoload:
|
||||
|
||||
```bash
|
||||
systemctl enable home-$USER.mount
|
||||
```
|
||||
|
||||
Here is a service to unmount flash card when it will be unneeded:
|
||||
|
||||
```bash
|
||||
# cat /etc/systemd/system/umount-key.service
|
||||
[Unit]
|
||||
Description=Unmount key card
|
||||
Before=local-fs.target
|
||||
After=home-arcanis.mount
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/umount /mnt/key
|
||||
|
||||
[Install]
|
||||
WantedBy=local-fs.target
|
||||
```
|
||||
|
||||
Enable:
|
||||
|
||||
```bash
|
||||
systemctl enable umount-key.service
|
||||
```
|
||||
|
||||
Reboot. Remove backups if all is ok. If not then you did a mistake, resurrect system from emergency mode.
|
||||
|
||||
## <a href="#whynotfstab" class="anchor" id="whynotfstab"><span class="octicon octicon-link"></span></a>Why not fstab?
|
||||
|
||||
In my case I could not to make flash mounting before home decryption. Thus I saw emergency mode on load in which I should just continue loading. There are two solutions in the Internet:
|
||||
|
||||
* Create entry with noauto option and then mount using the special command in `rc.local`.
|
||||
* Create entry with nofail option and then remount all partitions in `rc.local`.
|
||||
|
||||
In my opinion both of them are workarounds too much.
|
||||
|
||||
## <a href="#whynotpam" class="anchor" id="whynotpam"><span class="octicon octicon-link"></span></a>Why not pam?
|
||||
|
||||
Other solution is to mount using pam entry. In my case I have authentication without password on fingerprint so it doesn't work for me.
|
@ -1,327 +0,0 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: awesome-widgets, pytextmonitor
|
||||
title: Awesome Widgets - bells and whistles
|
||||
short: aw-v21-bells-and-whistles
|
||||
description: The paper deals with settings of a custom scripts and graphical bars in the new version of Awesome Widgets (2.1).
|
||||
---
|
||||
<h2><a href="#intro" class="anchor" id="intro"><span class="octicon octicon-link"></span></a>Introduction</h2>
|
||||
<p>For a start it is highly recommended copy file <code>$HOME/.kde4/share/config/extsysmon.conf</code> after widget update before you open widget settings, because old and new script settings are incompatible. Also I should note that these features can be configured from graphical interface, but I will describe how it can be done by simply editing the desktop file.</p>
|
||||
|
||||
<h2><a href="#general" class="anchor" id="general"><span class="octicon octicon-link"></span></a>General</h2>
|
||||
<p>Items are stored in the two directories: <code>/usr/share/awesomewidgets/%TYPE%/</code> and <code>$HOME/.local/share/awesomewidgets/%TYPE%/</code> (path may be differ in depend from your distro). Settings in the home directory have a higher priority that global ones.</p>
|
||||
|
||||
<h2><a href="#bars" class="anchor" id="bars"><span class="octicon octicon-link"></span></a>Bars</h2>
|
||||
<p>Directory is <code>desktops</code>, configuration files have the following fields:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Field</th>
|
||||
<th>Required</th>
|
||||
<th>Value</th>
|
||||
<th>Default</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<td>yes</td>
|
||||
<td>bar name. It should be as <code>barN</code> and should be unique</td>
|
||||
<td>none</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Comment</th>
|
||||
<td>no</td>
|
||||
<td>comment</td>
|
||||
<td>empty</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Value</th>
|
||||
<td>yes</td>
|
||||
<td>bar value. The following tags are available <code>cpu*</code>, <code>gpu</code>, <code>mem</code>, <code>swap</code>, <code>hdd*</code>, <code>bat</code></td>
|
||||
<td>cpu</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-ActiveColor</th>
|
||||
<td>yes</td>
|
||||
<td>active part fill in format <code>R,G,B,A</code></td>
|
||||
<td>0,0,0,130</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-InactiveColor</th>
|
||||
<td>yes</td>
|
||||
<td>inactive part fill in format <code>R,G,B,A</code></td>
|
||||
<td>255,255,255,130</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Type</th>
|
||||
<td>yes</td>
|
||||
<td>bar type. The following types are supported <code>Horizontal</code>, <code>Vertical</code>, <code>Circle</code>, <code>Graph</code></td>
|
||||
<td>Horizontal</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Direction</th>
|
||||
<td>yes</td>
|
||||
<td>the fill direction. The following variants are supported <code>LeftToRight</code>, <code>RightToLeft</code></td>
|
||||
<td>LeftToRight</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Height</th>
|
||||
<td>yes</td>
|
||||
<td>height, pixels</td>
|
||||
<td>100</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Width</th>
|
||||
<td>yes</td>
|
||||
<td>width, pixels</td>
|
||||
<td>100</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Number</th>
|
||||
<td>yes</td>
|
||||
<td>unique number which will be associated with the bar. The property has been introduced to provide compatibility with others items. Should be the same as number in Name is</td>
|
||||
<td>number from Name</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2><a href="#quotes" class="anchor" id="quotes"><span class="octicon octicon-link"></span></a>Quotes</h2>
|
||||
<p>Directory is <code>quotes</code>, configuration files have the following fields:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Field</th>
|
||||
<th>Required</th>
|
||||
<th>Value</th>
|
||||
<th>Default</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<td>yes</td>
|
||||
<td>quotes name</td>
|
||||
<td>none</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Comment</th>
|
||||
<td>no</td>
|
||||
<td>comment</td>
|
||||
<td>empty</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Ticker</th>
|
||||
<td>yes</td>
|
||||
<td>ticker from Yahoo! Finance system</td>
|
||||
<td>EURUSD=X</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Active</th>
|
||||
<td>no</td>
|
||||
<td>whether or not the quotes is active</td>
|
||||
<td>true</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Interval</th>
|
||||
<td>no</td>
|
||||
<td>update interval in standard widget intervals</td>
|
||||
<td>1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Number</th>
|
||||
<td>yes</td>
|
||||
<td>unique number which will be associated with the script</td>
|
||||
<td>random number which is less than 1000</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2><a href="#scripts" class="anchor" id="scripts"><span class="octicon octicon-link"></span></a>Scripts</h2>
|
||||
<p>Directory is <code>scripts</code>, configuration files have the following fields:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Field</th>
|
||||
<th>Required</th>
|
||||
<th>Value</th>
|
||||
<th>Default</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<td>yes</td>
|
||||
<td>script name</td>
|
||||
<td>none</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Comment</th>
|
||||
<td>no</td>
|
||||
<td>comment</td>
|
||||
<td>empty</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Exec</th>
|
||||
<td>yes</td>
|
||||
<td>path to executable file</td>
|
||||
<td>/usr/bin/true</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Prefix</th>
|
||||
<td>no</td>
|
||||
<td>prefix to executable file. Usually it's not required, but in other you may want to specify interpreter for example</td>
|
||||
<td></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Active</th>
|
||||
<td>no</td>
|
||||
<td>whether or not the script is active</td>
|
||||
<td>true</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Redirect</th>
|
||||
<td>no</td>
|
||||
<td>stream redirection. The following variants are available <code>stderr2stdout</code>, <code>nothing</code>, <code>stdout2stderr</code>, <code>swap</code>. stderr will be available, if you run application in the debug mode</td>
|
||||
<td>nothing</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Interval</th>
|
||||
<td>no</td>
|
||||
<td>update interval in standard widget intervals</td>
|
||||
<td>1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Number</th>
|
||||
<td>yes</td>
|
||||
<td>unique number which will be associated with the script</td>
|
||||
<td>random number which is less than 1000</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Filters</th>
|
||||
<td>no</td>
|
||||
<td>comma separated filters from <code>awesomewidgets-extscripts-filters.json</code></td>
|
||||
<td></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2><a href="#upgrade" class="anchor" id="upgrade"><span class="octicon octicon-link"></span></a>Upgrade</h2>
|
||||
<p>Directory is <code>upgrade</code>, configuration files have the following fields:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Field</th>
|
||||
<th>Required</th>
|
||||
<th>Value</th>
|
||||
<th>Default</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<td>yes</td>
|
||||
<td>upgrade name</td>
|
||||
<td>none</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Comment</th>
|
||||
<td>no</td>
|
||||
<td>comment</td>
|
||||
<td>empty</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Exec</th>
|
||||
<td>yes</td>
|
||||
<td>path to executable file</td>
|
||||
<td>/usr/bin/true</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Filter</th>
|
||||
<td>no</td>
|
||||
<td>the regexp which will be applied to command output. If set <code>X-AW-Null</code> will be ignored</td>
|
||||
<td></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Active</th>
|
||||
<td>no</td>
|
||||
<td>whether or not the upgrade script is active</td>
|
||||
<td>true</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Null</th>
|
||||
<td>no</td>
|
||||
<td>the number of lines which should be skipped in output</td>
|
||||
<td>0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Interval</th>
|
||||
<td>no</td>
|
||||
<td>update interval in standard widget intervals</td>
|
||||
<td>1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Number</th>
|
||||
<td>yes</td>
|
||||
<td>unique number which will be associated with the upgrade script</td>
|
||||
<td>random number which is less than 1000</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2><a href="#weather" class="anchor" id="weather"><span class="octicon octicon-link"></span></a>Weather</h2>
|
||||
<p>The weather uses data and API from <a href="//openweathermap.org/" title="OpenWeatherMap site">OpenWeatherMap</a>. Directory is <code>weather</code>, configuration files have the following fields:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Field</th>
|
||||
<th>Required</th>
|
||||
<th>Value</th>
|
||||
<th>Default</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<td>yes</td>
|
||||
<td>weather name</td>
|
||||
<td>none</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Comment</th>
|
||||
<td>no</td>
|
||||
<td>comment</td>
|
||||
<td>empty</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-City</th>
|
||||
<td>yes</td>
|
||||
<td>city</td>
|
||||
<td>London</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Country</th>
|
||||
<td>yes</td>
|
||||
<td>two-letter country code</td>
|
||||
<td>uk</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Image</th>
|
||||
<td>no</td>
|
||||
<td>use images as weather icon or text.</td>
|
||||
<td>false</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-TS</th>
|
||||
<td>yes</td>
|
||||
<td>time to which weather should be. <code>0</code> is a current weather, <code>1</code> - weather 3 hours later, etc</td>
|
||||
<td>0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Active</th>
|
||||
<td>no</td>
|
||||
<td>whether or not the monitor is active</td>
|
||||
<td>true</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Interval</th>
|
||||
<td>no</td>
|
||||
<td>update interval in standard widget intervals</td>
|
||||
<td>1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Number</th>
|
||||
<td>yes</td>
|
||||
<td>unique number which will be associated with the upgrade weather</td>
|
||||
<td>random number which is less than 1000</td>
|
||||
</tr>
|
||||
</table>
|
97
_posts/2014-12-19-aw-v21-bells-and-whistles.md
Normal file
97
_posts/2014-12-19-aw-v21-bells-and-whistles.md
Normal file
@ -0,0 +1,97 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: awesome-widgets, pytextmonitor
|
||||
title: Awesome Widgets - bells and whistles
|
||||
short: aw-v21-bells-and-whistles
|
||||
---
|
||||
The paper deals with settings of a custom scripts and graphical bars in the new version of Awesome Widgets (2.1).
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#intro" class="anchor" id="intro"><span class="octicon octicon-link"></span></a>Introduction
|
||||
|
||||
For a start it is highly recommended copy file `$HOME/.kde4/share/config/extsysmon.conf` after widget update before you open widget settings, because old and new script settings are incompatible. Also I should note that these features can be configured from graphical interface, but I will describe how it can be done by simply editing the desktop file.
|
||||
|
||||
## <a href="#general" class="anchor" id="general"><span class="octicon octicon-link"></span></a>General
|
||||
|
||||
Items are stored in the two directories: `/usr/share/awesomewidgets/%TYPE%/` and `$HOME/.local/share/awesomewidgets/%TYPE%/` (path may be differ in depend from your distro). Settings in the home directory have a higher priority that global ones.
|
||||
|
||||
## <a href="#bars" class="anchor" id="bars"><span class="octicon octicon-link"></span></a>Bars
|
||||
|
||||
Directory is `desktops`, configuration files have the following fields:
|
||||
|
||||
| Field | Required | Value | Default |
|
||||
| -------------------|----------|----------------------------------|------------|
|
||||
| Name | yes | bar name. It should be as `barN` and should be unique | none |
|
||||
| Comment | no | comment | empty |
|
||||
| X-AW-Value | yes | bar value. The following tags are available `cpu*`, `gpu`, `mem`, `swap`, `hdd*`, `bat` | cpu |
|
||||
| X-AW-ActiveColor | yes | active part fill in format `R,G,B,A` | 0,0,0,130 |
|
||||
| X-AW-InactiveColor | yes | inactive part fill in format `R,G,B,A` | 255,255,255,130 |
|
||||
| X-AW-Type | yes | bar type. The following types are supported `Horizontal`, `Vertical`, `Circle`, `Graph` | Horizontal |
|
||||
| X-AW-Direction | yes | the fill direction. The following variants are supported `LeftToRight`, `RightToLeft` | LeftToRight |
|
||||
| X-AW-Height | yes | height, pixels | 100 |
|
||||
| X-AW-Width | yes | width, pixels | 100 |
|
||||
| X-AW-Number | yes | unique number which will be associated with the bar. The property has been introduced to provide compatibility with others items. Should be the same as number in Name is | number from Name |
|
||||
|
||||
## <a href="#quotes" class="anchor" id="quotes"><span class="octicon octicon-link"></span></a>Quotes
|
||||
|
||||
Directory is `quotes`, configuration files have the following fields:
|
||||
|
||||
| Field | Required | Value | Default |
|
||||
|-------|----------|-------|---------|
|
||||
| Name | yes | quotes name | none |
|
||||
| Comment | no | comment | empty |
|
||||
| X-AW-Ticker | yes | ticker from Yahoo! Finance system | EURUSD=X |
|
||||
| X-AW-Active | no | whether or not the quotes is active | true |
|
||||
| X-AW-Interval | no | update interval in standard widget intervals | 1 |
|
||||
| X-AW-Number | yes | unique number which will be associated with the script | random number which is less than 1000 |
|
||||
|
||||
## <a href="#scripts" class="anchor" id="scripts"><span class="octicon octicon-link"></span></a>Scripts
|
||||
|
||||
Directory is `scripts`, configuration files have the following fields:
|
||||
|
||||
| Field | Required | Value | Default |
|
||||
|-------|----------|-------|---------|
|
||||
| Name | yes | script name | none |
|
||||
| Comment | no | comment | empty |
|
||||
| Exec | yes | path to executable file | /usr/bin/true |
|
||||
| X-AW-Prefix | no | prefix to executable file. Usually it's not required, but in other you may want to specify interpreter for example |
|
||||
| X-AW-Active | no | whether or not the script is active | true |
|
||||
| X-AW-Redirect | no | stream redirection. The following variants are available `stderr2stdout`, `nothing`, `stdout2stderr`, `swap`. stderr will be available, if you run application in the debug mode | nothing |
|
||||
| X-AW-Interval | no | update interval in standard widget intervals | 1 |
|
||||
| X-AW-Number | yes | unique number which will be associated with the script | random number which is less than 1000 |
|
||||
| X-AW-Filters | no | comma separated filters from `awesomewidgets-extscripts-filters.json` |
|
||||
|
||||
## <a href="#upgrade" class="anchor" id="upgrade"><span class="octicon octicon-link"></span></a>Upgrade
|
||||
|
||||
Directory is `upgrade`, configuration files have the following fields:
|
||||
|
||||
| Field | Required | Value | Default |
|
||||
|-------|----------|-------|---------|
|
||||
| Name | yes | upgrade name | none |
|
||||
| Comment | no | comment | empty |
|
||||
| Exec | yes | path to executable file | /usr/bin/true |
|
||||
| X-AW-Filter | no | the regexp which will be applied to command output. If set `X-AW-Null` will be ignored |
|
||||
| X-AW-Active | no | whether or not the upgrade script is active | true |
|
||||
| X-AW-Null | no | the number of lines which should be skipped in output | 0 |
|
||||
| X-AW-Interval | no | update interval in standard widget intervals | 1 |
|
||||
| X-AW-Number | yes | unique number which will be associated with the upgrade script | random number which is less than 1000 |
|
||||
|
||||
## <a href="#weather" class="anchor" id="weather"><span class="octicon octicon-link"></span></a>Weather
|
||||
|
||||
The weather uses data and API from [OpenWeatherMap](//openweathermap.org/ "OpenWeatherMap site"). Directory is `weather`, configuration files have the following fields:
|
||||
|
||||
| Field | Required | Value | Default |
|
||||
|-------|----------|-------|---------|
|
||||
| Name | yes | weather name | none |
|
||||
| Comment | no | comment | empty |
|
||||
| X-AW-City | yes | city | London |
|
||||
| X-AW-Country | yes | two-letter country code | uk |
|
||||
| X-AW-Image | no | use images as weather icon or text. | false |
|
||||
| X-AW-TS | yes | time to which weather should be. `0` is a current weather, `1` - weather 3 hours later, etc | 0 |
|
||||
| X-AW-Active | no | whether or not the monitor is active | true |
|
||||
| X-AW-Interval | no | update interval in standard widget intervals | 1 |
|
||||
| X-AW-Number | yes | unique number which will be associated with the upgrade weather | random number which is less than 1000 |
|
@ -1,161 +0,0 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: development, c++, cmake
|
||||
title: Add cppcheck and clang-format for a cmake project
|
||||
short: cppcheck-and-clang-format
|
||||
description: A small How-To which describes how to add automatic code style checking and static analyser to a project on <code>C++</code> which uses <code>cmake</code> as a build system.
|
||||
---
|
||||
<h2><a href="#project" class="anchor" id="project"><span class="octicon octicon-link"></span></a>Project</h2>
|
||||
<p>The project has the following structure:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
sources/
|
||||
|- CMakeLists.txt
|
||||
|- 3rdparty/
|
||||
|- first_component/
|
||||
|- second_component/
|
||||
{% endhighlight %}
|
||||
|
||||
<p><b>3rdparty</b> is a directory which contains additional libraries and which should be excluded from checking (<code>PROJECT_TRDPARTY_DIR</code> cmake variable is used to indicate path to this directory). Also let's assume that we have additional files (e.g. <code>*.qml</code>) in addition to common source files (<code>*.cpp</code>, <code>*.h</code>).</p>
|
||||
|
||||
<p>In addition the described below commands may be inserted to pre-commit hook; it allows us to troll colleagues which will be able to commit nothing till they read <code>CONTRIBUTING.md</code>.</p>
|
||||
|
||||
<h2><a href="#cppcheck" class="anchor" id="cppcheck"><span class="octicon octicon-link"></span></a>cppcheck</h2>
|
||||
<p>As far as there are no good (out-of-box) static analysers in open source we will use it. Knowledgeable people say that <a href="//cppcheck.sourceforge.net/" title="cppcheck site">cppcheck</a> in case of good configuration it is better than the any alternative, but its configuration is the same that the new project creation. <code>cppcheck</code> shows obvious errors and recommend to fix them.</p>
|
||||
|
||||
<h3><a href="#cppcheck-run" class="anchor" id="cppcheck-run"><span class="octicon octicon-link"></span></a>Example of run</h3>
|
||||
<p>Here it is:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
cppcheck --enable=warning,performance,portability,information,missingInclude --std=c++11 --library=qt.cfg --template="[{severity}][{id}] {message} {callstack} (On {file}:{line})" --verbose --quiet path/to/source/files/or/directory
|
||||
{% endhighlight %}
|
||||
|
||||
<ul>
|
||||
<li><code>--enable</code> says which notifications should be enabled. I've disabled <code>style</code> (we will use <code>clang-format</code> to do it), <code>unusedFunction</code> which shows false-positive for some methods.</li>
|
||||
<li><code>--std</code> says which standard should be used.</li>
|
||||
<li><code>--library=qt.cfg</code> a configuration file, which describes how to check files. The developers recommend to read the following <a href="//cppcheck.sourceforge.net/manual.pdf" title="cppcheck manual">manual</a>. I've used the ready template from <code>/usr/share/cppcheck/cfg/</code>.</li>
|
||||
<li><code>--template</code> is notification template.</li>
|
||||
<li><code>---verbose --quiet</code> are two "conflicting" options. The first one enables more verbose messages, the second one disables progress reports.</li>
|
||||
</ul>
|
||||
|
||||
<h3><a href="#cppcheck-cmake" class="anchor" id="cppcheck-cmake"><span class="octicon octicon-link"></span></a>cmake integration</h3>
|
||||
<p><code>cppcheck.cmake</code> file in the project root:</p>
|
||||
|
||||
{% highlight cmake %}
|
||||
# additional target to perform cppcheck run, requires cppcheck
|
||||
|
||||
# get all project files
|
||||
# HACK this workaround is required to avoid qml files checking ^_^
|
||||
file(GLOB_RECURSE ALL_SOURCE_FILES *.cpp *.h)
|
||||
foreach (SOURCE_FILE ${ALL_SOURCE_FILES})
|
||||
string(FIND ${SOURCE_FILE} ${PROJECT_TRDPARTY_DIR} PROJECT_TRDPARTY_DIR_FOUND)
|
||||
if (NOT ${PROJECT_TRDPARTY_DIR_FOUND} EQUAL -1)
|
||||
list(REMOVE_ITEM ALL_SOURCE_FILES ${SOURCE_FILE})
|
||||
endif ()
|
||||
endforeach ()
|
||||
|
||||
add_custom_target(
|
||||
cppcheck
|
||||
COMMAND /usr/bin/cppcheck
|
||||
--enable=warning,performance,portability,information,missingInclude
|
||||
--std=c++11
|
||||
--library=qt.cfg
|
||||
--template="[{severity}][{id}] {message} {callstack} \(On {file}:{line}\)"
|
||||
--verbose
|
||||
--quiet
|
||||
${ALL_SOURCE_FILES}
|
||||
)
|
||||
{% endhighlight %}
|
||||
|
||||
<p><code>cppcheck</code> may work with directories recursive, but I need to skip qml-files checking in my example, because this <code>cppcheck</code> will segfault on some of them. To do it source files search is used followed by the ejection of unnecessary files.</p>
|
||||
|
||||
<p>Include to the project (<code>CMakeLists.txt</code>)...</p>
|
||||
|
||||
{% highlight cmake %}
|
||||
include(cppcheck.cmake)
|
||||
{% endhighlight %}
|
||||
|
||||
<p>...and run:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
cmake
|
||||
make cppcheck
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Then edit files to avoid warnings in the future.</p>
|
||||
|
||||
<h3><a href="#cppcheck-adds" class="anchor" id="cppcheck-adds"><span class="octicon octicon-link"></span></a>Adds</h3>
|
||||
<ul>
|
||||
<li>You may add own directories to includes search, using <code>-I dir</code> option</li>
|
||||
<li>You may drop files and/or directories from checking by using <code>-i path/to/file/or/directory</code> option.</li>
|
||||
</ul>
|
||||
|
||||
<h2><a href="#clang" class="anchor" id="clang"><span class="octicon octicon-link"></span></a>clang-format</h2>
|
||||
<p><a href="//clang.llvm.org/docs/ClangFormat.html" title="clang-format site">clang-format</a> is used to automatic code style checking and correction. <a href="//astyle.sourceforge.net/" title="astyle site">astyle</a>, which has a very modest capabilities, and <a href="//uncrustify.sourceforge.net/" title="uncrustify site">uncrustify</a>, which on the contrary has too many options, should be mentioned from analogues.</p>
|
||||
|
||||
<h3><a href="#clang-run" class="anchor" id="clang-run"><span class="octicon octicon-link"></span></a>Example of run</h3>
|
||||
{% highlight bash %}
|
||||
clang-format -i -style=LLVM /path/to/source/files
|
||||
{% endhighlight %}
|
||||
|
||||
<p>(Unfortunately it <b>could not</b> work with directories recursive.)</p>
|
||||
|
||||
<ul>
|
||||
<li><code>-i</code> enables files auto replace (otherwise the result will be printed to stdout).</li>
|
||||
<li><code>-style</code> is a style preset selection or from file (<code>file</code>), see below.</li>
|
||||
</ul>
|
||||
|
||||
<h3><a href="#clang-cmake" class="anchor" id="clang-cmake"><span class="octicon octicon-link"></span></a>cmake integration</h3>
|
||||
<p><code>clang-format.cmake</code> file in the project root:</p>
|
||||
|
||||
{% highlight cmake %}
|
||||
# additional target to perform clang-format run, requires clang-format
|
||||
|
||||
# get all project files
|
||||
file(GLOB_RECURSE ALL_SOURCE_FILES *.cpp *.h)
|
||||
foreach (SOURCE_FILE ${ALL_SOURCE_FILES})
|
||||
string(FIND ${SOURCE_FILE} ${PROJECT_TRDPARTY_DIR} PROJECT_TRDPARTY_DIR_FOUND)
|
||||
if (NOT ${PROJECT_TRDPARTY_DIR_FOUND} EQUAL -1)
|
||||
list(REMOVE_ITEM ALL_SOURCE_FILES ${SOURCE_FILE})
|
||||
endif ()
|
||||
endforeach ()
|
||||
|
||||
add_custom_target(
|
||||
clangformat
|
||||
COMMAND /usr/bin/clang-format
|
||||
-style=LLVM
|
||||
-i
|
||||
${ALL_SOURCE_FILES}
|
||||
)
|
||||
{% endhighlight %}
|
||||
|
||||
<p>There is the same method to get source files list as for <code>cppcheck</code>, because <code>clang-format</code> doesn't support recursive directory search.</p>
|
||||
|
||||
<p>Include to the project (<code>CMakeLists.txt</code>)...</p>
|
||||
|
||||
{% highlight cmake %}
|
||||
include(clang-format.cmake)
|
||||
{% endhighlight %}
|
||||
|
||||
<p>...and run:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
cmake
|
||||
make clangformat
|
||||
{% endhighlight %}
|
||||
|
||||
<p>No other actions required.</p>
|
||||
|
||||
<h3><a href="#clang-adds" class="anchor" id="clang-adds"><span class="octicon octicon-link"></span></a>Adds</h3>
|
||||
<ul>
|
||||
<li>Configuration. You may see all options on the <a href="//clang.llvm.org/docs/ClangFormat.html" title="clang-format site">official site</a>. Also you may use <a href="//clangformat.com/" title="Site">interactive tool</a> to search for required options. To use the preset for your style use the following command:
|
||||
|
||||
{% highlight bash %}
|
||||
clang-format -style=LLVM -dump-config > .clang-format
|
||||
{% endhighlight %}
|
||||
|
||||
Then edit generated file <code>.clang-format</code>. To enable it you need set <code>-style=file</code> option, file should be placed to the any parent directory of each source file (e.g., to the project root). Also you may send required options to the command line directly, e.g. <code>-style="{BasedOnStyle: llvm, IndentWidth: 8}"</code></li>
|
||||
</ul>
|
165
_posts/2015-10-17-cppcheck-and-clang-format.md
Normal file
165
_posts/2015-10-17-cppcheck-and-clang-format.md
Normal file
@ -0,0 +1,165 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: development, c++, cmake
|
||||
title: Add cppcheck and clang-format for a cmake project
|
||||
short: cppcheck-and-clang-format
|
||||
---
|
||||
A small How-To which describes how to add automatic code style checking and static analyser to a project on `C++` which uses `cmake` as a build system.
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#project" class="anchor" id="project"><span class="octicon octicon-link"></span></a>Project
|
||||
|
||||
The project has the following structure:
|
||||
|
||||
```bash
|
||||
sources/
|
||||
|- CMakeLists.txt
|
||||
|- 3rdparty/
|
||||
|- first_component/
|
||||
|- second_component/
|
||||
```
|
||||
|
||||
**3rdparty** is a directory which contains additional libraries and which should be excluded from checking (`PROJECT_TRDPARTY_DIR` cmake variable is used to indicate path to this directory). Also let's assume that we have additional files (e.g. `*.qml`) in addition to common source files (`*.cpp`, `*.h`).
|
||||
|
||||
In addition the described below commands may be inserted to pre-commit hook; it allows us to troll colleagues which will be able to commit nothing till they read `CONTRIBUTING.md`.
|
||||
|
||||
## <a href="#cppcheck" class="anchor" id="cppcheck"><span class="octicon octicon-link"></span></a>cppcheck
|
||||
|
||||
As far as there are no good (out-of-box) static analysers in open source we will use it. Knowledgeable people say that [cppcheck](//cppcheck.sourceforge.net/ "cppcheck site") in case of good configuration it is better than the any alternative, but its configuration is the same that the new project creation. `cppcheck` shows obvious errors and recommend to fix them.
|
||||
|
||||
### <a href="#cppcheck-run" class="anchor" id="cppcheck-run"><span class="octicon octicon-link"></span></a>Example of run
|
||||
|
||||
Here it is:
|
||||
|
||||
```bash
|
||||
cppcheck --enable=warning,performance,portability,information,missingInclude --std=c++11 --library=qt.cfg --template="[{severity}][{id}] {message} {callstack} (On {file}:{line})" --verbose --quiet path/to/source/files/or/directory
|
||||
```
|
||||
|
||||
* `--enable` says which notifications should be enabled. I've disabled `style` (we will use `clang-format` to do it), `unusedFunction` which shows false-positive for some methods.
|
||||
* `--std` says which standard should be used.
|
||||
* `--library=qt.cfg` a configuration file, which describes how to check files. The developers recommend to read the following [manual](//cppcheck.sourceforge.net/manual.pdf "cppcheck manual"). I've used the ready template from `/usr/share/cppcheck/cfg/`.
|
||||
* `--template` is notification template.
|
||||
* `---verbose --quiet` are two "conflicting" options. The first one enables more verbose messages, the second one disables progress reports.
|
||||
|
||||
### <a href="#cppcheck-cmake" class="anchor" id="cppcheck-cmake"><span class="octicon octicon-link"></span></a>cmake integration
|
||||
|
||||
`cppcheck.cmake` file in the project root:
|
||||
|
||||
```cmake
|
||||
# additional target to perform cppcheck run, requires cppcheck
|
||||
|
||||
# get all project files
|
||||
# HACK this workaround is required to avoid qml files checking ^_^
|
||||
file(GLOB_RECURSE ALL_SOURCE_FILES *.cpp *.h)
|
||||
foreach (SOURCE_FILE ${ALL_SOURCE_FILES})
|
||||
string(FIND ${SOURCE_FILE} ${PROJECT_TRDPARTY_DIR} PROJECT_TRDPARTY_DIR_FOUND)
|
||||
if (NOT ${PROJECT_TRDPARTY_DIR_FOUND} EQUAL -1)
|
||||
list(REMOVE_ITEM ALL_SOURCE_FILES ${SOURCE_FILE})
|
||||
endif ()
|
||||
endforeach ()
|
||||
|
||||
add_custom_target(
|
||||
cppcheck
|
||||
COMMAND /usr/bin/cppcheck
|
||||
--enable=warning,performance,portability,information,missingInclude
|
||||
--std=c++11
|
||||
--library=qt.cfg
|
||||
--template="[{severity}][{id}] {message} {callstack} \(On {file}:{line}\)"
|
||||
--verbose
|
||||
--quiet
|
||||
${ALL_SOURCE_FILES}
|
||||
)
|
||||
```
|
||||
|
||||
`cppcheck` may work with directories recursive, but I need to skip qml-files checking in my example, because this `cppcheck` will segfault on some of them. To do it source files search is used followed by the ejection of unnecessary files.
|
||||
|
||||
Include to the project (`CMakeLists.txt`)...
|
||||
|
||||
```cmake
|
||||
include(cppcheck.cmake)
|
||||
```
|
||||
|
||||
...and run:
|
||||
|
||||
```bash
|
||||
cmake
|
||||
make cppcheck
|
||||
```
|
||||
|
||||
Then edit files to avoid warnings in the future.
|
||||
|
||||
### <a href="#cppcheck-adds" class="anchor" id="cppcheck-adds"><span class="octicon octicon-link"></span></a>Adds
|
||||
|
||||
* You may add own directories to includes search, using `-I dir` option
|
||||
* You may drop files and/or directories from checking by using `-i path/to/file/or/directory` option.
|
||||
|
||||
## <a href="#clang" class="anchor" id="clang"><span class="octicon octicon-link"></span></a>clang-format
|
||||
|
||||
[clang-format](//clang.llvm.org/docs/ClangFormat.html "clang-format site") is used to automatic code style checking and correction. [astyle](//astyle.sourceforge.net/ "astyle site"), which has a very modest capabilities, and [uncrustify](//uncrustify.sourceforge.net/ "uncrustify site"), which on the contrary has too many options, should be mentioned from analogues.
|
||||
|
||||
### <a href="#clang-run" class="anchor" id="clang-run"><span class="octicon octicon-link"></span></a>Example of run
|
||||
|
||||
```bash
|
||||
clang-format -i -style=LLVM /path/to/source/files
|
||||
```
|
||||
|
||||
(Unfortunately it **could not** work with directories recursive.)
|
||||
|
||||
* `-i` enables files auto replace (otherwise the result will be printed to stdout).
|
||||
* `-style` is a style preset selection or from file (`file`), see below.
|
||||
|
||||
### <a href="#clang-cmake" class="anchor" id="clang-cmake"><span class="octicon octicon-link"></span></a>cmake integration
|
||||
|
||||
`clang-format.cmake` file in the project root:
|
||||
|
||||
```cmake
|
||||
# additional target to perform clang-format run, requires clang-format
|
||||
|
||||
# get all project files
|
||||
file(GLOB_RECURSE ALL_SOURCE_FILES *.cpp *.h)
|
||||
foreach (SOURCE_FILE ${ALL_SOURCE_FILES})
|
||||
string(FIND ${SOURCE_FILE} ${PROJECT_TRDPARTY_DIR} PROJECT_TRDPARTY_DIR_FOUND)
|
||||
if (NOT ${PROJECT_TRDPARTY_DIR_FOUND} EQUAL -1)
|
||||
list(REMOVE_ITEM ALL_SOURCE_FILES ${SOURCE_FILE})
|
||||
endif ()
|
||||
endforeach ()
|
||||
|
||||
add_custom_target(
|
||||
clangformat
|
||||
COMMAND /usr/bin/clang-format
|
||||
-style=LLVM
|
||||
-i
|
||||
${ALL_SOURCE_FILES}
|
||||
)
|
||||
```
|
||||
|
||||
There is the same method to get source files list as for `cppcheck`, because `clang-format` doesn't support recursive directory search.
|
||||
|
||||
Include to the project (`CMakeLists.txt`)...
|
||||
|
||||
```cmake
|
||||
include(clang-format.cmake)
|
||||
```
|
||||
|
||||
...and run:
|
||||
|
||||
```bash
|
||||
cmake
|
||||
make clangformat
|
||||
```
|
||||
|
||||
No other actions required.
|
||||
|
||||
### <a href="#clang-adds" class="anchor" id="clang-adds"><span class="octicon octicon-link"></span></a>Adds
|
||||
|
||||
* Configuration. You may see all options on the [official site](//clang.llvm.org/docs/ClangFormat.html "clang-format site"). Also you may use [interactive tool](//clangformat.com/ "Site") to search for required options. To use the preset for your style use the following command:
|
||||
|
||||
```bash
|
||||
clang-format -style=LLVM -dump-config > .clang-format
|
||||
```
|
||||
|
||||
Then edit generated file `.clang-format`. To enable it you need set `-style=file` option, file should be placed to the any parent directory of each source file (e.g., to the project root). Also you may send required options to the command line directly, e.g. `-style="{BasedOnStyle: llvm, IndentWidth: 8}"`
|
@ -1,10 +0,0 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: site
|
||||
title: URL changes
|
||||
short: url-changes
|
||||
description: I would like to inform you that I've changed site and repository URL from <a href="//arcanis.name">arcanis.name</a> to <a href="//arcanis.me">arcanis.me</a>. It was done just because ME domain is more pretty. The old URLs will be still valid till Mar 2016 (date of the domain name registration), but at the moment I've setup URL redirection to the new URL. Sorry for any inconvenience.
|
||||
---
|
11
_posts/2016-01-09-url-changes.md
Normal file
11
_posts/2016-01-09-url-changes.md
Normal file
@ -0,0 +1,11 @@
|
||||
---
|
||||
category: en
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: site
|
||||
title: URL changes
|
||||
short: url-changes
|
||||
---
|
||||
|
||||
I would like to inform you that I've changed site and repository URL from [arcanis.name](//arcanis.name) to [arcanis.me](//arcanis.me). It was done just because ME domain is more pretty. The old URLs will be still valid till Mar 2016 (date of the domain name registration), but at the moment I've setup URL redirection to the new URL. Sorry for any inconvenience.
|
@ -23,6 +23,6 @@ hastr: true
|
||||
<a href="{{ post.url }}" title="{{ post.title }}">{{ post.title }}</a>
|
||||
</h2>
|
||||
<p><i>{{ post.date | date_to_string }}</i></p>
|
||||
<p>{{ post.description }}</p>
|
||||
<p>{{ post.excerpt }}</p>
|
||||
<p><b>Tags</b>: {{ post.tags }}</p>
|
||||
{% endfor %}
|
||||
|
@ -18,7 +18,7 @@
|
||||
{% else %}
|
||||
<item>
|
||||
<title>{{ post.title | xml_escape }}</title>
|
||||
<description>{{ post.description | xml_escape }}</description>
|
||||
<description>{{ post.excerpt | xml_escape }}</description>
|
||||
<pubDate>{{ post.date | date: "%a, %d %b %Y %H:%M:%S %z" }}</pubDate>
|
||||
<link>{{ site.url }}{{ post.url }}</link>
|
||||
<guid isPermaLink="true">{{ site.url }}{{ post.url }}</guid>
|
||||
|
1
feed.xml
1
feed.xml
@ -19,7 +19,6 @@
|
||||
<item>
|
||||
<title>{{ post.title | xml_escape }}</title>
|
||||
<description>
|
||||
{{ post.description | xml_escape }}
|
||||
{{ post.content | xml_escape}}
|
||||
</description>
|
||||
<pubDate>{{ post.date | date: "%a, %d %b %Y %H:%M:%S %z" }}</pubDate>
|
||||
|
@ -6,32 +6,37 @@ layout: paper
|
||||
tags: zshrc, настройка, linux
|
||||
title: О zshrc
|
||||
short: about-zshrc
|
||||
description: Это моя первая статья в блоге (я думаю, мне нужно что-нибудь для тестов =)). Существует множество похожих статей и, я думаю, не буду отличаться от большинства. Я просто хочу показать мой <code>.zshrc</code> и объяснить, что в нем есть и зачем оно нужно. Также, любые комментарии или дополнения приветствуются. <a href="//archlinux.org.ru/forum/topic/12752/" title="Тема на форуме">Оригинал</a> статьи.
|
||||
---
|
||||
<h2><a href="#prepare" class="anchor" id="prepare"><span class="octicon octicon-link"></span></a>Подготовка</h2>
|
||||
<p>Сначала установите необходимый минимум:</p>
|
||||
Это моя первая статья в блоге (я думаю, мне нужно что-нибудь для тестов =)). Существует множество похожих статей и, я думаю, не буду отличаться от большинства. Я просто хочу показать мой `.zshrc` и объяснить, что в нем есть и зачем оно нужно. Также, любые комментарии или дополнения приветствуются. [Оригинал](//archlinux.org.ru/forum/topic/12752/ "Тема на форуме") статьи.
|
||||
|
||||
{% highlight bash %}
|
||||
<!--more-->
|
||||
|
||||
## <a href="#prepare" class="anchor" id="prepare"><span class="octicon octicon-link"></span></a>Подготовка
|
||||
|
||||
Сначала установите необходимый минимум:
|
||||
|
||||
```bash
|
||||
pacman -Sy pkgfile zsh zsh-completions zsh-syntax-highlighting
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p><a href="//www.archlinux.org/packages/pkgfile/" title="Пакет Archlinux">pkgfile</a> очень полезная утилита. Данная команда также установит шелл, дополнения к нему и подсветку синтаксиса.</p>
|
||||
[pkgfile](//www.archlinux.org/packages/pkgfile/ "Пакет Archlinux") очень полезная утилита. Данная команда также установит шелл, дополнения к нему и подсветку синтаксиса.
|
||||
|
||||
<h2><a href="#configuration" class="anchor" id="configuration"><span class="octicon octicon-link"></span></a>Настройка шелла</h2>
|
||||
<p>Все доступные опции приведены <a href="//zsh.sourceforge.net/Doc/Release/Options.html" title="Документация zsh">здесь</a>.</p>
|
||||
## <a href="#configuration" class="anchor" id="configuration"><span class="octicon octicon-link"></span></a>Настройка шелла
|
||||
|
||||
<p>Указываем файл с историей, число команд хранящихся в кэше текущего сеанса и число команд, хранящихся в файле:</p>
|
||||
Все доступные опции приведены [здесь](//zsh.sourceforge.net/Doc/Release/Options.html "Документация zsh").
|
||||
|
||||
{% highlight bash %}
|
||||
Указываем файл с историей, число команд хранящихся в кэше текущего сеанса и число команд, хранящихся в файле:
|
||||
|
||||
```bash
|
||||
# history
|
||||
HISTFILE=~/.zsh_history
|
||||
HISTSIZE=500000
|
||||
SAVEHIST=500000
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Я не могу запомнить все комбинации <code>Ctrl+</code>, поэтому я назначаю клавиши на их стандартное использование:</p>
|
||||
Я не могу запомнить все комбинации `Ctrl+`, поэтому я назначаю клавиши на их стандартное использование:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# bindkeys
|
||||
bindkey '^[[A' up-line-or-search # up arrow for back-history-search
|
||||
bindkey '^[[B' down-line-or-search # down arrow for fwd-history-search
|
||||
@ -41,106 +46,106 @@ bindkey '\e[3~' delete-char # del
|
||||
bindkey '\e[4~' end-of-line # end
|
||||
bindkey '\e[5~' up-line-or-history # page-up
|
||||
bindkey '\e[6~' down-line-or-history # page-down
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Но здесь важно, что стрелки <code>вверх</code>/<code>вниз</code> служат для навигации по истории с учетом <b>уже введенной части</b> команды. А <code>PgUp</code>/<code>PgDown</code> <b>проигнорируют</b> уже введенную часть команды.</p>
|
||||
Но здесь важно, что стрелки `вверх`/`вниз` служат для навигации по истории с учетом **уже введенной части** команды. А `PgUp`/`PgDown` **проигнорируют** уже введенную часть команды.
|
||||
|
||||
<p>Автодополнение команд:</p>
|
||||
Автодополнение команд:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# autocomplete
|
||||
autoload -U compinit
|
||||
compinit
|
||||
zstyle ':completion:*' insert-tab false
|
||||
zstyle ':completion:*' max-errors 2
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Подключается полное автодополнение команд. <code>insert-tab false</code> включит автодополнение для <b>невведенной</b> команды (не знаю, зачем). <code>max-errors</code> устанавливает максимальное число опечаток, которые могут быть исправлены.</p>
|
||||
Подключается полное автодополнение команд. `insert-tab false` включит автодополнение для **невведенной** команды (не знаю, зачем). `max-errors` устанавливает максимальное число опечаток, которые могут быть исправлены.
|
||||
|
||||
<p>Приглашение:</p>
|
||||
Приглашение:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# promptinit
|
||||
autoload -U promptinit
|
||||
promptinit
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Включим цвета:</p>
|
||||
Включим цвета:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# colors
|
||||
autoload -U colors
|
||||
colors
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Различные опции.</p>
|
||||
<p>Смена директории без ввода <code>cd</code>:</p>
|
||||
Различные опции.
|
||||
Смена директории без ввода `cd`:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# autocd
|
||||
setopt autocd
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Корректировка опечаток (и шаблон вопроса):</p>
|
||||
Корректировка опечаток (и шаблон вопроса):
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# correct
|
||||
setopt CORRECT_ALL
|
||||
SPROMPT="Correct '%R' to '%r' ? ([Y]es/[N]o/[E]dit/[A]bort) "
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Отключаем е#$%ую пищалку:</p>
|
||||
Отключаем е#$%ую пищалку:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# disable beeps
|
||||
unsetopt beep
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Включаем калькулятор:</p>
|
||||
Включаем калькулятор:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# calc
|
||||
autoload zcalc
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Дополнение истории (<b>а не перезапись</b> файла):</p>
|
||||
Дополнение истории (**а не перезапись** файла):
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# append history
|
||||
setopt APPEND_HISTORY
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Не сохранять дубликаты в историю:</p>
|
||||
Не сохранять дубликаты в историю:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# ignore dups in history
|
||||
setopt HIST_IGNORE_ALL_DUPS
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>...и дополнительные пробелы:</p>
|
||||
...и дополнительные пробелы:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# ignore spaces in history
|
||||
setopt HIST_IGNORE_SPACE
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>...и пустые линии тоже:</p>
|
||||
...и пустые линии тоже:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# reduce blanks in history
|
||||
setopt HIST_REDUCE_BLANKS
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Включаем <code>pkgfile</code>:</p>
|
||||
Включаем `pkgfile`:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# pkgfile
|
||||
source /usr/share/doc/pkgfile/command-not-found.zsh
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h2><a href="#highlighting" class="anchor" id="highlighting"><span class="octicon octicon-link"></span></a>Подсветка синтаксиса</h2>
|
||||
## <a href="#highlighting" class="anchor" id="highlighting"><span class="octicon octicon-link"></span></a>Подсветка синтаксиса
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# highlighting
|
||||
source /usr/share/zsh/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
|
||||
ZSH_HIGHLIGHT_HIGHLIGHTERS=(main brackets pattern)
|
||||
@ -185,14 +190,15 @@ ZSH_HIGHLIGHT_STYLES[double-quoted-argument]='fg=yellow' # конс
|
||||
#ZSH_HIGHLIGHT_PATTERNS+=('rm -rf *' 'fg=white,bold,bg=red')
|
||||
# root
|
||||
#ZSH_HIGHLIGHT_STYLES[root]='bg=red'
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>В первой строке включаем подсветку. Затем включаем основную подсветку, а также подсветку скобок и шаблонов. Шаблоны указываются ниже (<code>rm -rf *</code> в примере). Также может быть включена подсветка команд от <code>root</code> и курсора <code>cursor</code>. Синтаксис настроек понятен, <code>fg</code> цвет шрифта, <code>bg</code> цвет фона.</p>
|
||||
В первой строке включаем подсветку. Затем включаем основную подсветку, а также подсветку скобок и шаблонов. Шаблоны указываются ниже (`rm -rf *` в примере). Также может быть включена подсветка команд от `root` и курсора `cursor`. Синтаксис настроек понятен, `fg` цвет шрифта, `bg` цвет фона.
|
||||
|
||||
<h2><a href="#prompt" class="anchor" id="prompt"><span class="octicon octicon-link"></span></a>$PROMPT и $RPROMPT</h2>
|
||||
<p>Я хочу использовать один файл <code>.zshrc</code> для рута и обычного пользователя:</p>
|
||||
## <a href="#prompt" class="anchor" id="prompt"><span class="octicon octicon-link"></span></a>$PROMPT и $RPROMPT
|
||||
|
||||
{% highlight bash %}
|
||||
Я хочу использовать один файл `.zshrc` для рута и обычного пользователя:
|
||||
|
||||
```bash
|
||||
# PROMPT && RPROMPT
|
||||
if [[ $EUID == 0 ]]; then
|
||||
# [root@host dir]#
|
||||
@ -211,11 +217,11 @@ else
|
||||
%{$fg_bold[yellow]%}%1/%{$reset_color%}\
|
||||
%{$fg_bold[white]%}]$ %{$reset_color%}"
|
||||
fi
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p><code>fg</code> цвет шрифта, <code>bg</code> цвет фона. <code>_bold</code> и <code>_no_bold</code> регулируют оттенок. Команды должны быть обрамлены в <code>%{ ... %}</code>, чтобы не показывались. Доступные цвета:</p>
|
||||
`fg` цвет шрифта, `bg` цвет фона. `_bold` и `_no_bold` регулируют оттенок. Команды должны быть обрамлены в `%{ ... %}`, чтобы не показывались. Доступные цвета:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
black
|
||||
red
|
||||
green
|
||||
@ -224,11 +230,11 @@ blue
|
||||
magenta
|
||||
cyan
|
||||
white
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Доступные переменные:</p>
|
||||
Доступные переменные:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
%n - имя пользователя
|
||||
%m - хостнейм (выставляется только в начале сессии)
|
||||
%M - хостнейм
|
||||
@ -241,11 +247,11 @@ white
|
||||
%d - текущая директория
|
||||
%~ - то же, домашняя директория будет заменена на ~
|
||||
%1/ - то же, но только последняя директория
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>RPROMPT (необходим пакет <code>acpi</code>):</p>
|
||||
RPROMPT (необходим пакет `acpi`):
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
precmd () {
|
||||
# battery charge
|
||||
function batcharge {
|
||||
@ -268,25 +274,26 @@ $(batcharge)\
|
||||
"%{$fg_bold[white]%}[%{$reset_color%}"\
|
||||
$returncode\
|
||||
"%{$fg_bold[white]%}]%{$reset_color%}"
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Мой RPROMPT показывает текущее время, заряд батареи и код возврата последнего приложения. <code>precmd()</code> необходимо для автоматического обновления. Конструкция <code>$(if.true.false)</code> является условным оператором в <code>zsh</code>.</p>
|
||||
Мой RPROMPT показывает текущее время, заряд батареи и код возврата последнего приложения. `precmd()` необходимо для автоматического обновления. Конструкция `$(if.true.false)` является условным оператором в `zsh`.
|
||||
|
||||
<h2><a href="#aliases" class="anchor" id="aliases"><span class="octicon octicon-link"></span></a>Аллиасы</h2>
|
||||
<p><b>Копируйте только те аллиасы, которые Вам необходимы.</b> Если какой-либо аллиас использует приложение, которое не установлено, это приведет к сбою загрузки конфигурационного файла.</p>
|
||||
## <a href="#aliases" class="anchor" id="aliases"><span class="octicon octicon-link"></span></a>Аллиасы
|
||||
|
||||
<p>Полезная (или не очень) функция:</p>
|
||||
**Копируйте только те аллиасы, которые Вам необходимы.** Если какой-либо аллиас использует приложение, которое не установлено, это приведет к сбою загрузки конфигурационного файла.
|
||||
|
||||
{% highlight bash %}
|
||||
Полезная (или не очень) функция:
|
||||
|
||||
```bash
|
||||
show_which() {
|
||||
OUTPUT=$(which $1 | cut -d " " -f7-)
|
||||
echo "Running '$OUTPUT'" 1>&2
|
||||
}
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Первая группа аллиасов:</p>
|
||||
Первая группа аллиасов:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
## alias
|
||||
# цветной grep
|
||||
alias grep='grep --colour=auto'
|
||||
@ -302,11 +309,11 @@ alias du='show_which du && du -k --total --human-readable'
|
||||
# замена less и zless на vimpager
|
||||
alias less='vimpager'
|
||||
alias zless='vimpager'
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>ls аллиасы (смотри <a href="//unixhelp.ed.ac.uk/CGI/man-cgi?ls" title="Мануал">man ls</a>):</p>
|
||||
ls аллиасы (смотри [man ls](//unixhelp.ed.ac.uk/CGI/man-cgi?ls "Мануал")):
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
alias ls='show_which ls && ls --color=auto --group-directories-first'
|
||||
alias ll='show_which ll && ls -l --human-readable'
|
||||
alias lr='show_which lr && ls --recursive'
|
||||
@ -315,11 +322,11 @@ alias lx='show_which lx && ll -X --ignore-backups'
|
||||
alias lz='show_which lz && ll -S --reverse'
|
||||
alias lt='show_which lt && ll -t --reverse'
|
||||
alias lm='show_which lm && la | more'
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Аллиасы для быстрого просмотра файлов из консоли (просто набери имя файла!):</p>
|
||||
Аллиасы для быстрого просмотра файлов из консоли (просто набери имя файла!):
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# alias -s
|
||||
alias -s {avi,mpeg,mpg,mov,m2v,mkv}=mpv
|
||||
alias -s {mp3,flac}=qmmp
|
||||
@ -327,11 +334,11 @@ alias -s {odt,doc,xls,ppt,docx,xlsx,pptx,csv}=libreoffice
|
||||
alias -s {pdf}=okular
|
||||
autoload -U pick-web-browser
|
||||
alias -s {html,htm}=opera
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>"sudo" аллиасы:</p>
|
||||
"sudo" аллиасы:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# sudo alias
|
||||
if [[ $EUID == 0 ]]; then
|
||||
alias fat32mnt='show_which fat32mnt && mount -t vfat -o codepage=866,iocharset=utf8,umask=000'
|
||||
@ -351,23 +358,24 @@ else
|
||||
alias staging-i686-build='show_which staging-i686-build && sudo staging-i686-build'
|
||||
alias staging-x86_64-build='show_which staging-x86_64-build && sudo staging-x86_64-build'
|
||||
fi
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Некоторые глобальные аллиасы. Если они включены, команда <code>cat foo g bar</code> будет эквивалентна <code>cat foo | grep bar</code>:</p>
|
||||
Некоторые глобальные аллиасы. Если они включены, команда `cat foo g bar` будет эквивалентна `cat foo | grep bar`:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# global alias
|
||||
alias -g g="| grep"
|
||||
alias -g l="| less"
|
||||
alias -g t="| tail"
|
||||
alias -g h="| head"
|
||||
alias -g dn="&> /dev/null &"
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h2><a href="#functions" class="anchor" id="functions"><span class="octicon octicon-link"></span></a>Функции</h2>
|
||||
<p>Специальная функция для <code>xrandr</code>:</p>
|
||||
## <a href="#functions" class="anchor" id="functions"><span class="octicon octicon-link"></span></a>Функции
|
||||
|
||||
{% highlight bash %}
|
||||
Специальная функция для `xrandr`:
|
||||
|
||||
```bash
|
||||
# function to contorl xrandr
|
||||
# EXAMPLE: projctl 1024x768
|
||||
projctl () {
|
||||
@ -388,11 +396,11 @@ projctl () {
|
||||
xrandr --output VGA1 --mode 1366x768 --output LVDS1 --mode 1366x768
|
||||
fi
|
||||
}
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>К сожалению, я не могу запомнить флаги <code>tar</code>, поэтому я использую специальные функции:</p>
|
||||
К сожалению, я не могу запомнить флаги `tar`, поэтому я использую специальные функции:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# function to extract archives
|
||||
# EXAMPLE: unpack file
|
||||
unpack () {
|
||||
@ -442,11 +450,11 @@ pack () {
|
||||
echo "'$1' is not a valid file"
|
||||
fi
|
||||
}
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Специальная функция для <code>su</code>:</p>
|
||||
Специальная функция для `su`:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
su () {
|
||||
CHECKSU=0
|
||||
for FLAG in $*; do
|
||||
@ -461,11 +469,11 @@ su () {
|
||||
/usr/bin/su $*
|
||||
fi
|
||||
}
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Функция, которая заменяет оригиналькую команду <code>rm</code>. Если Вы наберете <code>rm</code>, это будет эквивалентно перемещению в корзину, также, Вы можете легко восстановить удаленный файл:</p>
|
||||
Функция, которая заменяет оригиналькую команду `rm`. Если Вы наберете `rm`, это будет эквивалентно перемещению в корзину, также, Вы можете легко восстановить удаленный файл:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
rm () {
|
||||
# error check
|
||||
[ $# -eq 0 ] && { echo "Files are not set!"; return 1 }
|
||||
@ -505,11 +513,11 @@ rm () {
|
||||
fi
|
||||
done
|
||||
}
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Функция для автоматических обновлений путей после установки пакетов:</p>
|
||||
Функция для автоматических обновлений путей после установки пакетов:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
pacman () {
|
||||
/usr/bin/sudo /usr/bin/pacman $* && echo "$*" | grep -q "S\|R\|U" && rehash
|
||||
}
|
||||
@ -520,14 +528,15 @@ yaourt () {
|
||||
yatest () {
|
||||
/usr/bin/yaourt --config /etc/pactest.conf $* && echo "$*" | grep -q "S\|R\|U" && rehash
|
||||
}
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h2><a href="#variables" class="anchor" id="variables"><span class="octicon octicon-link"></span></a>Переменные</h2>
|
||||
<p>Рекомендуется хранить свои переменные в <code>~/.zshenv</code>. Но я все храню в одном файле.</p>
|
||||
## <a href="#variables" class="anchor" id="variables"><span class="octicon octicon-link"></span></a>Переменные
|
||||
|
||||
<p>Пути, маска создаваемых файлов, редактор и пейджер:</p>
|
||||
Рекомендуется хранить свои переменные в `~/.zshenv`. Но я все храню в одном файле.
|
||||
|
||||
{% highlight bash %}
|
||||
Пути, маска создаваемых файлов, редактор и пейджер:
|
||||
|
||||
```bash
|
||||
# path
|
||||
export PATH="$PATH:$HOME/.local/bin"
|
||||
# umask
|
||||
@ -535,25 +544,27 @@ umask 022
|
||||
# editor
|
||||
export EDITOR="vim"
|
||||
export PAGER="vimpager"
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Хэши. Если они включены, команда <code>~global</code> будет эквивалентна команде <code>/mnt/global</code>:</p>
|
||||
Хэши. Если они включены, команда `~global` будет эквивалентна команде `/mnt/global`:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# hash
|
||||
hash -d global=/mnt/global
|
||||
hash -d windows=/mnt/windows
|
||||
hash -d iso=/mnt/iso
|
||||
hash -d u1=/mnt/usbdev1
|
||||
hash -d u2=/mnt/usbdev2
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
## <a href="#screenshot" class="anchor" id="screenshot"><span class="octicon octicon-link"></span></a>Скриншот
|
||||
|
||||
<h2><a href="#screenshot" class="anchor" id="screenshot"><span class="octicon octicon-link"></span></a>Скриншот</h2>
|
||||
<div class="thumbnails">
|
||||
{% assign scrdesc = "Как оно выглядит" %}
|
||||
{% assign scrname = "zshrc_demo" %}
|
||||
{% include prj_scr.html %}
|
||||
</div>
|
||||
|
||||
<h2><a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>Файл</h2>
|
||||
<p><a href="//raw.github.com/arcan1s/dotfiles/master/zshrc" title="Github" type="text/plain">Мой</a> <code>.zshrc</code>.</p>
|
||||
## <a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>Файл
|
||||
|
||||
[Мой](//raw.github.com/arcan1s/dotfiles/master/zshrc "Github") `.zshrc`.
|
@ -1,203 +0,0 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: archlinux, linux, сборка, qutim
|
||||
title: Сборка Qutim с Qt5
|
||||
short: building-qutim-using-qt5
|
||||
description: Если кто-то не знает, <a href="//qutim.org" title="Домашняя страница Qutim">Qutim</a> - мультипротокольный кросс-платформенный месседжер. Написан он на <code>CPP</code> с использованием библиотек Qt. Проект активно развивается. В этой статье речь пойдет о реализации сборки данного пакета в Archlinux с использованием библиотек Qt5 (а не Qt4, как это делают текущие пакеты в AUR).
|
||||
---
|
||||
<h2><a href="#problems" class="anchor" id="problems"><span class="octicon octicon-link"></span></a>Что не так?</h2>
|
||||
<p>Да все так. Просто пакет использует для сборки систему <a href="//qt-project.org/wiki/qbs" title="Wiki">qbs</a>, которая, на мой взгляд, немного странная. Пакет, необходимый для сборки, <a href="//aur.archlinux.org/packages/qbs-git/" title="AUR">находится в AUR</a> (рекомендую git-версию). Когда я спросил у Andrea Scarpino (который сопровождает все KDE и Qt пакеты в официальные репозитории) по поводу переноса этого пакета в репозитории, он ответил, что всему свое время. В принципе, я с ним согласен, так как проект, судя по всему, еще немного сыроват.</p>
|
||||
|
||||
<h2><a href="#prepare" class="anchor" id="prepare"><span class="octicon octicon-link"></span></a>Подготовка</h2>
|
||||
<p>Установим зависимости. Что-то может быть пропустил, зависимости сканировал с использованием <code>namcap</code>:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
pacman -Sy --asdeps clang git libc++abi qt5-quick1 qt5-x11extras
|
||||
yaourt -S --asdeps jreen-git qbs-git
|
||||
{% endhighlight %}
|
||||
|
||||
<h3><a href="#qbs" class="anchor" id="qbs"><span class="octicon octicon-link"></span></a>Настройка qbs</h3>
|
||||
<p>Желающие могут почитать документацию <a href="//qt-project.org/wiki/qbs" title="Wiki">по ссылке</a> или посмотреть примеры (включены в пакет). Загвоздка в том, что эта штука использует файл настроек, который, во-первых, нужно сначала сгенерировать, во-вторых, хранится в домашней директории (и только там). В теории, генерация файла настроек (<code>~/.config/QtProject/qbs.conf</code>) происходит следующим образом:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
qbs-setup-qt --detect
|
||||
qbs-detect-toolchains
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Сначала находим Qt для сборки, потом находим инструментарий (компиляторы, например). Дальше вставляем инструментарий (например, нам для Qutim нужен <code>clang</code>) в Qt, например, так:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
sed 's/clang\\/qt-5-2-0\\/g' -i ~/.config/QtProject/qbs.conf
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Альтернативные варианты - править файл вручную или воспользоваться <code>qbs-config-ui</code> или <code>qbs-config</code> на Ваш выбор.</p>
|
||||
<p>Так или иначе, нужный файл мы сгенерировали, сохраним его в будущей директории сборки:</p>
|
||||
|
||||
{% highlight ini %}
|
||||
[General]
|
||||
|
||||
[Qt]
|
||||
filedialog=
|
||||
|
||||
[profiles]
|
||||
clang\cpp\compilerName=clang++
|
||||
clang\cpp\toolchainInstallPath=/usr/bin
|
||||
clang\qbs\architecture=x86_64
|
||||
clang\qbs\endianness=little
|
||||
clang\qbs\toolchain=clang, llvm, gcc
|
||||
gcc\cpp\compilerName=g++
|
||||
gcc\cpp\toolchainInstallPath=/usr/bin
|
||||
gcc\qbs\architecture=x86_64
|
||||
gcc\qbs\endianness=little
|
||||
gcc\qbs\toolchain=gcc
|
||||
qutim\Qt\core\binPath=/usr/lib/qt/bin
|
||||
qutim\Qt\core\buildVariant=release
|
||||
qutim\Qt\core\config=shared, qpa, no_mocdepend, release, qt_no_framework
|
||||
qutim\Qt\core\docPath=/usr/share/doc/qt
|
||||
qutim\Qt\core\incPath=/usr/include/qt
|
||||
qutim\Qt\core\libInfix=
|
||||
qutim\Qt\core\libPath=/usr/lib
|
||||
qutim\Qt\core\mkspecPath=/usr/lib/qt/mkspecs/linux-g++
|
||||
qutim\Qt\core\namespace=
|
||||
qutim\Qt\core\pluginPath=/usr/lib/qt/plugins
|
||||
qutim\Qt\core\qtConfig=minimal-config, small-config, medium-config, large-config, full-config, gtk2, gtkstyle, fontconfig, libudev, evdev, xlib, xcb-glx, xcb-xlib, xcb-sm, xrender, accessibility-atspi-bridge, linuxfb, c++11, accessibility, opengl, shared, qpa, reduce_exports, reduce_relocations, clock-gettime, clock-monotonic, mremap, getaddrinfo, ipv6ifname, getifaddrs, inotify, eventfd, system-jpeg, system-png, png, system-freetype, no-harfbuzz, system-zlib, nis, cups, iconv, glib, dbus, dbus-linked, openssl-linked, xcb, xinput2, alsa, pulseaudio, icu, concurrent, audio-backend, release
|
||||
qutim\Qt\core\version=5.2.0
|
||||
qutim\cpp\compilerName=clang++
|
||||
qutim\cpp\toolchainInstallPath=/usr/bin
|
||||
qutim\qbs\architecture=x86_64
|
||||
qutim\qbs\endianness=little
|
||||
qutim\qbs\toolchain=clang, llvm, gcc
|
||||
{% endhighlight %}
|
||||
|
||||
<p><a href="/resources/docs/qutim-qt5-git/qbs-qutim.conf" title="Файл" type="text/plain">qbs-qutim.conf</a></p>
|
||||
|
||||
<h3><a href="#patch" class="anchor" id="patch"><span class="octicon octicon-link"></span></a>Готовим патч для исходников</h3>
|
||||
<p>Первая проблема - <code>clang</code> (по крайней мере, в Archlinux):</p>
|
||||
|
||||
{% highlight diff %}
|
||||
diff -ruN qutim.orig/core/libqutim.qbs qutim/core/libqutim.qbs
|
||||
--- qutim.orig/core/libqutim.qbs 2014-01-06 15:39:56.000000000 +0400
|
||||
+++ qutim/core/libqutim.qbs 2014-01-06 15:44:54.502175067 +0400
|
||||
@@ -75,7 +75,7 @@
|
||||
cpp.linkerFlags: {
|
||||
var flags = base;
|
||||
if (qbs.toolchain.contains("clang") && qbs.targetOS.contains("linux"))
|
||||
- flags = flags.concat("-stdlib=libc++ -lcxxrt");
|
||||
+ flags = flags.concat("-lc++abi");
|
||||
return flags;
|
||||
}
|
||||
|
||||
{% endhighlight %}
|
||||
|
||||
<p>И пофиксить сборку библиотеки для Vk:</p>
|
||||
|
||||
{% highlight diff %}
|
||||
diff -ruN qutim.orig/protocols/vkontakte/vreen/vreen.qbs qutim/protocols/vkontakte/vreen/vreen.qbs
|
||||
--- qutim.orig/protocols/vkontakte/vreen/vreen.qbs 2014-01-06 15:41:42.000000000 +0400
|
||||
+++ qutim/protocols/vkontakte/vreen/vreen.qbs 2014-01-06 15:46:47.142178486 +0400
|
||||
@@ -5,6 +5,7 @@
|
||||
property string vreen_qml_path: "bin"
|
||||
property string vreen_lib_path: "lib"
|
||||
property string vreen_libexec_path: "lib"
|
||||
+ property string lib_path: "lib"
|
||||
|
||||
property string vreen_version_major: 1
|
||||
property string vreen_version_minor: 9
|
||||
{% endhighlight %}
|
||||
|
||||
<p><a href="/resources/docs/qutim-qt5-git/qutim-qbs-1.1.patch" title="Файл" type="text/plain">qutim-qbs-1.1.patch</a></p>
|
||||
|
||||
<h3><a href="#sources" class="anchor" id="sources"><span class="octicon octicon-link"></span></a>Получаем исходники</h3>
|
||||
|
||||
{% highlight bash %}
|
||||
# клонируем репозиторий
|
||||
git clone https://github.com/euroelessar/qutim
|
||||
# кладем файл настроек qbs
|
||||
mkdir -p .config/QtProject
|
||||
cp qbs-qutim.conf .config/QtProject/qbs.conf
|
||||
# создаем директорию сборки
|
||||
mkdir build
|
||||
# обновляем подмодули
|
||||
cd qutim
|
||||
git submodule update --init --recursive
|
||||
# патчим
|
||||
cd ..
|
||||
patch -p0 -i qutim-qbs-1.1.patch
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#build" class="anchor" id="build"><span class="octicon octicon-link"></span></a>Сборка</h2>
|
||||
|
||||
{% highlight bash %}
|
||||
cd qutim
|
||||
HOME=$(pwd) qbs -j $(nproc) -d ../build release profile:qutim
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Я пытался сделать универсальный способ сборки пакета, поэтому такое странное переназначение домашней директории. Флаг <code>-j</code> указывает число потоков сборки, флаг <code>-d</code> директорию сборки, <code>release</code> тип сборки (debug, release), <code>profile</code> используемый профиль, описанный в файле настроек.</p>
|
||||
|
||||
<h2><a href="#install" class="anchor" id="install"><span class="octicon octicon-link"></span></a>Установка</h2>
|
||||
|
||||
{% highlight bash %}
|
||||
HOME=$(pwd) sudo qbs install -d ../build --install-root "/usr" profile:qutim
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Из нового - указание корневого каталога (<code>--install-root</code>). Без этого пакет будет установлен в <code>/</code> (<code>/bin</code> и <code>/lib</code>).</p>
|
||||
|
||||
<h2><a href="#pkgbuild" class="anchor" id="pkgbuild"><span class="octicon octicon-link"></span></a>PKGBUILD</h2>
|
||||
|
||||
{% highlight bash %}
|
||||
pkgname=qutim-qt5-git
|
||||
_gitname=qutim
|
||||
pkgver=v0.3.1.967.gc56d61e
|
||||
pkgrel=1
|
||||
pkgdesc="Multiplatform instant messenger (qt5 build). Git version"
|
||||
arch=('i686' 'x86_64')
|
||||
url="http://qutim.org"
|
||||
license=('LGPL' 'GPL3')
|
||||
depends=('jreen-git' 'libc++abi' 'qt5-quick1' 'qt5-x11extras')
|
||||
makedepends=('clang' 'qbs')
|
||||
conflicts=(qutim-0.2_ru-git, qutim-0.3-git, qutim-stable, qutim-git)
|
||||
source=("${_gitname}::git+https://github.com/euroelessar/qutim.git"
|
||||
"qutim-qbs-1.1.patch"
|
||||
"qbs-qutim.conf")
|
||||
md5sums=('SKIP'
|
||||
'12c30176729a5230ff7e6effbb1b37f8'
|
||||
'40f096b269eb00b040035591fce8e259')
|
||||
|
||||
pkgver() {
|
||||
cd "${_gitname}"
|
||||
git describe --always | sed 's|-|.|g'
|
||||
}
|
||||
|
||||
prepare() {
|
||||
# FIXME: dirty hack
|
||||
mkdir -p "${srcdir}/.config/QtProject"
|
||||
cp "${srcdir}/qbs-qutim.conf" "${srcdir}/.config/QtProject/qbs.conf"
|
||||
# create build directory
|
||||
if [[ -d ${srcdir}/build ]]; then
|
||||
rm -rf "${srcdir}/build"
|
||||
fi
|
||||
mkdir "${srcdir}/build"
|
||||
|
||||
cd "${_gitname}"
|
||||
# update modules
|
||||
git submodule update --init --recursive
|
||||
# fix qbs build
|
||||
cd ..
|
||||
patch -p0 -i "${srcdir}/qutim-qbs-1.1.patch"
|
||||
}
|
||||
|
||||
build() {
|
||||
cd "${_gitname}"
|
||||
HOME="${srcdir}" qbs -j $(nproc) -d ../build release profile:qutim
|
||||
}
|
||||
|
||||
package() {
|
||||
cd "${srcdir}/${_gitname}"
|
||||
HOME="${srcdir}" qbs install -d ../build --install-root "${pkgdir}/usr" profile:qutim
|
||||
}
|
||||
{% endhighlight %}
|
||||
|
||||
<p><a href="/resources/docs/qutim-qt5-git/PKGBUILD" title="Файл" type="text/plain">PKGBUILD</a></p>
|
210
ru/_posts/2014-01-21-building-qutim-using-qt5.md
Normal file
210
ru/_posts/2014-01-21-building-qutim-using-qt5.md
Normal file
@ -0,0 +1,210 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: archlinux, linux, сборка, qutim
|
||||
title: Сборка Qutim с Qt5
|
||||
short: building-qutim-using-qt5
|
||||
---
|
||||
Если кто-то не знает, [Qutim](//qutim.org "Домашняя страница Qutim") - мультипротокольный кросс-платформенный месседжер. Написан он на `CPP` с использованием библиотек Qt. Проект активно развивается. В этой статье речь пойдет о реализации сборки данного пакета в Archlinux с использованием библиотек Qt5 (а не Qt4, как это делают текущие пакеты в AUR).
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#problems" class="anchor" id="problems"><span class="octicon octicon-link"></span></a>Что не так?
|
||||
|
||||
Да все так. Просто пакет использует для сборки систему [qbs](//qt-project.org/wiki/qbs "Wiki"), которая, на мой взгляд, немного странная. Пакет, необходимый для сборки, [находится в AUR](//aur.archlinux.org/packages/qbs-git/ "AUR") (рекомендую git-версию). Когда я спросил у Andrea Scarpino (который сопровождает все KDE и Qt пакеты в официальные репозитории) по поводу переноса этого пакета в репозитории, он ответил, что всему свое время. В принципе, я с ним согласен, так как проект, судя по всему, еще немного сыроват.
|
||||
|
||||
## <a href="#prepare" class="anchor" id="prepare"><span class="octicon octicon-link"></span></a>Подготовка
|
||||
|
||||
Установим зависимости. Что-то может быть пропустил, зависимости сканировал с использованием `namcap`:
|
||||
|
||||
```bash
|
||||
pacman -Sy --asdeps clang git libc++abi qt5-quick1 qt5-x11extras
|
||||
yaourt -S --asdeps jreen-git qbs-git
|
||||
```
|
||||
|
||||
### <a href="#qbs" class="anchor" id="qbs"><span class="octicon octicon-link"></span></a>Настройка qbs
|
||||
|
||||
Желающие могут почитать документацию [по ссылке](//qt-project.org/wiki/qbs "Wiki") или посмотреть примеры (включены в пакет). Загвоздка в том, что эта штука использует файл настроек, который, во-первых, нужно сначала сгенерировать, во-вторых, хранится в домашней директории (и только там). В теории, генерация файла настроек (`~/.config/QtProject/qbs.conf`) происходит следующим образом:
|
||||
|
||||
```bash
|
||||
qbs-setup-qt --detect
|
||||
qbs-detect-toolchains
|
||||
```
|
||||
|
||||
Сначала находим Qt для сборки, потом находим инструментарий (компиляторы, например). Дальше вставляем инструментарий (например, нам для Qutim нужен `clang`) в Qt, например, так:
|
||||
|
||||
```bash
|
||||
sed 's/clang\\/qt-5-2-0\\/g' -i ~/.config/QtProject/qbs.conf
|
||||
```
|
||||
|
||||
Альтернативные варианты - править файл вручную или воспользоваться `qbs-config-ui` или `qbs-config` на Ваш выбор.
|
||||
Так или иначе, нужный файл мы сгенерировали, сохраним его в будущей директории сборки:
|
||||
|
||||
```ini
|
||||
[General]
|
||||
|
||||
[Qt]
|
||||
filedialog=
|
||||
|
||||
[profiles]
|
||||
clang\cpp\compilerName=clang++
|
||||
clang\cpp\toolchainInstallPath=/usr/bin
|
||||
clang\qbs\architecture=x86_64
|
||||
clang\qbs\endianness=little
|
||||
clang\qbs\toolchain=clang, llvm, gcc
|
||||
gcc\cpp\compilerName=g++
|
||||
gcc\cpp\toolchainInstallPath=/usr/bin
|
||||
gcc\qbs\architecture=x86_64
|
||||
gcc\qbs\endianness=little
|
||||
gcc\qbs\toolchain=gcc
|
||||
qutim\Qt\core\binPath=/usr/lib/qt/bin
|
||||
qutim\Qt\core\buildVariant=release
|
||||
qutim\Qt\core\config=shared, qpa, no_mocdepend, release, qt_no_framework
|
||||
qutim\Qt\core\docPath=/usr/share/doc/qt
|
||||
qutim\Qt\core\incPath=/usr/include/qt
|
||||
qutim\Qt\core\libInfix=
|
||||
qutim\Qt\core\libPath=/usr/lib
|
||||
qutim\Qt\core\mkspecPath=/usr/lib/qt/mkspecs/linux-g++
|
||||
qutim\Qt\core\namespace=
|
||||
qutim\Qt\core\pluginPath=/usr/lib/qt/plugins
|
||||
qutim\Qt\core\qtConfig=minimal-config, small-config, medium-config, large-config, full-config, gtk2, gtkstyle, fontconfig, libudev, evdev, xlib, xcb-glx, xcb-xlib, xcb-sm, xrender, accessibility-atspi-bridge, linuxfb, c++11, accessibility, opengl, shared, qpa, reduce_exports, reduce_relocations, clock-gettime, clock-monotonic, mremap, getaddrinfo, ipv6ifname, getifaddrs, inotify, eventfd, system-jpeg, system-png, png, system-freetype, no-harfbuzz, system-zlib, nis, cups, iconv, glib, dbus, dbus-linked, openssl-linked, xcb, xinput2, alsa, pulseaudio, icu, concurrent, audio-backend, release
|
||||
qutim\Qt\core\version=5.2.0
|
||||
qutim\cpp\compilerName=clang++
|
||||
qutim\cpp\toolchainInstallPath=/usr/bin
|
||||
qutim\qbs\architecture=x86_64
|
||||
qutim\qbs\endianness=little
|
||||
qutim\qbs\toolchain=clang, llvm, gcc
|
||||
```
|
||||
|
||||
[qbs-qutim.conf](/resources/docs/qutim-qt5-git/qbs-qutim.conf "Файл")
|
||||
|
||||
### <a href="#patch" class="anchor" id="patch"><span class="octicon octicon-link"></span></a>Готовим патч для исходников
|
||||
|
||||
Первая проблема - `clang` (по крайней мере, в Archlinux):
|
||||
|
||||
```diff
|
||||
diff -ruN qutim.orig/core/libqutim.qbs qutim/core/libqutim.qbs
|
||||
--- qutim.orig/core/libqutim.qbs 2014-01-06 15:39:56.000000000 +0400
|
||||
+++ qutim/core/libqutim.qbs 2014-01-06 15:44:54.502175067 +0400
|
||||
@@ -75,7 +75,7 @@
|
||||
cpp.linkerFlags: {
|
||||
var flags = base;
|
||||
if (qbs.toolchain.contains("clang") && qbs.targetOS.contains("linux"))
|
||||
- flags = flags.concat("-stdlib=libc++ -lcxxrt");
|
||||
+ flags = flags.concat("-lc++abi");
|
||||
return flags;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
И пофиксить сборку библиотеки для Vk:
|
||||
|
||||
```diff
|
||||
diff -ruN qutim.orig/protocols/vkontakte/vreen/vreen.qbs qutim/protocols/vkontakte/vreen/vreen.qbs
|
||||
--- qutim.orig/protocols/vkontakte/vreen/vreen.qbs 2014-01-06 15:41:42.000000000 +0400
|
||||
+++ qutim/protocols/vkontakte/vreen/vreen.qbs 2014-01-06 15:46:47.142178486 +0400
|
||||
@@ -5,6 +5,7 @@
|
||||
property string vreen_qml_path: "bin"
|
||||
property string vreen_lib_path: "lib"
|
||||
property string vreen_libexec_path: "lib"
|
||||
+ property string lib_path: "lib"
|
||||
|
||||
property string vreen_version_major: 1
|
||||
property string vreen_version_minor: 9
|
||||
```
|
||||
|
||||
[qutim-qbs-1.1.patch](/resources/docs/qutim-qt5-git/qutim-qbs-1.1.patch "Файл")
|
||||
|
||||
### <a href="#sources" class="anchor" id="sources"><span class="octicon octicon-link"></span></a>Получаем исходники
|
||||
|
||||
```bash
|
||||
# клонируем репозиторий
|
||||
git clone https://github.com/euroelessar/qutim
|
||||
# кладем файл настроек qbs
|
||||
mkdir -p .config/QtProject
|
||||
cp qbs-qutim.conf .config/QtProject/qbs.conf
|
||||
# создаем директорию сборки
|
||||
mkdir build
|
||||
# обновляем подмодули
|
||||
cd qutim
|
||||
git submodule update --init --recursive
|
||||
# патчим
|
||||
cd ..
|
||||
patch -p0 -i qutim-qbs-1.1.patch
|
||||
```
|
||||
|
||||
## <a href="#build" class="anchor" id="build"><span class="octicon octicon-link"></span></a>Сборка
|
||||
|
||||
```bash
|
||||
cd qutim
|
||||
HOME=$(pwd) qbs -j $(nproc) -d ../build release profile:qutim
|
||||
```
|
||||
|
||||
Я пытался сделать универсальный способ сборки пакета, поэтому такое странное переназначение домашней директории. Флаг `-j` указывает число потоков сборки, флаг `-d` директорию сборки, `release` тип сборки (debug, release), `profile` используемый профиль, описанный в файле настроек.
|
||||
|
||||
## <a href="#install" class="anchor" id="install"><span class="octicon octicon-link"></span></a>Установка
|
||||
|
||||
```bash
|
||||
HOME=$(pwd) sudo qbs install -d ../build --install-root "/usr" profile:qutim
|
||||
```
|
||||
|
||||
Из нового - указание корневого каталога (`--install-root`). Без этого пакет будет установлен в `/` (`/bin` и `/lib`).
|
||||
|
||||
## <a href="#pkgbuild" class="anchor" id="pkgbuild"><span class="octicon octicon-link"></span></a>PKGBUILD
|
||||
|
||||
```bash
|
||||
pkgname=qutim-qt5-git
|
||||
_gitname=qutim
|
||||
pkgver=v0.3.1.967.gc56d61e
|
||||
pkgrel=1
|
||||
pkgdesc="Multiplatform instant messenger (qt5 build). Git version"
|
||||
arch=('i686' 'x86_64')
|
||||
url="http://qutim.org"
|
||||
license=('LGPL' 'GPL3')
|
||||
depends=('jreen-git' 'libc++abi' 'qt5-quick1' 'qt5-x11extras')
|
||||
makedepends=('clang' 'qbs')
|
||||
conflicts=(qutim-0.2_ru-git, qutim-0.3-git, qutim-stable, qutim-git)
|
||||
source=("${_gitname}::git+https://github.com/euroelessar/qutim.git"
|
||||
"qutim-qbs-1.1.patch"
|
||||
"qbs-qutim.conf")
|
||||
md5sums=('SKIP'
|
||||
'12c30176729a5230ff7e6effbb1b37f8'
|
||||
'40f096b269eb00b040035591fce8e259')
|
||||
|
||||
pkgver() {
|
||||
cd "${_gitname}"
|
||||
git describe --always | sed 's|-|.|g'
|
||||
}
|
||||
|
||||
prepare() {
|
||||
# FIXME: dirty hack
|
||||
mkdir -p "${srcdir}/.config/QtProject"
|
||||
cp "${srcdir}/qbs-qutim.conf" "${srcdir}/.config/QtProject/qbs.conf"
|
||||
# create build directory
|
||||
if [[ -d ${srcdir}/build ]]; then
|
||||
rm -rf "${srcdir}/build"
|
||||
fi
|
||||
mkdir "${srcdir}/build"
|
||||
|
||||
cd "${_gitname}"
|
||||
# update modules
|
||||
git submodule update --init --recursive
|
||||
# fix qbs build
|
||||
cd ..
|
||||
patch -p0 -i "${srcdir}/qutim-qbs-1.1.patch"
|
||||
}
|
||||
|
||||
build() {
|
||||
cd "${_gitname}"
|
||||
HOME="${srcdir}" qbs -j $(nproc) -d ../build release profile:qutim
|
||||
}
|
||||
|
||||
package() {
|
||||
cd "${srcdir}/${_gitname}"
|
||||
HOME="${srcdir}" qbs install -d ../build --install-root "${pkgdir}/usr" profile:qutim
|
||||
}
|
||||
```
|
||||
|
||||
[PKGBUILD](/resources/docs/qutim-qt5-git/PKGBUILD "Файл")
|
@ -1,76 +0,0 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: сайт, github pages
|
||||
title: Изменения сайта
|
||||
short: site-changes
|
||||
description: Решил немного поиграться с сайтом. Краткий список изменений ниже.
|
||||
---
|
||||
<h2><a href="#list" class="anchor" id="list"><span class="octicon octicon-link"></span></a>Cписок изменений:</h2>
|
||||
<ul>
|
||||
<li>Арендовал домен <code>arcanis.me</code>. Теперь, как и все белые люди, имею нормальный адрес. Небольшое описание (мне, как человеку далекому от интернет-технологий, пришлось немного попариться на эту тему). Арендуем домен, подключаем услугу редактирования DNS (для Ru-center <a href="//www.nic.ru/dns/service/dns_hosting/" title="Сервис">DNS-master</a>) - суммарно мне обошлось около 1100 рублей/год. Кладем в наш репозиторий с сайтом файл CNAME, содержащий имя желаемого домена. Идем и добавляем две записи в DNS для нашего домена:
|
||||
|
||||
{% highlight bash %}
|
||||
@ A 192.30.252.153
|
||||
@ A 192.30.252.154
|
||||
# перенаправление с www.*
|
||||
www CNAME @
|
||||
{% endhighlight %}
|
||||
|
||||
(<code>@</code> значит наш корневой домен.) Ждем пару часов. Результат можно узнать примерно так:
|
||||
|
||||
{% highlight bash %}
|
||||
$ dig domain.name +nostats +nocomments +nocmd
|
||||
; <<>> DiG 9.9.2-P2 <<>> domain.name +nostats +nocomments +nocmd
|
||||
;; global options: +cmd
|
||||
;domain.name. IN A
|
||||
domain.name. 912 IN A 192.30.252.153
|
||||
domain.name. 912 IN A 192.30.252.154
|
||||
...
|
||||
{% endhighlight %}</li>
|
||||
|
||||
<li>На радостях создал <a href="ftp://repo.arcanis.me/repo" title="Репозиторий">собственный репозиторий</a>, в котором будут лежать некоторые пакеты из AUR, которые я использую. Планируется поддержка обеих архитектур.</li>
|
||||
<li>Поскольку репозиторий требует ftp, то перевел samba на ftp. Проблему доступа решил опциями монтирования:
|
||||
|
||||
{% highlight bash %}
|
||||
# только чтение
|
||||
/home/arcanis/music /srv/ftp/music ext4 defaults,bind,ro 0 0
|
||||
/home/arcanis/arch/repo /srv/ftp/repo ext4 defaults,bind,ro 0 0
|
||||
# чтение и запись (файл ограничен 2 Гб)
|
||||
/home/arcanis/share.fs /srv/ftp/share ext4 defaults,rw 0 0
|
||||
{% endhighlight %}
|
||||
|
||||
Для отсутствия доступа извне к директории с музыкой, используется логин под специальным пользователем и ограничение <code>anon_world_readable_only=YES</code>. Также привожу свой файл настроек <code>/etc/vsftpd.conf</code>:
|
||||
|
||||
{% highlight bash %}
|
||||
anonymous_enable=YES
|
||||
anon_root=/srv/ftp
|
||||
local_enable=YES
|
||||
write_enable=YES
|
||||
local_umask=022
|
||||
anon_upload_enable=YES
|
||||
anon_mkdir_write_enable=YES
|
||||
anon_other_write_enable=YES
|
||||
anon_world_readable_only=YES
|
||||
dirmessage_enable=YES
|
||||
xferlog_enable=YES
|
||||
connect_from_port_20=YES
|
||||
nopriv_user=music
|
||||
ascii_upload_enable=YES
|
||||
ftpd_banner=Welcome to arcanis
|
||||
chroot_local_user=YES
|
||||
local_root=/srv/ftp/music
|
||||
listen=YES
|
||||
{% endhighlight %}
|
||||
|
||||
Теперь добавим переадресацию с <code>repo.arcanis.me</code> на нужный IP адрес. Для этого внесем следующие записи в DNS:
|
||||
|
||||
{% highlight bash %}
|
||||
repo A 89.249.170.38
|
||||
{% endhighlight %}
|
||||
|
||||
</li>
|
||||
<li>В ближайшее время (как дойду до магазина с деньгами) планируется приобретение небольшого сервера для работы на постоянной основе (компиляция пакетов, репозиторий, файлообмен, бэкапы).</li>
|
||||
</ul>
|
77
ru/_posts/2014-03-06-site-changes.md
Normal file
77
ru/_posts/2014-03-06-site-changes.md
Normal file
@ -0,0 +1,77 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: сайт, github pages
|
||||
title: Изменения сайта
|
||||
short: site-changes
|
||||
---
|
||||
Решил немного поиграться с сайтом. Краткий список изменений ниже.
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#list" class="anchor" id="list"><span class="octicon octicon-link"></span></a>Cписок изменений:
|
||||
|
||||
* Арендовал домен `arcanis.me`. Теперь, как и все белые люди, имею нормальный адрес. Небольшое описание (мне, как человеку далекому от интернет-технологий, пришлось немного попариться на эту тему). Арендуем домен, подключаем услугу редактирования DNS (для Ru-center [DNS-master](//www.nic.ru/dns/service/dns_hosting/ "Сервис")) - суммарно мне обошлось около 1100 рублей/год. Кладем в наш репозиторий с сайтом файл CNAME, содержащий имя желаемого домена. Идем и добавляем две записи в DNS для нашего домена:
|
||||
|
||||
```bash
|
||||
@ A 192.30.252.153
|
||||
@ A 192.30.252.154
|
||||
# перенаправление с www.*
|
||||
www CNAME @
|
||||
```
|
||||
|
||||
(`@` значит наш корневой домен.) Ждем пару часов. Результат можно узнать примерно так:
|
||||
|
||||
```bash
|
||||
$ dig domain.name +nostats +nocomments +nocmd
|
||||
; <<>> DiG 9.9.2-P2 <<>> domain.name +nostats +nocomments +nocmd
|
||||
;; global options: +cmd
|
||||
;domain.name. IN A
|
||||
domain.name. 912 IN A 192.30.252.153
|
||||
domain.name. 912 IN A 192.30.252.154
|
||||
...
|
||||
```
|
||||
|
||||
* На радостях создал [собственный репозиторий](ftp://repo.arcanis.me/repo "Репозиторий"), в котором будут лежать некоторые пакеты из AUR, которые я использую. Планируется поддержка обеих архитектур.
|
||||
* Поскольку репозиторий требует ftp, то перевел samba на ftp. Проблему доступа решил опциями монтирования:
|
||||
|
||||
```bash
|
||||
# только чтение
|
||||
/home/arcanis/music /srv/ftp/music ext4 defaults,bind,ro 0 0
|
||||
/home/arcanis/arch/repo /srv/ftp/repo ext4 defaults,bind,ro 0 0
|
||||
# чтение и запись (файл ограничен 2 Гб)
|
||||
/home/arcanis/share.fs /srv/ftp/share ext4 defaults,rw 0 0
|
||||
```
|
||||
|
||||
Для отсутствия доступа извне к директории с музыкой, используется логин под специальным пользователем и ограничение `anon_world_readable_only=YES`. Также привожу свой файл настроек `/etc/vsftpd.conf`:
|
||||
|
||||
```bash
|
||||
anonymous_enable=YES
|
||||
anon_root=/srv/ftp
|
||||
local_enable=YES
|
||||
write_enable=YES
|
||||
local_umask=022
|
||||
anon_upload_enable=YES
|
||||
anon_mkdir_write_enable=YES
|
||||
anon_other_write_enable=YES
|
||||
anon_world_readable_only=YES
|
||||
dirmessage_enable=YES
|
||||
xferlog_enable=YES
|
||||
connect_from_port_20=YES
|
||||
nopriv_user=music
|
||||
ascii_upload_enable=YES
|
||||
ftpd_banner=Welcome to arcanis
|
||||
chroot_local_user=YES
|
||||
local_root=/srv/ftp/music
|
||||
listen=YES
|
||||
```
|
||||
|
||||
Теперь добавим переадресацию с `repo.arcanis.me` на нужный IP адрес. Для этого внесем следующие записи в DNS:
|
||||
|
||||
```bash
|
||||
repo A 89.249.170.38
|
||||
```
|
||||
|
||||
* В ближайшее время (как дойду до магазина с деньгами) планируется приобретение небольшого сервера для работы на постоянной основе (компиляция пакетов, репозиторий, файлообмен, бэкапы).
|
@ -6,19 +6,23 @@ layout: paper
|
||||
tags: archlinux, настройка, linux
|
||||
title: Создание собственного репозитория
|
||||
short: creating-custom-repo
|
||||
description: Небольшая статья, посвященная созданию собственного репозитория для Archlinux.
|
||||
---
|
||||
<h2><a href="#prepare" class="anchor" id="prepare"><span class="octicon octicon-link"></span></a>Подготовка</h2>
|
||||
<p>Для начала находим сервер и желание с ним заниматься сексом. Для простоты, лучше, чтобы там стоял Archlinux, хотя, это и не совсем обязательно (можно создать отдельный корень под Arch). Из пакетов, пожалуй, нам понадобится только два, <code>devtools</code> и сам <code>pacman</code>:</p>
|
||||
Небольшая статья, посвященная созданию собственного репозитория для Archlinux.
|
||||
|
||||
{% highlight bash %}
|
||||
<!--more-->
|
||||
|
||||
## <a href="#prepare" class="anchor" id="prepare"><span class="octicon octicon-link"></span></a>Подготовка
|
||||
|
||||
Для начала находим сервер и желание с ним заниматься сексом. Для простоты, лучше, чтобы там стоял Archlinux, хотя, это и не совсем обязательно (можно создать отдельный корень под Arch). Из пакетов, пожалуй, нам понадобится только два, `devtools` и сам `pacman`:
|
||||
|
||||
```bash
|
||||
pacman -Sy devtools
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p><a href="//www.archlinux.org/packages/devtools/" title="Пакет Archlinux">devtools</a> - набор скриптов, предназначенный для автоматизации сборки пакетов в чистом чруте. Думаю, большинство мейнтейнеров Arch'а пользуются им.</p>
|
||||
<p>Создадим рабочие директории и установим цвета:</p>
|
||||
[devtools](//www.archlinux.org/packages/devtools/ "Пакет Archlinux") - набор скриптов, предназначенный для автоматизации сборки пакетов в чистом чруте. Думаю, большинство мейнтейнеров Arch'а пользуются им.
|
||||
Создадим рабочие директории и установим цвета:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# цвета
|
||||
if [ ${USECOLOR} == "yes" ]; then
|
||||
bblue='\e[1;34m'
|
||||
@ -52,41 +56,42 @@ if [ ! -d "${STAGINGDIR}" ]; then
|
||||
echo -e "${bwhite}[II] ${bblue}Creating directory ${bwhite}'${STAGINGDIR}'${cclose}"
|
||||
mkdir -p "${STAGINGDIR}" || error_mes "unknown"
|
||||
fi
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Директории <code>${REPODIR}/{i686,x86_64}</code> для самого репозитория, <code>${PREPAREDIR}</code> - директория, где будут лежать собранные пакеты, <code>${STAGINGDIR}</code> - директория, откуда будут собираться пакеты.</p>
|
||||
Директории `${REPODIR}/{i686,x86_64}` для самого репозитория, `${PREPAREDIR}` - директория, где будут лежать собранные пакеты, `${STAGINGDIR}` - директория, откуда будут собираться пакеты.
|
||||
|
||||
<h2><a href="#theory" class="anchor" id="theory"><span class="octicon octicon-link"></span></a>Немного теории</h2>
|
||||
<p>Создаем директорию, расшариваем ее (например, по <a href="/ru/2014/03/06/site-changes/" title="Статья про изменения сайта">ftp</a>). В ней две субдиректории - <code>i686</code> и <code>x86_64</code>, для каждого типа архитектур соответственно. И наполняем их набором пакетов по Вашему усмотрению.</p>
|
||||
## <a href="#theory" class="anchor" id="theory"><span class="octicon octicon-link"></span></a>Немного теории
|
||||
|
||||
<p>Процесс обновления репозитория можно разбить на следующие части:</p>
|
||||
<ol>
|
||||
<li>Создание PKGBUILD'ов (обновление их из AUR'а).</li>
|
||||
<li>Сборка пакетов для различных архитектур в чистом чруте.</li>
|
||||
<li>Подписывание пакетов.</li>
|
||||
<li>Создание списка пакетов.</li>
|
||||
<li>Обновление репозиториев:
|
||||
<ol><li>Удаление старых пакетов из репозитория.</li>
|
||||
<li>Копирование новых пакетов.</li>
|
||||
<li>Обновление базы.</li></ol>
|
||||
</li>
|
||||
<li>Очистка.</li>
|
||||
</ol>
|
||||
Создаем директорию, расшариваем ее (например, по [ftp](/ru/2014/03/06/site-changes/ "Статья про изменения сайта")). В ней две субдиректории - `i686` и `x86_64`, для каждого типа архитектур соответственно. И наполняем их набором пакетов по Вашему усмотрению.
|
||||
|
||||
<p>Теперь по шагам.</p>
|
||||
Процесс обновления репозитория можно разбить на следующие части:
|
||||
|
||||
<h3><a href="#pkgbuild" class="anchor" id="pkgbuild"><span class="octicon octicon-link"></span></a>Создание PKGBUILD'ов</h3>
|
||||
<p>Скачаем исходники для всех нужных пакетов из AUR'а:</p>
|
||||
1. Создание PKGBUILD'ов (обновление их из AUR'а).
|
||||
2. Сборка пакетов для различных архитектур в чистом чруте.
|
||||
3. Подписывание пакетов.
|
||||
4. Создание списка пакетов.
|
||||
5. Обновление репозиториев:
|
||||
1. Удаление старых пакетов из репозитория.
|
||||
2. Копирование новых пакетов.
|
||||
3. Обновление базы.
|
||||
6. Очистка.
|
||||
|
||||
{% highlight bash %}
|
||||
Теперь по шагам.
|
||||
|
||||
### <a href="#pkgbuild" class="anchor" id="pkgbuild"><span class="octicon octicon-link"></span></a>Создание PKGBUILD'ов
|
||||
|
||||
Скачаем исходники для всех нужных пакетов из AUR'а:
|
||||
|
||||
```bash
|
||||
cd "${STAGINGDIR}"
|
||||
yaourt -G package-name
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h3><a href="#building" class="anchor" id="building"><span class="octicon octicon-link"></span></a>Сборка пакетов</h3>
|
||||
<p>Автоматически соберем каждый пакет:</p>
|
||||
### <a href="#building" class="anchor" id="building"><span class="octicon octicon-link"></span></a>Сборка пакетов
|
||||
|
||||
{% highlight bash %}
|
||||
Автоматически соберем каждый пакет:
|
||||
|
||||
```bash
|
||||
func_build() {
|
||||
if [ ${USECOLOR} == "yes" ]; then
|
||||
_bblue='\e[1;34m'
|
||||
@ -122,19 +127,19 @@ export -f func_build
|
||||
echo -e "${bwhite}[II]${cclose} Building packages"
|
||||
cd "${STAGINGDIR}"
|
||||
/usr/bin/find -name 'PKGBUILD' -type f -execdir /usr/bin/bash -c "func_build "${PREPAREDIR}" "${ROOTDIR}"" \;
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Для удобства рекомендую добавить в файл <code>/etc/sudoers</code> следующие строки:</p>
|
||||
Для удобства рекомендую добавить в файл `/etc/sudoers` следующие строки:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
username ALL=NOPASSWD: /usr/bin/staging-i686-build
|
||||
username ALL=NOPASSWD: /usr/bin/staging-x86_64-build
|
||||
username ALL=NOPASSWD: /usr/bin/multilib-staging-build
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h3><a href="#signing" class="anchor" id="signing"><span class="octicon octicon-link"></span></a>Подпись пакетов</h3>
|
||||
### <a href="#signing" class="anchor" id="signing"><span class="octicon octicon-link"></span></a>Подпись пакетов
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# подпись
|
||||
if [ ${USEGPG} == "yes" ]; then
|
||||
echo -e "${bwhite}[II]${cclose} Signing"
|
||||
@ -143,34 +148,35 @@ if [ ${USEGPG} == "yes" ]; then
|
||||
/usr/bin/gpg -b ${PACKAGE}
|
||||
done
|
||||
fi
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Для удобства рекомендую настроить <a href="//wiki.archlinux.org/index.php/GPG#gpg-agent" title="ArchWiki">gpg-agent</a>.</p>
|
||||
Для удобства рекомендую настроить [gpg-agent](//wiki.archlinux.org/index.php/GPG#gpg-agent "ArchWiki").
|
||||
|
||||
<h3><a href="#list" class="anchor" id="list"><span class="octicon octicon-link"></span></a>Создание списка пакетов</h3>
|
||||
### <a href="#list" class="anchor" id="list"><span class="octicon octicon-link"></span></a>Создание списка пакетов
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# создание списка пакетов
|
||||
cd "${PREPAREDIR}"
|
||||
i686_PACKAGES=$(/usr/bin/find * -name '*-i686.pkg.tar.xz' -o -name '*-any.pkg.tar.xz')
|
||||
x86_64_PACKAGES=$(/usr/bin/find * -name '*-x86_64.pkg.tar.xz' -o -name '*-any.pkg.tar.xz')
|
||||
echo -e "${bwhite}[II] ${bblue}=>${cclose} i686 packages: \n${bwhite}${i686_PACKAGES}${cclose}"
|
||||
echo -e "${bwhite}[II] ${bblue}=>${cclose} x86_64 packages: \n${bwhite}${x86_64_PACKAGES}${cclose}"
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h3><a href="#updating" class="anchor" id="updating"><span class="octicon octicon-link"></span></a>Обновление репозиториев</h3>
|
||||
<p>Функция для удаления пакетов из базы данных и из репозитория:</p>
|
||||
### <a href="#updating" class="anchor" id="updating"><span class="octicon octicon-link"></span></a>Обновление репозиториев
|
||||
|
||||
{% highlight bash %}
|
||||
Функция для удаления пакетов из базы данных и из репозитория:
|
||||
|
||||
```bash
|
||||
func_remove() {
|
||||
_PACKAGE="$1"
|
||||
/usr/bin/rm -f "${_PACKAGE}"{,.sig}
|
||||
}
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Обновление репозитория <code>i686</code>:</p>
|
||||
Обновление репозитория `i686`:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# обновление репозитория i686
|
||||
echo -e "${bwhite}[II]${cclose} Updating ${bwhite}i686${cclose} repo"
|
||||
cd "${REPODIR}/i686"
|
||||
@ -185,11 +191,11 @@ for PACKAGE in ${i686_PACKAGES}; do
|
||||
/usr/bin/repo-add ${DBNAME}.db.tar.gz "${PACKAGE}"
|
||||
/usr/bin/repo-add --files ${DBNAME}.files.tar.gz "${PACKAGE}"
|
||||
done
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<p>Обновление репозитория <code>x86_64</code>:</p>
|
||||
Обновление репозитория `x86_64`:
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# обновление репозитория x86_64
|
||||
echo -e "${bwhite}[II]${cclose} Updating ${bwhite}x86_64${cclose} repo"
|
||||
cd "${REPODIR}/x86_64"
|
||||
@ -204,22 +210,23 @@ for PACKAGE in ${x86_64_PACKAGES}; do
|
||||
/usr/bin/repo-add ${DBNAME}.db.tar.gz "${PACKAGE}"
|
||||
/usr/bin/repo-add --files ${DBNAME}.files.tar.gz "${PACKAGE}"
|
||||
done
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h3><a href="#clear" class="anchor" id="clear"><span class="octicon octicon-link"></span></a>Очистка</h3>
|
||||
### <a href="#clear" class="anchor" id="clear"><span class="octicon octicon-link"></span></a>Очистка
|
||||
|
||||
{% highlight bash %}
|
||||
```bash
|
||||
# очистка
|
||||
cd "${PREPAREDIR}"
|
||||
/usr/bin/rm -rf *
|
||||
cd "${STAGINGDIR}"
|
||||
/usr/bin/rm -rf *
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h3><a href="#symlinks" class="anchor" id="symlinks"><span class="octicon octicon-link"></span></a>Создание симлинков</h3>
|
||||
<p>Вы можете захотеть создать директорию, которая будет содержать симлинки на актуальные версии пакетов с именами, не содержащими версии:</p>
|
||||
### <a href="#symlinks" class="anchor" id="symlinks"><span class="octicon octicon-link"></span></a>Создание симлинков
|
||||
|
||||
{% highlight bash %}
|
||||
Вы можете захотеть создать директорию, которая будет содержать симлинки на актуальные версии пакетов с именами, не содержащими версии:
|
||||
|
||||
```bash
|
||||
# создание симлинков
|
||||
if [ ${SYMLINK} == "yes" ]; then
|
||||
echo -e "${bwhite}[II]${cclose} Creating symlinks"
|
||||
@ -238,15 +245,17 @@ if [ ${SYMLINK} == "yes" ]; then
|
||||
/usr/bin/ln -sf "../x86_64/${PACKAGE}" "${PKGNAME}-x86_64.pkg.tar.xz"
|
||||
done
|
||||
fi
|
||||
{% endhighlight %}
|
||||
```
|
||||
|
||||
<h3><a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>Файл</h3>
|
||||
<p><a href="//github.com/arcan1s/repo-scripts" title="GitHub">Скрипты</a> целиком. Скачиваем исходники для пакетов, запускаем скрипт (при необходимости, редактируем переменные) и радуемся жизни.</p>
|
||||
### <a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>Файл
|
||||
|
||||
<h2><a href="#using" class="anchor" id="using"><span class="octicon octicon-link"></span></a>Использование репозитория</h2>
|
||||
<p>Просто добавляем в файл <code>/etc/pacman.conf</code> следующие строки:</p>
|
||||
[Скрипты](//github.com/arcan1s/repo-scripts "GitHub") целиком. Скачиваем исходники для пакетов, запускаем скрипт (при необходимости, редактируем переменные) и радуемся жизни.
|
||||
|
||||
{% highlight bash %}
|
||||
## <a href="#using" class="anchor" id="using"><span class="octicon octicon-link"></span></a>Использование репозитория
|
||||
|
||||
Просто добавляем в файл `/etc/pacman.conf` следующие строки:
|
||||
|
||||
```bash
|
||||
[$REPONAME]
|
||||
Server = ftp://$REPOADDRESS/repo/$arch
|
||||
{% endhighlight %}
|
||||
```
|
@ -1,86 +0,0 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: настройка, linux, archlinux
|
||||
title: Приложения, которые я использую
|
||||
short: my-desktop
|
||||
description: Небольшая статья, посвященная набору приложений и расширений, которые я использую в повседневной жизни на моем домашнем компьютере.
|
||||
---
|
||||
<h2><a href="#apps" class="anchor" id="apps"><span class="octicon octicon-link"></span></a>Приложения</h2>
|
||||
<ul>
|
||||
<li><p><b>Shell</b> - zshrc без вариантов. Некоторое описание моих настроек шелла могут быть найдены <a href="/ru/2014/01/14/about-zshrc/" title="Статья о zshrc">тут</a>. Сами настройки хранятся <a href="//raw.githubusercontent.com/arcan1s/dotfiles/master/zshrc" title="Файл" type="text/plain">тут</a> или <a href="//raw.githubusercontent.com/arcan1s/dotfiles/master/zshrc_server" title="Файл" type="text/plain">тут</a>.</p></li>
|
||||
|
||||
<li><p><b>DE</b> - KDE со всеми вытекающими (поэтому набор приложений, преимущественно, Qt-based). Некоторые подробности приготовления KDE будут даны ниже.</p></li>
|
||||
|
||||
<li><p><b>Работа с изображениями</b> - <a href="//kde.org/applications/graphics/gwenview/" title="Домашняя страница Gwenview">gwenview</a> для просмотра и быстрого редактирования, <a href="//kde.org/applications/graphics/kolourpaint/" title="Домашняя страница Kolourpaint">kolourpaint</a> для простого редактирования стандартных форматов пиксельной графики, <a href="//www.gimp.org/" title="Домашняя страница Gimp">gimp</a> (без плагинов, ибо не было необходимости) для более сурового редактирования и <a href="//www.inkscape.org/" title="Домашняя страница Inkskape">inkskape</a> для работы с векторной графикой.</p></li>
|
||||
|
||||
<li><p><b>Браузер</b> - Firefox, ранее Qupzilla, еще ранее Opera. Некоторый набор настроек Firefox будет дан ниже. Дополнительный браузер - Chromium. Консольный - elinks.</p></li>
|
||||
|
||||
<li><p><b>IM клиент</b> - <a href="//qutim.org" title="Домашняя страница Qutim">qutIM</a>. Кроссплатформенный, мультипротокольный, с необходимым набором фич. <a href="//kde.org/applications/internet/kopete/" title="Домашняя страница Kopete">Kopete</a>, который использовался ранее, часто падал, работал как хотел и вообще не дружил с кодировкой. Раньше еще был какой то консольный, но сейчас его нет. Для таких случаев предпочитаю использовать клиент с планшета. Skype для скайпа, очевидно.</p></li>
|
||||
|
||||
<li><p><b>Почтовый клиент</b> - <a href="//kde.org/applications/internet/kmail/" title="Домашняя страница Kmail">kmail</a>. Много фич, большая часть из которых мною используется, симпатично выглядит и удобный. Еще бы был DE-независимый, цены бы ему не было.</p></li>
|
||||
|
||||
<li><p><b>IRC клиент</b> - <a href="//konversation.kde.org/" title="Домашняя страница Konversation">konversation</a>. Самый обычный IRC-клиент. Хотя, если мне не изменяет память, qutIM тоже поддерживает IRC протокол, лично мне удобнее использовать отдельный клиент для этого.</p></li>
|
||||
|
||||
<li><p><b>Torrent клиент</b> - <a href="//www.transmissionbt.com/" title="Домашняя страница Transmission">transmission</a> с Qt5 интерфейсом (gtk тоже имеется). Для сервера он же, но без GUI.</p></li>
|
||||
|
||||
<li><p><b>Видео плеер</b> - <a href="//mpv.io/" title="Домашняя страница mpv">mpv</a>. Mplayer умер, а mplayer2 родился мертворожденным. Ах да, графические надстройки сверху ненужны.</p></li>
|
||||
|
||||
<li><p><b>Аудио плеер</b> - <a href="//qmmp.ylsoftware.com/" title="Домашняя страница Qmmp">qmmp</a>. Хороший, годный плеер с закосом под winamp. Легким движением руки делаем ему человеческий интерфейс aka simpleui.</p></li>
|
||||
|
||||
<li><p><b>Работа с аудио/видео</b> - <a href="//kde-apps.org/content/show.php?content=29024" title="Домашняя страница kdenlive">kdenlive</a> для работы с видео, <a href="//kde-apps.org/content/show.php?content=29024" title="Домашняя страница Soundkonverter">soundkonverter</a> для работы с аудио, <a href="//wiki.gnome.org/Apps/EasyTAG" title="Домашняя страница Easytag">easytag</a> для работы с аудио тегами (gtk, но зато единственный, чья функциональность меня устроила). Ну и командная строка и небольшие скрипты на bash.</p></li>
|
||||
|
||||
<li><p><b>Офис</b> - <a href="//wps-community.org/" title="Домашняя страница KO">Kingsoft Office</a> в качестве замены Microsoft Office; в общем то ничем не примечательный, разве что не так ущербно смотрится, как стандартные офисы, Qt-based и, говорят, с хорошей поддержкой стандартных форматов. Версия под линукс находится в состоянии альфы. <a href="//kile.sourceforge.net/" title="Домашняя страница Kile">Kile</a> в качестве фронтенда к LaTeX. <a href="//kde.org/applications/graphics/okular/" title="Домашняя страница Okular">Okular</a>, как просмотрщик всего. <a href="//goldendict.org/" title="Домашняя страница GoldenDict">GoldenDict</a> в качестве словаря.</p></li>
|
||||
|
||||
<li><p><b>Редакторы</b> - <a href="//www.kde.org/applications/utilities/kwrite/" title="Домашняя страница Kwrite">kwrite</a> в качестве легковесного редактора, <a href="//www.kde.org/applications/utilities/kate/" title="Домашняя страница Kate">kate</a> (с плагином <a href="//zaufi.github.io/kate-cpp-helper-plugin.html" title="Домашняя страница плагина">cpp-helper</a>) для более суровых вещей. Ну и, конечно, vim для консоли.</p></li>
|
||||
|
||||
<li><p><b>Научный софт</b>. Визуализаторы химические - <a href="//www.ks.uiuc.edu/Research/vmd/" title="Домашняя страница VMD">vmd</a>, <a href="//www.cgl.ucsf.edu/chimera/" title="Домашняя страница Chimera">chimera</a> и <a href="//pymol.org/" title="Домашняя страница Pymol">pymol</a>. Физический симулятор <a href="//kde.org/applications/education/step/" title="Домашняя страница Step">step</a>. Калькулятор <a href="//kde.org/applications/education/kalgebra/" title="Домашняя страница Kalgebra">kalgebra</a> и консольный <a href="//ipython.org/" title="Домашняя страница ipython">ipython</a>. Рисовалка графиков и анализ <a href="//qtiplot.com/" title="Домашняя страница Qtiplot">qtiplot</a> (его форк scidavis, к сожалению, полумертв), только рисовалка - <a href="//plasma-gate.weizmann.ac.il/Grace/" title="Домашняя страница Grace">grace</a>. <a href="//ruby.chemie.uni-freiburg.de/~martin/chemtool/chemtool.html" title="Домашняя страница Chemtool">Chemtool</a> в качестве замены ChemDraw.</p></li>
|
||||
|
||||
<li><p><b>Системное</b>. Файловый менеджер <a href="//kde.org/applications/system/dolphin/" title="Домашняя страница Dolphin">dolphin</a>, <a href="//doublecmd.sourceforge.net/" title="Домашняя страница Doublecmd">doublecmd</a> как двухпанельный менеджер. Эмуляторы терминала - <a href="//yakuake.kde.org/" title="Домашняя страница Yakuake">yakuake</a> и <a href="//software.schmorp.de/pkg/rxvt-unicode.html" title="Домашняя страница urxvt">urxvt</a> в качестве оконного. Графический интерфейс для архиваторов <a href="//kde.org/applications/utilities/ark/" title="Домашняя страница Ark">ark</a>.</p></li>
|
||||
</ul>
|
||||
|
||||
|
||||
<h2><a href="#kde" class="anchor" id="kde"><span class="octicon octicon-link"></span></a>Настройка KDE</h2>
|
||||
<div class="thumbnails">
|
||||
{% assign scrdesc = "Нотариально заверенный скриншот" %}
|
||||
{% assign scrname = "kde" %}
|
||||
{% include prj_scr.html %}
|
||||
</div>
|
||||
|
||||
<p>В качестве стиля Qt используется QtCurve, настройки могут быть найдены <a href="//github.com/arcan1s/dotfiles/tree/master/qtcurve" title="GitHub">здесь</a>, оформление окон оттуда же. Курсор <a href="//kde-look.org/content/show.php/Ecliz?content=110340" title="Домашняя страница курсоров">ecliz-small</a>. Тема плазмы <a href="//kde-look.org/content/show.php/Volatile?content=128110" title="Домашняя страница темы">volatile</a>. Значки <a href="//nitrux.in/" title="Домашняя страница Nitrux">compass</a>. Шрифты на базе Liberation.</p>
|
||||
|
||||
<p><b>Используемые виджеты</b> (слева направо, сверху вниз): <a href="//launchpad.net/plasma-widget-menubar" title="Домашняя страница виджета">menubar</a>, <a href="//userbase.kde.org/Homerun" title="Домашняя страница виджета">homerun</a> с прозрачной иконкой, <a href="//kde-apps.org/content/show.php?content=144808" title="Домашняя страница виджета">icontask</a>, <a href="/ru/projects/netctl-gui/" title="Домашняя страница виджета">netctl</a>, стандартный трей от KDE, <a href="//agateau.com/projects/colibri/" title="Домашняя страница виджета">colibri</a> в качестве уведомлений, <a href="/ru/projects/awesome-widgets" title="Домашняя страница виджета">Awesome Widgets</a>.</p>
|
||||
|
||||
<p>В качестве бонусного материала - яркие цвета в консоли (для <a href="//github.com/arcan1s/dotfiles/blob/master/themes/yakuake/My%20color.colorscheme" title="GitHub">konsole</a>):</p>
|
||||
<div class="thumbnails">
|
||||
{% assign scrdesc = "Как оно выглядит" %}
|
||||
{% assign scrname = "zshrc_demo" %}
|
||||
{% include prj_scr.html %}
|
||||
</div>
|
||||
|
||||
|
||||
<h2><a href="#firefox" class="anchor" id="firefox"><span class="octicon octicon-link"></span></a>Настройка Firefox</h2>
|
||||
<p>В самих настройках ничего интересного нет, я просто напишу список аддонов. Дико радует, что для того, чтобы интерфейс был минималистичным (и удобным), нужно поставить кучу плагинов.</p>
|
||||
<ul>
|
||||
<li><p><b>Adblock plus</b> - куда же без него.</p></li>
|
||||
<li><p><b>Add to search bar</b> - для кастомных поисков.</p></li>
|
||||
<li><p><b>Auto Refresh</b> - автоматическое обновление страниц.</p></li>
|
||||
<li><p><b>Clone tab</b> - добавляет функцию "Дублировать вкладку".</p></li>
|
||||
<li><p><b>Close tab by double click</b> - понятно, короче.</p></li>
|
||||
<li><p><b>New scrollbars</b> используется для кастомизации скроллбаров, потому что оригинальные смотрятся ущербно в Qt окружении.</p></li>
|
||||
<li><p><b>NoScript</b> используется, например, для I2P и Tor.</p></li>
|
||||
<li><p><b>PrivateTab</b> - добавляет приватную вкладку (а не окно).</p></li>
|
||||
<li><p><b>Proxy Selector</b> добавляет возможность использовать несколько прокси-серверов.</p></li>
|
||||
<li><p><b>QuickJava</b> используется примерно с той же целью, что и NoScript.</p></li>
|
||||
<li><p><b>RSS иконка в строке адреса</b> - очевидно.</p></li>
|
||||
<li><p><b>Словари для проверки орфографии</b> (eng/rus).</p></li>
|
||||
<li><p><b>Space Next</b> - на нажатие на пробел внизу страницы реагирует, как на нажатие кнопки "Далее".</p></li>
|
||||
<li><p><b>Speed Dial</b> - простая экспресс-панель.</p></li>
|
||||
<li><p><b>Status-4-Evar</b> - нормальная строка состояния.</p></li>
|
||||
<li><p><b>tab delabelifier</b> - сворачивает неиспользуемые вкладки.</p></li>
|
||||
<li><p><b>Tab Scope + Tab Scope Tweaker</b> - всплывающая подсказка у вкладок.</p></li>
|
||||
<li><p><b>accessKey</b> - пока не работает. Вообще служит для удобной навигации (opera-like) с клавиатуры.</p></li>
|
||||
<li><p><b>FXOpera</b> - нормальный минималистичный вид.</p></li>
|
||||
</ul>
|
76
ru/_posts/2014-05-07-my-desktop.md
Normal file
76
ru/_posts/2014-05-07-my-desktop.md
Normal file
@ -0,0 +1,76 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: настройка, linux, archlinux
|
||||
title: Приложения, которые я использую
|
||||
short: my-desktop
|
||||
---
|
||||
Небольшая статья, посвященная набору приложений и расширений, которые я использую в повседневной жизни на моем домашнем компьютере.
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#apps" class="anchor" id="apps"><span class="octicon octicon-link"></span></a>Приложения
|
||||
|
||||
* **Shell** - zshrc без вариантов. Некоторое описание моих настроек шелла могут быть найдены [тут](/ru/2014/01/14/about-zshrc/ "Статья о zshrc"). Сами настройки хранятся [тут](//raw.githubusercontent.com/arcan1s/dotfiles/master/zshrc "Файл") или [тут](//raw.githubusercontent.com/arcan1s/dotfiles/master/zshrc_server "Файл").
|
||||
* **DE** - KDE со всеми вытекающими (поэтому набор приложений, преимущественно, Qt-based). Некоторые подробности приготовления KDE будут даны ниже.
|
||||
* **Работа с изображениями** - [gwenview](//kde.org/applications/graphics/gwenview/ "Домашняя страница Gwenview") для просмотра и быстрого редактирования, [kolourpaint](//kde.org/applications/graphics/kolourpaint/ "Домашняя страница Kolourpaint") для простого редактирования стандартных форматов пиксельной графики, [gimp](//www.gimp.org/ "Домашняя страница Gimp") (без плагинов, ибо не было необходимости) для более сурового редактирования и [inkskape](//www.inkscape.org/ "Домашняя страница Inkskape") для работы с векторной графикой.
|
||||
* **Браузер** - Firefox, ранее Qupzilla, еще ранее Opera. Некоторый набор настроек Firefox будет дан ниже. Дополнительный браузер - Chromium. Консольный - elinks.
|
||||
* **IM клиент** - [qutIM](//qutim.org "Домашняя страница Qutim"). Кроссплатформенный, мультипротокольный, с необходимым набором фич. [Kopete](//kde.org/applications/internet/kopete/ "Домашняя страница Kopete"), который использовался ранее, часто падал, работал как хотел и вообще не дружил с кодировкой. Раньше еще был какой то консольный, но сейчас его нет. Для таких случаев предпочитаю использовать клиент с планшета. Skype для скайпа, очевидно.
|
||||
* **Почтовый клиент** - [kmail](//kde.org/applications/internet/kmail/ "Домашняя страница Kmail"). Много фич, большая часть из которых мною используется, симпатично выглядит и удобный. Еще бы был DE-независимый, цены бы ему не было.
|
||||
* **IRC клиент** - [konversation](//konversation.kde.org/ "Домашняя страница Konversation"). Самый обычный IRC-клиент. Хотя, если мне не изменяет память, qutIM тоже поддерживает IRC протокол, лично мне удобнее использовать отдельный клиент для этого.
|
||||
* **Torrent клиент** - [transmission](//www.transmissionbt.com/ "Домашняя страница Transmission") с Qt5 интерфейсом (gtk тоже имеется). Для сервера он же, но без GUI.
|
||||
* **Видео плеер** - [mpv](//mpv.io/ "Домашняя страница mpv"). Mplayer умер, а mplayer2 родился мертворожденным. Ах да, графические надстройки сверху ненужны.
|
||||
* **Аудио плеер** - [qmmp](//qmmp.ylsoftware.com/ "Домашняя страница Qmmp"). Хороший, годный плеер с закосом под winamp. Легким движением руки делаем ему человеческий интерфейс aka simpleui.
|
||||
* **Работа с аудио/видео** - [kdenlive](//kde-apps.org/content/show.php?content=29024 "Домашняя страница kdenlive") для работы с видео, [soundkonverter](//kde-apps.org/content/show.php?content=29024 "Домашняя страница Soundkonverter") для работы с аудио, [easytag](//wiki.gnome.org/Apps/EasyTAG "Домашняя страница Easytag") для работы с аудио тегами (gtk, но зато единственный, чья функциональность меня устроила). Ну и командная строка и небольшие скрипты на bash.
|
||||
* **Офис** - [Kingsoft Office](//wps-community.org/ "Домашняя страница KO") в качестве замены Microsoft Office; в общем то ничем не примечательный, разве что не так ущербно смотрится, как стандартные офисы, Qt-based и, говорят, с хорошей поддержкой стандартных форматов. Версия под линукс находится в состоянии альфы. [Kile](//kile.sourceforge.net/ "Домашняя страница Kile") в качестве фронтенда к LaTeX. [Okular](//kde.org/applications/graphics/okular/ "Домашняя страница Okular"), как просмотрщик всего. [GoldenDict](//goldendict.org/ "Домашняя страница GoldenDict") в качестве словаря.
|
||||
* **Редакторы** - [kwrite](//www.kde.org/applications/utilities/kwrite/ "Домашняя страница Kwrite") в качестве легковесного редактора, [kate](//www.kde.org/applications/utilities/kate/ "Домашняя страница Kate") (с плагином [cpp-helper](//zaufi.github.io/kate-cpp-helper-plugin.html "Домашняя страница плагина")) для более суровых вещей. Ну и, конечно, vim для консоли.
|
||||
* **Научный софт**. Визуализаторы химические - [vmd](//www.ks.uiuc.edu/Research/vmd/ "Домашняя страница VMD"), [chimera](//www.cgl.ucsf.edu/chimera/ "Домашняя страница Chimera") и [pymol](//pymol.org/ "Домашняя страница Pymol"). Физический симулятор [step](//kde.org/applications/education/step/ "Домашняя страница Step"). Калькулятор [kalgebra](//kde.org/applications/education/kalgebra/ "Домашняя страница Kalgebra") и консольный [ipython](//ipython.org/ "Домашняя страница ipython"). Рисовалка графиков и анализ [qtiplot](//qtiplot.com/ "Домашняя страница Qtiplot") (его форк scidavis, к сожалению, полумертв), только рисовалка - [grace](//plasma-gate.weizmann.ac.il/Grace/ "Домашняя страница Grace"). [Chemtool](//ruby.chemie.uni-freiburg.de/~martin/chemtool/chemtool.html "Домашняя страница Chemtool") в качестве замены ChemDraw.
|
||||
* **Системное**. Файловый менеджер [dolphin](//kde.org/applications/system/dolphin/ "Домашняя страница Dolphin"), [doublecmd](//doublecmd.sourceforge.net/ "Домашняя страница Doublecmd") как двухпанельный менеджер. Эмуляторы терминала - [yakuake](//yakuake.kde.org/ "Домашняя страница Yakuake") и [urxvt](//software.schmorp.de/pkg/rxvt-unicode.html "Домашняя страница urxvt") в качестве оконного. Графический интерфейс для архиваторов [ark](//kde.org/applications/utilities/ark/ "Домашняя страница Ark").
|
||||
|
||||
|
||||
## <a href="#kde" class="anchor" id="kde"><span class="octicon octicon-link"></span></a>Настройка KDE
|
||||
|
||||
<div class="thumbnails">
|
||||
{% assign scrdesc = "Нотариально заверенный скриншот" %}
|
||||
{% assign scrname = "kde" %}
|
||||
{% include prj_scr.html %}
|
||||
</div>
|
||||
|
||||
В качестве стиля Qt используется QtCurve, настройки могут быть найдены [здесь](//github.com/arcan1s/dotfiles/tree/master/qtcurve "GitHub"), оформление окон оттуда же. Курсор [ecliz-small](//kde-look.org/content/show.php/Ecliz?content=110340 "Домашняя страница курсоров"). Тема плазмы [volatile](//kde-look.org/content/show.php/Volatile?content=128110 "Домашняя страница темы"). Значки [compass](//nitrux.in/ "Домашняя страница Nitrux"). Шрифты на базе Liberation.
|
||||
|
||||
**Используемые виджеты** (слева направо, сверху вниз): [menubar](//launchpad.net/plasma-widget-menubar "Домашняя страница виджета"), [homerun](//userbase.kde.org/Homerun "Домашняя страница виджета") с прозрачной иконкой, [icontask](//kde-apps.org/content/show.php?content=144808 "Домашняя страница виджета"), [netctl](/ru/projects/netctl-gui/ "Домашняя страница виджета"), стандартный трей от KDE, [colibri](//agateau.com/projects/colibri/ "Домашняя страница виджета") в качестве уведомлений, [Awesome Widgets](/ru/projects/awesome-widgets "Домашняя страница виджета").
|
||||
|
||||
В качестве бонусного материала - яркие цвета в консоли (для [konsole](//github.com/arcan1s/dotfiles/blob/master/themes/yakuake/My%20color.colorscheme "GitHub")):
|
||||
|
||||
<div class="thumbnails">
|
||||
{% assign scrdesc = "Как оно выглядит" %}
|
||||
{% assign scrname = "zshrc_demo" %}
|
||||
{% include prj_scr.html %}
|
||||
</div>
|
||||
|
||||
|
||||
## <a href="#firefox" class="anchor" id="firefox"><span class="octicon octicon-link"></span></a>Настройка Firefox
|
||||
|
||||
В самих настройках ничего интересного нет, я просто напишу список аддонов. Дико радует, что для того, чтобы интерфейс был минималистичным (и удобным), нужно поставить кучу плагинов.
|
||||
|
||||
* **Adblock plus** - куда же без него.
|
||||
* **Add to search bar** - для кастомных поисков.
|
||||
* **Auto Refresh** - автоматическое обновление страниц.
|
||||
* **Clone tab** - добавляет функцию "Дублировать вкладку".
|
||||
* **Close tab by double click** - понятно, короче.
|
||||
* **New scrollbars** используется для кастомизации скроллбаров, потому что оригинальные смотрятся ущербно в Qt окружении.
|
||||
* **NoScript** используется, например, для I2P и Tor.
|
||||
* **PrivateTab** - добавляет приватную вкладку (а не окно).
|
||||
* **Proxy Selector** добавляет возможность использовать несколько прокси-серверов.
|
||||
* **QuickJava** используется примерно с той же целью, что и NoScript.
|
||||
* **RSS иконка в строке адреса** - очевидно.
|
||||
* **Словари для проверки орфографии** (eng/rus).
|
||||
* **Space Next** - на нажатие на пробел внизу страницы реагирует, как на нажатие кнопки "Далее".
|
||||
* **Speed Dial** - простая экспресс-панель.
|
||||
* **Status-4-Evar** - нормальная строка состояния.
|
||||
* **tab delabelifier** - сворачивает неиспользуемые вкладки.
|
||||
* **Tab Scope + Tab Scope Tweaker** - всплывающая подсказка у вкладок.
|
||||
* **accessKey** - пока не работает. Вообще служит для удобной навигации (opera-like) с клавиатуры.
|
||||
* **FXOpera** - нормальный минималистичный вид.
|
@ -1,39 +0,0 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: linux, archlinux, сборка
|
||||
title: Отключение baloo, gentoo-way
|
||||
short: disabling-baloo
|
||||
description: Пока ононимные онолитеги ЛОР'а ноют на тему baloo, я предпочел потратить 15 минут на то, чтобы отвязать приложения от этого чуда человеческой мысли.
|
||||
---
|
||||
<h2><a href="#disclaimer" class="anchor" id="disclaimer"><span class="octicon octicon-link"></span></a>Дисклеймер</h2>
|
||||
<p>Сам этим я не пользуюсь, поскольку предпочитаю менее деструктивные методы. Однако, судя по всему, все работает без проблем, поскольку жалоб нет. Так как патч делался действительно за несколько минут, то он просто выкорчевывает все вызовы baloo из исходников (возможно, когда-нибудь я сделаю нормальный патч).</p>
|
||||
|
||||
<p>С другой стороны, я настоятельно рекомендую людям, которым по каким-либо причинам baloo не нужен, отключить его из меню настроек (добавили пункт в 4.13.1), либо воспользоваться этой <a href="//blog.andreascarpino.it/disabling-baloo-the-arch-way/" title="Блог Скарпино">статьей</a>.</p>
|
||||
|
||||
<h2><a href="#intro" class="anchor" id="intro"><span class="octicon octicon-link"></span></a>Введение</h2>
|
||||
<p>В Archlinux, на текущий момент (2014-05-18) от baloo, помимо <b>baloo-widgets</b>, зависит <b>gwenview</b> и <b>kdepim</b>. В версии 4.13.0, почему то, <b>kactivities</b> тоже зависел от baloo, однако, эта зависимость не требовалась явно (таким образом, достаточно было просто пересобрать его, удалив baloo из списка зависимостей).</p>
|
||||
|
||||
<h2><a href="#gwenview" class="anchor" id="gwenview"><span class="octicon octicon-link"></span></a>gwenview</h2>
|
||||
<p>Тут все довольно просто. Разработчики сами позаботились за нас о возможных пожеланиях простых пользователей и добавили специальный флаг:</p>
|
||||
|
||||
{% highlight cmake %}
|
||||
//Semantic info backend for Gwenview (Baloo/Fake/None)
|
||||
GWENVIEW_SEMANTICINFO_BACKEND:STRING=Baloo
|
||||
{% endhighlight %}
|
||||
<p>Таким образом, в сценарий сборки к cmake добавляем нужный флаг:</p>
|
||||
{% highlight bash %}
|
||||
cmake ../gwenview-${pkgver} \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DKDE4_BUILD_TESTS=OFF \
|
||||
-DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DGWENVIEW_SEMANTICINFO_BACKEND=None
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#kdepim" class="anchor" id="kdepim"><span class="octicon octicon-link"></span></a>kdepim</h2>
|
||||
<p>Так как делалось все на скорую руку, то я предпочел пробежаться по исходникам с помощью grep и найти все упоминания baloo. Нужные строки (а это указания на baloo в файлах CMakeLists.txt, вызовы функций из его библиотек, объявления заголовочных файлов) просто закомментировал (в исходном коде местами пришлось добавить фейковые вызовы). Патч полностью здесь приводить не буду (он, к тому же, немного большой), а дам <a href="//gist.github.com/arcan1s/b698bb586faef627b3bb" title="Gist">ссылку на него</a> (4.13.3). Далее просто требуется применить этот патч к исходникам и пересобрать kdepim.</p>
|
||||
|
||||
<h2><a href="#packages" class="anchor" id="packages"><span class="octicon octicon-link"></span></a>Пакеты</h2>
|
||||
<p>Все пакеты для Archlinux для обеих архитектур доступны <a href="//wiki.archlinux.org/index.php/Unofficial_user_repositories#arcanisrepo" title="ArchWiki">в моем репозитории</a>.</p>
|
48
ru/_posts/2014-05-18-disabling-baloo.md
Normal file
48
ru/_posts/2014-05-18-disabling-baloo.md
Normal file
@ -0,0 +1,48 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: linux, archlinux, сборка
|
||||
title: Отключение baloo, gentoo-way
|
||||
short: disabling-baloo
|
||||
---
|
||||
Пока ононимные онолитеги ЛОР'а ноют на тему baloo, я предпочел потратить 15 минут на то, чтобы отвязать приложения от этого чуда человеческой мысли.
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#disclaimer" class="anchor" id="disclaimer"><span class="octicon octicon-link"></span></a>Дисклеймер
|
||||
|
||||
Сам этим я не пользуюсь, поскольку предпочитаю менее деструктивные методы. Однако, судя по всему, все работает без проблем, поскольку жалоб нет. Так как патч делался действительно за несколько минут, то он просто выкорчевывает все вызовы baloo из исходников (возможно, когда-нибудь я сделаю нормальный патч).
|
||||
|
||||
С другой стороны, я настоятельно рекомендую людям, которым по каким-либо причинам baloo не нужен, отключить его из меню настроек (добавили пункт в 4.13.1), либо воспользоваться этой [статьей](//blog.andreascarpino.it/disabling-baloo-the-arch-way/ "Блог Скарпино").
|
||||
|
||||
## <a href="#intro" class="anchor" id="intro"><span class="octicon octicon-link"></span></a>Введение
|
||||
|
||||
В Archlinux, на текущий момент (2014-05-18) от baloo, помимо **baloo-widgets**, зависит **gwenview** и **kdepim**. В версии 4.13.0, почему то, **kactivities** тоже зависел от baloo, однако, эта зависимость не требовалась явно (таким образом, достаточно было просто пересобрать его, удалив baloo из списка зависимостей).
|
||||
|
||||
## <a href="#gwenview" class="anchor" id="gwenview"><span class="octicon octicon-link"></span></a>gwenview
|
||||
|
||||
Тут все довольно просто. Разработчики сами позаботились за нас о возможных пожеланиях простых пользователей и добавили специальный флаг:
|
||||
|
||||
```cmake
|
||||
//Semantic info backend for Gwenview (Baloo/Fake/None)
|
||||
GWENVIEW_SEMANTICINFO_BACKEND:STRING=Baloo
|
||||
```
|
||||
Таким образом, в сценарий сборки к cmake добавляем нужный флаг:
|
||||
|
||||
```bash
|
||||
cmake ../gwenview-${pkgver} \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DKDE4_BUILD_TESTS=OFF \
|
||||
-DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DGWENVIEW_SEMANTICINFO_BACKEND=None
|
||||
```
|
||||
|
||||
## <a href="#kdepim" class="anchor" id="kdepim"><span class="octicon octicon-link"></span></a>kdepim
|
||||
|
||||
Так как делалось все на скорую руку, то я предпочел пробежаться по исходникам с помощью grep и найти все упоминания baloo. Нужные строки (а это указания на baloo в файлах CMakeLists.txt, вызовы функций из его библиотек, объявления заголовочных файлов) просто закомментировал (в исходном коде местами пришлось добавить фейковые вызовы). Патч полностью здесь приводить не буду (он, к тому же, немного большой), а дам [ссылку на него](//gist.github.com/arcan1s/b698bb586faef627b3bb "Gist") (4.13.3). Далее просто требуется применить этот патч к исходникам и пересобрать kdepim.
|
||||
|
||||
## <a href="#packages" class="anchor" id="packages"><span class="octicon octicon-link"></span></a>Пакеты
|
||||
|
||||
Все пакеты для Archlinux для обеих архитектур доступны [в моем репозитории](//wiki.archlinux.org/index.php/Unofficial_user_repositories#arcanisrepo "ArchWiki").
|
@ -1,186 +0,0 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: false
|
||||
layout: paper
|
||||
tags: archlinux
|
||||
title: Немного об Arch User Repository
|
||||
short: about-aur
|
||||
description: Статья посвященная работе с пользовательским репозиторием Archlinux. Постарался сделать акцент на сопровождении пакетов. Данная статья, в большей степени, представляет собой компиляцию нескольких англоязычных статей Wiki и немного личного опыта. Поэтому не уверен, что в данной статье на английском языке будет толк.
|
||||
---
|
||||
<h2><a href="#aur" class="anchor" id="aur"><span class="octicon octicon-link"></span></a>AUR</h2>
|
||||
<p>Итак, <a href="//aur.archlinux.org/" title="AUR">Arch User Repository</a> (AUR или АУР) - это репозиторий, поддерживаемый и развиваемый практически исключительно сообществом Archlinux. Есть еще отдельные люди, называемые <a href="//www.archlinux.org/trustedusers/" title="Доверенные пользователи">доверенными пользователями</a> (TU), на плечах которых лежит своеобразная "модерация" этого репозитория. На мой скромный взгляд, едва ли не единственное отличие Archlinux от других дистрибутивов - это наличие AUR'а. Отличие этого репозитория от обычных прежде всего в том, что он <b>не содержит</b> архивов с исходниками или собранных пакетов - только скрипт сборки (PKGBUILD) и, возможно, дополнительные текстовые файлы.</p>
|
||||
|
||||
<p>Конечно, вручную скачивать архив с сайта AUR'а, а также проверять обновления, не совсем удобно, поэтому существует <a href="//wiki.archlinux.org/index.php/AUR_Helpers" title="ArchWiki">набор хелперов</a>. Большинство хелперов представляет собой обертку над pacman. Я выделю только два - <a href="//aur.archlinux.org/packages/packer/" title="AUR">packer</a> - минималистичный, удобный, быстрый - и <a href="//aur.archlinux.org/packages/yaourt/" title="AUR">yaourt</a> - на шелле, но зато более функциональный. По не особо понятным мне причинам, в русскоязычном сегменте большее распространение получил yaourt, зарубежом - packer.</p>
|
||||
|
||||
<p>Помимо хелперов, существуют также консольные клиенты для работы с AUR. Я выделю, пожалуй, только один - <a href="//aur.archlinux.org/packages/python3-aur/" title="AUR">python-aur</a>. Иногда удобная альтернатива веб-интерфейсу.</p>
|
||||
|
||||
<p>Другая особенность данного репозитория - и не менее важная - <b>все действия с ним осуществляются на свой страх и риск</b>. Опасные и некорректные пакеты, конечно же, удаляются, но вполне могут быть и ошибки при сборке и еще все, что сможете придумать. Дык вот - работа с ним на вашей совести, и никто вам ничем не обязан, если что-то сломается. По этой же причине, ни один хелпер в обозримом будущем не будет перенесен в официальные репозитории.</p>
|
||||
|
||||
<p>У пакетов в AUR есть несколько характеристик, которых нет у пакетов в официальных репозиториях:
|
||||
<ul>
|
||||
<li>группа - скорее для удобства поиска, сортировки. Немного помогает доверенным пользователям.</li>
|
||||
<li>автор, мейнтейнер, последний приславший - люди, кто, соответственно, первый раз прислал данный пакет, сопровождает его в настоящий момент, и последний прислал.</li>
|
||||
<li>голоса - когда кому-либо понравился этот пакет или он находит его полезным, он голосует. Теоретически, пакеты, имеющие больше 10 голосов могут попасть в официальные репозитории (если найдется желающий среди доверенных пользователей). Другой путь в официальные репозитории - попасть в <a href="//www.archlinux.de/?page=PackageStatistics" title="Статистика">список часто используемых</a>, но вы же не пользуетесь <a href="//www.archlinux.org/packages/pkgstats" title="Пакет Archlinux">pkgstats</a>.</li>
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
<h2><a href="#install-from-aur" class="anchor" id="install-from-aur"><span class="octicon octicon-link"></span></a>Установка с AUR</h2>
|
||||
<p>Для работы с AUR требуется установить группу пакетов <a href="//www.archlinux.org/groups/x86_64/base-devel/" title="Группа пакетов Archlinux">base-devel</a>. Пакеты с этой группы, как правило, <b>не включены</b> в зависимости. Рекомендуемая установка пакетов с AUR выглядит примерно так:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
# скачать архив с PKGBUILD'ом c AUR
|
||||
curl -L -O //aur.archlinux.org/packages/fo/foo/foo.tar.gz
|
||||
cd foo
|
||||
# отредактировать / проверить PKGBUILD
|
||||
vi PKGBUILD
|
||||
# собрать пакет. Флаг -c удалить директорию сборки,
|
||||
# -s установить недостающие зависимости,
|
||||
# -r удалить их после установки,
|
||||
# -f перезаписать существующий пакет, если он есть
|
||||
makepkg -csrf
|
||||
# установить его
|
||||
pacman -U foo-0.1-1-i686.pkg.tar.xz
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#upload-to-aur" class="anchor" id="upload-to-aur"><span class="octicon octicon-link"></span></a>Загрузка пакета в AUR</h2>
|
||||
<p><b>Никаких</b> <code>makepkg -S</code>. С недавних пор данный метод считается устаревшим. Но обо всем по-порядку</p>
|
||||
|
||||
<p>Нам нужно загрузить архив на сайт. В этом архиве <b>должны быть</b> PKGBUILD и .AURINFO. По поводу первого я расскажу еще чуть ниже, второй генерируется автоматически. Также, там могут быть установочные скрипты (*.install), патчи, файлы лицензии (если не предоставляются апстримом с исходниками), сервисы systemd, скрипты запуска - это то, что обычно включено. <b>Никаких исходников</b>. И тем более <b>никаких бинарников</b>. (Шутки-шутками, а я помню пакет, в котором исходный код записывался с помощью <code>cat << EOF</code> прямо в тексте PKGBUILD'а.)</p>
|
||||
|
||||
<p>Все файлы кладем в одну директорию. Убедились, что install файл, если он есть, указан в переменной install, все другие исходные файлы указаны в массиве source, а хэш-суммы правильные (их легко можно сгенерировать, набрав <code>makepkg -g</code>). Далее из этой директории запустить команду <code>mkaurball</code> (пакет <a href="//www.archlinux.org/packages/pkgbuild-introspection" title="Пакет Archlinux">pkgbuild-introspection</a>) - и архив готов.</p>
|
||||
|
||||
<p>Несколько правил загрузки пакета в AUR:
|
||||
<ul>
|
||||
<li>Если такой пакет существует в официальном репозитории (любой версии), то <b>не нужно</b> заливать новый пакет. Если репозиторный пакет устарел, просто пометьте его, как устаревший. Исключение из этого правила составляют пакеты из системы контрля версий (VCS), о них чуть ниже.</li>
|
||||
<li>Проверьте AUR. Если такой пакет уже существует и у него есть мейнтейнер, вы <b>не сможете залить</b> свой пакет. Если у него нет мейнтейнера, то вы автоматически будете его сопровождающим после обновления. Еще может быть такой же пакет, но с другим названием, будьте внимательны.</li>
|
||||
<li>PKGBUILD должен следовать (более-менее) стандартам и должен быть более-менее аккуратным. В противном случае, пакет может быть удален без предупреждения.</li>
|
||||
<li>Пакет должен быть полезен еще кому-либо кроме Вас =)</li>
|
||||
<li>Рекомендуется проверить <b>собранный пакет и PKGBUILD</b> с помощью <a href="//www.archlinux.org/packages/namcap" title="Пакет Archlinux">namcap</a>. Это не даст 100% гарантии, но на основные ошибки укажет.</li>
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
<h2><a href="#maintaining" class="anchor" id="maintaining"><span class="octicon octicon-link"></span></a>Сопровождение пакетов</h2>
|
||||
<p>Если вы сопровождаете пакет и хотите его обновить, просто загрузите обновленный пакет еще раз. Читайте - и, по возможности, отвечайте - комментарии к вашему пакету, там иногда могут быть очень полезные замечания или дельные предложения. Если вы не хотите сопровождать больше ваш пакет (или нет времени), то, пожалуйста, нажмите на кнопку справа (бросить/disown), чтобы те, кто в нем заинтересован, смогли поддерживать его. Если есть пакет, который не имеет сопровождающего, и вы хотели бы им стать, вы также можете нажать на соответствующую кнопку справа в веб-интерфейсе =)</p>
|
||||
|
||||
<h2><a href="#aur-list" class="anchor" id="aur-list"><span class="octicon octicon-link"></span></a>Список рассылки AUR</h2>
|
||||
<p>По любому вопросу, связанному с работой AUR вы всегда можете обратиться в <a href="//mailman.archlinux.org/mailman/listinfo/aur-general" title="Список рассылки">список рассылки</a> <a href="mailto:aur-general@archlinux.org" title="email">aur-general (at) archlinux (dot) org</a>. На ваш вопрос ответят, вероятно, достаточно быстро; причем, ответить могут не только обычные пользователи, но и доверенные пользователи. Также, если вы вдруг неуверены в своем PKGBUILD'е, вы тоже можете всегда обратиться в список рассылки и показать свой PKGBUILD.</p>
|
||||
|
||||
<p>Существует также отдельный список <a href="//mailman.archlinux.org/mailman/listinfo/aur-requests" title="Список рассылки">рассылки для запросов</a> <a href="mailto:aur-requests@archlinux.org" title="email">aur-requests (at) archlinux (dot) org</a>. На текущий момент (AUR 3.2.0) общение через данный список рассылки напрямую не рекомендуется - все обычные запросы должны отсылаться с использованием веб-интерфейса (<a href="//mailman.archlinux.org/pipermail/aur-general/2014-July/029045.html" title="Тред">подробности</a>). Запросы, которые вы можете послать:
|
||||
<ul>
|
||||
<li><b>Удаление пакета</b>. Запрос должен включать <b>краткое описание причины</b>, почему вы его хотите удалить. Обычные причины - специальный патч, который больше не нужен; пакет уныл и более не поддерживается апстримом; переименование; функциональность предоставляется другим пакетом.</li>
|
||||
<li><b>"Бросить пакет"</b>. Лишить текущего мейнтейнера права сопровождать данный пакет. Официальное требование - вы должны связаться до этого с мейнтейнером по e-mail и <b>ожидать от него ответа в течение двух недель</b> (теперь это делается автоматически при отправке запроса через веб-интерфейс). Однако, если мейнтейнер неактивен в течение длительного времени, или пакет помечен, как устаревший, в течение длительного времени, то можно сделать исключение из этого правила. (Например, если пакет отмечен устаревшим более шести месяцев, то запрос удовлетворяется автоматически.)</li>
|
||||
<li><b>Объединение пакетов</b>. Если пакет подлежит удалению, но имеет голоса (или важные комментарии), то его можно объединить с другим, который предоставляет то же самое. Частный случай - это аналогично переименованию пакета из одного в другой.</li>
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
<p>Пожалуйста, пишите письма в список рассылки аккуратно. И, желательно, вежливо (а то потом будете генерировать что-то вроде <a href="//linux.sytes.net/post/2014/05/aur-driven-by-idiots/" title="Блог">такого</a>) (мы все знаем, что мы арче-школьники, не надо нас еще раз этим тыкать, мы обидимся). Также старайтесь избегать избыточного цитирования. И - это практически требование - предоставляйте ссылки на пакеты. Хороший вариант - составление списка ссылок в конце письма, а в теле ссылаться на них таким образом <code>[1]</code>. Если не уверены в корректности запроса - посмотрите <a href="//mailman.archlinux.org/pipermail/aur-requests/" title="Список рассылки">архив списка рассылки</a>.</p>
|
||||
|
||||
|
||||
<h2><a href="#pkgbuild" class="anchor" id="pkgbuild"><span class="octicon octicon-link"></span></a>PKGBUILD</h2>
|
||||
<p>PKGBUILD - это, де-факто, сценарий шелла, указывающий как и почему (в смысле, зачем) собираться пакету. Он имеет 4 части:
|
||||
<ul>
|
||||
<li><b>Объявление основных переменных</b>. Об этом я расскажу чуть ниже.</li>
|
||||
<li><b>Подготовка исходников</b>. Этот пункт необязательный. Включает в себя копирование (если вдруг нужно), применение патчей, sed и прочие мелочи. Функция обозначается, как <b>prepare()</b>.</li>
|
||||
<li><b>Сборка</b>. Также необязательный пункт. Здесь - и только здесь - должна проводиться компиляция. Функция обозначается, как <b>build()</b>.</li>
|
||||
<li><b>Установка</b>. Обязательный пункт. Здесь происходит копирование нужных файлов в указанный корень (<code>$pkgdir</code>). Функция обозначается, как <b>package()</b> (для совмещенных пакетов таких функций несколько и они называются примерно так: <b>package_$pkgname()</b>).</li>
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
<h3><a href="#pkgbuild-vars" class="anchor" id="pkgbuild-vars"><span class="octicon octicon-link"></span></a>Переменные PKGBUILD</h3>
|
||||
<p>Основные переменные следующие:
|
||||
<ul>
|
||||
<li><b>pkgbase</b> - группа пакетов. Например, пакеты <code>python-pyqt4</code> и <code>python2-pyqt4</code> имеют одну группу <code>pyqt4</code>.</li>
|
||||
<li><b>pkgname</b> - имя (или массив имен для совмещенных пакетов) пакета; обязательная переменная.</li>
|
||||
<li><b>pkgver</b> - версия пакета, указанная в апстриме, <b>pkgrel</b> - арче-специфичный релиз пакета.</li>
|
||||
<li><b>pkgdesc</b> - краткое описание пакета.</li>
|
||||
<li><b>arch</b> - массив архитектур. Как правило, <code>arch=('i686' 'x86_64')</code> для бинарных пакетов (очень-очень редко бывают пакеты, которые предоставляются только для одной архитектуры) и <code>arch=('any')</code> для пакетов, не содержащих бинарные файлы.</li>
|
||||
<li><b>url</b> - адрес апстрима.</li>
|
||||
<li><b>license</b> - лицензия. Если лицензия отлична от обычных (распространенные типы MIT, BSD и custom) - смотри пакет <a href="//www.archlinux.org/packages/core/any/licenses/" title="Пакет Archlinux">core/licenses</a> - то ее надо установить вместе с пакетом по пути <code>/usr/share/licenses/$pkgname/LICENSE</code>).</li>
|
||||
<li><b>depends</b> - массив зависимостей, <b>необходимых для работы</b> пакета. <b>optdepends</b> - это <b>дополнительные зависимости</b>, которые не необходимы для работы, но предоставляют дополнительную функциональность. <b>makedepends</b> - это зависимости, которые не включены в <b>depends</b>, но <b>необходимы при сборке</b> пакета.<br>
|
||||
Лучший способ проверить, правильно ли указаны зависимости сборки (зачастую, это самое важное) - попробуйте собрать пакет в чистом окружении (то есть совсем совсем чистом). И да, зависимости из группы <a href="//www.archlinux.org/groups/x86_64/base-devel/" title="Группа пакетов Archlinux">base-devel</a> указывать не надо.</li>
|
||||
<li>Следующие три переменные необязательны. <b>provides</b> - список пакетов, функциональность которых предоставляет данный пакет. <b>replaces</b> - список пакетов, которые данный пакет замещает (обычно используется для решения проблем с переименованием пакетов при обновлении). <b>conflicts</b> - список пакетов, с которым конфликтует данный пакет (имеет такие же файлы).<br>
|
||||
Пример различия <b>provides</b> и <b>replaces</b> - <a href="//www.archlinux.org/packages/gvim/" title="Пакет Archlinux">gvim</a> предоставляет <a href="//www.archlinux.org/packages/vim/" title="Пакет Archlinux">vim</a>, а <a href="//www.archlinux.org/packages/wireshark-gtk/" title="Пакет Archlinux">wireshark-gtk</a> замещает wireshark.</li>
|
||||
<li><b>install</b> - файл, содержащий сценарии, запускающиеся после установки/удаления/обновления (смотрите файл <code>/usr/share/pacman/proto.install</code>).</li>
|
||||
<li><b>source</b> - где брать исходники, файлы предоставляемые вместе с пакетом указываются только по имени, к данному массиму также прилагается массив хэш сумм (md5sums/sha1sums/sha256sums/sha384sums/sha512sums).</li>
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
<p>Все перечисленные выше переменные указываются в заголовке PKGBUILD. К ним также можно обращаться внутри PKGBUILD'а. Дополнительно стоит упомянуть переменные <b>startdir</b> - директория, откуда запускается makepkg, <b>srcdir</b> - директория с исходниками (<code>$startdir/src</code> по умолчанию), <b>pkgdir</b> - директория с собранным пакетом (<code>$startdir/pkg/$pkgname</code> по умолчанию). <b>Не используйте</b> переменную <b>startdir</b> без крайней необходимости.</p>
|
||||
|
||||
<h3><a href="#pkgbuild-features" class="anchor" id="pkgbuild-features"><span class="octicon octicon-link"></span></a>Некоторые особенности PKGBUILD'ов</h3>
|
||||
<p>К PKGBUILD применимы все правила программирования на шелле. Например, "смешная шутка":
|
||||
|
||||
{% highlight bash %}
|
||||
pkgdir="/usr pkg"
|
||||
rm -rf $pkgdir
|
||||
{% endhighlight %}
|
||||
|
||||
кому-то может показаться не очень смешной, увы. Поэтому все пути (да и вообще переменные - там где надо, конечно) лучше обрамлять в двойные кавычки (исключение - условия в двойных квадратных скобках <code>[[ ... ]]</code>). Если вы вводите какие-либо свои переменные, то настоятельно рекоммендуется добавить в начале подчеркивание <code>_</code> во избежание перекрытия переменными makepkg.</p>
|
||||
|
||||
<p>В русскоязычном сегменте до сих пор зачастую встречаются строки типа <code>make || return 1</code>. Дык вот, <code>return 1</code> теперь уже давно как не нужен.</p>
|
||||
|
||||
<p>Еще можно работать с рядом других переменных, определенных makepkg. Их список можно глянуть в <code>/etc/makepkg.conf</code>. Самые ходовые - флаги компиляции и <code>CARCH</code>. Так, например, если вы собираете пакет, исходники к которому предоставляются в бинарном виде (проприетарный драйвер, например), то кусок PKGBUILD может выглядеть так:
|
||||
|
||||
{% highlight bash %}
|
||||
if [ "${CARCH}" == "x86_64" ]; then
|
||||
_filearch=amd64
|
||||
md5sums=('1f58521c2ddb9195a26a0bb3713a52a6')
|
||||
else
|
||||
_filearch=i386
|
||||
md5sums=('ef5a8809b6bff8c9bcf5a28e860a606b')
|
||||
fi
|
||||
source=(${pkgname}-${pkgver}.tar.gz:://istodo.ru/distribs/${pkgname}-linux-${pkgver}-${_filearch}.tar.gz)
|
||||
{% endhighlight %}
|
||||
|
||||
</p>
|
||||
|
||||
<p><b>pkgbase</b> вообще удобная штука. Например, для создания пакетов одновременно для двух версий Python PKGBUILD может выглядеть <a href="//projects.archlinux.org/svntogit/community.git/tree/trunk/PKGBUILD?h=packages/python-biopython" title="Archlinux svn">примерно так</a>. Или, в общем случае, <a href="//aur.archlinux.org/packages/ne/netctl-gui/PKGBUILD" title="AUR">как-то так</a>.</p>
|
||||
|
||||
<p>Вообще говоря, для стандартных случаев существуют прототипы PKGBUILD'ов. Их можно найти в <code>/usr/share/pacman/</code>, хотя местами они могли немного устареть (больше года как). Так, прототипы для пакетов из системы контроля версий (git/svn/hg/bzr) однозначно устарели - сейчас используется другой, куда более аккуратный, формат. Настоятельно рекомендую ознакомиться на эту тему <a href="//wiki.archlinux.org/index.php/VCS_PKGBUILD_Guidelines" title="ArchWiki">с данной статьей</a>. Например, для пакета <b>qmmp-qsmmp-git</b> кусок PKGBUILD'а выглядит так:
|
||||
|
||||
{% highlight bash %}
|
||||
pkgname=qmmp-qsmmp-git
|
||||
_gitname=qsmmp
|
||||
pkgver=0.5.34.gcd1ca1a
|
||||
# еще какие-то строки
|
||||
makedepends=('git')
|
||||
source=(${_gitname}::git+//gitorious.org/qsmmp/qsmmp.git#branch=qmmp-9999)
|
||||
md5sums=('SKIP')
|
||||
pkgver() {
|
||||
cd "${_gitname}"
|
||||
local ver=`git describe --long`
|
||||
printf "%s" "${${ver//-/.}//qmmp./}"
|
||||
}
|
||||
{% endhighlight %}
|
||||
|
||||
А для пакета <b>kdeplasma-applets-stdin-svn</b> так:
|
||||
|
||||
{% highlight bash %}
|
||||
pkgname=kdeplasma-applets-stdin-svn
|
||||
pkgver=57
|
||||
pkgrel=1
|
||||
_pkgname=plasmoidstdin
|
||||
_pkgver=0.2
|
||||
# еще какие-то строки
|
||||
makedepends=('automoc4' 'cmake' 'subversion')
|
||||
source=(${_pkgname}::svn+//plasmoidstdin.svn.sourceforge.net/svnroot/${_pkgname}/${_pkgver}/trunk)
|
||||
md5sums=('SKIP')
|
||||
pkgver() {
|
||||
cd "${srcdir}/${_pkgname}"
|
||||
local ver=`svnversion`
|
||||
printf "%s" "${ver//[[:alpha:]]}"
|
||||
}
|
||||
{% endhighlight %}
|
||||
|
||||
Также, я отмечу, что некоторые пакеты имеют свой устоявшийся формат, поэтому, зачастую, полезно поискать что-то похожее в AUR и сделать свой PKGBUILD по образу и подобию.
|
||||
</p>
|
||||
|
||||
<h2><a href="#links" class="anchor" id="links"><span class="octicon octicon-link"></span></a>Дополнительные ссылки</h2>
|
||||
<ul>
|
||||
<li><a href="//pkgbuild.com/git/aur-mirror.git/" title="Зеркало">Зеркало (git)</a></li>
|
||||
<li><a href="//wiki.archlinux.org/index.php/AUR" title="ArchWiki">ArchWiki про AUR</a></li>
|
||||
<li><a href="//wiki.archlinux.org/index.php/PKGBUILD" title="ArchWiki">ArchWiki про PKGBUILD</a></li>
|
||||
<li><a href="//wiki.archlinux.org/index.php/Makepkg" title="ArchWiki">ArchWiki про makepkg</a></li>
|
||||
<li><a href="//wiki.archlinux.org/index.php/Arch_packaging_standards" title="ArchWiki">ArchWiki немного про стандарты</a> (внизу есть весьма полезные ссылки на гайды для конкретных типов пакетов)</li>
|
||||
</ul>
|
185
ru/_posts/2014-06-23-about-aur.md
Normal file
185
ru/_posts/2014-06-23-about-aur.md
Normal file
@ -0,0 +1,185 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: false
|
||||
layout: paper
|
||||
tags: archlinux
|
||||
title: Немного об Arch User Repository
|
||||
short: about-aur
|
||||
---
|
||||
Статья посвященная работе с пользовательским репозиторием Archlinux. Постарался сделать акцент на сопровождении пакетов. Данная статья, в большей степени, представляет собой компиляцию нескольких англоязычных статей Wiki и немного личного опыта. Поэтому не уверен, что в данной статье на английском языке будет толк.
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#aur" class="anchor" id="aur"><span class="octicon octicon-link"></span></a>AUR
|
||||
|
||||
Итак, [Arch User Repository](//aur.archlinux.org/ "AUR") (AUR или АУР) - это репозиторий, поддерживаемый и развиваемый практически исключительно сообществом Archlinux. Есть еще отдельные люди, называемые [доверенными пользователями](//www.archlinux.org/trustedusers/ "Доверенные пользователи") (TU), на плечах которых лежит своеобразная "модерация" этого репозитория. На мой скромный взгляд, едва ли не единственное отличие Archlinux от других дистрибутивов - это наличие AUR'а. Отличие этого репозитория от обычных прежде всего в том, что он **не содержит** архивов с исходниками или собранных пакетов - только скрипт сборки (PKGBUILD) и, возможно, дополнительные текстовые файлы.
|
||||
|
||||
Конечно, вручную скачивать архив с сайта AUR'а, а также проверять обновления, не совсем удобно, поэтому существует [набор хелперов](//wiki.archlinux.org/index.php/AUR_Helpers "ArchWiki"). Большинство хелперов представляет собой обертку над pacman. Я выделю только два - [packer](//aur.archlinux.org/packages/packer/ "AUR") - минималистичный, удобный, быстрый - и [yaourt](//aur.archlinux.org/packages/yaourt/ "AUR") - на шелле, но зато более функциональный. По не особо понятным мне причинам, в русскоязычном сегменте большее распространение получил yaourt, зарубежом - packer.
|
||||
|
||||
Помимо хелперов, существуют также консольные клиенты для работы с AUR. Я выделю, пожалуй, только один - [python-aur](//aur.archlinux.org/packages/python3-aur/ "AUR"). Иногда удобная альтернатива веб-интерфейсу.
|
||||
|
||||
Другая особенность данного репозитория - и не менее важная - **все действия с ним осуществляются на свой страх и риск**. Опасные и некорректные пакеты, конечно же, удаляются, но вполне могут быть и ошибки при сборке и еще все, что сможете придумать. Дык вот - работа с ним на вашей совести, и никто вам ничем не обязан, если что-то сломается. По этой же причине, ни один хелпер в обозримом будущем не будет перенесен в официальные репозитории.
|
||||
|
||||
У пакетов в AUR есть несколько характеристик, которых нет у пакетов в официальных репозиториях:
|
||||
|
||||
* группа - скорее для удобства поиска, сортировки. Немного помогает доверенным пользователям.
|
||||
* автор, мейнтейнер, последний приславший - люди, кто, соответственно, первый раз прислал данный пакет, сопровождает его в настоящий момент, и последний прислал.
|
||||
* голоса - когда кому-либо понравился этот пакет или он находит его полезным, он голосует. Теоретически, пакеты, имеющие больше 10 голосов могут попасть в официальные репозитории (если найдется желающий среди доверенных пользователей). Другой путь в официальные репозитории - попасть в [список часто используемых](//www.archlinux.de/?page=PackageStatistics "Статистика"), но вы же не пользуетесь [pkgstats](//www.archlinux.org/packages/pkgstats "Пакет Archlinux").
|
||||
|
||||
|
||||
## <a href="#install-from-aur" class="anchor" id="install-from-aur"><span class="octicon octicon-link"></span></a>Установка с AUR
|
||||
|
||||
Для работы с AUR требуется установить группу пакетов [base-devel](//www.archlinux.org/groups/x86_64/base-devel/ "Группа пакетов Archlinux"). Пакеты с этой группы, как правило, **не включены** в зависимости. Рекомендуемая установка пакетов с AUR выглядит примерно так:
|
||||
|
||||
```bash
|
||||
# скачать архив с PKGBUILD'ом c AUR
|
||||
curl -L -O //aur.archlinux.org/packages/fo/foo/foo.tar.gz
|
||||
cd foo
|
||||
# отредактировать / проверить PKGBUILD
|
||||
vi PKGBUILD
|
||||
# собрать пакет. Флаг -c удалить директорию сборки,
|
||||
# -s установить недостающие зависимости,
|
||||
# -r удалить их после установки,
|
||||
# -f перезаписать существующий пакет, если он есть
|
||||
makepkg -csrf
|
||||
# установить его
|
||||
pacman -U foo-0.1-1-i686.pkg.tar.xz
|
||||
```
|
||||
|
||||
## <a href="#upload-to-aur" class="anchor" id="upload-to-aur"><span class="octicon octicon-link"></span></a>Загрузка пакета в AUR
|
||||
|
||||
**Никаких** `makepkg -S`. С недавних пор данный метод считается устаревшим. Но обо всем по-порядку
|
||||
|
||||
Нам нужно загрузить архив на сайт. В этом архиве **должны быть** PKGBUILD и .AURINFO. По поводу первого я расскажу еще чуть ниже, второй генерируется автоматически. Также, там могут быть установочные скрипты (*.install), патчи, файлы лицензии (если не предоставляются апстримом с исходниками), сервисы systemd, скрипты запуска - это то, что обычно включено. **Никаких исходников**. И тем более **никаких бинарников**. (Шутки-шутками, а я помню пакет, в котором исходный код записывался с помощью `cat << EOF` прямо в тексте PKGBUILD'а.)
|
||||
|
||||
Все файлы кладем в одну директорию. Убедились, что install файл, если он есть, указан в переменной install, все другие исходные файлы указаны в массиве source, а хэш-суммы правильные (их легко можно сгенерировать, набрав `makepkg -g`). Далее из этой директории запустить команду `mkaurball` (пакет [pkgbuild-introspection](//www.archlinux.org/packages/pkgbuild-introspection "Пакет Archlinux")) - и архив готов.
|
||||
|
||||
Несколько правил загрузки пакета в AUR:
|
||||
|
||||
* Если такой пакет существует в официальном репозитории (любой версии), то **не нужно** заливать новый пакет. Если репозиторный пакет устарел, просто пометьте его, как устаревший. Исключение из этого правила составляют пакеты из системы контрля версий (VCS), о них чуть ниже.
|
||||
* Проверьте AUR. Если такой пакет уже существует и у него есть мейнтейнер, вы **не сможете залить** свой пакет. Если у него нет мейнтейнера, то вы автоматически будете его сопровождающим после обновления. Еще может быть такой же пакет, но с другим названием, будьте внимательны.
|
||||
* PKGBUILD должен следовать (более-менее) стандартам и должен быть более-менее аккуратным. В противном случае, пакет может быть удален без предупреждения.
|
||||
* Пакет должен быть полезен еще кому-либо кроме Вас =)
|
||||
* Рекомендуется проверить **собранный пакет и PKGBUILD** с помощью [namcap](//www.archlinux.org/packages/namcap "Пакет Archlinux"). Это не даст 100% гарантии, но на основные ошибки укажет.
|
||||
|
||||
|
||||
## <a href="#maintaining" class="anchor" id="maintaining"><span class="octicon octicon-link"></span></a>Сопровождение пакетов
|
||||
|
||||
Если вы сопровождаете пакет и хотите его обновить, просто загрузите обновленный пакет еще раз. Читайте - и, по возможности, отвечайте - комментарии к вашему пакету, там иногда могут быть очень полезные замечания или дельные предложения. Если вы не хотите сопровождать больше ваш пакет (или нет времени), то, пожалуйста, нажмите на кнопку справа (бросить/disown), чтобы те, кто в нем заинтересован, смогли поддерживать его. Если есть пакет, который не имеет сопровождающего, и вы хотели бы им стать, вы также можете нажать на соответствующую кнопку справа в веб-интерфейсе =)
|
||||
|
||||
## <a href="#aur-list" class="anchor" id="aur-list"><span class="octicon octicon-link"></span></a>Список рассылки AUR
|
||||
|
||||
По любому вопросу, связанному с работой AUR вы всегда можете обратиться в [список рассылки](//mailman.archlinux.org/mailman/listinfo/aur-general "Список рассылки") [aur-general (at) archlinux (dot) org](mailto:aur-general@archlinux.org "email"). На ваш вопрос ответят, вероятно, достаточно быстро; причем, ответить могут не только обычные пользователи, но и доверенные пользователи. Также, если вы вдруг неуверены в своем PKGBUILD'е, вы тоже можете всегда обратиться в список рассылки и показать свой PKGBUILD.
|
||||
|
||||
Существует также отдельный список [рассылки для запросов](//mailman.archlinux.org/mailman/listinfo/aur-requests "Список рассылки") [aur-requests (at) archlinux (dot) org](mailto:aur-requests@archlinux.org "email"). На текущий момент (AUR 3.2.0) общение через данный список рассылки напрямую не рекомендуется - все обычные запросы должны отсылаться с использованием веб-интерфейса ([подробности](//mailman.archlinux.org/pipermail/aur-general/2014-July/029045.html "Тред")). Запросы, которые вы можете послать:
|
||||
|
||||
* **Удаление пакета**. Запрос должен включать **краткое описание причины**, почему вы его хотите удалить. Обычные причины - специальный патч, который больше не нужен; пакет уныл и более не поддерживается апстримом; переименование; функциональность предоставляется другим пакетом.
|
||||
* **"Бросить пакет"**. Лишить текущего мейнтейнера права сопровождать данный пакет. Официальное требование - вы должны связаться до этого с мейнтейнером по e-mail и **ожидать от него ответа в течение двух недель** (теперь это делается автоматически при отправке запроса через веб-интерфейс). Однако, если мейнтейнер неактивен в течение длительного времени, или пакет помечен, как устаревший, в течение длительного времени, то можно сделать исключение из этого правила. (Например, если пакет отмечен устаревшим более шести месяцев, то запрос удовлетворяется автоматически.)
|
||||
* **Объединение пакетов**. Если пакет подлежит удалению, но имеет голоса (или важные комментарии), то его можно объединить с другим, который предоставляет то же самое. Частный случай - это аналогично переименованию пакета из одного в другой.
|
||||
|
||||
|
||||
Пожалуйста, пишите письма в список рассылки аккуратно. И, желательно, вежливо (а то потом будете генерировать что-то вроде [такого](//linux.sytes.net/post/2014/05/aur-driven-by-idiots/ "Блог")) (мы все знаем, что мы арче-школьники, не надо нас еще раз этим тыкать, мы обидимся). Также старайтесь избегать избыточного цитирования. И - это практически требование - предоставляйте ссылки на пакеты. Хороший вариант - составление списка ссылок в конце письма, а в теле ссылаться на них таким образом `[1]`. Если не уверены в корректности запроса - посмотрите [архив списка рассылки](//mailman.archlinux.org/pipermail/aur-requests/ "Список рассылки").
|
||||
|
||||
|
||||
## <a href="#pkgbuild" class="anchor" id="pkgbuild"><span class="octicon octicon-link"></span></a>PKGBUILD
|
||||
|
||||
PKGBUILD - это, де-факто, сценарий шелла, указывающий как и почему (в смысле, зачем) собираться пакету. Он имеет 4 части:
|
||||
|
||||
* **Объявление основных переменных**. Об этом я расскажу чуть ниже.
|
||||
* **Подготовка исходников**. Этот пункт необязательный. Включает в себя копирование (если вдруг нужно), применение патчей, sed и прочие мелочи. Функция обозначается, как **prepare()**.
|
||||
* **Сборка**. Также необязательный пункт. Здесь - и только здесь - должна проводиться компиляция. Функция обозначается, как **build()**.
|
||||
* **Установка**. Обязательный пункт. Здесь происходит копирование нужных файлов в указанный корень (`$pkgdir`). Функция обозначается, как **package()** (для совмещенных пакетов таких функций несколько и они называются примерно так: **package_$pkgname()**).
|
||||
|
||||
### <a href="#pkgbuild-vars" class="anchor" id="pkgbuild-vars"><span class="octicon octicon-link"></span></a>Переменные PKGBUILD
|
||||
|
||||
Основные переменные следующие:
|
||||
|
||||
* **pkgbase** - группа пакетов. Например, пакеты `python-pyqt4` и `python2-pyqt4` имеют одну группу `pyqt4`.
|
||||
* **pkgname** - имя (или массив имен для совмещенных пакетов) пакета; обязательная переменная.
|
||||
* **pkgver** - версия пакета, указанная в апстриме, **pkgrel** - арче-специфичный релиз пакета.
|
||||
* **pkgdesc** - краткое описание пакета.
|
||||
* **arch** - массив архитектур. Как правило, `arch=('i686' 'x86_64')` для бинарных пакетов (очень-очень редко бывают пакеты, которые предоставляются только для одной архитектуры) и `arch=('any')` для пакетов, не содержащих бинарные файлы.
|
||||
* **url** - адрес апстрима.
|
||||
* **license** - лицензия. Если лицензия отлична от обычных (распространенные типы MIT, BSD и custom) - смотри пакет [core/licenses](//www.archlinux.org/packages/core/any/licenses/ "Пакет Archlinux") - то ее надо установить вместе с пакетом по пути `/usr/share/licenses/$pkgname/LICENSE`).
|
||||
* **depends** - массив зависимостей, **необходимых для работы** пакета. **optdepends** - это **дополнительные зависимости**, которые не необходимы для работы, но предоставляют дополнительную функциональность. **makedepends** - это зависимости, которые не включены в **depends**, но **необходимы при сборке** пакета. Лучший способ проверить, правильно ли указаны зависимости сборки (зачастую, это самое важное) - попробуйте собрать пакет в чистом окружении (то есть совсем совсем чистом). И да, зависимости из группы [base-devel](//www.archlinux.org/groups/x86_64/base-devel/ "Группа пакетов Archlinux") указывать не надо.
|
||||
* Следующие три переменные необязательны. **provides** - список пакетов, функциональность которых предоставляет данный пакет. **replaces** - список пакетов, которые данный пакет замещает (обычно используется для решения проблем с переименованием пакетов при обновлении). **conflicts** - список пакетов, с которым конфликтует данный пакет (имеет такие же файлы). Пример различия **provides** и **replaces** - [gvim](//www.archlinux.org/packages/gvim/ "Пакет Archlinux") предоставляет [vim](//www.archlinux.org/packages/vim/ "Пакет Archlinux"), а [wireshark-gtk](//www.archlinux.org/packages/wireshark-gtk/ "Пакет Archlinux") замещает wireshark.
|
||||
* **install** - файл, содержащий сценарии, запускающиеся после установки/удаления/обновления (смотрите файл `/usr/share/pacman/proto.install`).
|
||||
* **source** - где брать исходники, файлы предоставляемые вместе с пакетом указываются только по имени, к данному массиму также прилагается массив хэш сумм (md5sums/sha1sums/sha256sums/sha384sums/sha512sums).
|
||||
|
||||
Все перечисленные выше переменные указываются в заголовке PKGBUILD. К ним также можно обращаться внутри PKGBUILD'а. Дополнительно стоит упомянуть переменные **startdir** - директория, откуда запускается makepkg, **srcdir** - директория с исходниками (`$startdir/src` по умолчанию), **pkgdir** - директория с собранным пакетом (`$startdir/pkg/$pkgname` по умолчанию). **Не используйте** переменную **startdir** без крайней необходимости.
|
||||
|
||||
### <a href="#pkgbuild-features" class="anchor" id="pkgbuild-features"><span class="octicon octicon-link"></span></a>Некоторые особенности PKGBUILD'ов
|
||||
|
||||
К PKGBUILD применимы все правила программирования на шелле. Например, "смешная шутка":
|
||||
|
||||
```bash
|
||||
pkgdir="/usr pkg"
|
||||
rm -rf $pkgdir
|
||||
```
|
||||
|
||||
кому-то может показаться не очень смешной, увы. Поэтому все пути (да и вообще переменные - там где надо, конечно) лучше обрамлять в двойные кавычки (исключение - условия в двойных квадратных скобках `[[ ... ]]`). Если вы вводите какие-либо свои переменные, то настоятельно рекоммендуется добавить в начале подчеркивание `_` во избежание перекрытия переменными makepkg.
|
||||
|
||||
В русскоязычном сегменте до сих пор зачастую встречаются строки типа `make || return 1`. Дык вот, `return 1` теперь уже давно как не нужен.
|
||||
|
||||
Еще можно работать с рядом других переменных, определенных makepkg. Их список можно глянуть в `/etc/makepkg.conf`. Самые ходовые - флаги компиляции и `CARCH`. Так, например, если вы собираете пакет, исходники к которому предоставляются в бинарном виде (проприетарный драйвер, например), то кусок PKGBUILD может выглядеть так:
|
||||
|
||||
```bash
|
||||
if [ "${CARCH}" == "x86_64" ]; then
|
||||
_filearch=amd64
|
||||
md5sums=('1f58521c2ddb9195a26a0bb3713a52a6')
|
||||
else
|
||||
_filearch=i386
|
||||
md5sums=('ef5a8809b6bff8c9bcf5a28e860a606b')
|
||||
fi
|
||||
source=(${pkgname}-${pkgver}.tar.gz:://istodo.ru/distribs/${pkgname}-linux-${pkgver}-${_filearch}.tar.gz)
|
||||
```
|
||||
|
||||
**pkgbase** вообще удобная штука. Например, для создания пакетов одновременно для двух версий Python PKGBUILD может выглядеть [примерно так](//projects.archlinux.org/svntogit/community.git/tree/trunk/PKGBUILD?h=packages/python-biopython "Archlinux svn"). Или, в общем случае, [как-то так](//aur.archlinux.org/packages/ne/netctl-gui/PKGBUILD "AUR").
|
||||
|
||||
Вообще говоря, для стандартных случаев существуют прототипы PKGBUILD'ов. Их можно найти в `/usr/share/pacman/`, хотя местами они могли немного устареть (больше года как). Так, прототипы для пакетов из системы контроля версий (git/svn/hg/bzr) однозначно устарели - сейчас используется другой, куда более аккуратный, формат. Настоятельно рекомендую ознакомиться на эту тему [с данной статьей](//wiki.archlinux.org/index.php/VCS_PKGBUILD_Guidelines "ArchWiki"). Например, для пакета **qmmp-qsmmp-git** кусок PKGBUILD'а выглядит так:
|
||||
|
||||
```bash
|
||||
pkgname=qmmp-qsmmp-git
|
||||
_gitname=qsmmp
|
||||
pkgver=0.5.34.gcd1ca1a
|
||||
# еще какие-то строки
|
||||
makedepends=('git')
|
||||
source=(${_gitname}::git+//gitorious.org/qsmmp/qsmmp.git#branch=qmmp-9999)
|
||||
md5sums=('SKIP')
|
||||
pkgver() {
|
||||
cd "${_gitname}"
|
||||
local ver=`git describe --long`
|
||||
printf "%s" "${${ver//-/.}//qmmp./}"
|
||||
}
|
||||
```
|
||||
|
||||
А для пакета **kdeplasma-applets-stdin-svn** так:
|
||||
|
||||
```bash
|
||||
pkgname=kdeplasma-applets-stdin-svn
|
||||
pkgver=57
|
||||
pkgrel=1
|
||||
_pkgname=plasmoidstdin
|
||||
_pkgver=0.2
|
||||
# еще какие-то строки
|
||||
makedepends=('automoc4' 'cmake' 'subversion')
|
||||
source=(${_pkgname}::svn+//plasmoidstdin.svn.sourceforge.net/svnroot/${_pkgname}/${_pkgver}/trunk)
|
||||
md5sums=('SKIP')
|
||||
pkgver() {
|
||||
cd "${srcdir}/${_pkgname}"
|
||||
local ver=`svnversion`
|
||||
printf "%s" "${ver//[[:alpha:]]}"
|
||||
}
|
||||
```
|
||||
|
||||
Также, я отмечу, что некоторые пакеты имеют свой устоявшийся формат, поэтому, зачастую, полезно поискать что-то похожее в AUR и сделать свой PKGBUILD по образу и подобию.
|
||||
|
||||
|
||||
## <a href="#links" class="anchor" id="links"><span class="octicon octicon-link"></span></a>Дополнительные ссылки
|
||||
|
||||
* [Зеркало (git)](//pkgbuild.com/git/aur-mirror.git/ "Зеркало")
|
||||
* [ArchWiki про AUR](//wiki.archlinux.org/index.php/AUR "ArchWiki")
|
||||
* [ArchWiki про PKGBUILD](//wiki.archlinux.org/index.php/PKGBUILD "ArchWiki")
|
||||
* [ArchWiki про makepkg](//wiki.archlinux.org/index.php/Makepkg "ArchWiki")
|
||||
* [ArchWiki немного про стандарты](//wiki.archlinux.org/index.php/Arch_packaging_standards "ArchWiki") (внизу есть весьма полезные ссылки на гайды для конкретных типов пакетов)
|
@ -1,143 +0,0 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: linux, разработка
|
||||
title: Написание своих дополнений для Shell. Zsh
|
||||
short: writting-own-completions-p1
|
||||
description: <figure class="img"><img src="/resources/papers/zsh_completion.png" alt="bash_completion"></figure> В данных статьях описываются некоторые основы создания файлов дополнений для собственной программы.
|
||||
---
|
||||
<h2><a href="#preamble" class="anchor" id="preamble"><span class="octicon octicon-link"></span></a>Преамбула</h2>
|
||||
<p>В процессе разработки <a href="/ru/projects/netctl-gui" title="Страница netctl-gui">одного своего проекта</a> возникло желание добавить также файлы дополнений (только не спрашивайте зачем). Благо я как-то уже брался за написание подобных вещей, но читать что-либо тогда мне было лень, и так и не осилил.</p>
|
||||
|
||||
<h2><a href="#introduction" class="anchor" id="introduction"><span class="octicon octicon-link"></span></a>Введение</h2>
|
||||
<p>Существует несколько возможных вариантов написания файла автодополнения для zsh. В случае данной статьи я остановлюсь только на одном из них, который предоставляет большие возможности и не требует больших затрат (например, работы с регулярными выражениями).</p>
|
||||
|
||||
<p>Рассмотрим на примере моего же приложения, часть справки к которому выглядит таким образом:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
netctl-gui [ -h | --help ] [ -e ESSID | --essid ESSID ] [ -с FILE | --config FILE ]
|
||||
[ -o PROFILE | --open PROFILE ] [ -t NUM | --tab NUM ] [ --set-opts OPTIONS ]
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Список флагов:</p>
|
||||
<ul>
|
||||
<li>флаги <code>-h</code> и <code>--help</code> не требуют аргументов;</li>
|
||||
<li>флаги <code>-e</code> и <code>--essid</code> требуют аргумента в виде строки, без дополнения;</li>
|
||||
<li>флаги <code>-c</code> и <code>--config</code> требуют аргумента в виде строки, файл с произвольной локацией;</li>
|
||||
<li>флаги <code>-o</code> и <code>--open</code> требуют аргумента в виде строки, дополнение по файлам из определенной директории;</li>
|
||||
<li>флаги <code>-t</code> и <code>--tab</code> требуют аргумента в виде строки, дополнение из указанного массива;</li>
|
||||
<li>флаг <code>--set-opts</code> требует аргумента в виде строки, дополнение из указанного массива, разделены запятыми;</li>
|
||||
</ul>
|
||||
|
||||
<h2><a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>Структура файла</h2>
|
||||
<p>В заголовке должно быть обязательно указано, что это файл дополнений и для каких приложений он служит (можно строкой, если в файле будет содержаться дополнение для нескольких команд):</p>
|
||||
|
||||
{% highlight bash %}
|
||||
#compdef netctl-gui
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Дальше идет описание флагов, вспомогательные функции и переменные. Замечу, что функции и переменные, которые будут использоваться для дополнения <b>должны возвращать массивы</b>, а не строки. В моем случае схема выглядит примерно так (все функции и переменные в этой главе умышленно оставлены пустыми):</p>
|
||||
|
||||
{% highlight bash %}
|
||||
# variables
|
||||
_netctl_gui_arglist=()
|
||||
_netctl_gui_settings=()
|
||||
_netctl_gui_tabs=()
|
||||
_netctl_profiles() {}
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Затем идут основные функции, которые будут вызываться для дополнения для определенной команды. В моем случае команда одна, и функция одна:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
# work block
|
||||
_netctl-gui() {}
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Далее <b>без выделения в отдельную функцию</b> идет небольшое шаманство, связанное с соотнесением приложения, которое было декларировано в первой строке, с функцией в теле скрипта:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
case "$service" in
|
||||
netctl-gui)
|
||||
_netctl-gui "$@" && return 0
|
||||
;;
|
||||
esac
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#flags" class="anchor" id="flags"><span class="octicon octicon-link"></span></a>Флаги</h2>
|
||||
<p>Как я и говорил во введении, существует несколько способов создания подобных файлов. В частности, они различаются декларацией флагов и их дальнейшей обработкой. В данном случае я буду использовать команду <code>_arguments</code>, которая требует специфичный формат переменных. Выглядит он таким образом <code>ФЛАГ[описание]:СООБЩЕНИЕ:ДЕЙСТВИЕ</code>. Последние два поля не обязательны и, как Вы увидите чуть ниже, вовсе и не нужны в некоторых местах. Если Вы предусматриваете два флага (короткий и длинный формат) на одно действие, то формат чуть-чуть усложняется: <code>{(ФЛАГ_2)ФЛАГ_1,(ФЛАГ_1)ФЛАГ_2}[описание]:СООБЩЕНИЕ:ДЕЙСТВИЕ</code>. Замечу, что, если Вы хотите сделать дополнения для двух типов флагов, но некоторые флаги не имеют второй записи, то Вам необходимо продублировать его таким образом: <code>{ФЛАГ,ФЛАГ}[описание]:СООБЩЕНИЕ:ДЕЙСТВИЕ</code>. <code>СООБЩЕНИЕ</code> - сообщение, которое будет показано, <code>ДЕЙСТВИЕ</code> - действие, которое будет выполнено после этого флага. В случае данного туториала, <code>ДЕЙСТВИЕ</code> будет иметь вид <code>->СОСТОЯНИЕ</code>.</p>
|
||||
|
||||
<p>Итак, согласно нашим требованиям, получается такое объявление аргументов:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl_gui_arglist=(
|
||||
{'(--help)-h','(-h)--help'}'[show help and exit]'
|
||||
{'(--essid)-e','(-e)--essid'}'[select ESSID]:type ESSID:->essid'
|
||||
{'(--config)-c','(-c)--config'}'[read configuration from this file]:select file:->files'
|
||||
{'(--open)-o','(-o)--open'}'[open profile]:select profile:->profiles'
|
||||
{'(--tab)-t','(-t)--tab'}'[open a tab with specified number]:select tab:->tab'
|
||||
{'--set-opts','--set-opts'}'[set options for this run, comma separated]:comma separated:->settings'
|
||||
)
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#variables" class="anchor" id="variables"><span class="octicon octicon-link"></span></a>Массивы переменных</h2>
|
||||
<p>В нашем случае есть два статических массива (не изменятся ни сейчас, ни через пять минут) (массивы умышленно уменьшены):</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl_gui_settings=(
|
||||
'CTRL_DIR'
|
||||
'CTRL_GROUP'
|
||||
)
|
||||
|
||||
_netctl_gui_tabs=(
|
||||
'1'
|
||||
'2'
|
||||
)
|
||||
{% endhighlight %}
|
||||
|
||||
<p>И есть динамический массив, который должен каждый раз генерироваться. Он содержит, в данном случае, файлы в указанной директории (это можно сделать и средствами zsh, кстати):</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl_profiles() {
|
||||
print $(find /etc/netctl -maxdepth 1 -type f -printf "%f\n")
|
||||
}
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#body" class="anchor" id="body"><span class="octicon octicon-link"></span></a>Тело функции</h2>
|
||||
<p>Помните, там выше было что-то про состояние? Оно хранится в переменной <code>$state</code>, и в теле функции делается проверка на то, чему оно равно, чтобы подобрать соответствующие действия. В начале также нужно не забыть вызвать <code>_arguments</code> с нашими флагами.</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl-gui() {
|
||||
_arguments $_netctl_gui_arglist
|
||||
case "$state" in
|
||||
essid)
|
||||
# не делать дополнения, ждать введенной строки
|
||||
;;
|
||||
files)
|
||||
# дополнение по существующим файлам
|
||||
_files
|
||||
;;
|
||||
profiles)
|
||||
# дополнение из функции
|
||||
# первая переменная описание
|
||||
# вторая массив для дополнения
|
||||
_values 'profiles' $(_netctl_profiles)
|
||||
;;
|
||||
tab)
|
||||
# дополнение из массива
|
||||
_values 'tab' $_netctl_gui_tabs
|
||||
;;
|
||||
settings)
|
||||
# дополнение из массива
|
||||
# флаг -s устанавливает разделитель и включает мультивыбор
|
||||
_values -s ',' 'settings' $_netctl_gui_settings
|
||||
;;
|
||||
esac
|
||||
}
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#conclusion" class="anchor" id="conclusion"><span class="octicon octicon-link"></span></a>Заключение</h2>
|
||||
<p>Файл хранится в директории <code>/usr/share/zsh/site-functions/</code> с произвольным, в общем-то, именем с префиксом <code>_</code>. Файл примера полностью может быть найден <a href="//raw.githubusercontent.com/arcan1s/netctl-gui/master/sources/gui/zsh-completions" title="Файл" type="text/plain">в моем репозитории</a>.</p>
|
||||
|
||||
<p>Дополнительная информация может быть найдена в репозитории <a href="//github.com/zsh-users/zsh-completions" title="GitHub">zsh-completions</a>. Например, там есть такой <a href="//github.com/zsh-users/zsh-completions/blob/master/zsh-completions-howto.org" title="Туториал">How-To</a>. А еще там есть много примеров.</p>
|
152
ru/_posts/2014-07-17-writting-own-completions-p1.md
Normal file
152
ru/_posts/2014-07-17-writting-own-completions-p1.md
Normal file
@ -0,0 +1,152 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: linux, разработка
|
||||
title: Написание своих дополнений для Shell. Zsh
|
||||
short: writting-own-completions-p1
|
||||
---
|
||||
<figure class="img"></figure> В данных статьях описываются некоторые основы создания файлов дополнений для собственной программы.
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#preamble" class="anchor" id="preamble"><span class="octicon octicon-link"></span></a>Преамбула
|
||||
|
||||
В процессе разработки [одного своего проекта](/ru/projects/netctl-gui "Страница netctl-gui") возникло желание добавить также файлы дополнений (только не спрашивайте зачем). Благо я как-то уже брался за написание подобных вещей, но читать что-либо тогда мне было лень, и так и не осилил.
|
||||
|
||||
## <a href="#introduction" class="anchor" id="introduction"><span class="octicon octicon-link"></span></a>Введение
|
||||
|
||||
Существует несколько возможных вариантов написания файла автодополнения для zsh. В случае данной статьи я остановлюсь только на одном из них, который предоставляет большие возможности и не требует больших затрат (например, работы с регулярными выражениями).
|
||||
|
||||
Рассмотрим на примере моего же приложения, часть справки к которому выглядит таким образом:
|
||||
|
||||
```bash
|
||||
netctl-gui [ -h | --help ] [ -e ESSID | --essid ESSID ] [ -с FILE | --config FILE ]
|
||||
[ -o PROFILE | --open PROFILE ] [ -t NUM | --tab NUM ] [ --set-opts OPTIONS ]
|
||||
```
|
||||
|
||||
Список флагов:
|
||||
|
||||
* флаги `-h` и `--help` не требуют аргументов;
|
||||
* флаги `-e` и `--essid` требуют аргумента в виде строки, без дополнения;
|
||||
* флаги `-c` и `--config` требуют аргумента в виде строки, файл с произвольной локацией;
|
||||
* флаги `-o` и `--open` требуют аргумента в виде строки, дополнение по файлам из определенной директории;
|
||||
* флаги `-t` и `--tab` требуют аргумента в виде строки, дополнение из указанного массива;
|
||||
* флаг `--set-opts` требует аргумента в виде строки, дополнение из указанного массива, разделены запятыми;
|
||||
|
||||
## <a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>Структура файла
|
||||
|
||||
В заголовке должно быть обязательно указано, что это файл дополнений и для каких приложений он служит (можно строкой, если в файле будет содержаться дополнение для нескольких команд):
|
||||
|
||||
```bash
|
||||
#compdef netctl-gui
|
||||
```
|
||||
|
||||
Дальше идет описание флагов, вспомогательные функции и переменные. Замечу, что функции и переменные, которые будут использоваться для дополнения **должны возвращать массивы**, а не строки. В моем случае схема выглядит примерно так (все функции и переменные в этой главе умышленно оставлены пустыми):
|
||||
|
||||
```bash
|
||||
# variables
|
||||
_netctl_gui_arglist=()
|
||||
_netctl_gui_settings=()
|
||||
_netctl_gui_tabs=()
|
||||
_netctl_profiles() {}
|
||||
```
|
||||
|
||||
Затем идут основные функции, которые будут вызываться для дополнения для определенной команды. В моем случае команда одна, и функция одна:
|
||||
|
||||
```bash
|
||||
# work block
|
||||
_netctl-gui() {}
|
||||
```
|
||||
|
||||
Далее **без выделения в отдельную функцию** идет небольшое шаманство, связанное с соотнесением приложения, которое было декларировано в первой строке, с функцией в теле скрипта:
|
||||
|
||||
```bash
|
||||
case "$service" in
|
||||
netctl-gui)
|
||||
_netctl-gui "$@" && return 0
|
||||
;;
|
||||
esac
|
||||
```
|
||||
|
||||
## <a href="#flags" class="anchor" id="flags"><span class="octicon octicon-link"></span></a>Флаги
|
||||
|
||||
Как я и говорил во введении, существует несколько способов создания подобных файлов. В частности, они различаются декларацией флагов и их дальнейшей обработкой. В данном случае я буду использовать команду `_arguments`, которая требует специфичный формат переменных. Выглядит он таким образом `ФЛАГ[описание]:СООБЩЕНИЕ:ДЕЙСТВИЕ`. Последние два поля не обязательны и, как Вы увидите чуть ниже, вовсе и не нужны в некоторых местах. Если Вы предусматриваете два флага (короткий и длинный формат) на одно действие, то формат чуть-чуть усложняется: `{(ФЛАГ_2)ФЛАГ_1,(ФЛАГ_1)ФЛАГ_2}[описание]:СООБЩЕНИЕ:ДЕЙСТВИЕ`. Замечу, что, если Вы хотите сделать дополнения для двух типов флагов, но некоторые флаги не имеют второй записи, то Вам необходимо продублировать его таким образом: `{ФЛАГ,ФЛАГ}[описание]:СООБЩЕНИЕ:ДЕЙСТВИЕ`. `СООБЩЕНИЕ` - сообщение, которое будет показано, `ДЕЙСТВИЕ` - действие, которое будет выполнено после этого флага. В случае данного туториала, `ДЕЙСТВИЕ` будет иметь вид `->СОСТОЯНИЕ`.
|
||||
|
||||
Итак, согласно нашим требованиям, получается такое объявление аргументов:
|
||||
|
||||
```bash
|
||||
_netctl_gui_arglist=(
|
||||
{'(--help)-h','(-h)--help'}'[show help and exit]'
|
||||
{'(--essid)-e','(-e)--essid'}'[select ESSID]:type ESSID:->essid'
|
||||
{'(--config)-c','(-c)--config'}'[read configuration from this file]:select file:->files'
|
||||
{'(--open)-o','(-o)--open'}'[open profile]:select profile:->profiles'
|
||||
{'(--tab)-t','(-t)--tab'}'[open a tab with specified number]:select tab:->tab'
|
||||
{'--set-opts','--set-opts'}'[set options for this run, comma separated]:comma separated:->settings'
|
||||
)
|
||||
```
|
||||
|
||||
## <a href="#variables" class="anchor" id="variables"><span class="octicon octicon-link"></span></a>Массивы переменных
|
||||
|
||||
В нашем случае есть два статических массива (не изменятся ни сейчас, ни через пять минут) (массивы умышленно уменьшены):
|
||||
|
||||
```bash
|
||||
_netctl_gui_settings=(
|
||||
'CTRL_DIR'
|
||||
'CTRL_GROUP'
|
||||
)
|
||||
|
||||
_netctl_gui_tabs=(
|
||||
'1'
|
||||
'2'
|
||||
)
|
||||
```
|
||||
|
||||
И есть динамический массив, который должен каждый раз генерироваться. Он содержит, в данном случае, файлы в указанной директории (это можно сделать и средствами zsh, кстати):
|
||||
|
||||
```bash
|
||||
_netctl_profiles() {
|
||||
print $(find /etc/netctl -maxdepth 1 -type f -printf "%f\n")
|
||||
}
|
||||
```
|
||||
|
||||
## <a href="#body" class="anchor" id="body"><span class="octicon octicon-link"></span></a>Тело функции
|
||||
|
||||
Помните, там выше было что-то про состояние? Оно хранится в переменной `$state`, и в теле функции делается проверка на то, чему оно равно, чтобы подобрать соответствующие действия. В начале также нужно не забыть вызвать `_arguments` с нашими флагами.
|
||||
|
||||
```bash
|
||||
_netctl-gui() {
|
||||
_arguments $_netctl_gui_arglist
|
||||
case "$state" in
|
||||
essid)
|
||||
# не делать дополнения, ждать введенной строки
|
||||
;;
|
||||
files)
|
||||
# дополнение по существующим файлам
|
||||
_files
|
||||
;;
|
||||
profiles)
|
||||
# дополнение из функции
|
||||
# первая переменная описание
|
||||
# вторая массив для дополнения
|
||||
_values 'profiles' $(_netctl_profiles)
|
||||
;;
|
||||
tab)
|
||||
# дополнение из массива
|
||||
_values 'tab' $_netctl_gui_tabs
|
||||
;;
|
||||
settings)
|
||||
# дополнение из массива
|
||||
# флаг -s устанавливает разделитель и включает мультивыбор
|
||||
_values -s ',' 'settings' $_netctl_gui_settings
|
||||
;;
|
||||
esac
|
||||
}
|
||||
```
|
||||
|
||||
## <a href="#conclusion" class="anchor" id="conclusion"><span class="octicon octicon-link"></span></a>Заключение
|
||||
|
||||
Файл хранится в директории `/usr/share/zsh/site-functions/` с произвольным, в общем-то, именем с префиксом `_`. Файл примера полностью может быть найден [в моем репозитории](//raw.githubusercontent.com/arcan1s/netctl-gui/master/sources/gui/zsh-completions "Файл").
|
||||
|
||||
Дополнительная информация может быть найдена в репозитории [zsh-completions](//github.com/zsh-users/zsh-completions "GitHub"). Например, там есть такой [How-To](//github.com/zsh-users/zsh-completions/blob/master/zsh-completions-howto.org "Туториал"). А еще там есть много примеров.
|
@ -1,135 +0,0 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: linux, разработка
|
||||
title: Написание своих дополнений для Shell. Bash
|
||||
short: writting-own-completions-p2
|
||||
description: <figure class="img"><img src="/resources/papers/bash_completion.png" alt="bash_completion"></figure> В данных статьях описываются некоторые основы создания файлов дополнений для собственной программы.
|
||||
---
|
||||
<h2><a href="#preamble" class="anchor" id="preamble"><span class="octicon octicon-link"></span></a>Преамбула</h2>
|
||||
<p>В процессе разработки <a href="/ru/projects/netctl-gui" title="Страница netctl-gui">одного своего проекта</a> возникло желание добавить также файлы дополнений (только не спрашивайте зачем). Благо я как-то уже брался за написание подобных вещей, но читать что-либо тогда мне было лень, и так и не осилил.</p>
|
||||
|
||||
<h2><a href="#introduction" class="anchor" id="introduction"><span class="octicon octicon-link"></span></a>Введение</h2>
|
||||
<p>Bash, в <a href="/ru/2014/07/17/writting-own-completions-p1" title="Статья о дополнениях zsh">отличие от zsh</a>, требует к себе некоторого велосипедостроения в отношении дополнений. Бегло погуглив, я не нашел более-менее нормальных туториалов, потому за основу были взяты имеющиеся в системе файлы дополнений для <code>pacman</code>.</p>
|
||||
|
||||
<p>Рассмотрим на примере все того же моего приложения. Я напомню, что часть справки к которому выглядит таким образом:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
netctl-gui [ -h | --help ] [ -e ESSID | --essid ESSID ] [ -с FILE | --config FILE ]
|
||||
[ -o PROFILE | --open PROFILE ] [ -t NUM | --tab NUM ] [ --set-opts OPTIONS ]
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Список флагов:</p>
|
||||
<ul>
|
||||
<li>флаги <code>-h</code> и <code>--help</code> не требуют аргументов;</li>
|
||||
<li>флаги <code>-e</code> и <code>--essid</code> требуют аргумента в виде строки, без дополнения;</li>
|
||||
<li>флаги <code>-c</code> и <code>--config</code> требуют аргумента в виде строки, файл с произвольной локацией;</li>
|
||||
<li>флаги <code>-o</code> и <code>--open</code> требуют аргумента в виде строки, дополнение по файлам из определенной директории;</li>
|
||||
<li>флаги <code>-t</code> и <code>--tab</code> требуют аргумента в виде строки, дополнение из указанного массива;</li>
|
||||
<li>флаг <code>--set-opts</code> требует аргумента в виде строки, дополнение из указанного массива, разделены запятыми;</li>
|
||||
</ul>
|
||||
|
||||
<h2><a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>Структура файла</h2>
|
||||
<p>Здесь <b>все</b> переменные должны возвращать массив. Каких-либо особых форматов тут уже нет. Сначала опишем флаги, потом уже все остальные переменные. Я напомню (так как ниже я уже не буду приводить функции более подробно), что <code>_netctl_profiles()</code>, в отличие от других переменных, должна возвращать актуальный на данный момент массив:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
# variables
|
||||
_netctl_gui_arglist=()
|
||||
_netctl_gui_settings=()
|
||||
_netctl_gui_tabs=()
|
||||
_netctl_profiles() {}
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Затем идут основные функции, которые будут вызываться для дополнения для определенной команды. В моем случае команда одна, и функция одна:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
# work block
|
||||
_netctl-gui() {}
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Далее, опять, <b>без выделения в отдельную функцию</b> делаем соответствие "функция-команда":</p>
|
||||
|
||||
{% highlight bash %}
|
||||
complete -F _netctl_gui netctl-gui
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#flags" class="anchor" id="flags"><span class="octicon octicon-link"></span></a>Флаги</h2>
|
||||
<p>Как было сказано выше, особого формата тут нет, доступные флаги располагаются просто массивом:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl_gui_arglist=(
|
||||
'-h'
|
||||
'--help'
|
||||
'-e'
|
||||
'--essid'
|
||||
'-c'
|
||||
'--config'
|
||||
'-o'
|
||||
'--open'
|
||||
'-t'
|
||||
'--tab'
|
||||
'--set-opts'
|
||||
)
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#variables" class="anchor" id="variables"><span class="octicon octicon-link"></span></a>Массивы переменных</h2>
|
||||
<p>Приведу только функцию, которая в zsh выглядела таким образом:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl_profiles() {
|
||||
print $(find /etc/netctl -maxdepth 1 -type f -printf "%f\n")
|
||||
}
|
||||
{% endhighlight %}
|
||||
|
||||
<p>В bash так не получится, пришлось чуть-чуть изменить:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl_profiles() {
|
||||
echo $(find /etc/netctl -maxdepth 1 -type f -printf "%f\n")
|
||||
}
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#body" class="anchor" id="body"><span class="octicon octicon-link"></span></a>Тело функции</h2>
|
||||
<p>За дополнение в bash отвечает переменная <code>COMPREPLY</code>. Для отслеживания текущего состояния нужно вызвать функцию <code>_get_comp_words_by_ref</code> с параметрами <code>cur</code> (текущая опция) и <code>prev</code> (предыдущая, собственно состояние). Ну и нужно несколько точек, на которых сворачивать в определенную часть case (переменные <code>want*</code>). Для генерации дополнения используется <code>compgen</code>. После флага <code>-W</code> ему подается список слов. (Есть еще флаг <code>-F</code>, который вызывает функцию, но у меня он помимо этого еще и ворнинг выдает.) Последним аргументом идет текущая строка, к которой и нужно генерировать дополнение.</p>
|
||||
|
||||
<p>Таким образом, наша функция выглядит так:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
_netctl_gui() {
|
||||
COMPREPLY=()
|
||||
wantfiles='-@(c|-config)'
|
||||
wantprofiles='-@(o|-open|s|-select)'
|
||||
wantsettings='-@(-set-opts)'
|
||||
|
||||
wanttabs='-@(t|-tab)'
|
||||
_get_comp_words_by_ref cur prev
|
||||
|
||||
if [[ $prev = $wantstring ]]; then
|
||||
# не делать дополнения, ждать введенной строки
|
||||
COMPREPLY=()
|
||||
elif [[ $prev = $wantfiles ]]; then
|
||||
# дополнение по существующим файлам
|
||||
_filedir
|
||||
elif [[ $prev = $wantprofiles ]]; then
|
||||
# дополнение из функции
|
||||
COMPREPLY=($(compgen -W '${_netctl_profiles[@]}' -- "$cur"))
|
||||
elif [[ $prev = $wanttabs ]]; then
|
||||
# дополнение из массива
|
||||
COMPREPLY=($(compgen -W '${_netctl_gui_tabs[@]}' -- "$cur"))
|
||||
elif [[ $prev = $wantsettings ]]; then
|
||||
# дополнение из массива
|
||||
# -S вставит запятую после, но вот мультивыбор не включил =(
|
||||
COMPREPLY=($(compgen -S ',' -W '${_netctl_gui_settings[@]}' -- "$cur"))
|
||||
else
|
||||
# вывести доступные аргументы
|
||||
COMPREPLY=($(compgen -W '${_netctl_gui_arglist[@]}' -- "$cur"))
|
||||
fi
|
||||
|
||||
true
|
||||
}
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#conclusion" class="anchor" id="conclusion"><span class="octicon octicon-link"></span></a>Заключение</h2>
|
||||
<p>Файл хранится в директории <code>/usr/share/bash-completion/completions/</code> с произвольным именем. Файл примера полностью может быть найден <a href="//raw.githubusercontent.com/arcan1s/netctl-gui/master/sources/gui/bash-completions" title="Файл" type="text/plain">в моем репозитории</a>.</p>
|
144
ru/_posts/2014-07-17-writting-own-completions-p2.md
Normal file
144
ru/_posts/2014-07-17-writting-own-completions-p2.md
Normal file
@ -0,0 +1,144 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: linux, разработка
|
||||
title: Написание своих дополнений для Shell. Bash
|
||||
short: writting-own-completions-p2
|
||||
---
|
||||
<figure class="img"></figure> В данных статьях описываются некоторые основы создания файлов дополнений для собственной программы.
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#preamble" class="anchor" id="preamble"><span class="octicon octicon-link"></span></a>Преамбула
|
||||
|
||||
В процессе разработки [одного своего проекта](/ru/projects/netctl-gui "Страница netctl-gui") возникло желание добавить также файлы дополнений (только не спрашивайте зачем). Благо я как-то уже брался за написание подобных вещей, но читать что-либо тогда мне было лень, и так и не осилил.
|
||||
|
||||
## <a href="#introduction" class="anchor" id="introduction"><span class="octicon octicon-link"></span></a>Введение
|
||||
|
||||
Bash, в [отличие от zsh](/ru/2014/07/17/writting-own-completions-p1 "Статья о дополнениях zsh"), требует к себе некоторого велосипедостроения в отношении дополнений. Бегло погуглив, я не нашел более-менее нормальных туториалов, потому за основу были взяты имеющиеся в системе файлы дополнений для `pacman`.
|
||||
|
||||
Рассмотрим на примере все того же моего приложения. Я напомню, что часть справки к которому выглядит таким образом:
|
||||
|
||||
```bash
|
||||
netctl-gui [ -h | --help ] [ -e ESSID | --essid ESSID ] [ -с FILE | --config FILE ]
|
||||
[ -o PROFILE | --open PROFILE ] [ -t NUM | --tab NUM ] [ --set-opts OPTIONS ]
|
||||
```
|
||||
|
||||
Список флагов:
|
||||
|
||||
* флаги `-h` и `--help` не требуют аргументов;
|
||||
* флаги `-e` и `--essid` требуют аргумента в виде строки, без дополнения;
|
||||
* флаги `-c` и `--config` требуют аргумента в виде строки, файл с произвольной локацией;
|
||||
* флаги `-o` и `--open` требуют аргумента в виде строки, дополнение по файлам из определенной директории;
|
||||
* флаги `-t` и `--tab` требуют аргумента в виде строки, дополнение из указанного массива;
|
||||
* флаг `--set-opts` требует аргумента в виде строки, дополнение из указанного массива, разделены запятыми;
|
||||
|
||||
## <a href="#file" class="anchor" id="file"><span class="octicon octicon-link"></span></a>Структура файла
|
||||
|
||||
Здесь **все** переменные должны возвращать массив. Каких-либо особых форматов тут уже нет. Сначала опишем флаги, потом уже все остальные переменные. Я напомню (так как ниже я уже не буду приводить функции более подробно), что `_netctl_profiles()`, в отличие от других переменных, должна возвращать актуальный на данный момент массив:
|
||||
|
||||
```bash
|
||||
# variables
|
||||
_netctl_gui_arglist=()
|
||||
_netctl_gui_settings=()
|
||||
_netctl_gui_tabs=()
|
||||
_netctl_profiles() {}
|
||||
```
|
||||
|
||||
Затем идут основные функции, которые будут вызываться для дополнения для определенной команды. В моем случае команда одна, и функция одна:
|
||||
|
||||
```bash
|
||||
# work block
|
||||
_netctl-gui() {}
|
||||
```
|
||||
|
||||
Далее, опять, **без выделения в отдельную функцию** делаем соответствие "функция-команда":
|
||||
|
||||
```bash
|
||||
complete -F _netctl_gui netctl-gui
|
||||
```
|
||||
|
||||
## <a href="#flags" class="anchor" id="flags"><span class="octicon octicon-link"></span></a>Флаги
|
||||
|
||||
Как было сказано выше, особого формата тут нет, доступные флаги располагаются просто массивом:
|
||||
|
||||
```bash
|
||||
_netctl_gui_arglist=(
|
||||
'-h'
|
||||
'--help'
|
||||
'-e'
|
||||
'--essid'
|
||||
'-c'
|
||||
'--config'
|
||||
'-o'
|
||||
'--open'
|
||||
'-t'
|
||||
'--tab'
|
||||
'--set-opts'
|
||||
)
|
||||
```
|
||||
|
||||
## <a href="#variables" class="anchor" id="variables"><span class="octicon octicon-link"></span></a>Массивы переменных
|
||||
|
||||
Приведу только функцию, которая в zsh выглядела таким образом:
|
||||
|
||||
```bash
|
||||
_netctl_profiles() {
|
||||
print $(find /etc/netctl -maxdepth 1 -type f -printf "%f\n")
|
||||
}
|
||||
```
|
||||
|
||||
В bash так не получится, пришлось чуть-чуть изменить:
|
||||
|
||||
```bash
|
||||
_netctl_profiles() {
|
||||
echo $(find /etc/netctl -maxdepth 1 -type f -printf "%f\n")
|
||||
}
|
||||
```
|
||||
|
||||
## <a href="#body" class="anchor" id="body"><span class="octicon octicon-link"></span></a>Тело функции
|
||||
|
||||
За дополнение в bash отвечает переменная `COMPREPLY`. Для отслеживания текущего состояния нужно вызвать функцию `_get_comp_words_by_ref` с параметрами `cur` (текущая опция) и `prev` (предыдущая, собственно состояние). Ну и нужно несколько точек, на которых сворачивать в определенную часть case (переменные `want*`). Для генерации дополнения используется `compgen`. После флага `-W` ему подается список слов. (Есть еще флаг `-F`, который вызывает функцию, но у меня он помимо этого еще и ворнинг выдает.) Последним аргументом идет текущая строка, к которой и нужно генерировать дополнение.
|
||||
|
||||
Таким образом, наша функция выглядит так:
|
||||
|
||||
```bash
|
||||
_netctl_gui() {
|
||||
COMPREPLY=()
|
||||
wantfiles='-@(c|-config)'
|
||||
wantprofiles='-@(o|-open|s|-select)'
|
||||
wantsettings='-@(-set-opts)'
|
||||
|
||||
wanttabs='-@(t|-tab)'
|
||||
_get_comp_words_by_ref cur prev
|
||||
|
||||
if [[ $prev = $wantstring ]]; then
|
||||
# не делать дополнения, ждать введенной строки
|
||||
COMPREPLY=()
|
||||
elif [[ $prev = $wantfiles ]]; then
|
||||
# дополнение по существующим файлам
|
||||
_filedir
|
||||
elif [[ $prev = $wantprofiles ]]; then
|
||||
# дополнение из функции
|
||||
COMPREPLY=($(compgen -W '${_netctl_profiles[@]}' -- "$cur"))
|
||||
elif [[ $prev = $wanttabs ]]; then
|
||||
# дополнение из массива
|
||||
COMPREPLY=($(compgen -W '${_netctl_gui_tabs[@]}' -- "$cur"))
|
||||
elif [[ $prev = $wantsettings ]]; then
|
||||
# дополнение из массива
|
||||
# -S вставит запятую после, но вот мультивыбор не включил =(
|
||||
COMPREPLY=($(compgen -S ',' -W '${_netctl_gui_settings[@]}' -- "$cur"))
|
||||
else
|
||||
# вывести доступные аргументы
|
||||
COMPREPLY=($(compgen -W '${_netctl_gui_arglist[@]}' -- "$cur"))
|
||||
fi
|
||||
|
||||
true
|
||||
}
|
||||
```
|
||||
|
||||
## <a href="#conclusion" class="anchor" id="conclusion"><span class="octicon octicon-link"></span></a>Заключение
|
||||
|
||||
Файл хранится в директории `/usr/share/bash-completion/completions/` с произвольным именем. Файл примера полностью может быть найден [в моем репозитории](//raw.githubusercontent.com/arcan1s/netctl-gui/master/sources/gui/bash-completions "Файл").
|
@ -1,38 +0,0 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: awesome-widgets, pytextmonitor
|
||||
title: Миграция Awesome Widgets (ex-PyTextMonitor) на версию 2.0
|
||||
short: migration-to-v2
|
||||
description: <figure class="img"><img src="/resources/papers/broken-computer.jpg" alt="broken-computer"></figure>В версии 2.0 произошел ряд значительных изменений (совершенно случайно, само по себе, я тут не при чем) и было полностью переписано пользовательское API. Данная статья призвана облегчить миграцию со старых версий PyTextMonitor (<1.11.0) на новую (>2.0).
|
||||
---
|
||||
<h2><a href="#new" class="anchor" id="new"><span class="octicon octicon-link"></span></a>Новые фичи</h2>
|
||||
<p>Во-первых, это ряд нововведений, среди которых:</p>
|
||||
|
||||
<ul>
|
||||
<li>Новый виджет - <b>Desktop panel</b>. Показывает список рабочих столов, выделяя активный. Умеет переключаться между ними по клику. Также умеет скрывать выбранные панели по хоткею.</li>
|
||||
<li>Новые теги - <code>hddfreemb</code>, <code>hddfreegb</code>, <code>memusedmb</code>, <code>memusedgb</code>, <code>memfreemb</code>, <code>memfreegb</code>, <code>swapfreemb</code>, <code>swapfreegb</code>. А также новые теги, связанные с новыми возможностями - <code>desktop</code>, <code>ndesktop</code>, <code>tdesktops</code>.</li>
|
||||
<li>Новый графический тултип - батарея. Двухцветный, в зависимости от статуса адаптора питания.</li>
|
||||
</ul>
|
||||
|
||||
<h2><a href="#changes" class="anchor" id="changes"><span class="octicon octicon-link"></span></a>Значительные изменения</h2>
|
||||
<p>Во-вторых, и это главное - произошел ряд изменений, из-за которых старые настройки <b>не будут</b> более работать. Среди пользовательских следует выделить:</p>
|
||||
|
||||
<ul>
|
||||
<li>Переписка основного виджета на <code>С++</code>, что вызвало переименование проекта в <b>Awesome Widgets</b>, а главного виджета в <b>Awesome Widget</b></li>
|
||||
<li>Настройки файлов батареи и адаптора питания <b>вынесены в DataEngine</b>.</li>
|
||||
<li><b>Убраны поля</b>. Теперь виджет представляет собой монолитное поле. Текст настраивается в специальном браузере.</li>
|
||||
<li>В связи с удалением отдельных полей, тултип теперь <b>настраивается отдельно</b>.</li>
|
||||
<li>Настройка выравнивания текста теперь может быть осуществлена только с использованием HTML тегов.</li>
|
||||
<li>В связи с объединением полей, несколько тегов были переименованы:
|
||||
<ul>
|
||||
<li><code>custom</code> (время) -> <code>ctime</code></li>
|
||||
<li><code>custom</code> (время работы) -> <code>cuptime</code></li>
|
||||
<li><code>time</code> (плеер) -> <code>duration</code></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<p>По любым проблемам, связанным с миграцией, не стесняйтесь оставлять здесь комментарий.</p>
|
36
ru/_posts/2014-09-04-migration-to-v2.md
Normal file
36
ru/_posts/2014-09-04-migration-to-v2.md
Normal file
@ -0,0 +1,36 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: awesome-widgets, pytextmonitor
|
||||
title: Миграция Awesome Widgets (ex-PyTextMonitor) на версию 2.0
|
||||
short: migration-to-v2
|
||||
---
|
||||
<figure class="img"></figure> В версии 2.0 произошел ряд значительных изменений (совершенно случайно, само по себе, я тут не при чем) и было полностью переписано пользовательское API. Данная статья призвана облегчить миграцию со старых версий PyTextMonitor (<1.11.0) на новую (>2.0).
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#new" class="anchor" id="new"><span class="octicon octicon-link"></span></a>Новые фичи
|
||||
|
||||
Во-первых, это ряд нововведений, среди которых:
|
||||
|
||||
* Новый виджет - **Desktop panel**. Показывает список рабочих столов, выделяя активный. Умеет переключаться между ними по клику. Также умеет скрывать выбранные панели по хоткею.
|
||||
* Новые теги - `hddfreemb`, `hddfreegb`, `memusedmb`, `memusedgb`, `memfreemb`, `memfreegb`, `swapfreemb`, `swapfreegb`. А также новые теги, связанные с новыми возможностями - `desktop`, `ndesktop`, `tdesktops`.
|
||||
* Новый графический тултип - батарея. Двухцветный, в зависимости от статуса адаптора питания.
|
||||
|
||||
## <a href="#changes" class="anchor" id="changes"><span class="octicon octicon-link"></span></a>Значительные изменения
|
||||
|
||||
Во-вторых, и это главное - произошел ряд изменений, из-за которых старые настройки **не будут** более работать. Среди пользовательских следует выделить:
|
||||
|
||||
* Переписка основного виджета на `С++`, что вызвало переименование проекта в **Awesome Widgets**, а главного виджета в **Awesome Widget**
|
||||
* Настройки файлов батареи и адаптора питания **вынесены в DataEngine**.
|
||||
* **Убраны поля**. Теперь виджет представляет собой монолитное поле. Текст настраивается в специальном браузере.
|
||||
* В связи с удалением отдельных полей, тултип теперь **настраивается отдельно**.
|
||||
* Настройка выравнивания текста теперь может быть осуществлена только с использованием HTML тегов.
|
||||
* В связи с объединением полей, несколько тегов были переименованы:
|
||||
* `custom` (время) -> `ctime`
|
||||
* `custom` (время работы) -> `cuptime`
|
||||
* `time` (плеер) -> `duration`
|
||||
|
||||
По любым проблемам, связанным с миграцией, не стесняйтесь оставлять здесь комментарий.
|
@ -1,172 +0,0 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: linux, systemd, ecryptfs
|
||||
title: Как зашифровать хомяк и не об%$#аться. For dummies
|
||||
short: ecnryption-home-directory
|
||||
description: <figure class="img"><img src="/resources/papers/single-door.jpg" alt="single-door"></figure>Статья посвящена шифрованию домашнего каталога с использованием ecryptfs и настройке автомонтирования посредством systemd с использованием ключа на флешке.
|
||||
---
|
||||
<h2><a href="#preparation" class="anchor" id="preparation"><span class="octicon octicon-link"></span></a>Шаг 0: Подготовка</h2>
|
||||
<ol>
|
||||
<li>Разлогинились пользователем. То есть совсем-совсем.</li>
|
||||
<li>Зашли под root в tty. Дальнейшие действия описаны от него.</li>
|
||||
<li>Передвинули наш хомяк и создали пустую директорию (<code>s/$USER/имя пользователя/</code>):
|
||||
|
||||
{% highlight bash %}
|
||||
mv /home/{$USER,$USER-org}
|
||||
mkdir /home/$USER
|
||||
chmod 700 /home/$USER
|
||||
chown $USER:users /home/$USER
|
||||
{% endhighlight %}
|
||||
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<h2><a href="#step1" class="anchor" id="step1"><span class="octicon octicon-link"></span></a>Шаг 1: Шифрование</h2>
|
||||
<p>Самое распространенное решение в интернетах - воспользоваться автоматическими тулзами. Однако в нашем случае они не подходят, так как нам необходимо импортировать сигнатуру ключа / пароля, что при данном решении невозможно (или у автора руки кривые).</p>
|
||||
|
||||
<p>Делается шифрование следующим образом (lol):</p>
|
||||
|
||||
{% highlight bash %}
|
||||
mount -t ecryptfs /home/$USER /home/$USER
|
||||
{% endhighlight %}
|
||||
|
||||
<p>В процессе он у нас задаст несколько вопросов (я предлагаю первое монтирование делать в интерактивном режиме). Ответы можно взять примерно такие (в комментариях показано, что эти опции делают), обратите внимание, что если вы что то измените, то изменится и некоторые строчки далее:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
# ключ или сертификат. Второе надежнее, но до тех пор пока не потеряете %)
|
||||
Select key type to use for newly created files:
|
||||
1) passphrase
|
||||
2) openssl
|
||||
Selection: 1
|
||||
# пароль
|
||||
Passphrase:
|
||||
# шифрование, ставим берем дефолт
|
||||
Select cipher:
|
||||
1) aes: blocksize = 16; min keysize = 16; max keysize = 32
|
||||
2) blowfish: blocksize = 8; min keysize = 16; max keysize = 56
|
||||
3) des3_ede: blocksize = 8; min keysize = 24; max keysize = 24
|
||||
4) twofish: blocksize = 16; min keysize = 16; max keysize = 32
|
||||
5) cast6: blocksize = 16; min keysize = 16; max keysize = 32
|
||||
6) cast5: blocksize = 8; min keysize = 5; max keysize = 16
|
||||
Selection [aes]: 1
|
||||
# размер ключа, берем дефолт
|
||||
Select key bytes:
|
||||
1) 16
|
||||
2) 32
|
||||
3) 24
|
||||
Selection [16]: 1
|
||||
# разрешать читать/писать в нешифрованные файлы в точке монтирования
|
||||
Enable plaintext passthrough (y/n) [n]: n
|
||||
# включить шифрование имен файлов
|
||||
Enable filename encryption (y/n) [n]: y
|
||||
Filename Encryption Key (FNEK) Signature [360d0573e701851e]:
|
||||
# многабукафниасилил
|
||||
Attempting to mount with the following options:
|
||||
ecryptfs_unlink_sigs
|
||||
ecryptfs_fnek_sig=360d0573e701851e
|
||||
ecryptfs_key_bytes=16
|
||||
ecryptfs_cipher=aes
|
||||
ecryptfs_sig=360d0573e701851e
|
||||
WARNING: Based on the contents of [/root/.ecryptfs/sig-cache.txt],
|
||||
it looks like you have never mounted with this key
|
||||
before. This could mean that you have typed your
|
||||
passphrase wrong.
|
||||
|
||||
# подтверждаем, выходим
|
||||
Would you like to proceed with the mount (yes/no)? : yes
|
||||
Would you like to append sig [360d0573e701851e] to
|
||||
[/root/.ecryptfs/sig-cache.txt]
|
||||
in order to avoid this warning in the future (yes/no)? : yes
|
||||
Successfully appended new sig to user sig cache file
|
||||
Mounted eCryptfs
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Далее просто копируем файлы из родного хомяка:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
cp -a /home/$USER-org/. /home/$USER
|
||||
{% endhighlight %}
|
||||
|
||||
<h2><a href="#step2" class="anchor" id="step2"><span class="octicon octicon-link"></span></a>Шаг 2: Автомонтирование с systemd</h2>
|
||||
<p>Создадим файл на флешке (я использовал microSD) со следующим содержанием (пароль только поставьте свой):</p>
|
||||
|
||||
{% highlight bash %}
|
||||
passphrase_passwd=someverystronguniqpassword
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Добавим автомонтирование флешки (направление <code>/mnt/key</code>) в <code>fstab</code> с опцией <code>ro</code>, например так:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
UUID=dc3ecb41-bc40-400a-b6bf-65c5beeb01d7 /mnt/key ext2 ro,defaults 0 0
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Теперь настроим монтирование хомяка. Опции монтирования можно подглядеть как то так:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
mount | grep ecryptfs
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Однако замечу, что там указаны не все опции, необходимо добавить также <code>key</code>, <code>no_sig_cache</code>, <code>ecryptfs_passthrough</code>. Таким образом, для systemd mount-юнит выглядит примерно так (любители shell-простыней смогут написать свой демон, потому что через <code>fstab</code> не сработает просто так (см. ниже)).</p>
|
||||
|
||||
{% highlight bash %}
|
||||
# cat /etc/systemd/system/home-$USER.mount
|
||||
[Unit]
|
||||
Before=local-fs.target
|
||||
After=mnt-key.mount
|
||||
|
||||
[Mount]
|
||||
What=/home/$USER
|
||||
Where=/home/$USER
|
||||
Type=ecryptfs
|
||||
Options=rw,nosuid,nodev,relatime,key=passphrase:passphrase_passwd_file=/mnt/key/keyfile,no_sig_cache,ecryptfs_fnek_sig=XXXXX,ecryptfs_sig=XXXXX,ecryptfs_cipher=aes,ecryptfs_key_bytes=16,ecryptfs_passthrough=n,ecryptfs_unlink_sigs
|
||||
|
||||
[Install]
|
||||
WantedBy=local-fs.target
|
||||
{% endhighlight %}
|
||||
|
||||
<p><code>XXXXX</code> нужно заменить на сигнатуру из опций, с которыми сейчас смонтирована директория. Также нужно вставить имя пользователя и отредактировать путь к файлу с паролем (и имя mount-юнита), если это необходимо. Автозагрука:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
systemctl enable home-$USER.mount
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Сервис для отмонтирования флешки, когда она не нужна будет:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
# cat /etc/systemd/system/umount-key.service
|
||||
[Unit]
|
||||
Description=Unmount key card
|
||||
Before=local-fs.target
|
||||
After=home-arcanis.mount
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/umount /mnt/key
|
||||
|
||||
[Install]
|
||||
WantedBy=local-fs.target
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Включаем:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
systemctl enable umount-key.service
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Перезагружаемся, если все ок, удаляем бекап. Если нет - значит что то где то неправильно сделали, восстанавливаем из режима восстановления.</p>
|
||||
|
||||
<h2><a href="#whynotfstab" class="anchor" id="whynotfstab"><span class="octicon octicon-link"></span></a>Почему не fstab?</h2>
|
||||
<p>В моем случае, мне не получилось заставить флешку монтироваться раньше. Таким образом на загрузке я попадал в консоль восстановления из которой нужно было просто продолжить загрузку. Существующие в интернете методы предлагают два возможных варианта:</p>
|
||||
|
||||
<ul>
|
||||
<li>Создать запись с опцией noauto, потом монтировать через специальную запись в <code>rc.local</code>.</li>
|
||||
<li>Создать запись с опцией nofail, потом перемонтировать все разделы через <code>rc.local</code>.</li>
|
||||
</ul>
|
||||
|
||||
<p>Оба варианта меня не устроили в виду их костыльности.</p>
|
||||
|
||||
<h2><a href="#whynotpam" class="anchor" id="whynotpam"><span class="octicon octicon-link"></span></a>Почему не pam?</h2>
|
||||
<p>Другое распространенное предложение - монтировать через запись в настройках pam. Мне этот вариант не подходит, так как у меня авторизация беспарольная по отпечатку пальца.</p>
|
174
ru/_posts/2014-12-12-encryption-home-directory.md
Normal file
174
ru/_posts/2014-12-12-encryption-home-directory.md
Normal file
@ -0,0 +1,174 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: linux, systemd, ecryptfs
|
||||
title: Как зашифровать хомяк и не об%$#аться. For dummies
|
||||
short: ecnryption-home-directory
|
||||
---
|
||||
<figure class="img"></figure> Статья посвящена шифрованию домашнего каталога с использованием ecryptfs и настройке автомонтирования посредством systemd с использованием ключа на флешке.
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#preparation" class="anchor" id="preparation"><span class="octicon octicon-link"></span></a>Шаг 0: Подготовка
|
||||
|
||||
1. Разлогинились пользователем. То есть совсем-совсем.
|
||||
2. Зашли под root в tty. Дальнейшие действия описаны от него.
|
||||
3. Передвинули наш хомяк и создали пустую директорию (`s/$USER/имя пользователя/`):
|
||||
|
||||
```bash
|
||||
mv /home/{$USER,$USER-org}
|
||||
mkdir /home/$USER
|
||||
chmod 700 /home/$USER
|
||||
chown $USER:users /home/$USER
|
||||
```
|
||||
|
||||
## <a href="#step1" class="anchor" id="step1"><span class="octicon octicon-link"></span></a>Шаг 1: Шифрование
|
||||
|
||||
Самое распространенное решение в интернетах - воспользоваться автоматическими тулзами. Однако в нашем случае они не подходят, так как нам необходимо импортировать сигнатуру ключа / пароля, что при данном решении невозможно (или у автора руки кривые).
|
||||
|
||||
Делается шифрование следующим образом (lol):
|
||||
|
||||
```bash
|
||||
mount -t ecryptfs /home/$USER /home/$USER
|
||||
```
|
||||
|
||||
В процессе он у нас задаст несколько вопросов (я предлагаю первое монтирование делать в интерактивном режиме). Ответы можно взять примерно такие (в комментариях показано, что эти опции делают), обратите внимание, что если вы что то измените, то изменится и некоторые строчки далее:
|
||||
|
||||
```bash
|
||||
# ключ или сертификат. Второе надежнее, но до тех пор пока не потеряете %)
|
||||
Select key type to use for newly created files:
|
||||
1) passphrase
|
||||
2) openssl
|
||||
Selection: 1
|
||||
# пароль
|
||||
Passphrase:
|
||||
# шифрование, ставим берем дефолт
|
||||
Select cipher:
|
||||
1) aes: blocksize = 16; min keysize = 16; max keysize = 32
|
||||
2) blowfish: blocksize = 8; min keysize = 16; max keysize = 56
|
||||
3) des3_ede: blocksize = 8; min keysize = 24; max keysize = 24
|
||||
4) twofish: blocksize = 16; min keysize = 16; max keysize = 32
|
||||
5) cast6: blocksize = 16; min keysize = 16; max keysize = 32
|
||||
6) cast5: blocksize = 8; min keysize = 5; max keysize = 16
|
||||
Selection [aes]: 1
|
||||
# размер ключа, берем дефолт
|
||||
Select key bytes:
|
||||
1) 16
|
||||
2) 32
|
||||
3) 24
|
||||
Selection [16]: 1
|
||||
# разрешать читать/писать в нешифрованные файлы в точке монтирования
|
||||
Enable plaintext passthrough (y/n) [n]: n
|
||||
# включить шифрование имен файлов
|
||||
Enable filename encryption (y/n) [n]: y
|
||||
Filename Encryption Key (FNEK) Signature [360d0573e701851e]:
|
||||
# многабукафниасилил
|
||||
Attempting to mount with the following options:
|
||||
ecryptfs_unlink_sigs
|
||||
ecryptfs_fnek_sig=360d0573e701851e
|
||||
ecryptfs_key_bytes=16
|
||||
ecryptfs_cipher=aes
|
||||
ecryptfs_sig=360d0573e701851e
|
||||
WARNING: Based on the contents of [/root/.ecryptfs/sig-cache.txt],
|
||||
it looks like you have never mounted with this key
|
||||
before. This could mean that you have typed your
|
||||
passphrase wrong.
|
||||
|
||||
# подтверждаем, выходим
|
||||
Would you like to proceed with the mount (yes/no)? : yes
|
||||
Would you like to append sig [360d0573e701851e] to
|
||||
[/root/.ecryptfs/sig-cache.txt]
|
||||
in order to avoid this warning in the future (yes/no)? : yes
|
||||
Successfully appended new sig to user sig cache file
|
||||
Mounted eCryptfs
|
||||
```
|
||||
|
||||
Далее просто копируем файлы из родного хомяка:
|
||||
|
||||
```bash
|
||||
cp -a /home/$USER-org/. /home/$USER
|
||||
```
|
||||
|
||||
## <a href="#step2" class="anchor" id="step2"><span class="octicon octicon-link"></span></a>Шаг 2: Автомонтирование с systemd
|
||||
|
||||
Создадим файл на флешке (я использовал microSD) со следующим содержанием (пароль только поставьте свой):
|
||||
|
||||
```bash
|
||||
passphrase_passwd=someverystronguniqpassword
|
||||
```
|
||||
|
||||
Добавим автомонтирование флешки (направление `/mnt/key`) в `fstab` с опцией `ro`, например так:
|
||||
|
||||
```bash
|
||||
UUID=dc3ecb41-bc40-400a-b6bf-65c5beeb01d7 /mnt/key ext2 ro,defaults 0 0
|
||||
```
|
||||
|
||||
Теперь настроим монтирование хомяка. Опции монтирования можно подглядеть как то так:
|
||||
|
||||
```bash
|
||||
mount | grep ecryptfs
|
||||
```
|
||||
|
||||
Однако замечу, что там указаны не все опции, необходимо добавить также `key`, `no_sig_cache`, `ecryptfs_passthrough`. Таким образом, для systemd mount-юнит выглядит примерно так (любители shell-простыней смогут написать свой демон, потому что через `fstab` не сработает просто так (см. ниже)).
|
||||
|
||||
```bash
|
||||
# cat /etc/systemd/system/home-$USER.mount
|
||||
[Unit]
|
||||
Before=local-fs.target
|
||||
After=mnt-key.mount
|
||||
|
||||
[Mount]
|
||||
What=/home/$USER
|
||||
Where=/home/$USER
|
||||
Type=ecryptfs
|
||||
Options=rw,nosuid,nodev,relatime,key=passphrase:passphrase_passwd_file=/mnt/key/keyfile,no_sig_cache,ecryptfs_fnek_sig=XXXXX,ecryptfs_sig=XXXXX,ecryptfs_cipher=aes,ecryptfs_key_bytes=16,ecryptfs_passthrough=n,ecryptfs_unlink_sigs
|
||||
|
||||
[Install]
|
||||
WantedBy=local-fs.target
|
||||
```
|
||||
|
||||
`XXXXX` нужно заменить на сигнатуру из опций, с которыми сейчас смонтирована директория. Также нужно вставить имя пользователя и отредактировать путь к файлу с паролем (и имя mount-юнита), если это необходимо. Автозагрука:
|
||||
|
||||
```bash
|
||||
systemctl enable home-$USER.mount
|
||||
```
|
||||
|
||||
Сервис для отмонтирования флешки, когда она не нужна будет:
|
||||
|
||||
```bash
|
||||
# cat /etc/systemd/system/umount-key.service
|
||||
[Unit]
|
||||
Description=Unmount key card
|
||||
Before=local-fs.target
|
||||
After=home-arcanis.mount
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/umount /mnt/key
|
||||
|
||||
[Install]
|
||||
WantedBy=local-fs.target
|
||||
```
|
||||
|
||||
Включаем:
|
||||
|
||||
```bash
|
||||
systemctl enable umount-key.service
|
||||
```
|
||||
|
||||
Перезагружаемся, если все ок, удаляем бекап. Если нет - значит что то где то неправильно сделали, восстанавливаем из режима восстановления.
|
||||
|
||||
## <a href="#whynotfstab" class="anchor" id="whynotfstab"><span class="octicon octicon-link"></span></a>Почему не fstab?
|
||||
|
||||
В моем случае, мне не получилось заставить флешку монтироваться раньше. Таким образом на загрузке я попадал в консоль восстановления из которой нужно было просто продолжить загрузку. Существующие в интернете методы предлагают два возможных варианта:
|
||||
|
||||
* Создать запись с опцией noauto, потом монтировать через специальную запись в `rc.local`.
|
||||
* Создать запись с опцией nofail, потом перемонтировать все разделы через `rc.local`.
|
||||
|
||||
Оба варианта меня не устроили в виду их костыльности.
|
||||
|
||||
## <a href="#whynotpam" class="anchor" id="whynotpam"><span class="octicon octicon-link"></span></a>Почему не pam?
|
||||
|
||||
Другое распространенное предложение - монтировать через запись в настройках pam. Мне этот вариант не подходит, так как у меня авторизация беспарольная по отпечатку пальца.
|
@ -1,327 +0,0 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: awesome-widgets, pytextmonitor
|
||||
title: Awesome Widgets - свистелки и перделки
|
||||
short: aw-v21-bells-and-whistles
|
||||
description: Данная статья посвящена обсуждению настройки своих скриптов и графических баров в новой версии Awesome Widgets (2.1).
|
||||
---
|
||||
<h2><a href="#intro" class="anchor" id="intro"><span class="octicon octicon-link"></span></a>Введение</h2>
|
||||
<p>Для начала, я настоятельно рекомендую для после обновления <b>не открывая настроек виджета</b> скопировать в безопасное место файл <code>$HOME/.kde4/share/config/extsysmon.conf</code>, так как старые настройки кастомных скриптов теперь несовместимы. Вообще, следует заметить, что все фичи можно настраивать и из графического интерфейса, однако я опишу, как это делается простым редактированием desktop файлов.</p>
|
||||
|
||||
<h2><a href="#general" class="anchor" id="general"><span class="octicon octicon-link"></span></a>Общее</h2>
|
||||
<p>Все элементы хранятся в двух директориях: <code>/usr/share/awesomewidgets/%TYPE%/</code> и <code>$HOME/.local/share/awesomewidgets/%TYPE%/</code> (пути могут немного отличаться в зависимости от используемого дистрибутива). Настройки в домашней директории перезаписывают глобальные настройки.</p>
|
||||
|
||||
<h2><a href="#bars" class="anchor" id="bars"><span class="octicon octicon-link"></span></a>Бары</h2>
|
||||
<p>Директория называется <code>desktops</code>, файлы настроек имеют следующие поля:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Поле</th>
|
||||
<th>Обязательное</th>
|
||||
<th>Значение</th>
|
||||
<th>По-умолчанию</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<td>да</td>
|
||||
<td>имя бара. Должно иметь вид <code>barN</code> и быть уникальным</td>
|
||||
<td>none</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Comment</th>
|
||||
<td>нет</td>
|
||||
<td>комментарий</td>
|
||||
<td>empty</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Value</th>
|
||||
<td>да</td>
|
||||
<td>значение бара. Доступны теги <code>cpu*</code>, <code>gpu</code>, <code>mem</code>, <code>swap</code>, <code>hdd*</code>, <code>bat</code></td>
|
||||
<td>cpu</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-ActiveColor</th>
|
||||
<td>да</td>
|
||||
<td>заполнение активной части в формате <code>R,G,B,A</code></td>
|
||||
<td>0,0,0,130</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-InactiveColor</th>
|
||||
<td>да</td>
|
||||
<td>заполнение неактивной части в формате <code>R,G,B,A</code></td>
|
||||
<td>255,255,255,130</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Type</th>
|
||||
<td>да</td>
|
||||
<td>тип бара. Поддерживаемые типы <code>Horizontal</code>, <code>Vertical</code>, <code>Circle</code>, <code>Graph</code></td>
|
||||
<td>Horizontal</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Direction</th>
|
||||
<td>да</td>
|
||||
<td>направление заполнения. Доступны варианты <code>LeftToRight</code>, <code>RightToLeft</code></td>
|
||||
<td>LeftToRight</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Height</th>
|
||||
<td>да</td>
|
||||
<td>высота в пикселях</td>
|
||||
<td>100</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Width</th>
|
||||
<td>да</td>
|
||||
<td>ширина в пикселях</td>
|
||||
<td>100</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Number</th>
|
||||
<td>да</td>
|
||||
<td>уникальный номер, который будет ассоциирован с данным баром. Введено для совместимости с другими расширениями. Должно быть такое же, как и в поле Name</td>
|
||||
<td>число из Name</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2><a href="#quotes" class="anchor" id="quotes"><span class="octicon octicon-link"></span></a>Котировки</h2>
|
||||
<p>Директория называется <code>quotes</code>, файлы настроек имеют следующие поля:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Поле</th>
|
||||
<th>Обязательное</th>
|
||||
<th>Значение</th>
|
||||
<th>По-умолчанию</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<td>да</td>
|
||||
<td>имя котировок</td>
|
||||
<td>none</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Comment</th>
|
||||
<td>нет</td>
|
||||
<td>комментарий</td>
|
||||
<td>empty</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Ticker</th>
|
||||
<td>да</td>
|
||||
<td>тикер из системы Yahoo! Finance</td>
|
||||
<td>EURUSD=X</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Active</th>
|
||||
<td>нет</td>
|
||||
<td>активны или нет данные котировки</td>
|
||||
<td>true</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Interval</th>
|
||||
<td>да</td>
|
||||
<td>интервал запуска котировок в стандартных интервалах обновления виджета</td>
|
||||
<td>1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Number</th>
|
||||
<td>да</td>
|
||||
<td>уникальный номер, который будет ассоциирован с данными котировками</td>
|
||||
<td>случайное число меньше 1000</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2><a href="#scripts" class="anchor" id="scripts"><span class="octicon octicon-link"></span></a>Скрипты</h2>
|
||||
<p>Директория называется <code>scripts</code>, файлы настроек имеют следующие поля:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Поле</th>
|
||||
<th>Обязательное</th>
|
||||
<th>Значение</th>
|
||||
<th>По-умолчанию</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<td>да</td>
|
||||
<td>имя скрипта</td>
|
||||
<td>none</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Comment</th>
|
||||
<td>нет</td>
|
||||
<td>комментарий</td>
|
||||
<td>empty</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Exec</th>
|
||||
<td>да</td>
|
||||
<td>путь к исполняемому файлу</td>
|
||||
<td>/usr/bin/true</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Prefix</th>
|
||||
<td>нет</td>
|
||||
<td>префикс к исполняемому файлу. Обычно не требуется, однако в отдельных случаях может потребоваться явно указать путь, например, к используемому интерпретатору</td>
|
||||
<td></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Active</th>
|
||||
<td>нет</td>
|
||||
<td>активен или нет данный скрипт</td>
|
||||
<td>true</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Redirect</th>
|
||||
<td>нет</td>
|
||||
<td>перенаправление потоков сообщений. Доступны варианты <code>stderr2stdout</code>, <code>nothing</code>, <code>stdout2stderr</code>, <code>swap</code>. stderr доступен, если запустить в режиме отладки</td>
|
||||
<td>nothing</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Interval</th>
|
||||
<td>да</td>
|
||||
<td>интервал запуска скрипта в стандартных интервалах обновления виджета</td>
|
||||
<td>1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Number</th>
|
||||
<td>да</td>
|
||||
<td>уникальный номер, который будет ассоциирован с данным скриптом</td>
|
||||
<td>случайное число меньше 1000</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Filters</th>
|
||||
<td>нет</td>
|
||||
<td>фильтры из <code>awesomewidgets-extscripts-filters.json</code> разделенные запятой</td>
|
||||
<td></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2><a href="#upgrade" class="anchor" id="upgrade"><span class="octicon octicon-link"></span></a>Обновления</h2>
|
||||
<p>Директория называется <code>upgrade</code>, файлы настроек имеют следующие поля:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Поле</th>
|
||||
<th>Обязательное</th>
|
||||
<th>Значение</th>
|
||||
<th>По-умолчанию</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<td>да</td>
|
||||
<td>имя скрипта обновлений</td>
|
||||
<td>none</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Comment</th>
|
||||
<td>нет</td>
|
||||
<td>комментарий</td>
|
||||
<td>empty</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Exec</th>
|
||||
<td>да</td>
|
||||
<td>путь к исполняемому файлу</td>
|
||||
<td>/usr/bin/true</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Filter</th>
|
||||
<td>нет</td>
|
||||
<td>регулярное выражение, которое будет применено к выдаче команды. Если не пустое, параметр <code>X-AW-Null</code> будет проигнорирован</td>
|
||||
<td></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Active</th>
|
||||
<td>нет</td>
|
||||
<td>активен или нет данный скрипт обновления</td>
|
||||
<td>true</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Null</th>
|
||||
<td>нет</td>
|
||||
<td>число строк stdout, которые будут пропущены при подсчете</td>
|
||||
<td>0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Interval</th>
|
||||
<td>да</td>
|
||||
<td>интервал запуска скрипта в стандартных интервалах обновления виджета</td>
|
||||
<td>1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Number</th>
|
||||
<td>да</td>
|
||||
<td>уникальный номер, который будет ассоциирован с данным скриптом</td>
|
||||
<td>случайное число меньше 1000</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<h2><a href="#weather" class="anchor" id="weather"><span class="octicon octicon-link"></span></a>Погода</h2>
|
||||
<p>Для показа погоды используются данные и API <a href="//openweathermap.org/" title="Сайт OpenWeatherMap">OpenWeatherMap</a>. Директория называется <code>weather</code>, файлы настроек имеют следующие поля:</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Поле</th>
|
||||
<th>Обязательное</th>
|
||||
<th>Значение</th>
|
||||
<th>По-умолчанию</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<td>да</td>
|
||||
<td>имя погоды</td>
|
||||
<td>none</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Comment</th>
|
||||
<td>нет</td>
|
||||
<td>комментарий</td>
|
||||
<td>empty</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-City</th>
|
||||
<td>да</td>
|
||||
<td>город</td>
|
||||
<td>London</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Country</th>
|
||||
<td>да</td>
|
||||
<td>двухбуквенное обозначения страны</td>
|
||||
<td>uk</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Image</th>
|
||||
<td>нет</td>
|
||||
<td>использовать изображения в качестве иконки погоды или текст</td>
|
||||
<td>uk</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-TS</th>
|
||||
<td>да</td>
|
||||
<td>на какое время прогноз (целое число). <code>0</code> - текущая погода, <code>1</code> - погода через 3 часа и т.д.</td>
|
||||
<td>0</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Active</th>
|
||||
<td>нет</td>
|
||||
<td>активен или нет данный монитор погоды</td>
|
||||
<td>true</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Interval</th>
|
||||
<td>да</td>
|
||||
<td>интервал запуска монитора в стандартных интервалах обновления виджета</td>
|
||||
<td>1</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>X-AW-Number</th>
|
||||
<td>да</td>
|
||||
<td>уникальный номер, который будет ассоциирован с данным монитором</td>
|
||||
<td>случайное число меньше 1000</td>
|
||||
</tr>
|
||||
</table>
|
97
ru/_posts/2014-12-19-aw-v21-bells-and-whistles.md
Normal file
97
ru/_posts/2014-12-19-aw-v21-bells-and-whistles.md
Normal file
@ -0,0 +1,97 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: awesome-widgets, pytextmonitor
|
||||
title: Awesome Widgets - свистелки и перделки
|
||||
short: aw-v21-bells-and-whistles
|
||||
---
|
||||
Данная статья посвящена обсуждению настройки своих скриптов и графических баров в новой версии Awesome Widgets (2.1).
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#intro" class="anchor" id="intro"><span class="octicon octicon-link"></span></a>Введение
|
||||
|
||||
Для начала, я настоятельно рекомендую для после обновления **не открывая настроек виджета** скопировать в безопасное место файл `$HOME/.kde4/share/config/extsysmon.conf`, так как старые настройки кастомных скриптов теперь несовместимы. Вообще, следует заметить, что все фичи можно настраивать и из графического интерфейса, однако я опишу, как это делается простым редактированием desktop файлов.
|
||||
|
||||
## <a href="#general" class="anchor" id="general"><span class="octicon octicon-link"></span></a>Общее
|
||||
|
||||
Все элементы хранятся в двух директориях: `/usr/share/awesomewidgets/%TYPE%/` и `$HOME/.local/share/awesomewidgets/%TYPE%/` (пути могут немного отличаться в зависимости от используемого дистрибутива). Настройки в домашней директории перезаписывают глобальные настройки.
|
||||
|
||||
## <a href="#bars" class="anchor" id="bars"><span class="octicon octicon-link"></span></a>Бары
|
||||
|
||||
Директория называется `desktops`, файлы настроек имеют следующие поля:
|
||||
|
||||
| Поле | Обязательное | Значение | По-умолчанию |
|
||||
|------|--------------|----------|--------------|
|
||||
| Name | да | имя бара. Должно иметь вид `barN` и быть уникальным | none |
|
||||
| Comment | нет | комментарий | empty |
|
||||
| X-AW-Value | да | значение бара. Доступны теги `cpu*`, `gpu`, `mem`, `swap`, `hdd*`, `bat` | cpu |
|
||||
| X-AW-ActiveColor | да | заполнение активной части в формате `R,G,B,A` | 0,0,0,130 |
|
||||
| X-AW-InactiveColor | да | заполнение неактивной части в формате `R,G,B,A` | 255,255,255,130 |
|
||||
| X-AW-Type | да | тип бара. Поддерживаемые типы `Horizontal`, `Vertical`, `Circle`, `Graph` | Horizontal |
|
||||
| X-AW-Direction | да | направление заполнения. Доступны варианты `LeftToRight`, `RightToLeft` | LeftToRight |
|
||||
| X-AW-Height | да | высота в пикселях | 100 |
|
||||
| X-AW-Width | да | ширина в пикселях | 100 |
|
||||
| X-AW-Number | да | уникальный номер, который будет ассоциирован с данным баром. Введено для совместимости с другими расширениями. Должно быть такое же, как и в поле Name | число из Name |
|
||||
|
||||
## <a href="#quotes" class="anchor" id="quotes"><span class="octicon octicon-link"></span></a>Котировки
|
||||
|
||||
Директория называется `quotes`, файлы настроек имеют следующие поля:
|
||||
|
||||
| Поле | Обязательное | Значение | По-умолчанию |
|
||||
|------|--------------|----------|--------------|
|
||||
| Name | да | имя котировок | none |
|
||||
| Comment | нет | комментарий | empty |
|
||||
| X-AW-Ticker | да | тикер из системы Yahoo! Finance | EURUSD=X |
|
||||
| X-AW-Active | нет | активны или нет данные котировки | true |
|
||||
| X-AW-Interval | да | интервал запуска котировок в стандартных интервалах обновления виджета | 1 |
|
||||
| X-AW-Number | да | уникальный номер, который будет ассоциирован с данными котировками | случайное число меньше 1000 |
|
||||
|
||||
## <a href="#scripts" class="anchor" id="scripts"><span class="octicon octicon-link"></span></a>Скрипты
|
||||
|
||||
Директория называется `scripts`, файлы настроек имеют следующие поля:
|
||||
|
||||
| Поле | Обязательное | Значение | По-умолчанию |
|
||||
|------|--------------|----------|--------------|
|
||||
| Name | да | имя скрипта | none |
|
||||
| Comment | нет | комментарий | empty |
|
||||
| Exec | да | путь к исполняемому файлу | /usr/bin/true |
|
||||
| X-AW-Prefix | нет | префикс к исполняемому файлу. Обычно не требуется, однако в отдельных случаях может потребоваться явно указать путь, например, к используемому интерпретатору |
|
||||
| X-AW-Active | нет | активен или нет данный скрипт | true |
|
||||
| X-AW-Redirect | нет | перенаправление потоков сообщений. Доступны варианты `stderr2stdout`, `nothing`, `stdout2stderr`, `swap`. stderr доступен, если запустить в режиме отладки | nothing |
|
||||
| X-AW-Interval | да | интервал запуска скрипта в стандартных интервалах обновления виджета | 1 |
|
||||
| X-AW-Number | да | уникальный номер, который будет ассоциирован с данным скриптом | случайное число меньше 1000 |
|
||||
| X-AW-Filters | нет | фильтры из `awesomewidgets-extscripts-filters.json` разделенные запятой |
|
||||
|
||||
## <a href="#upgrade" class="anchor" id="upgrade"><span class="octicon octicon-link"></span></a>Обновления
|
||||
|
||||
Директория называется `upgrade`, файлы настроек имеют следующие поля:
|
||||
|
||||
| Поле | Обязательное | Значение | По-умолчанию |
|
||||
|------|--------------|----------|--------------|
|
||||
| Name | да | имя скрипта обновлений | none |
|
||||
| Comment | нет | комментарий | empty |
|
||||
| Exec | да | путь к исполняемому файлу | /usr/bin/true |
|
||||
| X-AW-Filter | нет | регулярное выражение, которое будет применено к выдаче команды. Если не пустое, параметр `X-AW-Null` будет проигнорирован |
|
||||
| X-AW-Active | нет | активен или нет данный скрипт обновления | true |
|
||||
| X-AW-Null | нет | число строк stdout, которые будут пропущены при подсчете | 0 |
|
||||
| X-AW-Interval | да | интервал запуска скрипта в стандартных интервалах обновления виджета | 1 |
|
||||
| X-AW-Number | да | уникальный номер, который будет ассоциирован с данным скриптом | случайное число меньше 1000 |
|
||||
|
||||
## <a href="#weather" class="anchor" id="weather"><span class="octicon octicon-link"></span></a>Погода
|
||||
|
||||
Для показа погоды используются данные и API [OpenWeatherMap](//openweathermap.org/ "Сайт OpenWeatherMap"). Директория называется `weather`, файлы настроек имеют следующие поля:
|
||||
|
||||
| Поле | Обязательное | Значение | По-умолчанию |
|
||||
|------|--------------|----------|--------------|
|
||||
| Name | да | имя погоды | none |
|
||||
| Comment | нет | комментарий | empty |
|
||||
| X-AW-City | да | город | London |
|
||||
| X-AW-Country | да | двухбуквенное обозначения страны | uk |
|
||||
| X-AW-Image | нет | использовать изображения в качестве иконки погоды или текст | uk |
|
||||
| X-AW-TS | да | на какое время прогноз (целое число). `0` - текущая погода, `1` - погода через 3 часа и т.д. | 0 |
|
||||
| X-AW-Active | нет | активен или нет данный монитор погоды | true |
|
||||
| X-AW-Interval | да | интервал запуска монитора в стандартных интервалах обновления виджета | 1 |
|
||||
| X-AW-Number | да | уникальный номер, который будет ассоциирован с данным монитором | случайное число меньше 1000 |
|
@ -1,161 +0,0 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: разработка, c++, cmake
|
||||
title: Добавляем cppcheck и clang-format для проекта на cmake
|
||||
short: cppcheck-and-clang-format
|
||||
description: Небольшое How-To посвященное прикручиванию автоматической проверки стиля, а также статического анализатора к проекту на <code>C++</code>, который использует в качестве системы сборки <code>cmake</code>.
|
||||
---
|
||||
<h2><a href="#project" class="anchor" id="project"><span class="octicon octicon-link"></span></a>Проект</h2>
|
||||
<p>Наш проект имеет следующую структуру:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
sources/
|
||||
|- CMakeLists.txt
|
||||
|- 3rdparty/
|
||||
|- first_component/
|
||||
|- second_component/
|
||||
{% endhighlight %}
|
||||
|
||||
<p><b>3rdparty</b> - директория с различными дополнительными библиотеками, которую надо исключить из проверок (в дальнейшем соответствует переменной cmake <code>PROJECT_TRDPARTY_DIR</code>). Дополнительно допустим, что у нас, помимо обычных файлов исходного кода (<code>*.cpp</code>, <code>*.h</code>) есть еще какие-либо (например, <code>*.qml</code>).</p>
|
||||
|
||||
<p>Дополнительно используемые ниже команды можно вставить в pre-commit hook и невозбранно тролить коллег по ынтырпрайзу, не давая им закоммитить ничего, пока они не научатся читать <code>CONTRIBUTING.md</code>.</p>
|
||||
|
||||
<h2><a href="#cppcheck" class="anchor" id="cppcheck"><span class="octicon octicon-link"></span></a>cppcheck</h2>
|
||||
<p>Коль скоро нормальных (из коробки) статических анализаторов не завезли в open source будем использовать то, что имеется. Знатоки говорят, что <a href="//cppcheck.sourceforge.net/" title="Сайт cppcheck">cppcheck</a> при должной конфигурации будет лучше, чем любой аналог, но конфигурация его для достаточно большого проекта похожа больше на написание нового проекта. Суть добавления cppheck к проекту сводится к указанию очевидных недоработок в коде и тыканью в <s>лужу</s> них.</p>
|
||||
|
||||
<h3><a href="#cppcheck-run" class="anchor" id="cppcheck-run"><span class="octicon octicon-link"></span></a>Общий пример запуска</h3>
|
||||
<p>Тут все, казалось бы, очень просто:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
cppcheck --enable=warning,performance,portability,information,missingInclude --std=c++11 --library=qt.cfg --template="[{severity}][{id}] {message} {callstack} (On {file}:{line})" --verbose --quiet path/to/source/files/or/directory
|
||||
{% endhighlight %}
|
||||
|
||||
<ul>
|
||||
<li><code>--enable</code> говорит о том, какие уведомления надо включить. Я выключил <code>style</code> (для этого ниже мы заведем <code>clang-format</code>), <code>unusedFunction</code> - выдает false-positive для некоторых мест.</li>
|
||||
<li><code>--std</code> говорит об используемом стандарте.</li>
|
||||
<li><code>--library=qt.cfg</code> некий файл настроек, который говорит о том, что и как надо обрабатывать. Добрые разработчики предлагаю почитать на эту тему <a href="//cppcheck.sourceforge.net/manual.pdf" title="cppcheck мануал">мануал</a>. В данном случае я использовал шаблон из <code>/usr/share/cppcheck/cfg/</code>.</li>
|
||||
<li><code>--template</code> - шаблон строки уведомления.</li>
|
||||
<li><code>---verbose --quiet</code> две противоречащие друг другу опции. Первая включает более информативные сообщения, вторая выключает отчет о прогрессе.</li>
|
||||
</ul>
|
||||
|
||||
<h3><a href="#cppcheck-cmake" class="anchor" id="cppcheck-cmake"><span class="octicon octicon-link"></span></a>Интеграция с cmake</h3>
|
||||
<p>Файл <code>cppcheck.cmake</code> в корне проекта:</p>
|
||||
|
||||
{% highlight cmake %}
|
||||
# additional target to perform cppcheck run, requires cppcheck
|
||||
|
||||
# get all project files
|
||||
# HACK this workaround is required to avoid qml files checking ^_^
|
||||
file(GLOB_RECURSE ALL_SOURCE_FILES *.cpp *.h)
|
||||
foreach (SOURCE_FILE ${ALL_SOURCE_FILES})
|
||||
string(FIND ${SOURCE_FILE} ${PROJECT_TRDPARTY_DIR} PROJECT_TRDPARTY_DIR_FOUND)
|
||||
if (NOT ${PROJECT_TRDPARTY_DIR_FOUND} EQUAL -1)
|
||||
list(REMOVE_ITEM ALL_SOURCE_FILES ${SOURCE_FILE})
|
||||
endif ()
|
||||
endforeach ()
|
||||
|
||||
add_custom_target(
|
||||
cppcheck
|
||||
COMMAND /usr/bin/cppcheck
|
||||
--enable=warning,performance,portability,information,missingInclude
|
||||
--std=c++11
|
||||
--library=qt.cfg
|
||||
--template="[{severity}][{id}] {message} {callstack} \(On {file}:{line}\)"
|
||||
--verbose
|
||||
--quiet
|
||||
${ALL_SOURCE_FILES}
|
||||
)
|
||||
{% endhighlight %}
|
||||
|
||||
<p><code>cppcheck</code> умеет рекурсивно директории проверять, однако, на моем примере, мне нужно было пропустить проверку qml-файлов, потому что open source проект, в лучших традициях, сегфолтился на некоторых из них - именно для этого используется поиск исходных файлов с дальнейшим выбрасыванием из них файлов, которые не должны проверяться.</p>
|
||||
|
||||
<p>Включаем в проект (<code>CMakeLists.txt</code>)...</p>
|
||||
|
||||
{% highlight cmake %}
|
||||
include(cppcheck.cmake)
|
||||
{% endhighlight %}
|
||||
|
||||
<p>...и запускаем:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
cmake
|
||||
make cppcheck
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Дальше руками вносим необходимые исправления.</p>
|
||||
|
||||
<h3><a href="#cppcheck-adds" class="anchor" id="cppcheck-adds"><span class="octicon octicon-link"></span></a>Дополнительно</h3>
|
||||
<ul>
|
||||
<li>Можно добавить свои директории для поиска хидеров, используя опцию <code>-I dir</code>.</li>
|
||||
<li>Можно вычеркнуть файлы и/или директории из проверки, используя опцию <code>-i path/to/file/or/directory</code>.</li>
|
||||
</ul>
|
||||
|
||||
<h2><a href="#clang" class="anchor" id="clang"><span class="octicon octicon-link"></span></a>clang-format</h2>
|
||||
<p><a href="//clang.llvm.org/docs/ClangFormat.html" title="Сайт clang-format">clang-format</a> предназначен для автоматического подгона стиля под желаемый или требуемый. Среди аналогов стоит выделить <a href="//astyle.sourceforge.net/" title="Сайт astyle">astyle</a>, который имеет очень скромные возможности, и <a href="//uncrustify.sourceforge.net/" title="Сайт uncrustify">uncrustify</a>, который, наоборот, имеет слишком много опций.</p>
|
||||
|
||||
<h3><a href="#clang-run" class="anchor" id="clang-run"><span class="octicon octicon-link"></span></a>Общий пример запуска</h3>
|
||||
{% highlight bash %}
|
||||
clang-format -i -style=LLVM /path/to/source/files
|
||||
{% endhighlight %}
|
||||
|
||||
<p>(К сожалению, он <b>не умеет</b> в рекурсивный обход директории.)</p>
|
||||
|
||||
<ul>
|
||||
<li><code>-i</code> включает автозамену файлов (в противном случае, результат будет печататься в stdout).</li>
|
||||
<li><code>-style</code> выбор определенного стиля либо из предустановленных, либо из файла (<code>file</code>), см. ниже.</li>
|
||||
</ul>
|
||||
|
||||
<h3><a href="#clang-cmake" class="anchor" id="clang-cmake"><span class="octicon octicon-link"></span></a>Интеграция с cmake</h3>
|
||||
<p>Файл <code>clang-format.cmake</code> в корне проекта:</p>
|
||||
|
||||
{% highlight cmake %}
|
||||
# additional target to perform clang-format run, requires clang-format
|
||||
|
||||
# get all project files
|
||||
file(GLOB_RECURSE ALL_SOURCE_FILES *.cpp *.h)
|
||||
foreach (SOURCE_FILE ${ALL_SOURCE_FILES})
|
||||
string(FIND ${SOURCE_FILE} ${PROJECT_TRDPARTY_DIR} PROJECT_TRDPARTY_DIR_FOUND)
|
||||
if (NOT ${PROJECT_TRDPARTY_DIR_FOUND} EQUAL -1)
|
||||
list(REMOVE_ITEM ALL_SOURCE_FILES ${SOURCE_FILE})
|
||||
endif ()
|
||||
endforeach ()
|
||||
|
||||
add_custom_target(
|
||||
clangformat
|
||||
COMMAND /usr/bin/clang-format
|
||||
-style=LLVM
|
||||
-i
|
||||
${ALL_SOURCE_FILES}
|
||||
)
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Аналогичных способ поиска исходных файлов, как и для <code>cppcheck</code>, поскольку <code>clang-format</code> не умеет в рекурсию.</p>
|
||||
|
||||
<p>Включаем в проект (<code>CMakeLists.txt</code>)...</p>
|
||||
|
||||
{% highlight cmake %}
|
||||
include(clang-format.cmake)
|
||||
{% endhighlight %}
|
||||
|
||||
<p>...и запускаем:</p>
|
||||
|
||||
{% highlight bash %}
|
||||
cmake
|
||||
make clangformat
|
||||
{% endhighlight %}
|
||||
|
||||
<p>Никаких дополнительных действий не требуется.</p>
|
||||
|
||||
<h3><a href="#clang-adds" class="anchor" id="clang-adds"><span class="octicon octicon-link"></span></a>Дополнительно</h3>
|
||||
<ul>
|
||||
<li>Настройка. Можно почитать опции на <a href="//clang.llvm.org/docs/ClangFormat.html" title="Сайт clang-format">официальном сайте</a>. Также можно воспользоваться <a href="//clangformat.com/" title="Сайт">интерактивной утилитой</a> для просмотра опций. Для использования уже готового стиля за базу используем следующую команду:
|
||||
|
||||
{% highlight bash %}
|
||||
clang-format -style=LLVM -dump-config > .clang-format
|
||||
{% endhighlight %}
|
||||
|
||||
Далее редактируется полученный файл <code>.clang-format</code>. Для включения его необходимо передать опцию <code>-style=file</code>, файл должен находиться в одной из родительских директории для каждого файла (например, в корне проекта). Также, можно передать нужные опции прямо в командной строке, например <code>-style="{BasedOnStyle: llvm, IndentWidth: 8}"</code>.</li>
|
||||
</ul>
|
165
ru/_posts/2015-10-17-cppcheck-and-clang-format.md
Normal file
165
ru/_posts/2015-10-17-cppcheck-and-clang-format.md
Normal file
@ -0,0 +1,165 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: разработка, c++, cmake
|
||||
title: Добавляем cppcheck и clang-format для проекта на cmake
|
||||
short: cppcheck-and-clang-format
|
||||
---
|
||||
Небольшое How-To посвященное прикручиванию автоматической проверки стиля, а также статического анализатора к проекту на `C++`, который использует в качестве системы сборки `cmake`.
|
||||
|
||||
<!--more-->
|
||||
|
||||
## <a href="#project" class="anchor" id="project"><span class="octicon octicon-link"></span></a>Проект
|
||||
|
||||
Наш проект имеет следующую структуру:
|
||||
|
||||
```bash
|
||||
sources/
|
||||
|- CMakeLists.txt
|
||||
|- 3rdparty/
|
||||
|- first_component/
|
||||
|- second_component/
|
||||
```
|
||||
|
||||
**3rdparty** - директория с различными дополнительными библиотеками, которую надо исключить из проверок (в дальнейшем соответствует переменной cmake `PROJECT_TRDPARTY_DIR`). Дополнительно допустим, что у нас, помимо обычных файлов исходного кода (`*.cpp`, `*.h`) есть еще какие-либо (например, `*.qml`).
|
||||
|
||||
Дополнительно используемые ниже команды можно вставить в pre-commit hook и невозбранно тролить коллег по ынтырпрайзу, не давая им закоммитить ничего, пока они не научатся читать `CONTRIBUTING.md`.
|
||||
|
||||
## <a href="#cppcheck" class="anchor" id="cppcheck"><span class="octicon octicon-link"></span></a>cppcheck
|
||||
|
||||
Коль скоро нормальных (из коробки) статических анализаторов не завезли в open source будем использовать то, что имеется. Знатоки говорят, что [cppcheck](//cppcheck.sourceforge.net/ "Сайт cppcheck") при должной конфигурации будет лучше, чем любой аналог, но конфигурация его для достаточно большого проекта похожа больше на написание нового проекта. Суть добавления cppheck к проекту сводится к указанию очевидных недоработок в коде и тыканью в ~~лужу~~ них.
|
||||
|
||||
### <a href="#cppcheck-run" class="anchor" id="cppcheck-run"><span class="octicon octicon-link"></span></a>Общий пример запуска
|
||||
|
||||
Тут все, казалось бы, очень просто:
|
||||
|
||||
```bash
|
||||
cppcheck --enable=warning,performance,portability,information,missingInclude --std=c++11 --library=qt.cfg --template="[{severity}][{id}] {message} {callstack} (On {file}:{line})" --verbose --quiet path/to/source/files/or/directory
|
||||
```
|
||||
|
||||
* `--enable` говорит о том, какие уведомления надо включить. Я выключил `style` (для этого ниже мы заведем `clang-format`), `unusedFunction` - выдает false-positive для некоторых мест.
|
||||
* `--std` говорит об используемом стандарте.
|
||||
* `--library=qt.cfg` некий файл настроек, который говорит о том, что и как надо обрабатывать. Добрые разработчики предлагаю почитать на эту тему [мануал](//cppcheck.sourceforge.net/manual.pdf "cppcheck мануал"). В данном случае я использовал шаблон из `/usr/share/cppcheck/cfg/`.
|
||||
* `--template` - шаблон строки уведомления.
|
||||
* `---verbose --quiet` две противоречащие друг другу опции. Первая включает более информативные сообщения, вторая выключает отчет о прогрессе.
|
||||
|
||||
### <a href="#cppcheck-cmake" class="anchor" id="cppcheck-cmake"><span class="octicon octicon-link"></span></a>Интеграция с cmake
|
||||
|
||||
Файл `cppcheck.cmake` в корне проекта:
|
||||
|
||||
```cmake
|
||||
# additional target to perform cppcheck run, requires cppcheck
|
||||
|
||||
# get all project files
|
||||
# HACK this workaround is required to avoid qml files checking ^_^
|
||||
file(GLOB_RECURSE ALL_SOURCE_FILES *.cpp *.h)
|
||||
foreach (SOURCE_FILE ${ALL_SOURCE_FILES})
|
||||
string(FIND ${SOURCE_FILE} ${PROJECT_TRDPARTY_DIR} PROJECT_TRDPARTY_DIR_FOUND)
|
||||
if (NOT ${PROJECT_TRDPARTY_DIR_FOUND} EQUAL -1)
|
||||
list(REMOVE_ITEM ALL_SOURCE_FILES ${SOURCE_FILE})
|
||||
endif ()
|
||||
endforeach ()
|
||||
|
||||
add_custom_target(
|
||||
cppcheck
|
||||
COMMAND /usr/bin/cppcheck
|
||||
--enable=warning,performance,portability,information,missingInclude
|
||||
--std=c++11
|
||||
--library=qt.cfg
|
||||
--template="[{severity}][{id}] {message} {callstack} \(On {file}:{line}\)"
|
||||
--verbose
|
||||
--quiet
|
||||
${ALL_SOURCE_FILES}
|
||||
)
|
||||
```
|
||||
|
||||
`cppcheck` умеет рекурсивно директории проверять, однако, на моем примере, мне нужно было пропустить проверку qml-файлов, потому что open source проект, в лучших традициях, сегфолтился на некоторых из них - именно для этого используется поиск исходных файлов с дальнейшим выбрасыванием из них файлов, которые не должны проверяться.
|
||||
|
||||
Включаем в проект (`CMakeLists.txt`)...
|
||||
|
||||
```cmake
|
||||
include(cppcheck.cmake)
|
||||
```
|
||||
|
||||
...и запускаем:
|
||||
|
||||
```bash
|
||||
cmake
|
||||
make cppcheck
|
||||
```
|
||||
|
||||
Дальше руками вносим необходимые исправления.
|
||||
|
||||
### <a href="#cppcheck-adds" class="anchor" id="cppcheck-adds"><span class="octicon octicon-link"></span></a>Дополнительно
|
||||
|
||||
* Можно добавить свои директории для поиска хидеров, используя опцию `-I dir`.
|
||||
* Можно вычеркнуть файлы и/или директории из проверки, используя опцию `-i path/to/file/or/directory`.
|
||||
|
||||
## <a href="#clang" class="anchor" id="clang"><span class="octicon octicon-link"></span></a>clang-format
|
||||
|
||||
[clang-format](//clang.llvm.org/docs/ClangFormat.html "Сайт clang-format") предназначен для автоматического подгона стиля под желаемый или требуемый. Среди аналогов стоит выделить [astyle](//astyle.sourceforge.net/ "Сайт astyle"), который имеет очень скромные возможности, и [uncrustify](//uncrustify.sourceforge.net/ "Сайт uncrustify"), который, наоборот, имеет слишком много опций.
|
||||
|
||||
### <a href="#clang-run" class="anchor" id="clang-run"><span class="octicon octicon-link"></span></a>Общий пример запуска
|
||||
|
||||
```bash
|
||||
clang-format -i -style=LLVM /path/to/source/files
|
||||
```
|
||||
|
||||
(К сожалению, он **не умеет** в рекурсивный обход директории.)
|
||||
|
||||
* `-i` включает автозамену файлов (в противном случае, результат будет печататься в stdout).
|
||||
* `-style` выбор определенного стиля либо из предустановленных, либо из файла (`file`), см. ниже.
|
||||
|
||||
### <a href="#clang-cmake" class="anchor" id="clang-cmake"><span class="octicon octicon-link"></span></a>Интеграция с cmake
|
||||
|
||||
Файл `clang-format.cmake` в корне проекта:
|
||||
|
||||
```cmake
|
||||
# additional target to perform clang-format run, requires clang-format
|
||||
|
||||
# get all project files
|
||||
file(GLOB_RECURSE ALL_SOURCE_FILES *.cpp *.h)
|
||||
foreach (SOURCE_FILE ${ALL_SOURCE_FILES})
|
||||
string(FIND ${SOURCE_FILE} ${PROJECT_TRDPARTY_DIR} PROJECT_TRDPARTY_DIR_FOUND)
|
||||
if (NOT ${PROJECT_TRDPARTY_DIR_FOUND} EQUAL -1)
|
||||
list(REMOVE_ITEM ALL_SOURCE_FILES ${SOURCE_FILE})
|
||||
endif ()
|
||||
endforeach ()
|
||||
|
||||
add_custom_target(
|
||||
clangformat
|
||||
COMMAND /usr/bin/clang-format
|
||||
-style=LLVM
|
||||
-i
|
||||
${ALL_SOURCE_FILES}
|
||||
)
|
||||
```
|
||||
|
||||
Аналогичных способ поиска исходных файлов, как и для `cppcheck`, поскольку `clang-format` не умеет в рекурсию.
|
||||
|
||||
Включаем в проект (`CMakeLists.txt`)...
|
||||
|
||||
```cmake
|
||||
include(clang-format.cmake)
|
||||
```
|
||||
|
||||
...и запускаем:
|
||||
|
||||
```bash
|
||||
cmake
|
||||
make clangformat
|
||||
```
|
||||
|
||||
Никаких дополнительных действий не требуется.
|
||||
|
||||
### <a href="#clang-adds" class="anchor" id="clang-adds"><span class="octicon octicon-link"></span></a>Дополнительно
|
||||
|
||||
* Настройка. Можно почитать опции на [официальном сайте](//clang.llvm.org/docs/ClangFormat.html "Сайт clang-format"). Также можно воспользоваться [интерактивной утилитой](//clangformat.com/ "Сайт") для просмотра опций. Для использования уже готового стиля за базу используем следующую команду:
|
||||
|
||||
```bash
|
||||
clang-format -style=LLVM -dump-config > .clang-format
|
||||
```
|
||||
|
||||
Далее редактируется полученный файл `.clang-format`. Для включения его необходимо передать опцию `-style=file`, файл должен находиться в одной из родительских директории для каждого файла (например, в корне проекта). Также, можно передать нужные опции прямо в командной строке, например `-style="{BasedOnStyle: llvm, IndentWidth: 8}"`.
|
@ -1,10 +0,0 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: сайт
|
||||
title: Изменения URL
|
||||
short: url-changes
|
||||
description: Хочу заметить, что я изменил адреса сайта и репозитория с <a href="//arcanis.name">arcanis.name</a> на <a href="//arcanis.me">arcanis.me</a>. Изменения были сделаны исключительно потому что ME домен чуть более симпатичнее. Старые адреса пока еще рабочие и будут такими до марта 2016 год (дата регистрации домена), но на текущий момент я настроил переадресацию со старых адресов на новые. Извините за недобства.
|
||||
---
|
10
ru/_posts/2016-01-09-url-changes.md
Normal file
10
ru/_posts/2016-01-09-url-changes.md
Normal file
@ -0,0 +1,10 @@
|
||||
---
|
||||
category: ru
|
||||
type: paper
|
||||
hastr: true
|
||||
layout: paper
|
||||
tags: сайт
|
||||
title: Изменения URL
|
||||
short: url-changes
|
||||
---
|
||||
Хочу заметить, что я изменил адреса сайта и репозитория с [arcanis.name](//arcanis.name) на [arcanis.me](//arcanis.me). Изменения были сделаны исключительно потому что ME домен чуть более симпатичнее. Старые адреса пока еще рабочие и будут такими до марта 2016 год (дата регистрации домена), но на текущий момент я настроил переадресацию со старых адресов на новые. Извините за недобства.
|
@ -24,6 +24,6 @@ hastr: true
|
||||
<a href="{{ post.url }}" title="{{ post.title }}">{{ post.title }}</a>
|
||||
</h1>
|
||||
<p><i>{% include shortdate_to_ru.html %}</i></p>
|
||||
<p>{{ post.description }}</p>
|
||||
<p>{{ post.excerpt }}</p>
|
||||
<p><b>Теги</b>: {{ post.tags }}</p>
|
||||
{% endfor %}
|
||||
|
@ -18,7 +18,7 @@
|
||||
{% else %}
|
||||
<item>
|
||||
<title>{{ post.title | xml_escape }}</title>
|
||||
<description>{{ post.description | xml_escape }}</description>
|
||||
<description>{{ post.excerpt | xml_escape }}</description>
|
||||
<pubDate>{{ post.date | date: "%a, %d %b %Y %H:%M:%S %z" }}</pubDate>
|
||||
<link>{{ site.url }}{{ post.url }}</link>
|
||||
<guid isPermaLink="true">{{ site.url }}{{ post.url }}</guid>
|
||||
|
@ -19,7 +19,6 @@
|
||||
<item>
|
||||
<title>{{ post.title | xml_escape }}</title>
|
||||
<description>
|
||||
{{ post.description | xml_escape }}
|
||||
{{ post.content | xml_escape}}
|
||||
</description>
|
||||
<pubDate>{{ post.date | date: "%a, %d %b %Y %H:%M:%S %z" }}</pubDate>
|
||||
|
Loading…
Reference in New Issue
Block a user