OSDN Git Service

[update] : Added --clean
[alterlinux/wfa.git] / wfa
diff --git a/wfa b/wfa
index 5e4018b..e9c6ce3 100755 (executable)
--- a/wfa
+++ b/wfa
 #!/usr/bin/env bash
+#
+# 1. Author info
+#
+# Yamada Hayao
+# Twitter: @Hayao0819
+# Email  : hayao@fascode.net
+#
+# (c) 2019-2020 Fascode Network.
+#
+# 2. Overview
+# 
+# Wfa is a multilingual AUR helper written in bash that is being developed to replace yaourt
+#
+# 3. License
+# 
+#        DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 
+#                    Version 2, December 2004 
+#
+# Copyright (C) 2004 Sam Hocevar <sam@hocevar.net> 
+#
+# 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.
+#
+#
 
 set -eu
 
+
+######################################################################################
+# ここから翻訳データ
+
+declare -A ja_JP=(
+    ["Undefined operation"]="未定義のオペレーションです"
+    ["only one operation may be used at a time"]="一度に使用できるオペレーションは1つだけです"
+    ["Failed to set the argument of %s"]="%sの引数の設定に失敗しました"
+    ["Setting that command is not currently supported"]="そのコマンドの設定は現在サポートされていません"
+    ["Searching in AUR ..."]="AUR内を検索しています..."
+    ["No package with an exact name match was found"]="完全に一致する名前のパッケージが見つかりませんでした"
+    ["Select a package %s with an exact name match"]="名前が完全に一致するパッケージ %s を選択します"
+    ["Download PKGBUILD of %s"]="%s のPKGBUILDをダウンロード"
+    ["Get PKGBUILD from %s"]="%sからPKGBUILDを取得します"
+    ["PKGBUILD has already been downloaded"]="PKGBUILDは既にダウンロードされています"
+    ["Do you want to overwrite and download? [n] :"]="上書きダウンロードしますか? [n] :"
+    ["Unpacking the tarball of PKGBUILD ..."]="PKGBUILDを展開しています ..."
+    [".SRCINFO was not found.\nGenerating it using makepkg"]=".SCRINFOが見つかりませんでした。makepkgを使用して生成しています"
+    ["Conflict(s) was found"]="衝突が見つかりました"
+    ["Install dependent packages..."]="依存パッケージをインストールします..."
+    ["Found %s"]="%s を見つけました"
+    ["Packages to cleanBuild? [n] :"]="パッケージをクリーンビルドしますか? [n] :"
+    ["Could not find all required packages:\n  %s"]="必要なすべてのパッケージが見つかりませんでした     %s"
+    ["This is a feature that has not been implemented yet"]="まだ実装されていない機能です"
+
+    ["(Orphaned)"]="(メンテナ不在)"
+    ["[Installed]"]="[インストール済み]"
+    ["This is a feature that has not been implemented yet"]="まだ実装されていない機能です"
+)
+######################################################################################
+# ここからデフォルト設定の定義
+
+#-- wfa configs --#
+wfa_version="0.1"
+wfa_name="WFA"
+wfa_command="wfa"
+
+#-- options (int) --#
+option_y_count=0
+sync_clean_count=0
+
+#-- options (str) --#
+aururl="https://aur.archlinux.org/"
+operation="none"
+
+#-- options (bool) --#
+bash_debug=false
+debug=false
+force_aur=false
 msgdebug=false
 nocolor=false
-debug=false
+noconfirm=false
+nodeps=false
+nomakepkgconf=false
+sync_search=false
+sync_upgrade=false
+
+#-- makepkg --#
+# 実行ファイル
+makepkg_command="/usr/bin/makepkg" 
+# 設定ファイル
+makepkg_config="/etc/makepkg.conf"
+# 引数
+makepkg_args=""
+
+#-- pacman --#
+# 実行ファイル
+pacman_command="/usr/bin/pacman"
+# 設定ファイル
+pacman_config="/etc/pacman.conf"
+# 引数
 pacman_args=""
-operation="none"
 
-wfa_version="0.1"
-aururl="https://aur.archlinux.org/"
+#-- git --#
+# 実行ファイル
+git_command="/usr/bin/git"
+# 引数
+git_args=""
+
+#-- gpg --#
+# 実行ファイル
+gpg_command="/usr/bin/gpg"
+# 引数
+gpg_args=""
+
+#-- sudo --#
+# 実行ファイル
+sudo_command="/usr/bin/sudo"
+# 引数
+sudo_args=""
+
+
+
+######################################################################################
+# ここからメッセージ関連の関数定義
+
 
 # メッセージ出力の制御
 # https://github.com/FascodeNet/alterlinux/blob/dev/tools/msg.sh の変数名にアンダーバーを追加し関数化
@@ -33,7 +151,7 @@ msg() {
     local _output="stdout"
 
     _help() {
-        echo "usage ${0} [option] [type] [message]"
+        echo "usage msg [option] [type] [message]"
         echo
         echo "Display a message with a colored app name and message type label"
         echo
@@ -269,44 +387,96 @@ msg() {
     done
 }
 
+# テキストの翻訳
+#set -xv
+translate() {
+    local _msg_translate
+    _msg_translate() {
+        local _get_text
+        local _locale="$(echo "${LANG}" | cut -d "." -f 1)"
+
+        _get_text() {
+            set +eu
+            local _translated_text="$(eval echo '$'{${_locale}[\"${*}\"]})"
+            set -eu
+            if [[ -z "${_translated_text}" ]]; then
+                echo "${*}"
+            else
+                echo "${_translated_text}"
+            fi
+        }
+
+        local _text _fulltext=() _main
+
+        if declare -p "${_locale}" 2> /dev/null 1>/dev/null; then
+            _main="$(_get_text ${1})"
+        else
+            _main="${1}"
+        fi
+        shift 1
+        echo "$(printf "${_main}" "${@}")"
+    }
+    _msg_translate "${@}"
+}
+
+
+
 # Show an INFO message
 # $1: message string
 msg_info() {
-    local _msg_opts="-a WFA"
+    if [[ "${msgdebug}" = false ]]; then
+        set +xv
+    fi
+    local _msg_opts="-a ${wfa_name}"
     if [[ "${1}" = "-n" ]]; then
         _msg_opts="${_msg_opts} -o -n"
         shift 1
     fi
     [[ "${msgdebug}" = true ]] && _msg_opts="${_msg_opts} -x"
     [[ "${nocolor}"  = true ]] && _msg_opts="${_msg_opts} -n"
-    msg ${_msg_opts} info "${1}"
+    msg ${_msg_opts} info "$(translate "${@}")"
+    if [[ "${bash_debug}" = true ]]; then
+        set -xv
+    fi
 }
 
 # Show an Warning message
 # $1: message string
 msg_warn() {
-    local _msg_opts="-a WFA"
+    if [[ "${msgdebug}" = false ]]; then
+        set +xv
+    fi
+    local _msg_opts="-a ${wfa_name}"
     if [[ "${1}" = "-n" ]]; then
         _msg_opts="${_msg_opts} -o -n"
         shift 1
     fi
     [[ "${msgdebug}" = true ]] && _msg_opts="${_msg_opts} -x"
     [[ "${nocolor}"  = true ]] && _msg_opts="${_msg_opts} -n"
-    msg ${_msg_opts} warn "${1}"
+    msg ${_msg_opts} warn "$(translate "${@}")"
+    if [[ "${bash_debug}" = true ]]; then
+        set -xv
+    fi
 }
 
 # Show an debug message
 # $1: message string
 msg_debug() {
+    if [[ "${msgdebug}" = false ]]; then
+        set +xv
+    fi
     if [[ "${debug}" = true ]]; then
-        local _msg_opts="-a WFA"
+        local _msg_opts="-a ${wfa_name}"
         if [[ "${1}" = "-n" ]]; then
             _msg_opts="${_msg_opts} -o -n"
             shift 1
         fi
         [[ "${msgdebug}" = true ]] && _msg_opts="${_msg_opts} -x"
         [[ "${nocolor}"  = true ]] && _msg_opts="${_msg_opts} -n"
-        msg ${_msg_opts} debug "${1}"
+        msg ${_msg_opts} debug "$(translate "${@}")"
+    fi
+    if [[ "${bash_debug}" = true ]]; then
+        set -xv
     fi
 }
 
@@ -314,51 +484,166 @@ msg_debug() {
 # $1: message string
 # $2: exit code number (with 0 does not exit)
 msg_error() {
-    local _msg_opts="-a WFA"
+    if [[ "${msgdebug}" = false ]]; then
+        set +xv
+    fi
+    local _msg_opts="-a ${wfa_name}"
     if [[ "${1}" = "-n" ]]; then
         _msg_opts="${_msg_opts} -o -n"
         shift 1
     fi
     [[ "${msgdebug}" = true ]] && _msg_opts="${_msg_opts} -x"
     [[ "${nocolor}"  = true ]] && _msg_opts="${_msg_opts} -n"
-    msg ${_msg_opts} error "${1}"
-    if [[ -n "${2:-}" ]]; then
-        exit ${2}
+    msg ${_msg_opts} error "$(translate "${@}")"
+    if [[ "${bash_debug}" = true ]]; then
+        set -xv
+    fi
+}
+
+text() {
+    local OPTIND OPTARG arg _textcolor _decotypes=() _message
+    while getopts "c:b" arg; do
+        case ${arg} in
+            c)
+                case "${OPTARG}" in
+                    "black")
+                        _textcolor="30"
+                        ;;
+                    "red")
+                        _textcolor="31"
+                        ;;
+                    "green")
+                        _textcolor="32"
+                        ;;
+                    "yellow")
+                        _textcolor="33"
+                        ;;
+                    "blue")
+                        _textcolor="34"
+                        ;;
+                    "magenta")
+                        _textcolor="35"
+                        ;;
+                    "cyan")
+                        _textcolor="36"
+                        ;;
+                    "white")
+                        _textcolor="37"
+                        ;;
+                    *)
+                        return 1
+                        ;;
+                esac
+                ;;
+            b)
+                _decotypes+=(1)
+                ;;
+        esac
+    done
+    shift $((OPTIND - 1))
+
+    _message="${@}"
+    _message="$(translate "${@}")"
+    if [[ "${nocolor}" = true ]]; then
+        echo -ne "${@}"
+    else
+        echo -ne "\e[$([[ -v _textcolor ]] && echo -n ";${_textcolor}"; [[ -v _decotypes ]] && echo -n ";${_decotypes}")m${_message}\e[m"
     fi
 }
 
+######################################################################################
+# ここから実際の処理開始
+# ここから下のメッセージは翻訳可能です
+
+# rm helper
+# Delete the file if it exists.
+# For directories, rm -rf is used.
+# If the file does not exist, skip it.
+# remove <file> <file> ...
+remove() {
+    local _list=($(echo "$@")) _file
+    for _file in "${_list[@]}"; do
+        msg_debug "Removing ${_file}"
+        if [[ -f "${_file}" ]]; then    
+            rm -f "${_file}"
+        elif [[ -d "${_file}" ]]; then
+            rm -rf "${_file}"
+        fi
+    done
+}
+
 usage (){
+    local _pacman_help=false
+
     local _wfa_usage
     _wfa_usage() {
         echo "Usage:"
-        echo "wfa"
-        echo "wfa <operation> [...]"
+        echo "${wfa_command}"
+        echo "${wfa_command} <operation> [...]"
         echo
         echo "operations:"
-        echo "wfa {-h --help}"
-        echo "wfa {-V --version}"
-        #echo "wfa {-D --database}    <options> <package(s)>"
-        #echo "wfa {-F --files}       [options] [package(s)]"
-        echo "wfa {-Q --query}       [options] [package(s)]"
-        echo "wfa {-R --remove}      [options] <package(s)>"
-        echo "wfa {-S --sync}        [options] [package(s)]"
-        #echo "wfa {-T --deptest}     [options] [package(s)]"
-        #echo "wfa {-U --upgrade}     [options] <file(s)>"
+        echo "    ${wfa_command} {-h --help}"
+        echo "    ${wfa_command} {-V --version}"
+       #echo "    ${wfa_command} {-D --database}    <options> <package(s)>"
+       #echo "    ${wfa_command} {-F --files}       [options] [package(s)]"
+        echo "    ${wfa_command} {-Q --query}       [options] [package(s)]"
+        echo "    ${wfa_command} {-R --remove}      [options] <package(s)>"
+        echo "    ${wfa_command} {-S --sync}        [options] [package(s)]"
+       #echo "    ${wfa_command} {-T --deptest}     [options] [package(s)]"
+       #echo "    ${wfa_command} {-U --upgrade}     [options] <file(s)>"
+       #echo
+       #echo "New operations:"
+       #echo "    ${wfa_command} {-P --show}        [options]"
+       #echo "    ${wfa_command} {-G --getpkgbuild} [package(s)]"
+        echo
+        echo "New options:"
+        echo "       --repo             Assume targets are from the repositories"
+        echo "    -a --aur              Assume targets are from the AUR"
+        echo
+        echo "Permanent configuration options:"
+        echo "    --aururl      <url>   Set an alternative AUR URL"
+        echo "    --makepkg     <file>  makepkg command to use"
+        echo "    --mflags      <flags> Pass arguments to makepkg"
+        echo "    --pacman      <file>  pacman command to use"
+        echo "    --git         <file>  git command to use"
+        echo "    --gitflags    <flags> Pass arguments to git"
+        echo "    --gpg         <file>  gpg command to use"
+        echo "    --gpgflags    <flags> Pass arguments to gpg"
+        echo "    --config      <file>  pacman.conf file to use"
+        echo "    --makepkgconf <file>  makepkg.conf file to use"
+        echo "    --nomakepkgconf       Use the default makepkg.conf"
+        echo
+    }
+
+    local _wfa_usage_sync
+    _wfa_usage_sync() {
+        echo "usage:  ${wfa_command} {-S --sync} [options] [package(s)]"
+        echo "options:"
+        echo "  -b, --dbpath <path>  set an alternate database location"
+        echo "      --config <path>  set an alternate configuration file"
+        echo "      --noconfirm      do not ask for any confirmation"
+
     }
 
     if [[ "${operation}" = "none" ]]; then
         _wfa_usage
+    elif [[ "${_pacman_help}" = true ]]; then
+        "${pacman_command}" -h --${operation}
+    elif [[ "$(type -t "_wfa_usage_${operation}" )" = "function" ]]; then
+        _wfa_usage_${operation}
     else
-        pacman -h --${operation}
+        msg_error "Undefined operation"
+        exit 1
     fi
 }
 
 set_operation() {
     if [[ "${operation}" = "none" ]]; then
         operation="${1}"
-        add_pacman_args "--${operation}"
+        add_args pacman "--${operation}"
     else
-        msg_error "only one operation may be used at a time" 1
+        msg_error "only one operation may be used at a time"
+        exit 1
     fi
 }
 
@@ -371,23 +656,62 @@ run_sudo() {
 }
 
 run_pacman() {
-    run_sudo pacman ${pacman_args} ${@}
+    run_sudo "${pacman_command}" ${@}
 }
 
 # pacmanの引数を追加する
 # https://github.com/FascodeNet/aptpac/blob/master/aptpac のADD_OPTION関数を参考
-add_pacman_args() {
-    local _pacman_args_array=(${pacman_args})
-    _pacman_args_array+=(${@})
-    pacman_args=${_pacman_args_array[@]}
-    msg_debug "PACMAN ARGS: ${pacman_args}"
+# Usage: add_args [pacman/makepkg] <args1> <args2>...
+add_args() {
+    local _target="${1}"
+    local _args_array
+    shift 1
+
+    case "${_target}" in
+        "makepkg")
+            _args_array=(${makepkg_args})
+            _args_array+=(${@})
+            makepkg_args=${_args_array[@]}
+            msg_debug "makepkg ARGS: ${makepkg_args}"
+            ;;
+
+        "pacman")
+            _args_array=(${pacman_args})
+            _args_array+=(${@})
+            pacman_args=${_args_array[@]}
+            msg_debug "pacman ARGS: ${pacman_args}"
+            ;;
+        "git")
+            _args_array=(${mpg_args})
+            _args_array+=(${@})
+            git_args=${_args_array[@]}
+            msg_debug "git ARGS: ${git_args}"
+            ;;
+        "gpg")
+            _args_array=(${gpg_args})
+            _args_array+=(${@})
+            gpg_args=${_args_array[@]}
+            msg_debug "gpg ARGS: ${gpg_args}"
+            ;;
+        "sudo")
+            _args_array=(${sudo_args})
+            _args_array+=(${@})
+            sudo_args=${_args_array[@]}
+            msg_debug "sudo ARGS: ${sudo_args}"
+            ;;
+        *)
+            msg_error "Failed to set the argument of %s" "${_target}"
+            msg_error "Setting that command is not currently supported"
+            exit 1
+            ;;
+    esac
 }
 
 # 引数で指定されたパッケージがAUR以外の場所に存在しない場合にのみ正常終了します(AURのパッケージの場合に正常終了)
 check_aur_package() {
     local _package="${1}"
     # 参考: https://qiita.com/Hayao0819/items/a8740a17301fafa2fdab
-    if [[ -z "$(pacman -Fq "${_package}" 2>/dev/null | grep -o ".*${_package}$")" ]]; then
+    if [[ -z "$(pacman -Ssq "${_package}" 2>/dev/null | grep -o ".*${_package}$")" ]]; then
         #AUR以外のリポジトリに存在しない
         return 0
     else
@@ -396,8 +720,19 @@ check_aur_package() {
 }
 
 
+# 引数で指定されたパッケージが既にインストールされている場合は正常終了します。
+check_installed_package() {
+    local _package="${1}"
+    if "${pacman_command}" -Qq "${_package}" > /dev/null 2>&1; then
+        return 0
+    else
+        return 1
+    fi
+}
+
+# ~/.cacheに相当するディレクトリを返します
 get_cache_dir() {
-    local _user_config_dir
+    local _user_config_dir _cache_dir
     if [[ -v XDG_CONFIG_HOME ]]; then
         _user_config_dir="${XDG_CONFIG_HOME}"
     else
@@ -407,14 +742,30 @@ get_cache_dir() {
         source "${_use_config_dir}/user-dirs.dirs"
     fi
     if [[ -v XDG_CACHE_HOME ]]; then
-        echo -n "${XDG_CACHE_HOME}"
-        return 0
+        _cache_dir="${XDG_CACHE_HOME}"
     else
-        echo -n "${HOME}/.cache"
-        return 0
+        _cache_dir="${HOME}/.cache"
     fi
+    echo -n "${_cache_dir}"
+}
+
+# Usage: get_srcinfo_data <path> <var>
+# 参考: https://qiita.com/withelmo/items/b0e1ffba639dd3ae18c0
+get_srcinfo_data() {
+    local _srcinfo="${1}" _ver="${2}"
+    local _srcinfo_json=$(python << EOF
+from srcinfo.parse import parse_srcinfo; import json
+text = """
+$(cat ${1})
+"""
+parsed, errors = parse_srcinfo(text)
+print(json.dumps(parsed))
+EOF
+)
+    echo "${_srcinfo_json}" | jq -rc "${2}" | tr '\n' ' '
 }
 
+
 # AURからパッケージをビルドしてインストールします
 # 現在1つのパッケージしか指定できません
 install_aur_package() {
@@ -424,16 +775,218 @@ install_aur_package() {
     if [[ ! -v wfa_cache_dir ]]; then
         wfa_cache_dir="$(get_cache_dir)/wfa"
     fi
-    mkdir -p "${wfa_cache_dir}"
+    mkdir -p "${wfa_cache_dir}/archive"
+    mkdir -p "${wfa_cache_dir}/build/${_package}"
 
     # AurJsonから値を取得
+    msg_info "Searching in AUR ..."
     local _aur_json=$(curl -sL "https://aur.archlinux.org/rpc/?v=5&type=search&by=name&arg=${_package}" | jq -r)
     if (( "$(echo "${_aur_json}" | jq -r ".resultcount")" == 0 )); then
-        msg_error "Could not find all required packages:\n     ${_package}" 1
-       fi
+        msg_error "Could not find all required packages:\n     ${_package}"
+        exit 1
+    fi
+
+    local _found_packages="$(echo "${_aur_json}" | jq -r --tab '.results[].Name')"
+    #msg_debug "Found package: $(echo ${_found_packages} | tr '\n' ' ')"
+
+    if [[ -n "$(echo "${_found_packages}" | grep -x "${_package}" )" ]]; then
+        msg_debug "Select a package %s with an exact name match" "${_package}"
+    else
+        msg_error "No package with an exact name match was found"
+        exit 1
+    fi
+
+    # PKGBUILDをダウンロード
+    msg_info "Download PKGBUILD of %s" "${_package}"
+    _aur_json=$(echo "${_aur_json}" | jq -r ".results[] | select(.Name == \"${_package}\")" )
+    local _aur_snapshot_url="${aururl%/}$(echo "${_aur_json}" | jq -r ".URLPath")"
+    local _aur_version="$(echo "${_aur_json}" | jq -r ".Version")"
+    msg_debug "Get PKGBUILD from %s" "${_aur_snapshot_url}"
+
+    local _pkgbuild_archive_path="${wfa_cache_dir}/archive/${_package}-${_aur_version}"
+    local _download_pkgbuild=true
+    if [[ -f "${_pkgbuild_archive_path}" ]]; then
+        msg_warn "PKGBUILD has already been downloaded"
+        msg_warn -n "Do you want to overwrite and download? [n] :"
+        local _yes_or_no
+        if [[ "${noconfirm}" = true ]]; then
+            echo
+            _yes_or_no="No"
+        else
+            read _yes_or_no
+        fi
+        case "${_yes_or_no}" in
+            "y" | "Y" | "yes" | "Yes" | "YES" ) _download_pkgbuild=true  ;;
+            *                                 ) _download_pkgbuild=false ;;
+        esac
+    fi
+    if [[ "${_download_pkgbuild}" = true ]]; then
+        remove "${_pkgbuild_archive_path}"
+        curl -L -C - -f -o "${_pkgbuild_archive_path}" "${_aur_snapshot_url}"
+    fi
+
+    # PKGBUILDを展開
+    msg_info "Unpacking the tarball of PKGBUILD ..."
+    tar -xv -f "${_pkgbuild_archive_path}" -C "${wfa_cache_dir}/build/" > /dev/null 2>&1
+
+    # .SRCINFOを解析
+    local _build_dir="${wfa_cache_dir}/build/${_package}"
+    if [[ ! -f "${_build_dir}/.SRCINFO" ]]; then
+        msg_warn ".SRCINFO was not found.\nGenerating it using makepkg"
+        (
+            cd "${_build_dir}"
+            "${makepkg_command}" --printsrcinfo > "${_build_dir}/.SRCINFO"
+        )
+    fi
+
+    local _makedepends="$(get_srcinfo_data "${_build_dir}/.SRCINFO" ".makedepends[]?")"
+    local _depends="$(get_srcinfo_data "${_build_dir}/.SRCINFO" ".depends[]?")"
+    local _conflicts="$(get_srcinfo_data "${_build_dir}/.SRCINFO" ".conflicts[]?")"
+    msg_debug "makedepends: %s" "${_makedepends}"
+    msg_debug "depends: %s" "${_depends}"
+    msg_debug "conflicts: %s " "${_conflicts}"
+
+
+    # 衝突を確認
+    local _pkg _conflicts_found=false
+    for _pkg in ${_conflicts[@]}; do
+        if "${pacman_command}" -Qq "${_pkg}" > /dev/null 2>&1 ; then
+            _conflicts_found=true
+            msg_error "${_package} is colliding with ${_pkg}"
+        fi
+    done
+    if "${pacman_command}" -Qq "${_package}" > /dev/null 2>&1 &&  [[ ! "$("${pacman_command}" -Qq "${_package}" 2> /dev/null)" = "${_package}" ]]; then
+        msg_error "${_package} is colliding with $("${pacman_command}" -Qq "${_package}")"
+        _conflicts_found=true
+    fi
+    if [[ "${_conflicts_found}" = true ]]; then
+        msg_error "Conflict(s) was found"
+        exit 1
+    fi
+
+
+    # 依存パッケージをインストール
+    if [[ "${nodeps}" = false ]]; then
+        msg_info "Install dependent packages..."
+        local _force_aur="${force_aur}"
+        force_aur=false
+        install_package "${_depends}"
+        force_aur="${_force_aur}"
+        unset _force_aur
+    fi
+
+    # ビルド準備
+    # srcdirの確認
+    if [[ -d "${_build_dir}/src" ]]; then
+        msg_info "Found %s" "${_build_dir}/src"
+        msg_info -n "Packages to cleanBuild? [n] :"
+        local _yes_or_no
+        unset _yes_or_no
+        if [[ "${noconfirm}" = true ]]; then
+            echo
+            _yes_or_no="No"
+        else
+            read _yes_or_no
+        fi
+        case "${_yes_or_no}" in
+            "y" | "Y" | "yes" | "Yes" | "YES" ) add_args makepkg "--clean" ;;
+        esac
+    fi
+
+
+    # ビルド
+    add_args "makepkg" "-sf"
+    (
+        cd "${_build_dir}"
+        "${makepkg_command}" "${makepkg_args}"
+    )
+
 
-    local _found_packages="$(echo "${_aur_json}" | jq -r --tab '.results[].Name' | tr '\n' ' ')"
-       msg_debug "Found package: ${_found_packages}"
+    # ビルド後のパッケージ一覧を生成
+    (
+        cd "${_build_dir}"
+        "${makepkg_command}" --printsrcinfo > "${_build_dir}/.SRCINFO"
+    )
+    local _pkgnames=($(get_srcinfo_data "${_build_dir}/.SRCINFO" ".packages | keys[]" | sed 's/ //g'))
+    local _pkgver="$(get_srcinfo_data "${_build_dir}/.SRCINFO" ".pkgver" | sed 's/ //g')"
+    local _pkgrel="$(get_srcinfo_data "${_build_dir}/.SRCINFO" ".pkgrel" | sed 's/ //g')"
+    local _arch_array=($(get_srcinfo_data "${_build_dir}/.SRCINFO" ".arch[]"))
+    local _arch _pkgname
+    if [[ "${_arch_array[*]}" = "any" ]]; then
+        _arch="any"
+    else
+        _arch="$(uname -m)"
+    fi
+    local _PKGEXT=$(
+        source "${makepkg_config}"
+        echo "${PKGEXT}"
+    )
+    local _pkgfilelist=()
+    for _pkgname in ${_pkgnames[@]}; do
+        _pkgfilelist+=("${_build_dir}/${_pkgname}-${_pkgver}-${_pkgrel}-${_arch}${_PKGEXT}")
+    done
+
+    # インストール
+    run_pacman -U --noconfirm ${_pkgfilelist[@]}
+}
+
+# AURのパッケージを検索
+search_aur_package() {
+    local _package="${1}"
+    #msg_info "Searching in AUR ..."
+    local _aur_json=$(curl -sL "https://aur.archlinux.org/rpc/?v=5&type=search&by=name-desc&arg=${_package}" | jq -r )
+    local _found_result_count="$(echo "${_aur_json}" | jq -r ".resultcount")"
+    if (( "${_found_result_count}" == 0 )); then
+        msg_error "Could not find all required packages:\n     %s" "${_package}"
+        exit 1
+    fi
+    _aur_json=$(echo "${_aur_json}" | jq -r ".results[]")
+
+    local _found_pkgname=($(echo "${_aur_json}" | jq -r ".Name" ))
+
+    local  _found_package __pkgver __popularity __vote __pkgdesc __orphaned __installed __output_text=()
+    for _found_package in ${_found_pkgname[@]}; do
+        __orphaned=false
+        __installed=false
+        _found_json="$(echo ${_aur_json} | jq "select(.Name == \"${_found_package}\")")"
+
+        #echo "${_found_json}"
+        __pkgver="$(echo "${_found_json}" | jq -r ".Version" )"
+        __popularity="$(echo "${_found_json}" | jq -r ".Popularity" )"
+        __vote="$(echo "${_found_json}" | jq -r ".NumVotes" )"
+        __pkgdesc="$(echo "${_found_json}" | jq -r ".Description" )"
+
+        # 人気度の少数2位以下を四捨五入
+        # 参考: http://www.rivhiro-weather.com/knowledge/?p=536
+        msg_debug "Row popularity: %s" "${__popularity}"
+        __popularity="$(printf "%g\n" "${__popularity}" | awk '{printf("%4.2f", $1)}')"
+
+        # 孤児判定
+        #参考: https://www.366service.com/jp/qa/7c95f46e5236039134ff5b862ae2cd13
+        if ! echo "${_found_json}" | jq -r --exit-status ".Maintainer" 1> /dev/null 2> /dev/null ; then
+            __orphaned=true
+        fi
+
+        # インストール済み判定
+        if check_installed_package "${_found_package}"; then
+            __installed=true
+        fi
+
+        __output_text+=(
+            "$(text -c blue -b "aur")/$(text -b "${_found_package}") $(text -c cyan "${__pkgver}") (+$(text -b "${__vote} ${__popularity}"))"
+        )
+        
+        if [[ "${__orphaned}" = true ]]; then
+            __output_text+=("$(text -bc red "(Orphaned)")")
+        fi
+
+        if [[ "${__installed}" = true ]]; then
+            __output_text+=("$(text -bc cyan "[Installed]")")
+        fi
+        echo "${__output_text[*]}"
+        echo "    ${__pkgdesc}"
+        unset __pkgver __popularity __vote __pkgdesc _found_json __orphaned __installed __output_text
+    done
 }
 
 # バージョンを表示して終了
@@ -441,40 +994,86 @@ operation_version() {
     # Pyalpmからlibalpmの値を取得
     # 参考: https://pyalpm.readthedocs.io/en/latest/pyalpm/pyalpm.html
     local _libalpm_version="$(python3 -c 'import pyalpm; print(pyalpm.alpmversion())')"
-    local _pacman_version="$(pacman -Q pacman | cut -d ' ' -f 2)"
+    local _pacman_version="$("${pacman_command}" -Q pacman | cut -d ' ' -f 2)"
     echo "wfa v${wfa_version} - pacman v${_pacman_version} - libalpm v${_libalpm_version}"
 }
 
 operation_remove() {
-    run_pacman "${specified_packages[@]}"
+    run_pacman ${pacman_args} "${specified_packages[@]}"
 }
 
-operation_sync() {
+# Usage: install_package <package1> <package2>...
+install_package() {
     local _package
-    for _package in ${specified_packages[@]}; do
-        if ! check_aur_package "${_package}"; then
-            # 公式パッケージなのでpacmanでそのままインストール
-            run_pacman "${_package}"
-        else
-            # AUR上のパッケージの場合の処理
-            install_aur_package "${_package}"
-            #msg_error "Getting the AUR package has not been implemented yet." 1
+    for _package in ${@}; do
+        if ! check_installed_package "${_package}"; then
+            if ! check_aur_package "${_package}"; then
+                # 公式パッケージなのでpacmanでそのままインストール
+                run_pacman ${pacman_args} "${_package}"
+            else
+                # AUR上のパッケージの場合の処理
+                install_aur_package "${_package}"
+                #msg_error "Getting the AUR package has not been implemented yet.
+                #exit 1
+            fi
         fi
     done
 }
 
+upgrade_aur_package() {
+    #ここまで翻訳
+    msg_error "This is a feature that has not been implemented yet"
+}
+
+operation_sync(){
+    local _package
+    if (( "${sync_clean_count}" >= 1 )); then
+        remove "$(get_cache_dir)/wfa"
+        run_pacman ${pacman_args} $(
+            local _count
+            for _count in $(seq 1 ${sync_clean_count}); do
+                echo -n "-c "
+            done
+        )
+    fi
+
+
+    if [[ "${sync_search}" = true ]]; then
+        for _package in ${specified_packages[@]}; do
+            search_aur_package "${_package}"
+        done
+        "${pacman_command}" ${pacman_args} ${specified_packages[@]} || :
+    else
+        if [[ "${sync_upgrade}" = true ]]; then
+            upgrade_aur_package
+            run_pacman ${pacman_args} --sysupgrade
+        fi
+        for _package in ${specified_packages[@]}; do
+            if ! check_aur_package "${_package}" && [[ "${force_aur}" = false ]]; then
+                # 公式パッケージなのでpacmanでそのままインストール
+                run_pacman ${pacman_args} "${_package}"
+            else
+                # AUR上のパッケージの場合の処理
+                install_aur_package "${_package}"
+                #msg_error "Getting the AUR package has not been implemented yet."
+                #exit 1
+            fi
+        done
+    fi
+}
+
 
 # Parse options
 ARGUMENT="${@}"
-_opt_short="QRShVdb:"
-_opt_long="query,remove,sync,help,version,debug,dbpath:,aururl"
+_opt_short="QRShVdb:aysuc"
+_opt_long="query,remove,sync,help,version,debug,dbpath:,aururl,aur,noconfirm,config:,makepkg:,mflags:,pacman:,git:,gitflags:,gpg:,gpgflags:,makepkgconf:,nomakepkgconf,nodeps,refresh,bash-debug,msg-debug,sysupgrade,color:,nocolor.clean"
 
 OPT=$(getopt -o ${_opt_short} -l ${_opt_long} -- ${ARGUMENT})
 [[ ${?} != 0 ]] && exit 1
+unset _opt_short _opt_long
 
 eval set -- "${OPT}"
 msg_debug "Argument: ${OPT}"
-unset OPT _opt_short _opt_long
 
 while :; do
     case ${1} in
@@ -494,19 +1093,133 @@ while :; do
             set_operation "version"
             shift 1
             ;;
-        -d | --debug)
+        --)
+            shift
+            break
+            ;;
+        *)
+            shift 1
+            ;;
+    esac
+done
+
+eval set -- "${OPT}"
+
+while :; do
+    case ${1} in
+        -a | --aur)
+            force_aur=true
+            msg_debug "Assume targets are from the AUR"
+            shift 1
+            ;;
+        --debug)
             debug=true
-            add_pacman_args "--debug"
+            add_args pacman "--debug"
+            shift 1
+            ;;
+        -d | --nodeps)
+            nodeps=true
+            add_args pacman "--nodeps"
             shift 1
             ;;
         -b | --dbpath)
-            add_pacman_args "--dbpath '${2}'"
+            add_args pacman "--dbpath '${2}'"
             shift 2
             ;;
+        -y | --refresh)
+            option_y_count=$(( option_y_count + 1 ))
+            shift 1
+            ;;
+        -s | --search)
+            add_args pacman "--search"
+            sync_search=true
+            shift 1
+            ;;
+        -u | --sysupgrade)
+            sync_upgrade=true
+            shift 1
+            ;;
+        -c | --clean)
+            sync_clean_count=$(( sync_clean_count + 1 ))
+            shift 1
+            ;;
         --aururl)
             aururl="${2}"
             shift 2
             ;;
+        --noconfirm)
+            add_args pacman "--noconfirm"
+            noconfirm=true
+            shift 1
+            ;;
+        --config)
+            pacman_config="${2}"
+            add_args pacman "--config ${2}"
+            shift 2
+            ;;
+        --makepkg)
+            makepkg_command="${2}"
+            shift 2
+            ;;
+        --mflags)
+            makepkg_args="${2}"
+            shift 2
+            ;;
+        --pacman)
+            pacman_command="${2}"
+            shift 2
+            ;;
+        --git)
+            git_command="${2}"
+            shift 2
+            ;;
+        --gitflags)
+            git_args="${2}"
+            shift 2
+            ;;
+        --makepkgconfig)
+            if [[ "${nomakepkgconf}" = false ]]; then
+                makepkg_config="${2}"
+            else
+                msg_warn "--nomakepkgconf is specified.\n--makepkgconf has been ignored."
+            fi
+            shift 2
+            ;;
+        --nomakepkgconf)
+            makepkg_config="/etc/makepkg.conf"
+            nomakepkgconf=true
+            shift 1
+        ;;
+        --bash-debug)
+            bash_debug=true
+            set -xv
+            shift 1
+            ;;
+        --msg-debug)
+            msgdebug=true
+            shift 1
+            ;;
+        --color)
+            case "${2}" in
+                "never")
+                    nocolor=true
+                    add_args pacman "--color never"
+                    ;;
+                "always")
+                    nocolor=false
+                    add_args pacman "--color always"
+                    ;;
+                "auto")
+                    msg_error "auto is not currently supported."
+                    add_args pacman "--color auto"
+                    ;;
+            esac
+            ;;
+        --nocolor)
+            nocolor=true
+            add_args pacman "--color never"
+            shift 1
+            ;;
         -h | --help)
             usage
             shift 1
@@ -517,14 +1230,20 @@ while :; do
             break
             ;;
         *)
-            msg_error "Invalid argument '${1}'"
-            _usage 1
+            shift 1
             ;;
     esac
 done
 
 specified_packages=(${@})
 
+# Run database update
+if (( "${option_y_count}" == 1 )); then
+    run_pacman -Sy
+elif (( "${option_y_count}" >= 2 )); then
+    run_pacman -Syy
+fi
+
 case "${operation}" in
     "version")
         operation_version
@@ -539,6 +1258,7 @@ case "${operation}" in
         exit 0
         ;;
     *)
-        msg_error "Undefined operation." 1
+        msg_error "Undefined operation"
+        exit 1
         ;;
 esac