summaryrefslogtreecommitdiff
path: root/src/maintenance-tools/parabola-dependents
blob: 4e6b7dcc57dc3d38e804867aae22308d10f69834 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
#!/bin/bash

readonly ABSLIBRE_DIR=/packages/abslibre
readonly ABS_PACKAGES_DIR=/packages/arch/packages
readonly ABS_COMMUNITY_DIR=/packages/arch/community
readonly DEBUG=0

readonly BE_VERBOSE=$( [[ "${1}" == '-v' ]] && echo 1 || echo 0 ) ; (( $BE_VERBOSE )) && shift ;
readonly PKGBUILD_SED_RX='s|/PKGBUILD$|| ; s|([^/]*/)?([^/]+)/([^/]+)$|\2 \3|'
readonly DEP=$( sed -E "${PKGBUILD_SED_RX}" <<<${1} | cut -d ' ' -f 2 )

# readonly REPOS=( nonprism nonsystemd{-testing,} libre{-testing,}
readonly REPOS=( nonprism{-testing,} nonsystemd{-testing,} libre{-testing,}
                 kernels{-testing,} testing core extra community{-testing,}
                 pcr{-testing,} nonprism-multilib{-testing,} nonsystemd-multilib
                 libre-multilib{-testing,} multilib{-testing,} pcr-multilib{-testing,} )
readonly TEMP_DB_NAME=parabola-dependents
readonly DUMMY_PKGBUILD='pkgname=%s
pkgver=0.0.0
pkgrel=42
pkgdesc="dummy PKGBUILD for experimentation"
arch=(armv7h i686 x86_64)
url=https://nowhere.man
license=(GPL)
provides=(%s)
source=(PKGBUILD)
sha256sums=(SKIP)
package() { echo "created '"'\${pkgname}'"' package" ; }'
readonly USAGE="USAGE:
  parabola-dependents [-v] <PACKAGE_BASE>
  parabola-dependents [-v] <PKGBUILD>
  parabola-dependents [-v] <SODEP>

  List all parabola packages which are dependents of a specified package.
  This includes direct dependents, transitive dependents, and makedepends dependents.

  NOTE: The verbose report does not account for makedepends of packages not in abslibre.

  The positional argument: <PACKAGE_BASE> or <PKGBUILD> may be a 'pkgbase' name,
  or a path to an abslibre 'pkgbase' directory, or a path to a PKGBUILD.
  Paths may be absolute or relative. They will all resolve to a 'pkgbase' name.

  The positional argument: <SODEP> may be of the forms: 'libfoo.so' or 'libfoo.so=1-64'.

  If 'pkgbase' does not exist in any database, a dummy package will be created,
  in memory, upon which for pactree to reflect.

  By default, only first-order dependents are listed,
  with counts of higher-order dependents.

  Note: This script makes no assumption regarding the state of the ABS trees.
        You will need to manage them manually (eg: \`git pull && git checkout master\`).
        It will however, ignore any PKGBUILDs which are not checked-in to the master branch.

  Note: This script can take several minutes to complete, if the dependency-graph is large.

  Options:
    -v
      Itemize all higher-order dependents, displaying the dependency-chain."
readonly INVALID_ARG_MSG="no dependency package specified\n\n${USAGE}"
readonly UNPRIVILEGED_MSG="this script requires super-user privileges"
readonly CBLUE='\033[0;36m'
readonly CRED='\033[0;31m'
readonly CYELLOW='\033[0;33m'
readonly CEND='\033[0m'
readonly SEP_CHAR='='
DB_DIR=''       # Init()
CFG_FILE=''     # Init()
PACMAN_OPTS=''  # Init()
PACTREE_OPTS='' # Init()

ParabolaDependents=()        # CollectResults()
ArchDependents=()            # CollectResults()
ParabolaMakedependents=()    # CollectResults()
ArchMakedependents=()        # CollectResults()
declare -A HiorderDependents # CollectResults()


## helpers ##

Log() # (log_fmt [fmt_args]*)
{
  local log_fmt=$1
  local fmt_args=( "${@:2}" )

  printf "${CBLUE}${log_fmt}${CEND}\n" "${fmt_args[@]}" >&2
}

LogError() # (log_fmt [fmt_args]*)
{
  local log_fmt=$1
  local fmt_args=( "${@:2}" )

  printf "${CRED}ERROR: ${log_fmt}${CEND}\n" "${fmt_args[@]}" >&2
}

LogScriptError() # (source_file func_name line_n)
{
  local source_file="$1"
  local func_name=$2
  local line_n=$3
  local err_loc="$(awk "(( NR == ${line_n} )) { print }" ${source_file})"

  LogError "in ${func_name}\n${line_n}: %s\n" "${err_loc}"
}

Exit() # (log_fmt [fmt_args]*)
{
  LogError "$@" ; exit 1 ;
}

ParsePkgbuilds() # ("abs_dir" "dep_chains")
(
  local abs_dir="$1"
  local dep_chains=( "${@:2}" )
  local pkgbuild repo pkgbase
# echo "ParsePkgbuilds() (${#dep_chains[@]}) dep_chains=${dep_chains[@]}" >&2 # ; return ;
# for ea in "${dep_chains[@]}" ; do echo "=$ea" >&2 ; done ; return ;
  set +o errexit +o errtrace ; trap '' EXIT INT TERM ERR ; # reset debug traps

  cd "${abs_dir}"
  for pkgbuild in $(find . -name PKGBUILD)
  do  git ls-tree master ${pkgbuild} | grep -E '/PKGBUILD$' > /dev/null || continue

# echo "ParsePkgbuilds() pkgbuild=${pkgbuild}" >&2

      source ${pkgbuild}

      if   grep ^${DEP}$ <<<${makedepends[*]} > /dev/null || false
      then # parse direct makedepends
           repo=$(   sed -E "${PKGBUILD_SED_RX}" <<<${pkgbuild} | cut -d ' ' -f 1)
           pkgbase=$(sed -E "${PKGBUILD_SED_RX}" <<<${pkgbuild} | cut -d ' ' -f 2)
           echo ${repo}/${pkgbase}
      else # collect transitive makedepends
           for makedepend in ${makedepends[*]}
           do if   grep -E "( |/)${makedepend}( |$)" <<<${dep_chains[@]} > /dev/null
              then echo "[${pkgbase}] <- ${makedepend}"
echo "ParsePkgbuilds() pkgbuild=${pkgbuild} makedepend=${makedepend} in-chain" >&2
# else echo "ParsePkgbuilds() pkgbuild=${pkgbuild} makedepend=${makedepend} not in-chain" >&2
              fi
           done
      fi
  done
)

IsArchRepo() # (repo)
{
  local repo=$1 ; [[ "${repo}" =~ ^(community|core|extra|multilib|testing)$ ]]
}

IsFirstOrderDep() # ("dep_chain")
{
  local dep_chain="$@"

  (( $(tr '<' '\n' <<<${dep_chain} | wc -l) == 2 ))
}

PrintDependent() # ("dep_chain")
{
  local dep_chain="$@"
  local dep_pkg via_pkg
  declare -i n_hiorder_deps

  if   (( BE_VERBOSE ))
  then # display all transitive dependents
       echo "  ${dep_chain/ /${SEP_CHAR}}"
  elif IsFirstOrderDep "${dep_chain}"
  then # display only first-order dependents
       dep_pkg=$(sed 's|.*<- ||'                 <<<${dep_chain})
       via_pkg=$(sed 's|.*\] <- \([^ ]*\).*|\1|' <<<${dep_chain})
       n_hiorder_deps=${HiorderDependents[${via_pkg}]}

       echo -n "  ${dep_pkg}${SEP_CHAR}"
       (( n_hiorder_deps )) && echo "(plus ${n_hiorder_deps} higher-order deps)" || echo
  fi
}

## business ##

Init()
{
  # find or create the temporary workspace
  readonly DB_DIR="$( db_dir=$(ls -1 -d /tmp/${TEMP_DB_NAME}.??? 2> /dev/null | head -n 1)
                      [[ -d "${db_dir}" ]]                                       &&
                      echo "${db_dir}"                                           ||
                      su $(logname) -c "mktemp -d -p /tmp -t ${TEMP_DB_NAME}.XXX" )"
  readonly CFG_FILE=${DB_DIR}/pacman-all.conf
  readonly PACMAN_OPTS="--config=${CFG_FILE}"
  readonly PACTREE_OPTS="${PACMAN_OPTS} --sync --reverse --chain"

# TODO: `pactree --chain` is an unpublished custom feature
export PATH="/code/pacman-contrib/src:${PATH}"

  # populate or update the temporary package database
  if ! (( DEBUG )) || ! (( $(ls -1 /tmp/${TEMP_DB_NAME}.??? | wc -l) ))
  then Log "updating database ...."
       printf "[options]\nArchitecture = auto\n"                     > ${CFG_FILE}
       printf "DBPath = ${DB_DIR}\n"                                >> ${CFG_FILE}
       for repo in ${REPOS[@]}
       do  printf "[${repo}]\nInclude = /etc/pacman.d/mirrorlist\n" >> ${CFG_FILE}
       done
       pacman ${PACMAN_OPTS} -Sy &> /dev/null
  else Log "skipping database update in DEBUG mode - delete ${DB_DIR} to sync"
  fi

  # create dummy for missing dependency package or sodep
  local log_msg dep pkgbase dummy_pkg
  if   ! pacman ${PACMAN_OPTS} -Ss ^${DEP}$ &> /dev/null
  then if   [[ "${DEP}" =~ (.*)\.so=? ]]
       then log_msg="creating dummy package for sodep: '${DEP}'"
            dep=${DEP} ; pkgbase=$(sed 's|^\([0-9a-z@._+-]*\)|\1|' <<<${BASH_REMATCH[1]}) ;
       else log_msg="pkgbase: '${DEP}' not found - creating dummy package"
            dep=''     ; pkgbase=${DEP} ;
       fi
       dummy_pkg=${pkgbase}-0.0.0-42-$(uname -m).pkg.tar.xz

       [[ ! -f ${DB_DIR}/${dummy_pkg} ]] && Log "${log_msg}" || break

       cd ${DB_DIR}
       printf "${DUMMY_PKGBUILD}\n" "${pkgbase}" "${dep}" > ./PKGBUILD
       su $(logname) -c 'makepkg --force &> /dev/null'

       if   [[ -f ./${dummy_pkg} ]]
       then repo-add ${TEMP_DB_NAME}.db.tar ./${dummy_pkg} &> /dev/null
            printf "[${TEMP_DB_NAME}]\nServer = file://${DB_DIR}\n"  >> ${CFG_FILE}
            pacman ${PACMAN_OPTS} -Sy &> /dev/null

            Log "dummy package '${pkgbase}' created"
       else Exit "makepkg failed"
       fi
  fi
}

CollectResults()
{
  local dep_chains dep_chain dep_pkg via_pkg repos repo

  # query database for dependents
  Log "querying database ...."
  mapfile -t dep_chains < <(pactree ${PACTREE_OPTS} ${DEP} | sort)

  # compile results
  Log "compiling results ...."
  for dep_chain in "${dep_chains[@]}"
  do  # example dep_chains:
      #   first-order dep: '[$DEP] <- $dep_pkg'
      #   high-order dep:  '[$DEP] <- $via_pkg <- transitive_dep <- $dep_pkg'
      dep_pkg=$(sed 's|.*<- ||'                 <<<${dep_chain})
      via_pkg=$(sed 's|.*\] <- \([^ ]*\).*|\1|' <<<${dep_chain})
      repos="$(pacman ${PACMAN_OPTS} -Si ${dep_pkg} | grep Repository | \
               cut -d ':' -f 2 | tr -d ' '                              )"
      for repo in ${repos}
      do  if   IsArchRepo ${repo}
          then ArchDependents+=(     "${dep_chain}" )
          else ParabolaDependents+=( "${dep_chain}" )
          fi
          if   ! IsFirstOrderDep "${dep_chain}"
          then HiorderDependents[${via_pkg}]=$(( ${HiorderDependents[${via_pkg}]} + 1 ))
          fi
      done
  done

  # parse PKGBUILDs for makedepends
  Log "searching abslibre ...."
  ParabolaMakedependents+=( $(ParsePkgbuilds "${ABSLIBRE_DIR}"      "${dep_chains[@]}") )
  Log "searching abs ...."
  ArchMakedependents+=(     $(ParsePkgbuilds "${ABS_PACKAGES_DIR}"  "${dep_chains[@]}") )
  ArchMakedependents+=(     $(ParsePkgbuilds "${ABS_COMMUNITY_DIR}" "${dep_chains[@]}") )
}

PrintReport()
{
  local dep_chain
  local has_firstorder_deps=0

  # report parabola abslibre packages with some degree of run-time dependency
  # on the input package or sodep
  if   (( ${#ParabolaDependents[*]} ))
  then for dep_chain in "${ParabolaDependents[@]}"
       do  IsFirstOrderDep "${dep_chain}" && has_firstorder_deps=1 || :
       done
       if   (( BE_VERBOSE || has_firstorder_deps ))
       then Log "\ndirect$( ! (( BE_VERBOSE )) || echo " and transitive") parabola dependents:"
       fi
# echo "PrintReport() ${ParabolaDependents[*]}"
       for dep_chain in "${ParabolaDependents[@]}"
       do  PrintDependent "${dep_chain}"
       done | column --table --separator="${SEP_CHAR}" --table-wrap=2
  fi

  # report arch abs packages with some degree of run-time dependency
  # on the input package or sodep
  if   (( BE_VERBOSE && ${#ArchDependents[@]} ))
  then Log "\ndirect$( ! (( BE_VERBOSE )) || echo " and transitive") arch dependents:"
       for dep_chain in "${ArchDependents[@]}"
       do  PrintDependent "${dep_chain}"
       done | column --table --separator="${SEP_CHAR}" --table-wrap=2
  else echo -e "\n(${#ArchDependents[@]} arch dependents)"
  fi

  # report parabola abslibre packages with some degree of build-time dependency
  # on the input package or sodep
  if   (( ${#ParabolaMakedependents[*]} ))
  then Log "\nparabola build dependents:"
       printf "  %s\n" ${ParabolaMakedependents[*]}
  fi

  # report arch abs packages with some degree of build-time dependency
  # on the input package or sodep
  if   (( ${#ArchMakedependents[*]} ))
  then Log "\narch build dependents:"
       printf "  %s\n" ${ArchMakedependents[*]}
  fi
}

Cleanup()
{
  if   [[ -d "${DB_DIR}" && "${DB_DIR}" =~ ^${TEMP_DB_NAME}\....$ ]] && ! (( DEBUG ))
  then rm --force --recursive ${DB_DIR}
  fi
}


set -o errexit -o errtrace
trap 'Cleanup'                                                         EXIT INT TERM
trap 'LogScriptError "${BASH_SOURCE[0]}" "${FUNCNAME[0]}" "${LINENO}"' ERR


(( ! EUID )) || ! echo -e "${UNPRIVILEGED_MSG}" || exit 1
(( $#     )) || ! echo -e "${INVALID_ARG_MSG}"  || exit 1


export LC_ALL=C
Init
CollectResults
PrintReport