Friday, September 29, 2017

Useful Bash scripts/tools

Sometimes, we may get new environment to work with, and we may feel some lack of tools, or we would like to make some installations faster than we usually do. That's tools like Docker, Vagrant so developed.

I work in command line on my work laptop in Git Bash for Windows or on servers. From time to time, I make some scripts to optimize some actions.

Bash scrips

Install PS1 colorization for Bash (Windows/Unix)

Sources: https://gist.github.com/andkirby/389f18642fc08d1b0711d17978445f2b
Installation:
$ curl -Ls bit.ly/bash-ps1 | bash
$ . ~/.bashrc

.bashrc file initial content

Sources: https://gist.github.com/andkirby/0e2982bee321aa611bc66385dee5f399
Installation:
$  curl -Ls https://bit.ly/bash-init | bash
$ . ~/.bashrc

Install PHP binaries on Windows in Bash

Sources: https://gist.github.com/andkirby/67e87e319c376b8676d559edb759e3fe
Installation:
$ curl -Ls bit.ly/php-bash-win | bash

Install NodeJs and npm binaries in Bash for Windows

Sources: https://gist.github.com/andkirby/3f65c5a6499739c842e25fb7f6d5e682
Installation:
$ curl -Ls https://gist.github.com/andkirby/3f65c5a6499739c842e25fb7f6d5e682/raw/node-npm-git-bash-win.sh | bash

Slack Message Sender

Sources: https://gist.github.com/andkirby/67a774513215d7ba06384186dd441d9e
Installation:
$ curl -s https://gist.githubusercontent.com/andkirby/67a774513215d7ba06384186dd441d9e/raw --output /usr/bin/slack
$ chmod +x /usr/bin/slack

Install colors for nano editor

Sources: https://gist.github.com/andkirby/65607ce983c3a732ff94cc2ce4220b6d
Installation:
$ curl -Ls https://gist.githubusercontent.com/andkirby/65607ce983c3a732ff94cc2ce4220b6d/raw | bash -s -- $(cd; pwd)

SemVer sorting using Bash

Sources: https://github.com/rikby/semversort
Installation:
$ curl -Ls https://raw.github.com/rikby/semversort/master/download | bash

sscp - some wrap for scp tool

Sources: https://github.com/rikby/sscp
Installation:
$ curl -Ls https://raw.github.com/rikby/sscp/master/download | bash

xd_swi - PHP Xdebug library switcher

Sources: https://github.com/rikby/xdebug-switcher
Installation:
$ curl -Ls https://raw.github.com/rikby/xdebug-switcher/master/download | bash

Binaries Downloader - tool to download released binaries from GitHub

Sources: https://github.com/rikby/bin-downloader
Lots of my scripts use this tool to make downloading onto a target environment.

Saturday, September 12, 2015

Highlighting bash prompt and adding GIT branch

I like colors in command line. I like any colors! :)
I would like to share my own setting for bash prompt. There is comments that's why you will understand how it works.

But before you start I'd suggest to try this fast way to make it.
You just need to run this online script:

$ curl -L bit.ly/bash-ps1 | bash
$ . ~/.bashrc

That's how it will look like:








Thursday, August 14, 2014

Nginx - Simple dynamic sitemap rewrite configuration

A little note to remember...
The main goal is to create dynamic loading sitemap.xml file from some directory.
At the begining we have locale code. And sitemap file can requested from some directory.
Files should be placed to a particular directory.


location ~ /sitemap.xml|/([a-z][a-z]|[a-z][a-z]-[a-z][a-z])/(.*)sitemap.xml {
    root   /usr/local/www/apache22/data/project/;
    index /sitemap/sitemap.xml;
    try_files /sitemap/$1/$2/sitemap.xml /sitemap/$1/sitemap.xml;
}

Monday, June 23, 2014

Shell - Set GIT command output to variable

Just small note... I tried to make some shell script which works with GIT commands. So, I need to set shell output to some variable.
var=$(git pull)

I cannot do that with such approach. It always show me result.
The answer I found by link.
So we need to add a little change:
var=$(git pull 2>&1)

# or
var=$(git pull > /dev/null 2>&1)
Works!

Tuesday, May 14, 2013

PhpStorm - File - Convert line endings for files inside folder (recursive)

In the past time I've tried find any converter to convert line endings of files (it means a lot of files with one operation). There is plug-in for PhpStorm but it doesn't proper work. I've found one tool which has resolved this issue.
So, website for Swiss File Knife and some tricks related to this topic.

Update for PhpStorm (v6.0.2)

PhpStorm has possibility for batch convert line endings:
Choose folder inside navigator -> Manu File -> Line Separators

Seems in the previous versions this feature wasn't added.

Wednesday, April 17, 2013

GIT - Use global hooks / templates

There is an opportunity to use global hooks. So how you set up it? The configuration option init.templatedir will help us in that.

At first you can check exist value:
git config --global --get-all init.templatedir

If there is exist some you can check it. But if it's empty you can set up it by your path:
git config --global init.templatedir 'c:\Program Files (x86)\Git\share\git-core\templates\'
You may have another path from non-Windows system and in this way this link might help you.
It remains only put you hooks files into hooks directory:
c:\Program Files (x86)\Git\share\git-core\templates\hooks
and run command:
git init
Don't forget you have set up only templates. This templates don't used directly. By the last one command templates will copied to your .git directory. Also exist files cannot be overwritten.  So when you've created new project for copy hooks you have to run git init.

That's all.

Monday, April 8, 2013

PHPStorm - Supporting Factory methods in Magento

I'm pleased to present a new feature in new PhpStorm 6.0.1 EAP build 129.177/196 which supports generic Factory Method pattern.

How to use

So, all is ok but how to generate file .phpstorm.meta.php? We have good tool n98-magerun which can generate our needed file for Magento in the environment of PHPStorm.
So all we need that this command with expected result:

# php n98-magerun.phar dev:ide:phpstorm:meta
Generating definitions for blocks group
Generating definitions for helpers group
Generating definitions for models group
Generating definitions for resource helpers group
Generating definitions for resource models group
File .phpstorm.meta.php generated


That's all. Your IDE is supporting Magento Factory methods now. Also, in theory, this feature works for other libraries.

Thursday, December 6, 2012

FreeBSD - Upgrade PHP version. Trouble with install pkgconf-0.8.9 from pkg-config-0.25_1

I got an error when try update PHP from 5.3.6 to latest 5.3.x.
===> Installing for pkgconf-0.8.9

 ===> pkgconf-0.8.9 conflicts with installed package(s):
 pkg-config-0.25_1

 They install files into the same place.
 Please remove them first with pkg_delete(1).
 *** Error code 1

 Stop in /usr/ports/devel/pkgconf.
 *** Error code 1

 Stop in /usr/ports/lang/php5.

In previous time I updated ports.
So, it happens because port got some updates which you can see in /usr/ports/UPDATING
It say:
AFFECTS: users of devel/pkg-config
  AUTHOR: bapt@FreeBSD.org

  devel/pkg-config has been replaced by devel/pkgconf

  # portmaster -o devel/pkgconf devel/pkg-config
  or
  # portupgrade -fo devel/pkgconf pkg-config-\*

  pkgng:
  # pkg set -o devel/pkg-config:devel/pkgconf
  # pkg install -f devel/pkgconf
I chose portmaster -o devel/pkgconf devel/pkg-config and updated relation. Further it try to install PHP again.

I found this solution from forum.

Friday, November 23, 2012

Git - Get all short hashes in line by filter. Add custom command to Git

Get all short hashes in line by filter

On work we have to add all hashes of Git revisions into an appropriate task. We wrote in the commit comments code of task and title:

Fixed PROJECT1-1245: Bug on the product page in the product price
- Fixed bug in the price calculation
- Updated tests


When I did many commits I have to copy each hash and paste to ticket.
73b7468,97fdcc7,60914f6,439bd39,e32ff69,199aa4

It's not dificult but we are programmers! :) So, I throught that it would be good to write a little script which will do this one.
#!/bin/sh
# Get all hashes by filtering of commit comment
if [ "$1" != "" ]; then
    OUT=$(git log --pretty=format:'%h' --reverse --grep $@)
    OUT=$(echo -e $OUT) #del line break
    echo ${OUT// /","}
else
    echo "Please set filter string as first parameter."
    exit
fi

Call to script in Git bash:

$ ~/get_hash.sh PROJECT1-1245
73b7468,97fdcc7,60914f6,439bd39,e32ff69,199aa46


Also you can add any Git parameters:

$ ~/get_hash.sh PROJECT1-1245 -3
439bd39,e32ff69,199aa46


Add custom command to Git

Let's make it as Git functional. :) I gave to this command name allhash. So we have to copy this file to
C:\Program Files (x86)\Git\libexec\git-core (on Windows 64)
with new filename by mask git-newcommandname. Our file have to get name git-allhash.
Let's call out new command:

$ git allhash PROJECT1-1245
73b7468,97fdcc7,60914f6,439bd39,e32ff69,199aa46

$ git allhash PROJECT1-1245 -3
439bd39,e32ff69,199aa46

Monday, August 13, 2012

PHPUnit - Error installing package of PHPUnit (Windows)

When I have install one package of PHPUnit under Windows I got error message:
No releases available for package "pear.phpunit.de/PHPUnit_Selenium"
install failed


I found error message in file /PEAR/REST/13.php this message and look PEAR_Error object.

[message] => SECURITY ERROR: Will not write to C:\Users\kirby\AppData\Local\Temp\pear\cache\972ec004d6044accd5359e2e011b92cerest.cacheid as it is symlinked to C:\Users\kirby\AppData\Local\Temp\pear\cache\972ec004d6044accd5359e2e011b92cerest.cacheid - Possible symlink attack


NOTE: Plz, go to %TMP% OR %TEMP% for find yours TEMP directory.

In truth, I did not found any simlinks. I chose simple solution: remove all cache files.
You can do it or manually or via command (recommended):
pear clear-cache

Wednesday, May 30, 2012

Magento - Position of validate message

Once I had a problem with position of the validate message "This is a required field." which should be close of hidden field. I need to add validation to some block, but it was from outside the parent blocks of input element. I was looking for how it work, and found simple solution: parent block should has CSS class «field-row».

<span class="field-row">
<input class="required-entry" id="some_id" type="hidden" />
</span>

Wednesday, May 23, 2012

Magento - error on recover data from backup

When I made backup of Magento (v1.5) and recover data from this backup then I got following error:

Magento: Recoverable Error: Argument 1 passed to Mage_Core_Model_Store::setWebsite() must be an instance of Mage_Core_Model_Website


I found solution (on this page):

SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;

Tuesday, April 3, 2012

Magento - How to add new field type into Varien_Data_Form

Happens so that in the admin panel when we create new forms then it is necessary to add some element to the form Varien_Data_Form. Following example will shows how it can be done.

<?php
class My_Module_Block_Adminhtml_Product_Edit_Tab_Types extends Mage_Adminhtml_Block_Widget_Form
{
    //...

    /**
     * Prepare form
     *
     * @return Mage_Adminhtml_Block_Widget_Form
     */
    public function _prepareForm()
    {
        $form = new Varien_Data_Form();
        $this->setForm($form);
        $fieldset = $form->addFieldset('base_fieldset', array());

        $fieldset->addType('my_type',
            Mage::getConfig()->getBlockClassName('myModule/adminhtml_renderer_myType'));

        $fieldset->addField('my_type', 'label', array(
            'name'      => 'name_my_type',
            'label'     => $this->__('My Type'),
            'value'     => 'default value',
            'value_class'   => 'my-type-css-class',
        ));
        parent::_prepareForm();
        return $this;
    }

    //...
}

Next step we need to create necessary render model.


<?php
class My_Module_Block_Adminhtml_Renderer_MyType extends Varien_Data_Form_Element_Abstract
{
    /**
     * Get Html output.
     *
     * @return string
     */
    public function getElementHtml()
    {
        //do something for make HTML output
        $toHtml = "<div>My Type</div>"
        return $toHtml;
    }
}

That's all.

Wednesday, February 22, 2012

PhpStorm - Новый PhpStorm 4.0 EAP build, и где мои настройки?

Вчера узнал о новом EAP билде PhpStorm 4.0 и сегодня решил поставить. Запускается вроде бы шустро. В остальном изменений сильных не заметил пока. Но... Куда же подевались мои Live Templates, настройки? IDE теперь слаживает в ~/.WebIde40/ (было в ~/.WebIde10/). Тайна кроется в файле %PhpStorm%/bin/PhpStorm.exe.vmoptions (Windows), в параметре sessionname. Он равен как раз имени директории, только без точки. Структура все-таки внутри похожая, и но раз JetBrains перенесли в другую директорию, то наверное все же что-то изменили в новой версии. В общем, можно просто указать старое имя директории и забыть, или просинхронизировать директории.

Если вы последовали моему примеру и положили templates в DropBox, то теперь нам остается удалить templates директорию и создать симлинк по примеру (для Windows):
mklink /D c:\Users\kirby\.WebIde40\config\templates\ d:\MyDocs\dropBox\IT\phpstorm\templates\
Перезапускаем "шторм" и у нас все на месте.

Если с Live Templates мы справились, то и с пропавшими настройками/горячими клавишами можно/нужно поступить также. Нужно проделать те же операции, но только с директорией с options/keymaps и настройки/горячие клавиши "шторма" вернутся.
Есть и другие "полезные" директории, которые можно тоже просинхронизировать.

Wednesday, February 8, 2012

PhpStorm - Синхонизация Live Template

Локально шаблоны лежат в папке ~/.WebIde10/config/templates.
"~" -- это директория пользователя в системе. Под Windows это как правило C:\Users\[username].
Можно создать ссылку в DropBox, и эти шаблоны никуда не пропадут. Правда лучше настроить так чтобы на самом деле они лежали в DropBox, а директория PhpStorm ссылалась на источник.

На моем примере это так (Windows):
копируем содержимое
c:\Users\kirby\.WebIde10\config\templates\ ⇒ d:\MyDocs\dropBox\IT\phpstorm\templates\
и выполняем команду
mklink /D c:\Users\kirby\.WebIde10\config\templates\ d:\MyDocs\dropBox\IT\phpstorm\templates\

PhpStorm - Мои Live Template

Приведу некоторые live template. ...для тех кто может найдет это интересным, т.к. иногда полезно подсматривать в то, кто как делает :)

Групповой PhpDoc блок
Все время забываю как он пишется :) Итак...
Имя: group_comment
Писать имя не прийдется, достаточно применить к выделению. Правда выделять нужно так чтобы не было в выделении пробелов слева, иначе будет криво.
/**#@+
 * Group comment
 */
$SELECTION$
/**#@-*/

Switch..case
Имя: swi
(Нативной кажется нет, или не такая была...)
switch ($NAME$) {
    case 'v1':
        break;

    default:
        break;
}

Для мадженты:

PhpDoc для класса
Имя: cldoc
/**
 * Class of ...
 *
 * @category   Mage
 * @package    Mage_ModuleName
 * @author     Magento Cool Team 
 */

Создание модели
Имя: mm
Mage::getModel('$END$');


Создание хелпера
Имя: mh
Mage::helper('$END$');



Monday, February 6, 2012

PhpStorm - Live Template

О live tempate, почитать можно на Википедии - Zen Coding.
В PhpStorm можно использовать как существующие, так и свои. Перейти к настройкам можно в Settings ⇒ Live Templates. При создании, можно использовать переменные.
PhpStorm имеет только две предустановленные переменные:
$END$ - место курсора после вставки.
$SELECTION$ - место вставки выделенного текста.
Нетрудно догадаться что последнюю переменную нужно применять для шаблонов которые работают с выделением.

Также если вы хотите вставлять данные в определенных местах, то просто добавьте в эти места переменные со своим именем. При вставке у вас окажется курсор на первой переменной. При заполнении и нажатии TAB вы перейдете к следующей.

PHP - Speed Test

array_push()
Бывает в коде попадается функция array_push(). Заранее думаю что это медленее от кострукции $array[] = 'value'. Решил потестить.
Результаты:
Method array_push() $arr[] = 'value'
Time 1.3622 0.1044
Performance8% 100%
В документации тоже говорится об этом.

empty()
В коде можно использовать empty($data['key']) или isset($data['key']) && $data['key'] != true. Что же быстрее?
Method isset empty
Time 0.0476  0.0297 
Performance63%  100%
В целом разница не существенная -- ругать не будут :). Но все же лучше во всех отношениях использовать empty() потому что это почти в два раза быстрее, и меньше кода будет.

Результаты на 100 000 итераций.

Wednesday, February 1, 2012

PhpStorm - Мои горячие клавиши

Most useful hotkeys from PhpStorm

Documentation
CTRL+Q -+ pick cursor upon method/variable/constant/function/class and after pressing key combination it will show documentation of this element.

Selected
CTRL+ALT+T - Applying Live Template to the selected code.
CTRL+J - Insert Live Template pattern.
CTRL+D - Copy selected below. The same if you press CTRL+C, CTRL+V, CTRL+V. I believe this function a bit useless, that's why I updated binding of this key from "Duplicate Line or Block" to  "Duplicate Line". I found it useful to not fully select row and copy the code.

Manipulations
CTRL+SHIFT+UP - Move  a code line(s)  above.
CTRL+SHIFT+DOWN -  Move a code line(s) below. 
CTRL+Y - Remove a code line(s).
CTRL+Z - Rollback changes.
CTRL+SHIFT +Z - Roll-forward changes.

Tabs / Navigation
CTRL+TAB / CTRL+SHIFT+TAB - Switching opened tabs and internal windows. Like in many applications.
ALT+LEFT/RIGHT - Quick switching of tabs.
CTRL+ALT+LEFT/RIGHT - Moving through the history where you have been backward/forward. Very useful, use often. Cursor move to the same place where it was.
CTRL+B - Go to place of declaring of an entity in the code (method, variable, etc.).

Searching
CTRL+N - Find class by name. You can type only capital letters.
CTRL+SHIFT+N - Find file by filename/path to filename.
CTRL+SHIFT+ALT+N - Find matching by classes and methods (functions).

CTRL+SHIFT+A - Find menu element.

CTRL+F7 -Add selected text to the search in opened document.
F3 - Search by document forward.
SHIFT+F3 -  Search by document backward.
SHIFT,  SHIFT - Search everywhere. It collects all search features.

Clipboard
You can put into clipboard several copied values.
CTRL+SHIFT+V - Paste from the history of the clipboard.

History
CTRL+E - Show the history of opened files.
CTRL+ SHIFT+ E - Show the history of edited files.

Bookmarks (Bookmarks mnemonic)
F11 - Add simple bookmark.
CTRL+F11 -  Add bookmark with name in the form of letters or number. 
SHIFT+F11 - Look all bookmarks.

VCS Management
CTRL+` - context VCS menu of current file.
CTRL+K - Commit.
CTRL+T - Update (Pull).

Рефакторинг
SHIFT+F6 - Глобальное переименование. В диалоговом меню вы увидите также галочки для установки скопа поиска. Как правило если затрагиваются другие файлы, то это показывается в другом окне для подтверждения. Как правило страюсь все переименовывать с помощью этого.
CTRL+ALT+C - Выделенное перенести в константу (переведет все найденные значения в файле при желании)
CTRL+ALT+V - Выделенное перенести в переменную
CTRL+ALT+M - Выделенное перенести в новый метод класса
CTRL+ALT+F - Выделенное перенести в свойство класса

Другое
CTRL+SHIFT+X - Открыть командную строку (Там же можно пользовать и GIT'ом например)
CTRL+ALT+S - Настройки
CTRL+P - Показать передаваемые параметры внутри метода/фукции/класса. Когда курсор внутри скобок: $this->func(|);
CTRL+Q - Показать документ сущности

P.S. Настоятельно рекомендую использовать нативную раскладку для PhpStorm, а не для Eclipse, и т.д. Почему? Во-первых, потому что выше перечисленные методы будут либо на других местах, либо вообще не будет. Во-вторых, когда подходишь к коллеге по работе, то вы будете нервничать поняв что у него все "по дефолту".

Friday, January 27, 2012

PhpStorm - Memory usage

Как-то нужно было увеличить память в PhpStorm, чтобы ему легче было развернуться. Чтобы это сделать нужно править файл "%PHPSTORM_DIR%\bin\PhpStorm.exe.vmoptions". И нас интересует параметр "-Xmx". По умолчанию там стоит 500m что означает 500 МБ. Вы можете задать 1 ГБ и это будет выглядеть так: "-Xmx1g". Также можете поставить меньше если необходимо. Если же поставить очень много, то выдаст ошибку "The JVM could not be started. The maximum heap size (-Xmx) might be too large."
Как поставить, например, 2 ГБ, я не разбирался. 1-го ГБ вполне должно хватить.
Напомню что это под Windows. Но под другими системами должно быть что-то подобное.

P.S.
Столкнулся так с проблемой в PHPStorm 6 (EAP) на домашнем компьютере, когда этот параметр сильно завышен. Времени разбираться не было (возможно это из-за окружения) и закоментировал параметр -Xmx и "шторм" завелся.