Skip to content

Instantly share code, notes, and snippets.

@websterl3o
Last active March 25, 2023 17:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save websterl3o/5b8eae5db42cb8e0e05621089b16c490 to your computer and use it in GitHub Desktop.
Save websterl3o/5b8eae5db42cb8e0e05621089b16c490 to your computer and use it in GitHub Desktop.

Terminal Bash, Zsh e Tinker

Otimização de tempo e produtividade


O que é Shell?

Shell é um programa que permite a comunicação entre o usuário e o computador.

O que é Bash

O Bash é um shell ou interpretador de comandos, ou seja, ele interpreta os comandos que você digita e os executa. Ele é o interpretador padrão do Linux e do Mac OS X.

Zsh

Zsh ou "Oh My Zsh" é um shell interativo de linha de comando para Unix. É um fork do Bash, com muitas funcionalidades extras, incluindo suporte a plugins e temas.

Tinker

O Tinker é uma ferramenta interativa do Laravel que permite que você execute comandos do Laravel em seu terminal.



Escrevendo comandos no Terminal


Comandos básicos bash

Comando Descrição
sudo Executa um comando como administrador
pwd Mostra o diretório atual em que você está
ls Lista os arquivos e diretórios do diretório atual
cd Navega entre os diretórios
mkdir Cria um novo diretório
touch Cria um novo arquivo
rm Remove um arquivo ou diretório
mv Renomeia ou move um arquivo ou diretório
cp Copia um arquivo ou diretório
cat Imprime o conteúdo de um arquivo
echo Imprime uma mensagem na tela
clear Limpa a tela do terminal
history Mostra o histórico de comandos que você executou

Arquivo Zshrc

O arquivo .zshrc é um arquivo de configuração do Zsh. Ele é executado sempre que você abre um novo terminal. Nele você pode definir variáveis de ambiente, aliases, funções, etc.


Criando atalhos (alias, function)

alias

O alias é um comando que permite que você crie atalhos para comandos.

Exemplos:

alias c_zshrc="code ~/.zshrc"
alias zshreload="source ~/.zshrc"
alias gco="git commit -am "
alias pa="php artisan "
alias pat="php artisan tinker"
alias pu="vendor/bin/phpunit --colors"
alias puf="pu --filter "
alias limpaCache="php artisan config:clear && php artisan cache:clear && php artisan view:clear && php artisan route:clear && php artisan debugbar:clear && redis-cli FLUSHALL"

Criando comandos

function

O function é um comando que permite que você crie comandos.

Exemplo:

# nLaravel <versao> <nome projeto>
# Cria projeto com versão especifica do laravel
function nLaravel() {
    composer create-project laravel/laravel=$1 $2
}

# Cria checkout apartir da branch atual de acordo com as regras estabelecidas
# Ex: gtB <tipo de demanda>/<numero da issue>-<nome da branch>
function gtB() {
    if [ "$3" ]; then
        git checkout -b "$1/$2-$3"
        return
    fi
    git checkout -b "$1/$2"
}

# Executa o phpunit com a cobertura de testes
# Ex: ./vendor/bin/phpunit --coverage-html=../$1
function pu_cove() {
    ./vendor/bin/phpunit --coverage-html=../$1
}

# Limpar a configuração do php do valet
# Ao excluir esse arquivo força o valet a regerar a configuração do php.
# Ex: clear_config_php
function clear_config_php() {
    # Esse caminho deve ser alterado para o caminho do valet da sua maquina esse é o usado no mac
    rm ~/.config/valet/valet.sock
}

# Importa banco de dados seja ele sql ou tar.gz
# Exemplo: fuma /caminho/do/arquivo.sql nome_do_banco
function fuma() {
    mysql -uroot -p'app' -e 'DROP DATABASE IF EXISTS $2; CREATE DATABASE $2;'
    echo 'Creating...';
    if [[ $1:t:e == "sql" ]]; then
        mysql -uroot -p'app' $2 < $1
    else
        tar -xzOf $1 | mysql -uroot -p'app' $2
    fi
    echo 'DB create success!';
    echo 'Updating password...';
    mysql -uroot -p'app' -D $2 -e 'UPDATE users SET password = "$2y$10$5tFHYlIfoModxRAp.oSn/ur3u5f7VkBrkrU8SgA7EJNvW4eLBN7ri"'
    echo 'Update password';
    echo 'OK';
}

# Remove completamente docker
function drm(){
    echo 'Desligando containers'
    docker-compose down -v
    echo 'Removendo volumes'
    rm -rf .docker
}

# Reeinicia o docker
function drs(){
    echo 'Reiniciando containers'
    drm
    echo 'Subindo containers'
    docker-compose up -d --build
}

Unindo Zshrc e Tinker

# Gera senha encriptada
# Ex: bcrypt a
function bcrypt() {
    echo "echo bcrypt('$1')" | php artisan tinker
}

# Codifica Hash de id
# Ex: encode "App\User" "30762"
function encode() {
    echo "echo $1::encodeHash($2);" | php artisan tinker
}

# Decodifica Hash de id
# Ex: decode "User" "use4k0rvv"
function decode() {
    echo "echo $1::decodeHash('$2');" | php artisan tinker
}

# Fatura uma venda usando o id
function faturaVenda() {
    echo "event(new App\Events\Faturamento(App\Venda::find('$1')));" | php artisan tinker
}

# clearCachePermission
# Limpa cache de permissão
function clearCachePermission() {
    echo "app()->make(\Spatie\Permission\PermissionRegistrar::class)->forgetCachedPermissions();" | php artisan tinker
}

# Fatura uma venda usando o hash
function faturaVendaHash() {
    echo "event(new App\Events\Faturamento(App\Venda::findByHash('$1')));" | php artisan tinker
}

# Realiza um find usando o id informado, tambem pode pegar ate 3 nives de relação/colunas especificas
# Ex: find "App\Plano" 25029
# Ex: find "App\Plano" 25029 produto
# Ex: find "App\Plano" 25029 produto user pedidos
function find() {
    echo "";
    echo "$(tput bold)Execute:";
    if [ -z "${3}" ];
        then
            echo '$(tput bold)$1::find("$2")->toArray();';
            echo "";
            echo "dd($1::find('$2')->toArray());" | php artisan tinker
        elif [ -z "${4}" ];
        then
            echo '$(tput bold)$1::find("$2")->$3;';
            echo "";
            echo "dd($1::find('$2')->$3);" | php artisan tinker
        elif [ -z "${5}" ];
        then
            echo '$(tput bold)$1::find("$2")->$3->$4;';
            echo "";
            echo "dd($1::find('$2')->$3->$4);" | php artisan tinker
        else
            echo '$(tput bold)$1::find("$2")->$3->$4->$5;';
            echo "";
            echo "dd($1::find('$2')->$3->$4->$5);" | php artisan tinker
    fi
}

# Realiza um find usando a Hash informada
# Ex: findByHash "App\Plano" "pla1row2"
# Ex: findByHash "App\Plano" "pla1row2" produto
# Ex: findByHash "App\Plano" "pla1row2" produto user pedidos
function findByHash() {
    echo "";
    echo "$(tput bold)Execute:";
    if [ -z "${3}" ]
        then
            echo '$(tput bold)$1::findByHash("$2")->toArray();';
            echo "";
            echo "dd($1::findByHash('$2')->toArray());" | php artisan tinker
    elif [ -z "${4}" ]
        then
            echo '$(tput bold)$1::findByHash("$2")->$3;';
            echo "";
            echo "dd($1::findByHash('$2')->$3);" | php artisan tinker
    elif [ -z "${5}" ]
        then
            echo '$(tput bold)$1::findByHash("$2")->$3->$4;';
            echo "";
            echo "dd($1::findByHash('$2')->$3->$4);" | php artisan tinker
    else
        echo '$(tput bold)$1::findByHash("$2")->$3->$4->$5;';
        echo "";
        echo "dd($1::findByHash('$2')->$3->$4->$5);" | php artisan tinker
    fi
}

Um problema e uma solução

A monolito hoje ela passa por um problema com relação as rotas que ela possui, que é que nos temos rotas de mais, isso faz com que o terminal quebre a resposta quando tentamos ver as rotas, para resolver isso eu criei um arquivo php que faz uma leitura utilizando o mesmo recurso que o laravel usa quando usamos o php artisan route:list, ele pega todas essas rotas e lista pra mim utilizando html basico.

Solução:

pat _script_urls_system_generate.php
<?php

use Illuminate\Routing\Router;
use Illuminate\Support\Str;

$router = app(Router::class);

$file_path = '../routes-'.Str::lower(config('app.name')).'.html';

try {
    echo 'Preparing HTML...'.PHP_EOL;
    $title       = 'Routes and Controllers';
    $description = 'Routes and controllers of the system.';

    $html = '<html>';
    $html .= '<head>';
    $html .= "<title>$title</title>";
    $html .= "<meta name='description' content='$description'>";
    $html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">';
    $html .= '</head>';
    $html .= '<body>';
    $html .= '<div class="bd-gutter my-md-4 mx-md-4 bd-layout">';
    $html .= '<main class="bd-main"><div class="bd-intro pt-2 ps-lg-2">';
    $html .= '<div class="d-md-flex align-items-center justify-content-between">
    <h1 class="bd-title mb-0" id="content">'.$title.'</h1>
    </div>';
    $html .= "<p class='bd-lead'>$description</p>";
    $html .= '</div>';

    $html .= '<div class="table-responsive">';
    $html .= '<table class="table table-striped table-dark">';
    $html .= '<thead>';
    $html .= '<tr>';
    $html .= '<th scope="col"></th>';
    $html .= '<th scope="col">Route Name</th>';
    $html .= '<th scope="col">Method</th>';
    $html .= '<th scope="col">URL</th>';
    $html .= '<th scope="col">Action</th>';
    $html .= '<th scope="col">Middleware</th>';
    $html .= '</tr>';
    $html .= '</thead>';
    $html .= '<tbody>';

    echo 'Generating table with routes...'.PHP_EOL;
    foreach ($router->getRoutes() as $route) {
        $html .= '<tr scope="row">';

        if (strpos($route->uri(), 'api/') !== false) {
            $html .= '<td><span class="badge rounded-pill text-bg-info" style="color: #fff !important;background: linear-gradient(135deg, #36a3f7 30%, #00c5dc 100%) !important;">API</span></td>';
        } else {
            $html .= '<td><span class="badge rounded-pill text-bg-info" style="color: #fff !important;background: linear-gradient(135deg, #34bfa3 30%, #00c5dc 100%) !important;">WEB</span></td>';
        }

        $html .= "<td>{$route->getName()}</td>";

        if (implode('|', $route->methods()) == 'GET|HEAD') {
            $html .= '<td><span class="badge rounded-pill text-bg-success">GET</span></td>';
        } elseif (implode('|', $route->methods()) == 'POST') {
            $html .= '<td><span class="badge rounded-pill text-bg-primary">POST</span></td>';
        } elseif (implode('|', $route->methods()) == 'PUT') {
            $html .= '<td><span class="badge rounded-pill text-bg-warning">PUT</span></td>';
        } elseif (implode('|', $route->methods()) == 'PATCH') {
            $html .= '<td><span class="badge rounded-pill text-bg-warning">PATCH</span></td>';
        } elseif (implode('|', $route->methods()) == 'DELETE') {
            $html .= '<td><span class="badge rounded-pill text-bg-danger">DELETE</span></td>';
        } else {
            $html .= '<td><span class="badge rounded-pill text-bg-secondary">'.implode('|', $route->methods()).'</span></td>';
        }

        $html .= '<td>'.config('app.url').'<span>/'.$route->uri().'</span>'.'</td>';
        $html .= '<td>'.ltrim($route->getActionName(), '\\').'</td>';
        $html .= '<td>';
        foreach ($route->middleware() as $middleware) {
            $html .= '<span class="badge rounded-pill text-bg-secondary">'.$middleware.'</span>';
        }
        $html .= '</td>';
        $html .= '</tr>';
    }

    $html .= '</tbody>';
    $html .= '</table>';
    $html .= '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>';
    $html .= '</div>';
    $html .= '</main>';
    $html .= '</div>';
    $html .= '</body>';
    $html .= '</html>';

    echo 'Saving file in "'.$file_path.'"...'.PHP_EOL;
    file_put_contents($file_path, $html);
    echo 'Done!'.PHP_EOL;
} catch (\Throwable $th) {
    echo 'Error: '.$th->getMessage().PHP_EOL;
}
exit();

Extra:

function trem() {
    echo '
        oooOOOOOOOOOOO"
        o   ____          :::::::::::::::::: :::::::::::::::::: __|-----|__
        Y_,_|[]| --++++++ |[][][][][][][][]| |[][][][][][][][]| |  [] []  |
        {|_|_|__|;|______|;|________________|;|________________|;|_________|;
        /oo--OO   oo  oo   oo oo      oo oo   oo oo      oo oo   oo     oo
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    '
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment