HRR Co., Ltd.

技術的な記録を残していくことを目的としています。1次情報を大事にしています。

HugoをCygwinで使ってみる

はじめに

最終的なゴールは静的コンテンツのブログサイト構築です。
その第一歩として、Hugoのインストールを行います。
Windows 10 + Cygwin です。

自前でサーバーを準備して、ブログシステムを入れたいと思っています。
真っ先に思いついたのがWordPressでした。
しかしWordPressはしょっちゅう脆弱性に対する更新プログラムが配られているようなイメージがあります(偏見でしたらすみません…)。
ちょっとメンテナンスが大変になるなと。

そこで、早さや脆弱性対策を鑑みて、静的コンテンツでリリースできる形を目指しました。
そこで選んだのがHugoです。

Hugoとは

gohugo.io

Hugo is a fast and modern static site generator written in Go, and designed to make website creation fun again.

HugoはGo言語で書かれた早くてモダンな静的サイトジェネレータですよ。またWebサイトの創作を再び面白くするためにデザインされてますよ。(意訳)

と書かれている通り、静的サイトを生成するツールです。
インプットはMarkdownファイルで、アウトプットがディレクトリ付きのサイトになります。

Hugoのインストール

gohugo.io

何となくMac推しであるような気が…。
Cygwinで使う場合は、Windowsのexeファイルを手に入れるのが早いと思います。

github.com

私の場合は hugo_0.58.1_Windows-64bit.zip でした。
これの中身、hugo.exe/usr/local/bin/ にコピーすればOKです。試しに下記コマンドを実行してみるといいと思います。

$ hugo version
Hugo Static Site Generator v0.58.1-24277B92 windows/amd64 BuildDate: 2019-09-06T09:19:22Z

Hugoを使ってみる

gohugo.io

Quick Start があるので、これに従います。

Step 1: Install Hugo

これは終わったのでスキップします。

Step 2: Create a New Site

新しいサイトを作成します。
作業ディレクトリを作成しておきます。

$ mkdir -p ~/work/hugo/
$ cd ~/work/hugo/

記載されたコマンドを実行します。

$ hugo new site quickstart
Congratulations! Your new Hugo site is created in C:\cygwin64\home\${USER}\work\hugo\quickstart.

Just a few more steps and you're ready to go:

1. Download a theme into the same-named folder.
   Choose a theme from https://themes.gohugo.io/ or
   create your own with the "hugo new theme <THEMENAME>" command.
2. Perhaps you want to add some content. You can add single files
   with "hugo new <SECTIONNAME>\<FILENAME>.<FORMAT>".
3. Start the built-in live server via "hugo server".

Visit https://gohugo.io/ for quickstart guide and full documentation.

このあとの手順も出力されてますね。
簡単に訳すと、

  1. テーマを同じ名前をつけたフォルダにダウンロードしてね。
  2. 多分あなたはコンテンツを追加したいよね。hugo new <SECTIONNAME>\<FILENAME>.<FORMAT> でシングルファイルを追加できるよ。
  3. hugo server でビルトインの本番サーバーを立ち上げよう。

こんな感じでしょうか。

Step 3: Add a Theme

というわけで、テーマを追加します。
今回は書いてあるとおりに、anankeというテーマを入れてみます。
Git使います。

cd quickstart
 
# テーマのダウンロードと設置
git init
git submodule add https://github.com/budparr/gohugo-theme-ananke.git themes/ananke
 
# テーマを設定ファイルに追加
echo 'theme = "ananke"' >> config.toml 

こんな感じで、設定ファイルに書き込まれます。手動で書いてもいいですね。

$ cat config.toml
baseURL = "http://example.org/"
languageCode = "en-us"
title = "My New Hugo Site"
theme = "ananke"

Step 4: Add Some Content

ブログなので、コンテンツを追加します。
上にも書いたとおり、形式はhugo new <SECTIONNAME>\<FILENAME>.<FORMAT>です。
具体的には、

hugo new posts/my-first-post.md

こんな感じです。
これならコマンドを叩く必要を感じないかもしれませんが、タイトルや投稿日をファイルの中に書く必要があります(下の画像を参照のこと)。
それをファイルに書き込んでくれるので、生成はコマンドが便利かと思います。

$ cat content/posts/my-first-post.md
---
title: "My First Post"
date: 2019-10-31T06:13:32+09:00
draft: true
---

記事本文もわかるように、下のように軽く追記しておきます。

---
title: "My First Post"
date: 2019-10-31T06:13:32+09:00
draft: true
---
てすと

Step 5: Start the Hugo server

あとはビルトインサーバーが、コマンド一発で立ち上がります。

hugo server -D

-D--buildDraftsでもよく、ドラフトの記事(作成途中、未公開)も含めて表示しちゃうオプションのようです。

URLはデフォルトで http://localhost:1313/ のようですので、表示してみましょう。
きっと画像のようになるはず。

f:id:hrroct:20191029153120p:plain

Step 6: Customize the Theme

テーマのカスタマイズも必要かもしれませんが、何よりサイト名や言語設定を変更しておく必要があります。

$ cat config.toml
baseURL = "http://example.org/"
languageCode = "en-us"
title = "My New Hugo Site"
theme = "ananke"

それぞれの項目を、自分に合わせた内容に修正します。

Step 7: Build static pages

最後です。
最終目標である、静的コンテンツを生成します。コマンドは簡単で、

hugo

と打つだけです。
./public/フォルダに出力されますが、コンテンツがdraft: falseの場合、この出力に含まれませんので、ご注意ください。
(というか出力されたら困るものですが…)

おわりに

というわけで、記事はMarkdownなどテキスト形式で書くことができ、hugoコマンド一発で静的コンテンツの生成ができます。
あとはこれをサーバーに公開するところまで、ワンストップでできるといいのですが…。

それはまた調べてみます。
以上でした!

GASでセルの書式を指定して値を入れる

はじめに

小ネタです。
GAS (Google Apps Script) を利用して、セルに値を入れる際、書式を指定したいケースがあると思います。

例えば、IDや電話番号など、頭に0がつく数字の場合。そのまま入れると、おそらく0が消えて値が入ることになると思います。
そんなときの書式の指定方法です。

やり方

developers.google.com

setNumberFormatメソッドを使います。
例にあるように、decimalの指定もできますし、

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var cell = sheet.getRange("B2");
// Always show 3 decimal points
cell.setNumberFormat("0.000");

@を指定することで、書式なしで(raw textで)入れることもできます。

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var telNumber = "09000000000";
sheet.getRange(1, 2).setNumberFormat('@').setValue(telNumber);

指定できるものは、ドキュメントに書いてあるので、詳細はそちらを見ましょう。

developers.google.com

最後に

GASを使う機会が増えてきました。
Macでも問題なく使うことができたり、GmailGoogle Driveと連携できるのがいいですね。

以上でした。

RustをWindows 10 (Cygwin)で試してみた話

はじめに

最近はすっかりWeb系スクリプト言語しか触らなくなってしまいました。
たまには毛色の異なる言語を使いたいと思い、Rustに手を出してみました。

Windows 10でCygwinを使った環境構築と、「Hello, World」までをやります。

参考URL:
rustup.rs - The Rust toolchain installer プログラミング言語Rust

手順

Rustのインストール

下記に書いてある通りではあるんですが…細かく見ていきます。
rustup.rs

doc.rust-jp.rs

Windowsの場合はexeをダウンロードして実行するのが普通のようですが、

If you're a Windows Subsystem for Linux user run the following in your terminal, then follow the onscreen instructions to install Rust.

WSLユーザーはターミナルで下記を実行して、Rustをインストールしてね(意訳)

とあるので、Cygwinの私はコマンドで実行してみました。
もしコマンドでインストールできなかった場合は、上記URLのページ内にある

You appear to be running Windows 64-bit. If not, display all supported installers.

の後半部分をクリックして、インストーラーをダウンロードするとよいと思います。

$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
info: downloading installer

Rust Visual C++ prerequisites

Rust requires the Microsoft C++ build tools for Visual Studio 2013 or later,
but they don\'t seem to be installed.

The easiest way to acquire the build tools is by installing Microsoft Visual
C++ Build Tools 2019 which provides just the Visual C++ build tools:

  https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019

Please ensure the Windows 10 SDK component is included when installing the
Visual C++ Build Tools.

Alternately, you can install Visual Studio 2019, Visual Studio 2017, Visual
Studio 2015, or Visual Studio 2013 and during install select the "C++ tools":

  https://visualstudio.microsoft.com/downloads/

Install the C++ build tools before proceeding.

If you will be targeting the GNU ABI or otherwise know what you are doing then
it is fine to continue installation without the build tools, but otherwise,
install the C++ build tools before proceeding.

Continue? (Y/n) 

Rust requires the Microsoft C++ build tools for Visual Studio 2013 or later, but they don't seem to be installed.

Microsoft C++ build tools for Visual Studio 2013 かそれ以降が入っていないぞと言われました。
これが必要になるんですね。

Build Tools for Visual Studio 2019 のインストール

visualstudio.microsoft.com

上にもURLがありましたが、こちらからインストールが可能です。
Visual Studio 2019 のツール」→「Build Tools for Visual Studio 2019」
と探してみてください。

インストールを進めていくと、下記画面になります。 今回は左上の「C++ Build Tools」を選択すればOKです。

f:id:hrroct:20190816161104p:plain

Rustのインストール (続き)

先程の画面から、「Y」を入力して進めると、↓のような感じになります。

Welcome to Rust!

This will download and install the official compiler for the Rust programming
language, and its package manager, Cargo.

It will add the cargo, rustc, rustup and other commands to Cargo\'s bin
directory, located at:

  C:\Users\${USER}\.cargo\bin

This path will then be added to your PATH environment variable by modifying the
HKEY_CURRENT_USER/Environment/PATH registry key.

You can uninstall at any time with rustup self uninstall and these changes will
be reverted.

Current installation options:

   default host triple: x86_64-pc-windows-msvc
     default toolchain: stable
  modify PATH variable: yes

1) Proceed with installation (default)
2) Customize installation
3) Cancel installation
>1

デフォルト設定でよいので、1で進めます。

info: syncing channel updates for 'stable-x86_64-pc-windows-msvc'
info: latest update on 2019-07-04, rust version 1.36.0 (a53f9df32 2019-07-03)
info: downloading component 'rustc'
info: downloading component 'rust-std'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rustc'
info: installing component 'rust-std'
info: installing component 'cargo'
info: installing component 'rust-docs'
info: default toolchain set to 'stable'

  stable installed - rustc 1.36.0 (a53f9df32 2019-07-03)


Rust is installed now. Great!

To get started you need Cargo's bin directory (%USERPROFILE%\.cargo\bin) in
your PATH environment variable. Future applications will automatically have the
correct environment, but you may need to restart your current shell.

Press the Enter key to continue.

これでいったん完了です。
exeファイルはこちらに格納されています。

$ ls -l /cygdrive/c/Users/${USER}/.cargo/bin/
合計 94512
-rwx------+ 12 ${USER} ${GROUPS} 8062381 726 22:40 cargo.exe
-rwx------+ 12 ${USER} ${GROUPS} 8062381 726 22:40 cargo-clippy.exe
-rwx------+ 12 ${USER} ${GROUPS} 8062381 726 22:40 cargo-fmt.exe
-rwx------+ 12 ${USER} ${GROUPS} 8062381 726 22:40 cargo-miri.exe
-rwx------+ 12 ${USER} ${GROUPS} 8062381 726 22:40 clippy-driver.exe
-rwx------+ 12 ${USER} ${GROUPS} 8062381 726 22:40 rls.exe
-rwx------+ 12 ${USER} ${GROUPS} 8062381 726 22:40 rustc.exe
-rwx------+ 12 ${USER} ${GROUPS} 8062381 726 22:40 rustdoc.exe
-rwx------+ 12 ${USER} ${GROUPS} 8062381 726 22:40 rustfmt.exe
-rwx------+ 12 ${USER} ${GROUPS} 8062381 726 22:40 rust-gdb.exe
-rwx------+ 12 ${USER} ${GROUPS} 8062381 726 22:40 rust-lldb.exe
-rwx------+ 12 ${USER} ${GROUPS} 8062381 726 22:40 rustup.exe

このままだとパスが通っていないので、シムリンクを/usr/local/binに作成して、コマンドを実行できるようにします。

$ ./cargo --version
cargo 1.36.0 (c4fcfb725 2019-05-15)
$ cd /usr/local/bin
$ ln -s /cygdrive/c/Users/${USER}/.cargo/bin/cargo.exe cargo
$ ln -s /cygdrive/c/Users/${USER}/.cargo/bin/rustc.exe rustc
$ ln -s /cygdrive/c/Users/${USER}/.cargo/bin/rustup.exe rustup
$
$ cargo --version
cargo 1.36.0 (c4fcfb725 2019-05-15)
$
$ rustc --version
rustc 1.36.0 (a53f9df32 2019-07-03)
$
$ rustup --version
rustup 1.18.3 (435397f48 2019-05-22)

これでインストール作業はおしまいです。

Hello, World!

doc.rust-jp.rs

こちらを見て進めていきます。
プロジェクト用のディレクトリを作成し、

$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world

ファイルを作成します。

vim main.rs

ファイルの中身はこれだけです。

fn main() {
    println!("Hello, world!");
}

コンパイルして…
ちなみにコンパイルするとアレコレファイルが出来上がります。

$ rustc main.rs
$ ls -l
total 1357
-rwxr-xr-x 1 ${USER} ${GROUPS}  139264 Jul 26 19:17 main.exe
-rwxr-xr-x 1 ${USER} ${GROUPS} 1249280 Jul 26 19:17 main.pdb
-rw-r--r-- 1 ${USER} ${GROUPS}      46 Jul 26 18:46 main.rs

最後に生成された実行ファイルを実行すると…できました。

$ ./main
Hello, world!

Hello, World! その2

Cargoという、一緒にインストールしたパッケージManagerを使います。
Hello, world! くらいでは恩恵は感じませんが、基本はこのCargo経由でコンパイルするのが普通のようです。

まずはディレクトリ構成を変更、実行ファイルも一旦削除します。

$ mkdir src
$ mv main.rs src/main.rs
$ rm main  # Windowsなら'del main.exe'になります

コンパイルするには、下記コマンドを実行します。
lsも実行してみましたが、勝手にファイルやディレクトリが生成されています、

$ cargo build
   Compiling hello_world v0.0.1 (C:\cygwin64\home\${USER}\work\rust\hello_world)
    Finished dev [unoptimized + debuginfo] target(s) in 0.50s
$ ls -l
total 1222
-rwxr-xr-x  1 ${USER} ${GROUPS}     143 Jul 26 18:35 Cargo.lock
-rw-r--r--  1 ${USER} ${GROUPS}     104 Jul 26 18:35 Cargo.toml
-rwxr-xr-x  1 ${USER} ${GROUPS} 1249280 Jul 26 18:17 main.pdb
drwxr-xr-x+ 1 ${USER} ${GROUPS}       0 Jul 26 18:34 src
drwxr-xr-x+ 1 ${USER} ${GROUPS}       0 Jul 26 18:35 target

buildコマンドに引数を付けない場合、debugモードでコンパイルされているようです。
実行するには下記のコマンドを叩きます。

$ ./target/debug/hello_world
Hello, world!

いちいち階層を辿らなくとも、cargoコマンドを使っても実行できます、

$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target\debug\hello_world.exe`
Hello, world!

debugではなく、releaseモードでコンパイルする場合はこちら。

$ cargo build --release
   Compiling hello_world v0.0.1 (C:\cygwin64\home\${USER}\work\rust\hello_world)
    Finished release [optimized] target(s) in 0.25s
$ ./target/release/hello_world
Hello, world!

lsするとわかりますが、各ディレクトリに実行ファイルができていますね。
しかも容量が微妙に違います。debugモードの機能が仕組まれているんでしょうね。
(詳細は調べてません…)

$ ls -l ./target/{debug,release}/hello_world
-rwxr-xr-x 2 ${USER} ${GROUPS} 139776 Jul 26 18:35 ./target/debug/hello_world
-rwxr-xr-x 2 ${USER} ${GROUPS} 137216 Jul 26 18:38 ./target/release/hello_world

最後に

私は元々C言語系をやっていて、それからWebの世界に入りました。
そのせいかRustは懐かしさを覚えつつも、最近の言語である便利さも兼ね備えれていると感じました。

ぜひスクリプト言語がメインの方も、気分転換に他の言語を触ってみてはいかがでしょうか。 以上でした!

Python3でWebサイトのスクレイピングをCygwinから (2)

はじめに

hrroct.hatenablog.com

先日(よくみたら去年でした)の続き兼小ネタです。
さすがに前回書いた記事だけでは、実践したときに困ったことがあったので。

実例: tableタグのデータを拾ってみよう

例として、下記のtableのtrタグの内容を取得します。

<table>
    <thead>...</thead>
    <tbody>
        <tr><th>aaa</th><td class="name">bbb</td><td class="image"><img src="..." alt="ccc"></td></tr>
        <tr><th>ddd</th><td class="name">eee</td><td class="image"></td></tr>
        ...
    </tbody>
</table>
# coding: UTF-8

# Webサイトへのアクセスに使うライブラリをimport
import urllib.request
from bs4 import BeautifulSoup

url = "対象のURL"

try:
    # URLにアクセス
    html = urllib.request.urlopen(url)
except:
    print('Cannot open the url.')

try:
    # HTMLのパース
    soup = BeautifulSoup(html, "html.parser")
except:
    print('Cannnot read the html data.')

# HTMLを解析、欲しいデータを持ってくる
targets = soup.select('#target table tbody tr')

ここまではいいと思いますが、ここから先です。

# タグの中の文字列を取得する
for target in targets:
    header= target.select_one('th').get_text()
    name = target.select_one('td.name').get_text()
    image = target.select_one('td.image img')
    if image is None:
        image = ''
    else:
        image = image['alt']
    print(header + ',' + name + ',' + image)

ポイントは3つでしょうか。

  1. selectはlistオブジェクトで取得ができるので、select_oneで一つに絞りました。
  2. また、タグがない場合にはNoneが返るので、if文でチェックを入れました。
  3. 属性値の取得は、image['alt']でできました。
    (厳密にはalt属性の有無も見るべきなんでしょうが…)

さいごに

普段Pythonを使わないので、拙いながらも動かすことを優先しました。
わからなくなったら、やはりマニュアルを見るに限ります。
www.crummy.com

以上でした。

Tera Termで作業ログを残す(マクロ編)

はじめに

hrroct.hatenablog.com

以前は、Tera Termの設定画面からやりました。
しかし、この方法ではログに残さなくてもよい場合も残してしまいます。
(開発環境での作業などログに残さなくてもいいし…)

そこで、Tera Termマクロでログを残すことで、ログインマクロに仕込んで使えるようにしました。

やり方

ttssh2.osdn.jp

ここに書いてあるといえばそれまでなのですが…
使い方を紹介します。

私の場合

日時(年月日と時分秒)とホスト名をログファイル名につけるようにしています。

teraterm_20190610_210536_hostName.log

こうなります。

;; ホスト名取得 (testlinkで一応接続確認)
testlink
if result > 1 then
    gethostname hostname
endif

;; 日時を取得
gettime timestr "%Y%m%d_%H%M%S"

;; ログファイル名に日時とホスト名を入れる。
sprintf2 filename 'C:\log\teraterm_%s_%s.log' timestr hostname

;; ログ開始
logopen filename 0 0

ユーザー名をつけたい方もいると思います。
そういう場合は、下記のように取得できます。

; ユーザ名を取得
getenv 'USERNAME' username

ちなみに、ターミナルを落とせばログ取得は終わるので、明示的にログを終了させていません。
必要な方は、logcloseコマンドを入れておきましょう。

ttssh2.osdn.jp

おわりに

「ログ採取をしながら、定型処理を連続実行させる。」というワザもあるみたいです。
必要な方は、ぜひマニュアルを見てみてください。

ttssh2.osdn.jp

以上でした!