Quantcast
Channel: プログラミング
Viewing all articles
Browse latest Browse all 8666

Goメモ-474 (gitignore.ioのAPIを利用して .gitignore ファイルを出力) - いろいろ備忘録日記

$
0
0

関連記事

GitHub - devlights/blog-summary: ブログ「いろいろ備忘録日記」のまとめ

概要

以下、自分用のメモです。

プロジェクトを新規作成した際に、.gitignoreを生成するのは最早デフォルトになっていますね。

GithubやGitLabなどを使ってリポジトリを作成した場合は、デフォルトで作成してくれますので、あまり気になったりしませんが

そういうのを利用せずにローカルで作成している場合、どこかのプロジェクトで作っていた .gitignoreをコピーして持ってくることが多いのではないでしょうか。

私は、gitignore.ioから良く生成したりしています。

このWebサービスさん、APIを公開してくださっているので自分のプログラムから呼び出して出力することも出来ます。

以下、サンプルです。

サンプル

package main

import (
    "fmt""io""log""net/http""os""github.com/integrii/flaggy"
)

const (
    BASE_URL = "https://gitignore.io/api/"
)

var (
    langCmd *flaggy.Subcommand
    listCmd *flaggy.Subcommand

    lang string
)

func init() {
    langCmd = flaggy.NewSubcommand("lang")
    langCmd.Description = "指定した言語で .gitignore を出力"
    langCmd.AddPositionalValue(&lang, "", 1, true, "言語 (ex: go, python, java,,,)")

    listCmd = flaggy.NewSubcommand("list")
    listCmd.Description = "利用可能言語リストを出力"

    flaggy.AttachSubcommand(langCmd, 1)
    flaggy.AttachSubcommand(listCmd, 1)

    flaggy.SetName("gitignore")
    flaggy.SetDescription(".gitignoreを生成するツール")
    flaggy.SetVersion("v1.0.0")
}

func main() {
    flaggy.Parse()

    if err := run(); err != nil {
        log.Fatal(err)
    }
}

func run() error {
    var (
        err error
    )

    switch {
    case langCmd.Used:
        err = request(fmt.Sprintf("%s%s", BASE_URL, lang))
    case listCmd.Used:
        err = request(fmt.Sprintf("%s%s", BASE_URL, "list"))
    default:
        flaggy.ShowHelp("")
    }

    if err != nil {
        return err
    }

    returnnil
}

func request(url string) error {
    var (
        res *http.Response
        err error
    )

    res, err = http.Get(url)
    if err != nil {
        return err
    }
    defer res.Body.Close()

    _, err = io.Copy(os.Stdout, res.Body)
    if err != nil {
        return err
    }

    returnnil
}

以下のようにして利用します。

$ go build -o gitignore .
$ ./gitignore lang Go
# Created by https://www.toptal.com/developers/gitignore/api/Go# Edit at https://www.toptal.com/developers/gitignore?templates=Go### Go #### If you prefer the allow list template instead of the deny list, see community template:# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore## Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, built with `go test -c`
*.test# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# Dependency directories (remove the comment below to include it)# vendor/# Go workspace file
go.work

# End of https://www.toptal.com/developers/gitignore/api/Go

以下にアップしてありますので、良かったらご参考まで。

try-golang/examples/singleapp/gitignore at main · devlights/try-golang · GitHub

参考情報

Goのおすすめ書籍


過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。


Viewing all articles
Browse latest Browse all 8666