Next.jsとGoogle Books APIs で書籍検索する

はじめに

学習したことのアウトプットとして記録しました。 現在プログラミング学習中の実務未経験の者であり、技術的な内容などに誤りを含む可能性があるので不適切な記述などがありましたらコメントで教えていただけると幸いです

Google Books APIs

Google Books APIsは、Googleブックスにある情報を取得できるAPIです。 検索する際の項目は(リクエスト)

APIで以下の情報が入手できます(レスポンス)

  • Googleブックス上のID
  • 書籍タイトル / サブタイトル
  • 著者
  • 出版日
  • 書籍についての説明文(あらすじなど)
  • ISBN10 / ISBN13
  • ページ数
  • サムネ画像のURL

APIを利用するには楽天AmazonAPIと違って認証が必要なく、誰でも簡単に利用できます

https://developers.google.com/books/docs/v1/using?hl=ja

Next.js のプロジェクトを作成します。

npx create-react-app search-books

pages/api/ の下に books.ts を作成し、 Google Books APIs からデータを取得し、JSONデータを整形後、フロントに返す処理を書きます。

import type { NextApiRequest, NextApiResponse } from 'next';
import { Book } from '@/types/types';

//Google Books API で書籍を検索する関数
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Book[]>
) {
  let q = req.query.q || '';
  q = Array.isArray(q) ? q[0] : q;
  const data = await getData(q);
  res.status(200).json(data);
}

// Google Books API の実行と取得結果(JSON)の整形を行う関数
export async function getData(query: string): Promise<Book[]> {
  const response = await fetch(
    '<https://www.googleapis.com/books/v1/volumes?q=>' + encodeURIComponent(query)
  );
  const jsonData = await response.json();
  return jsonData.items.map((elem: any) => {
    return {
      id: elem.id,
      title: elem.volumeInfo.title,
      description: elem.volumeInfo?.description,
      pageCount: elem?.pageCount,
      image: elem.volumeInfo?.imageLinks?.thumbnail,
    };
  });
}

検索条件を設定するだけで、JSON形式で返ってきます

<https://www.googleapis.com/books/v1/volumes?q=検索したい用語>

複数語句検索したい場合は

<https://www.googleapis.com/books/v1/volumes?q=検索したい用語1> + 検索したい用語2

また次のようなフィールドを検索できます。

1 2
intitle: タイトル
inauthor: 作成者
inpublisher: パブリッシャー内
subject: ボリュームのカテゴリリス
isbn: ISBN 番号
lccn: 米国議会図書館管理番
oclc: Online Computer Library Center 番号

キーワードの後に続くテキストがそれぞれで見つかった結果を返します。

GET <https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes&key=yourAPIKey>

書籍検索ページの作成

import axios from 'axios'

const fetcher = url => axios.get(url).then(res => res.data)

function App () {
  const { data, error } = useSWR('/api/data', fetcher)
  // ...
}

import { useState } from 'react';
import useSWR from 'swr';
:

  const [query, setQuery] = useState('');
  //検索ボタンをクリックした時の処理
  //サーバーサイドのAPIを呼び出し書籍情報を取得する
  const apiUrl = '/api/books?q=';
  const { data, error } = useSWR(
    query ? `${apiUrl}${encodeURIComponent(query)}` : null,
    fetcher
  );

検索フォーム

  return (
    <form onSubmit={handleFormSubmit}>
      <input
        type='text'
        placeholder='書籍検索'
        value={query}
        onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
          setQuery(e.target.value)
        }
      />
      <button type='submit'>
        検索
      </button>
    </form>
  );
}

Google Books APIのデメリット

  • 普通に書店で並んでいる書籍などでも、情報が見つからないときある
  • 取得できるのは「書籍」だけじゃなく研究論文などもある
  • 1日あたりの利用上限は1,000件

その他 本・書籍関係のAPI

https://developers.google.com/books/docs/overview?hl=ja

https://webservice.rakuten.co.jp/documentation/books-magazine-search

https://iss.ndl.go.jp/information/api/

https://calil.jp/doc/api.html

https://openbd.jp/

参考

https://developers.google.com/books/docs/v1/using?hl=ja#PerformingSearch

https://labo.kon-ruri.co.jp/google-books-apis/

https://zenn.dev/roofeehim/articles/993b7b9f64f7e2

https://www.sukerou.com/2022/02/nextjs-google-books-apis.html

Next.js とQiita API を使って、記事データを取得する

はじめに

学習したことのアウトプットとして記録しました。 現在プログラミング学習中の実務未経験の者であり、技術的な内容などに誤りを含む可能性があるので不適切な記述などがありましたらコメントで教えていただけると幸いです


今回はuseSWRを使用しました

https://swr.vercel.app/ja/docs/getting-started

  • SWRとは、Next.jsを作成しているVercel製のライブラリ

useSWRは外部APIからのデータ取得、ローディング状態、エラーが発生した時をシンプルに記述できます。

Suspenseを使わず、useEffectで取得したデータをuseStateに格納して利用するコードの場合

const Profile = () => {
  const [profile, setProfile] = useState(null)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    (async () => {
      setLoading(true)

      const res = await fetch('/api/user')
      setProfile(await res.json())

      setLoading(false)
    })()
  }, [])

  if (profile === null || loading) {
    return <div>loading</div>
  }

  return <div>hello {profile.name}</div>
}

useSWRを使うと短く記述できる

import useSWR from 'swr'

function Profile () {
  const { data, error, isLoading } = useSWR('/api/user/123', fetcher)

  if (error) return <div>failed to load</div>
  if (isLoading) return <div>loading...</div>

  // データをレンダリングする
  return <div>{data.name}</div>
}

レスポンスの型を用意

// Pick で利用したいプロパティのみを抽出する

export type QiitaItemsProps = Pick<
  QiitaItemResponse,
  'id' | 'title' | 'user' | 'tags' | 'url'
>;

// Qiita Api レスポンスの型定義
export interface QiitaItemResponse {
  rendered_body: string;
  body: string;
  coediting: boolean;
  comments_count: number;
  created_at: string;
  group: {
    created_at: string;
    description: string;
    name: string;
    private: boolean;
    updated_at: string;
    url_name: string;
  };
  id: string;
  likes_count: number;
  private: boolean;
  reactions_count: number;
  tags: [
    {
      name: string;
      versions: string[];
    },
  ];
  title: string;
  updated_at: string;
  url: string;
  user: {
    description: string;
    facebook_id: string;
    followees_count: number;
    followers_count: number;
    github_login_name: string;
    id: string;
    items_count: number;
    linkedin_id: string;
    location: string;
    name: string;
    organization: string;
    permanent_id: number;
    profile_image_url: string;
    team_only: boolean;
    twitter_screen_name: string;
    website_url: string;
  };
  page_views_count: number;
  team_membership: {
    name: string;
  };
}

検索キーワードからQiitaAPIを叩いて検索結果を一覧表示する

export default function QiitaArticle() {
    const [query, setQuery] = useState('');
    const apiUrl = '<https://qiita.com/api/v2/items?per_page=25&query=>';
    const { data, error } = useSWR(
    query ? `${apiUrl}${encodeURIComponent(query)}` : null,
    fetcher
  );

検索フォーム

    <form onSubmit={handleFormSubmit} className='mt-12 mb-6'>
      <input
        type='text'
        placeholder='例: React'
        value={query}
        className='shadow appearance-none border rounded w-10/12 py-2 px-3 mb-4 text-gray-700 leading-tight focus:outline-none focus:shadow-outline'
        onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
          setQuery(e.target.value)
        }
      />
      <button
        type='submit'
        className='text-gray-800 font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline'
      >
        検索
      </button>
    </form>

<div>
  {error && <div>データの読み込み中にエラーが発生しました。</div>}
  {data && (
    <div>
      {data.map((item: QiitaItemsProps) => (
        <QiitaItem key={item.id} item={item} />
      ))}
    </div>
  )}
</div>

Ruby optparseについて

 

optparseとは

 Rubyではオプション解析を良い感じにやってくれるライブラリが用意されており、それがoptparseです。

OptionParserオブジェクトを作成し、そのオブジェクトに対して、コマンドラインオプションを追加することができる

 

  • parse()メソッド: コマンドライン引数を解析するためのメソッドである。引数として、コマンドライン引数のリストを渡すことができる
  • on()メソッド: コマンドラインオプションを追加するためのメソッドである。引数として、オプションの名前、エイリアス、説明、ブロックを渡すことができる
  • accept()メソッド: 引数の型を定義するためのメソッドである。引数として、型とその型に対応するブロックを渡すことができる
  • OptionParser::Completionクラス: コマンドラインオプションの補完を行うためのクラスである。OptionParserオブジェクトに対して、Completionオブジェクトを追加することができる

 

Class: OptionParser (Ruby 2.5.1)

class OptionParser - Documentation for Ruby 2.1.0

GitHub - ruby/optparse: OptionParser is a class for command-line option analysis.

HOWTO parse command line options with Ruby OptionParser · ReadySteadyCode

https://apidock.com/ruby/OptionParser

alchemists.io

基本的な使い方

 

require 'optparse'

# 1. OptionParserオブジェクトを作成する。
opt_parser = OptionParser.new do |opts|
  opts.banner = "Usage: example.rb [options]"

  # 2. OptionParserオブジェクトに対して、コマンドラインオプションを追加する。
  opts.on("-f", "--file FILE", "File name") do |file|
    puts "File name: #{file}"
  end

  opts.on("-n", "--number NUMBER", Integer, "Number") do |number|
    puts "Number: #{number}"
  end

  opts.on("-s", "--string STRING", "String") do |string|
    puts "String: #{string}"
  end
end

# 3. parse()メソッドを呼び出して、コマンドライン引数を解析する。
opt_parser.parse!


個人開発で使うReactのライブラリをまとめました

はじめに

学習したことのアウトプットとして書きました。 現在プログラミング学習中の実務未経験の者であり、技術的な内容などに誤りを含む可能性があるので不適切な記述などがありましたらコメントで教えていただけると幸いです


ライブラリを実装する際の注意

ライブラリを実装するとそれだけ処理が重くなり、レンダリングが遅くなるので過度に使い過ぎないようにするのがいい。👉 成果物の使いやすさを重視

UI, CSSフレームワーク

https://mui.com/

https://ant.design/

https://react-bootstrap.github.io/

https://chakra-ui.com/

https://headlessui.com/

https://nextui.org/

https://mantine.dev/

https://tailwindcss.com/

https://ui.shadcn.com/

HTTP Client

https://github.com/axios/axios

キャッシュ

  • RectQueryの方が多機能なので様々な機能を使いたいときはReactQuery
  • とりあえず導入したいときはSWR

https://swr.vercel.app/ja

https://tanstack.com/query/latest

フォーム、バリデーション

https://react-hook-form.com/

https://github.com/jquense/yup

https://github.com/colinhacks/zod

テキストフォーム

自動でサイズ調整してくれる

https://github.com/Andarist/react-textarea-autosize

状態管理

https://zustand-demo.pmnd.rs/

https://github.com/pmndrs/zustand

https://jotai.org/

https://recoiljs.org/

https://redux.js.org/

参考https://react-uncle-blog.netlify.app/blog/react-state-managment

アイコン

https://react-icons.github.io/react-icons/

https://fontawesome.com/v5/docs/web/use-with/react

https://mui.com/material-ui/material-icons/

ポップアップ

https://react-hot-toast.com/

https://www.npmjs.com/package/react-toastify

ローディング

https://mhnpd.github.io/react-loader-spinner/

https://www.npmjs.com/package/react-loading

セレクトボックス

https://react-select.com/home

オーディオ再生

https://howlerjs.com/

アニメーション

https://www.react-spring.dev/

https://www.framer.com/motion/

紙吹雪

https://www.npmjs.com/package/react-confetti


最後に

よく見かけるようなものを初心者がまとめてみました おすすめがあったら教えてください

Rails7でミニアプリ作るときのセットアップ

セットアップ

mkdir アプリの名前
# ディレクトリを作成

cd アプリの名前
# 作業ディレクトリを移動

ruby -v
# Rubyのバージョンを確認

bundle init
# Gemfileを作成
# gem 'rails'と修正

bundle install

rails new . -d postgresql -j esbuild --skip-test
# データベースを postgresqlに指定
# JSバンドラーを esbuild
# 何も指定しない場合、importmapになる
# テストユニットの作成をスキップ

オプション 意味
-d/ --database=mysql データベースの指定。 mysql とか postgresql などを指定する
-skip-test testを作成しない。RSpecに変更したいときに使うと良い。

rails new するときによく使うオプション - Hack Your Design!

https://qiita.com/kyntk/items/0936598a903ac74e607d

gemファイルに以下を追加し bundle install

gem 'cssbundling-rails'

tailwindをインストール

bundle exec rails css:install:tailwind

daisyUIをインストール場合

https://daisyui.com/

yarn add daisyui

tailwind.config.jsを修正

module.exports = {
  content: [
    './app/views/**/*.html.erb',
    './app/helpers/**/*.rb',
    './app/assets/stylesheets/**/*.css',
    './app/javascript/**/*.js'
  ],
  plugins: [
    require("daisyui"),
  ],
}

データベースを作成

bundle exec rails db:create

</details>

gemの導入

group :development, :test do
 :
  gem 'bullet'
  gem 'pry-byebug'
  gem 'pry-rails'
  gem 'rspec-rails'
  gem 'factory_bot_rails'
  gem 'rubocop'
  gem 'rubocop-rails'
end
group :development do
	:

  gem 'better_errors'
  gem 'binding_of_caller'
end

gem 'annotate'
gem 'enum_help'
# 日本語化、多言語化対応
gem 'rails-i18n'

<details><summary>各gemのgithub</summary>

https://github.com/flyerhzm/bullet

https://github.com/BetterErrors/better_errors

https://github.com/banister/binding_of_caller

https://github.com/ctran/annotate_models

https://github.com/thoughtbot/factory_bot_rails

</details>

検索

https://github.com/activerecord-hackery/ransack

ページネーション

https://github.com/kaminari/kaminari

ファイルアップロード

https://github.com/carrierwaveuploader/carrierwave

https://railsguides.jp/active_storage_overview.html

デコレーター

https://github.com/amatsuda/active_decorator

https://github.com/drapergem/draper

使い方

https://nekorails.hatenablog.com/entry/2018/10/13/070437

ユーザー認証(ログイン、ログアウト等)

https://github.com/heartcombo/devise

https://github.com/Sorcery/sorcery

SEO

https://github.com/kpumuk/meta-tags

環境変数を管理

https://github.com/bkeepers/dotenv

https://pikawaka.com/rails/dotenv-rails

参考

https://blog.to-ko-s.com/recomended-gems/

https://qiita.com/tikaranimaru/items/d5b42fa78772cbdcc192

https://qiita.com/tikaranimaru/items/689230e01a7b1af7fb4a

rubocopの設定

https://qiita.com/piggydev/items/074e020e07af7ebc872d

config.generators do |g|
  g.skip_routes true
  g.assets false
  g.helper false
  g.test_framework false
end

タイムゾーンなどの設定

config.time_zone = 'Asia/Tokyo'
config.active_record.default_timezone = :local
config.i18n.default_locale = :ja
config.i18n.load_path += Dir[Rails.root.join('config', 'locales','**', '*.{rb,yml}').to_s]

RSpecの設定

bundle exec rails generate rspec:install

# rails_helperを読み込む
--require rails_helper
# 出力結果をドキュメント風にして見やすくする
--format documentation
# 出力結果を色分けする
--color

# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'factory_bot'  # 追加
require 'rspec/rails'

# コメントアウト解除
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }

begin
  ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
  puts e.to_s.strip
  exit 1
end
RSpec.configure do |config|
  config.use_transactional_fixtures = true
  config.infer_spec_type_from_file_location!

  config.include FactoryBot::Syntax::Methods  # 追加
end


# コメントアウト解除
config.filter_run_when_matching :focus

annotate

bundle exec rails g annotate:install
bundle exec annotate

lib/tasks/auto_annotate_models.rake が作成される

https://techracho.bpsinc.jp/ikeda-kazuyuki/2014_08_29/18876

bullet

Rails.application.configure do
	#ここから追加
  config.after_initialize do
    Bullet.enable        = true
    Bullet.alert         = true
    Bullet.bullet_logger = false
    Bullet.console       = false
    Bullet.rails_logger  = true
    Bullet.add_footer    = true
  end
:

Bullet.enable bulletを有効
Bullet.alert JavaScriptアラートをポップアップで表示
Bullet.bullet_logger bullet用のログファイルをlog/bullet.logに出力
Bullet.console bulletがN+1を検出した際にブラウザのconsole.logにメッセージを出力
Bullet.growl Growlがインストールされている場合、Growlメッセージを表示
Bullet.rails_logger bulletがN+1を検出した際にrailsログを出力
Bullet.add_footer ブラウザで表示しているページの左下隅にN+1検出情報を表示

【Rails】N+1問題をアラート表示してくれるgem「bullet」を初心者向けにまとめてみた|TechTechMedia

その他

OGP画像設定

https://zenn.dev/yoshiki105/articles/eb093bf603e728

作成はこちらのサイトを使用している人が多い

https://www.canva.com/

Google Analytics

https://zenn.dev/yoiyoicho/articles/1fe05797a1bbc4

RailsアプリをDocker化する方法

はじめに

学習したことのアウトプットとして記録しました。 現在プログラミング学習中の実務未経験の者であり、技術的な内容などに誤りを含む可能性があるので不適切な記述などがありましたらコメントで教えていただけると幸いです

概要

すでに作成されたRailsアプリをDocker化する方法についてまとめてみました

Dockerfileとdocker-compose.ymlを用意

  • アプリケーション用とdb用のコンテナを使用します

ここではRuby 3.2.2を使用しています。RubyはDockerイメージとして提供されており、このベースイメージを使用することでRubyアプリケーションを実行できます。

host: db
user: postgres
port: 5432
password: <%= ENV.fetch("DATABASE_PASSWORD") %>

# Dockerコンテナのベースイメージを指定します。
# 元のWebアプリの.ruby-version、Gemfileを参考にします。
FROM ruby:3.2.2
# コンテナ内でLinuxパッケージの更新と必要なパッケージのインストールを行います。
# apt-get コマンドを使用して、ビルドツール、PostgreSQLクライアント、Node.js、libpq-devなどがインストールされます。
# -y オプションは、パッケージのインストール時に確認プロンプトを無効にしています。
RUN apt-get update && apt-get install -y \\\\
    build-essential \\\\
    libpq-dev \\\\
    nodejs \\\\
    postgresql-client \\\\
    yarn
# この行は、作業ディレクトリを /rails-docker に設定します。後続のコマンドはこのディレクトリ内で実行されます。
WORKDIR /rails-docker
#ローカルの Gemfile と Gemfile.lock ファイルをコンテナ内の /rails-docker/ ディレクトリにコピーします。
COPY Gemfile Gemfile.lock /rails-docker/
# Bundlerを使用してGemfileに記載されているGem依存関係をインストールします。
RUN bundle install
CMD rails s -p 3000 -b '0.0.0.0'

version: '3.9'

#データベースのデータを永続的に保存するためにdb-dataを使用
volumes:
  db-data:

#コンテナとサービスの定義
services:
#Railsアプリケーションのコンテナを指定
  web:
#Dockerイメージを現在のディレクトリ(.)からビルド
    build: .
#ホストのポート 3000 とコンテナのポート 3000 をマッピングし、Railsアプリケーションにアクセスできるようにします。
    ports:
      - '3000:3000'
#アプリケーションのコードや設定ファイルを同期させるためにローカルのファイルをコンテナ内にマウントします。
    volumes:
      - '.:/rails-docker'
#コンテナ内の環境変数を設定します。データベースのパスワードを設定します。
    environment:
      - 'DATABASE_PASSWORD=postgres'
#ターミナルをサポートし、コンテナに対話的にアクセスできるようにします。
    tty: true
    stdin_open: true
#このサービスが依存しているサービスを指定します。
    depends_on:
      - db
#他のコンテナとのリンクを設定します
    links:
      - db
#PostgreSQLデータベースのコンテナを指定します。
  db:
    image: postgres:15.3
#データベースのデータを永続的に保存するために db-data ボリュームをマウントします。
    volumes:
      - 'db-data:/var/lib/postgresql/data'
#PostgreSQLデータベースの設定を環境変数で指定します。ユーザー名,パスワードを設定します
    environment:
      - 'POSTGRES_USER=postgres'
      - 'POSTGRES_PASSWORD=postgres'

config/database.yml修正を修正します。

db作成,migrate

docker-compose build
docker-compose run web rails db:create db:migrate
docker-compose up

#コンテナをバックグラウンドで起動
docker-compose up -d
#コンテナ内に入るには
docker-compose exec web bash

ブラウザ上でhttp://localhost:3000 にアクセスします 起動できたらOK。

Gitについてまとめました

コマンド 意味
git init ディレクトリをGit管理下に置きたい時、実行すべきコマンド。リポジトリを作成することで、ディレクトリをGit管理できるようになる。このコマンドで.gitと言う隠しフォルダとGitに関連するファイルが作成される。
git add . カレントディレクトリ以下のすべての変更内容が追加
git add -all すべての変更内容がインデックスに追加
git add -A すべての変更内容がインデックスに追加
git commit -m ファイルをコミットする
git log コミットのログを確認
git log -p コミットのログだけでなくファイルの修正内容まで確認することが出来る
git branch -c 現在のブランチの複製
git branch ブランチ名 ブランチの作成
git branch -b ブランチ名 ブランチを作成し、そのあと当該ブランチに切り替える
git checkout 変更の取り消し
git checkout . 現在のワークツリーの修正を取り消す(破棄)git restore .でも同じことができる
git checkout ブランチ名 ブランチを切り替え
git switch ブランチ名 ブランチを切り替え
git diff ワークツリーでの修正内容の確認をすることが出来る
git diff –cached 「ステージングエリア」と「ローカルリポジトリ」の内容(直前のコミット)との差分を確認できる
git merge 別のブランチのコミットの変更内容を、現在のブランチに取り込む
git pull origin ブランチ名 ・リモートブランチをローカルブランチにマージする<br/>・リモートブランチを取ってきて、現在のブランチに取り込む(現在のローカルブランチに「ブランチ名」の変更を取り込む)<br/>git fetch、git mergeを同時に行うコマンド
git push ローカルブランチをリモートブランチに反映する
git fetch リモートブランチの最新情報をローカルに取ってくる。コマンドを実行するとgit branch -aなどのコマンドの結果に、リモートブランチの最新の情報が反映される。ソースコードの更新は行われないので、変更を反映させる場合は別途mergeやpullコマンドが必要
git rebase 過去のコミットを修正する※コミット履歴を改変することを嫌う人もいるので、使って良いかはチームのメンバーに確認する
git rebase -i 対話形式で過去のコミットを修正することが出来て、過去のコミットをまとめることも出来る
squash git rebaseコマンドを実行した後に出す命令として、squashが使用されることがある。記載したコミットがそれの前のコミットに統合される。
git reflog コミット履歴の確認。人為的ミスで、マージしてないブランチを削除してしまったり、git reset --hardコマンドで期待したコミットよりも過去のコミットまで戻ってしまった場合などに、HEADの動きの履歴をみることができる。
git remote -v リモートリポジトリのURL情報を確認する
git remote add リモートリポジトリの略称 リモートリポジトリのURL リモートリポジトリのURL情報を設定する。基本的にリモートリポジトリの略称の部分はoriginが使われるので、git remote add origin リモートリポジトリのURLの様な形になる。
git reset --hard HEAD^ 直近のコミットの記録と併せて変更内容ごと全て削除される
git reset --soft HEAD^ 直近のコミットは無くなり、直近のコミットでの修正内容はワークツリーに置かれる
git reset HEAD^ 直近のコミットを取り消す
git reset HEAD~n n個前のコミットを取り消す
git reset ファイル名 インデックスに追加したファイルを戻す
git restore –staged ステージングエリアの変更の取り消し
git restore --staged [ファイル名] インデックスへ追加したファイルの登録を取り消す
git restore --source=コミットハッシュ値 ファイル名 指定したコミットの内容を復元
git restore . 現在のワークツリーの修正内容を破棄。git checkout .でも同じことができる
git revert コミットID 対象のコミットで行われた変更を取り消す。間違えて行ったコミットをプッシュした場合に、その内容を打ち消すために使える。対象のコミット自体を削除するわけではない。
git rm git管理しているファイルの削除
git rm --cached Gitからは対象のファイルを削除するが、ワークツリーには対象のファイルは保持することができる。ファイルを残したままgit管理対象外になるため既に管理しているファイルなどをgit管理対象外にしたい場合に利用されやすい
git stash 現在の修正内容を一旦退避させる
git stash apply 退避した内容を元に戻す
git stash apply -u trackedになっていないファイル(git addしていない)ファイルを含めて退避する
git stash list 退避したものが確認できる
git stash pop また退避させたものを再度反映して、かつstashを削除
git tag 最新のコミットにタグを指定する
git tag -d タグを削除する
git ignore ファイルをGitで管理しない指定をする
  • Untrackedとはgitで管理ができてない状態

Git-flow

  • masterブランチとは別にdevelopブランチがあり、その他にfeature、release、hotfixというブランチがある
  • developブランチでの開発作業を進めた後に、releaseブランチを作成し、成果は最終的にmasterブランチへマージする

メリット

  • 比較的大きい規模の開発でも通用するフロー
  • 複数の権限を適切に扱える
  • ソフトウェア開発に向く

デメリット

  • 開発者がmasterブランチではなくdevelopブランチを利用しなくてはいけない →開発者が誤って変更をdevelopブランチではなくmasterブランチだけにマージするようなミスになる

github flow

  • featureブランチとmasterブランチしか使わない。

メリット

  • 小さい規模から大規模まで対応
  • SaaSwebサービス)のような常に機能アップし続けるようなプロジェクトに最適
  • コンフリクト(修正箇所の衝突)が少なくなる

デメリット

  • 権限はmasterへのコミット権限(コミッタ)と パッチ作成者(コントリビュータ)しかないため、組織体制によっては適用できない可能性がある
  • テスト環境、本番環境などの環境分けを行う仕組みもない

参考

https://www.youtube.com/watch?v=qerW4vBftNA

https://www.udemy.com/course/unscared_git/

https://backlog.com/ja/git-tutorial/stepup/31/

https://zenn.dev/ryo_4947123/books/497459787cb294/viewer/branchstrategy_githubflow