Introduction

What ?

Brain is like a draft notebook. A place to store all my notes.

Why ?

While browsering dev.to, I found this article :

Then I decide to give this concept a shot.

Licence

You can do whatever the fuck you want with this.

        DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                Version 2, December 2004

Copyright 2017 papey

Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.

        DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

 0. You just DO WHAT THE FUCK YOU WANT TO.

Dev

Golang

Testing tips, golang edition

Documentation

Files

Test file should be place in the package directory and should be name using the following convention :

  • repo : github.com/go/pkg
  • package : github.com/go/pkg/example
  • package file : example/pkg.go
  • test file : exemple/pkg_test.go

Run

go test github.com/go/pkg/package

fmt.Println is not working

Gniagniagnia, use

t.Log()

or

t.Logf()

also,

go test github.com/go/pkg/package -v

How to fail

Mark test as failed (next tests executed)

t.Fail()

Mark test as failed AND exit

t.FailNow()

Print and mark test as failed

t.Error()

or

t.Errorf()

Print, mark test as failed AND exit

t.Fatal()

or

t.Fatalf()

I don't want my tests to be messy (kudos @athoune)

Assert

Shit, i want to disable my oauth test on my CI

if os.Getenv("DRONE") == "true" {
	t.Skip("Skipping test in CI environment")
}

Short mode

This test is too long ? Skip it !

if testing.Short() {
    t.Skip("Skipping test in short mode")
}
go test github.com/go/pkg/package --short

Rust

serde

Serde is rust create used to serialize and deserialize stuff.

For example, this can be used to deserialize toml into a dedicated struct.

Example, with toml

Here is how serde after version 1.0 (included) should be used with serialize/deserialize mechanisms.

Be careful, there is breaking changes before version 1.0 and you can find confusing docs.

main.rs file

// uses
use serde::Deserialize;

#[derive(Deserialize)]
struct Config {
    name: String,
    url: String,
}

fn main() {
    let content = r#"name = "example"
url = "https://example.com""#;

    let conf: Config = toml::from_str(content).unwrap();

    println!("name: {}, url: {}", conf.name, conf.url)

}

Cargo.toml file

[package]
name = "safiste"
version = "0.1.0"
authors = ["El Famoso Safiste"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serde = { version = "1.0.94", features = ["derive"] }
toml = "0.5.1"

Output

name: example, url: https://example.com

Testing

Cargo test and println!

To see stdout when using cargo run (kudos CobaltVelvet)

cargo run -- --nocapture

Web

All dev web stuff goes here

front

Babel and babel-preset-stage-2

If you want use the "Spead Operator" eg ... in javascript, you need babel-preset-stage-2.

yarn add -D babel-preset-stage-2

Then enable it your babelrc :

{
    "presets": [
        ["es2015", { "modules": false }],
        ["stage-2"]
    ]
}

js

Presentation of the main ES6 features

Spread Operator

It allows an iterable to expand items in it.

array = [1, 2];
appended = [3,4];

all = [...aray, ...appended]
console.log(all)

This can be usefull in some situations like this one :

array = [1, 2, 3, 4];
console.log(Math.min(...array));

instead of the old syntax

array = [1, 2, 3, 4];
console.log(Math.min.apply(null, array));

Rest Operator

Represent infinite number or args in an array

const sum = (...numbers) => {
    return numbers.reduce((previous, current) => {
        return previous + current;
    });
};

Arrow Function

Function can now be written like this

const f = (a, b) => a + b;
console.log(f(1,2));

instead of

function f(a, b) {
    return a + b;
}
console.log(f(1,2));

Default parameters

With arrow syntax !

const f = (a = 10) => console.log(a);
f();
f(1);

Destructuring (arrays and objects)

With arrays

const array = [1, 2];
const [a, b] = array;
console.log(a, b)

or objects

const person = { name: "Jesus", age: "33" };
const { name, age } = person;
console.log(name, age);

Regex

Non capturing group

  • 8 cats
  • 9 dogs
  • 10 cows

Match and capture ONLY the number of cats and dogs using ?:, for non capturing groups

(\d+) (?:cats|dogs)

Tools

Git

Fetch a remote branch

  • Create a local branch that tracks a remote branch
git checkout --track origin/develop

If you want to change the name of the local branch (NOT A GOOD IDEA)

git checkout --track -b gniagnia origin/develop

Ammend without editing commit message

git commit --ammend --no-edit

Copy current HEAD sha sum to clipboard

git rev-parse HEAD | xclip

SVN

Commit only selected files

svn commit -m "Message" README src/example/script.pl

Ops

macOS

iTerm

Sync sessions

Toogle the feature

⌘ + ⇧ + i

Will toggle sync and input will be sent to all sessions

GNU/Linux

Debian

Upgrade to latest stable

Enure backups !

Ensure everything is up to date

apt update
apt upgrade
apt dist-upgrade

Check package db consistency

dpkg -C

Check hold packages

Hold packages will not be upgraded, ensure there is no deps shit

apt-mark showhold

If there is anything, check with dpkg --audit

Update source list

Check

sed s/$OLDSTABLE/$STABLE/g /etc/apt/sources.list
# for exemple
sed s/stretch/buster/g /etc/apt/sources.list

Is it's ok, go

sed -i s/stretch/buster/g /etc/apt/sources.list

Do not forget stuff in source.list.d

find /etc/apt/sources.list.d/ -type f -exec sed -i s/stretch/buster/g {} \;

Simulate

apt update
apt list --upgradable

Go

apt upgrade
apt dist-upgrade

Clean

apt autoclean

Enjoy !

Shell Tips

Find stuff eating all SWAP (kudos gardouille)

find /proc -maxdepth 2 -type f -iname status -exec grep -HR VmSwap {} \; | grep -v " 0 kB"

Tools

Ansible

List all tags

ansible-playbook -i host.targets -v site.yml --list-tags

Start at a specific task (life savior)

ansible-playbook -i host.targets -v site.yml --start-at-task "The audacious task"

List hosts

ansible-playbook -i host.targets -v site.yml --list-hosts

Limit hosts

ansible-playbook -i host.targets -v site.yml --limit hostname

Jinja2, templates & carriage return

To tell Jinja2 to not mess with carriage return in templates add

#jinja2: trim_blocks:False
---

at the top of the template file

Import vs include (kudos @href)

If you want to exec a sets of tasks when a condition is true, use import_tasks.

- name: Include init tasks
  import_tasks: init.yml
  tags:
    - init
  when: proof.stat.exists == False

ìnclude_tasks will add all tasks to play run, even if the when condition is false.

Exec task(s) if a specific service is found

- name: Is Docker running ?
  service_facts:

- name: Push Telegraf docker input config if needed
  template:
    src: inputs/input.docker.conf.j2
    dest: /etc/telegraf/telegraf.d/input.docker.conf
  notify: reload telegraf
  when: "'docker' in services"

Docker

Inspect

Get container ip

docker container inspect --format='{{range .NetworkSettings.Networks }}{{ .IPAddress }}{{ end }}' upbeat_babbage

MongoDB

Non interactive conn from CLI (kudos lukhas)

Docs says

mongo --username user --password 'passwd'

Reality says

mongo --username user --password='passwd'

OpenSSL

Checking

CSR

openssl req -text -noout -verify -in request.csr

Key

openssl rsa -in privkey.key -check

Cert

openssl x509 -in certficate.crt -text -noout

Tmux

El famoso terminal multiplexer (sorry not sorry but screen is a piece of shit).

Sync panels

Sync panels can be quite usefull to do the same tasks on a different set of servers.

tmux.conf file

[...]
unbind S
bind S set-windows-option synchronize-panes
[...]

How to use it

Typical use case can be updating let's say 3 Debian servers.

  1. start tmux

  2. split in 3, use ssh to connect to the targets1.

  3. use bind prefix + S to activate sync2

  4. apt update && apt upgrade

  5. And voilà !

  6. 1

    a dedicated session can be used to automate stuff, more on that later...

    2

    by default, Ctrl + b