git 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. #!/usr/bin/env bash
  2. # NOTE: if the output of this backend has to change (e.g. we change what gets
  3. # included in the archive (e.g. LFS), or we change the format of the archive
  4. # (e.g. tar options, compression ratio or method)), we MUST update the format
  5. # version in the variable BR_FMT_VERSION_git, in package/pkg-download.mk.
  6. # We want to catch any unexpected failure
  7. set -e
  8. # Download helper for git, to be called from the download wrapper script
  9. #
  10. # Options:
  11. # -q Be quiet.
  12. # -r Clone and archive sub-modules.
  13. # -o FILE Generate archive in FILE.
  14. # -u URI Clone from repository at URI.
  15. # -c CSET Use changeset CSET.
  16. # -n NAME Use basename NAME.
  17. #
  18. # Environment:
  19. # GIT : the git command to call
  20. # shellcheck disable=SC1090 # Only provides mk_tar_gz()
  21. . "${0%/*}/helpers"
  22. # Save our path and options in case we need to call ourselves again
  23. myname="${0}"
  24. declare -a OPTS=("${@}")
  25. # This function is called when an error occurs. Its job is to attempt a
  26. # clone from scratch (only once!) in case the git tree is borked, or in
  27. # case an unexpected and unsupported situation arises with submodules
  28. # or uncommitted stuff (e.g. if the user manually mucked around in the
  29. # git cache).
  30. _on_error() {
  31. local ret=${?}
  32. printf "Detected a corrupted git cache.\n" >&2
  33. if ${BR_GIT_BACKEND_FIRST_FAULT:-false}; then
  34. printf "This is the second time in a row; bailing out\n" >&2
  35. exit ${ret}
  36. fi
  37. export BR_GIT_BACKEND_FIRST_FAULT=true
  38. printf "Removing it and starting afresh.\n" >&2
  39. popd >/dev/null
  40. rm -rf "${git_cache}"
  41. exec "${myname}" "${OPTS[@]}" || exit ${ret}
  42. }
  43. quiet=
  44. large_file=0
  45. recurse=0
  46. while getopts "${BR_BACKEND_DL_GETOPTS}" OPT; do
  47. case "${OPT}" in
  48. q) quiet=-q; exec >/dev/null;;
  49. l) large_file=1;;
  50. r) recurse=1;;
  51. o) output="${OPTARG}";;
  52. u) uri="${OPTARG}";;
  53. c) cset="${OPTARG}";;
  54. d) dl_dir="${OPTARG}";;
  55. n) basename="${OPTARG}";;
  56. :) printf "option '%s' expects a mandatory argument\n" "${OPTARG}"; exit 1;;
  57. \?) printf "unknown option '%s'\n" "${OPTARG}" >&2; exit 1;;
  58. esac
  59. done
  60. shift $((OPTIND-1)) # Get rid of our options
  61. # Create and cd into the directory that will contain the local git cache
  62. git_cache="${dl_dir}/git"
  63. mkdir -p "${git_cache}"
  64. pushd "${git_cache}" >/dev/null
  65. # Any error now should try to recover
  66. trap _on_error ERR
  67. set -E
  68. # Caller needs to single-quote its arguments to prevent them from
  69. # being expanded a second time (in case there are spaces in them)
  70. _git() {
  71. if [ -z "${quiet}" ]; then
  72. printf '%s ' GIT_DIR="${git_cache}/.git" "${GIT}" "${@}"; printf '\n'
  73. fi
  74. _plain_git "$@"
  75. }
  76. # Note: please keep command below aligned with what is printed above
  77. _plain_git() {
  78. # shellcheck disable=SC2086 # We want word-splitting for GIT
  79. eval GIT_DIR="${git_cache}/.git" ${GIT} "${@}"
  80. }
  81. # Create a warning file, that the user should not use the git cache.
  82. # It's ours. Our precious.
  83. cat <<-_EOF_ >"${dl_dir}/git.readme"
  84. IMPORTANT NOTE!
  85. The git tree located in this directory is for the exclusive use
  86. by Buildroot, which uses it as a local cache to reduce bandwidth
  87. usage.
  88. Buildroot *will* trash any changes in that tree whenever it needs
  89. to use it. Buildroot may even remove it in case it detects the
  90. repository may have been damaged or corrupted.
  91. Do *not* work in that directory; your changes will eventually get
  92. lost. Do *not* even use it as a remote, or as the source for new
  93. worktrees; your commits will eventually get lost.
  94. _EOF_
  95. # Initialise a repository in the git cache. If the repository already
  96. # existed, this is a noop, unless the repository was broken, in which
  97. # case this magically restores it to working conditions. In the latter
  98. # case, we might be missing blobs, but that's not a problem: we'll
  99. # fetch what we need later anyway.
  100. #
  101. # We can still go through the wrapper, because 'init' does not use the
  102. # path pointed to by GIT_DIR, but really uses the directory passed as
  103. # argument.
  104. _git init .
  105. # Ensure the repo has an origin (in case a previous run was killed).
  106. if ! _plain_git remote |grep -q -E '^origin$'; then
  107. _git remote add origin "'${uri}'"
  108. fi
  109. _git remote set-url origin "'${uri}'"
  110. printf "Fetching all references\n"
  111. _git fetch origin
  112. _git fetch origin -t -f
  113. # Try to get the special refs exposed by some forges (pull-requests for
  114. # github, changes for gerrit...). There is no easy way to know whether
  115. # the cset the user passed us is such a special ref or a tag or a sha1
  116. # or whatever else. We'll eventually fail at checking out that cset,
  117. # below, if there is an issue anyway. Since most of the cset we're gonna
  118. # have to clone are not such special refs, consign the output to oblivion
  119. # so as not to alarm unsuspecting users, but still trace it as a warning.
  120. if ! _git fetch origin "'${cset}:${cset}'" >/dev/null 2>&1; then
  121. printf "Could not fetch special ref '%s'; assuming it is not special.\n" "${cset}"
  122. fi
  123. # Check that the changeset does exist. If it does not, re-cloning from
  124. # scratch won't help, so we don't want to trash the repository for a
  125. # missing commit. We just exit without going through the ERR trap.
  126. if ! _git rev-parse --quiet --verify "'${cset}^{commit}'" >/dev/null 2>&1; then
  127. printf "Commit '%s' does not exist in this repository.\n" "${cset}"
  128. exit 1
  129. fi
  130. # The new cset we want to checkout might have different submodules, or
  131. # have sub-dirs converted to/from a submodule. So we would need to
  132. # deregister _current_ submodules before we checkout.
  133. #
  134. # Using "git submodule deinit --all" would remove all the files for
  135. # all submodules, including the corresponding .git files or directories.
  136. # However, it was only introduced with git-1.8.3, which is too recent
  137. # for some enterprise-grade distros.
  138. #
  139. # So, we fall-back to just removing all submodules directories. We do
  140. # not need to be recursive, as removing a submodule will de-facto remove
  141. # its own submodules.
  142. #
  143. # For recent git versions, the repository for submodules is stored
  144. # inside the repository of the super repository, so the following will
  145. # only remove the working copies of submodules, effectively caching the
  146. # submodules.
  147. #
  148. # For older versions however, the repository is stored in the .git/ of
  149. # the submodule directory, so the following will effectively remove the
  150. # the working copy as well as the repository, which means submodules
  151. # will not be cached for older versions.
  152. #
  153. # shellcheck disable=SC2016 # Will be expanded by git-foreach
  154. cmd='printf "Deregistering submodule \"%s\"\n" "${path}" && cd .. && rm -rf "${path##*/}"'
  155. _git submodule --quiet foreach "'${cmd}'"
  156. # Checkout the required changeset, so that we can update the required
  157. # submodules.
  158. _git checkout -f -q "'${cset}'"
  159. # Get rid of now-untracked directories (in case a git operation was
  160. # interrupted in a previous run, or to get rid of empty directories
  161. # that were parents of submodules removed above).
  162. _git clean -ffdx
  163. # Get date of commit to generate a reproducible archive.
  164. # %ci is ISO 8601, so it's fully qualified, with TZ and all.
  165. date="$( _plain_git log -1 --pretty=format:%ci )"
  166. # There might be submodules, so fetch them.
  167. if [ ${recurse} -eq 1 ]; then
  168. _git submodule update --init --recursive
  169. # Older versions of git will store the absolute path of the git tree
  170. # in the .git of submodules, while newer versions just use relative
  171. # paths. Detect and fix the older variants to use relative paths, so
  172. # that the archives are reproducible across a wider range of git
  173. # versions. However, we can't do that if git is too old and uses
  174. # full repositories for submodules.
  175. # shellcheck disable=SC2016 # Will be expanded by git-foreach
  176. cmd='printf "%s\n" "${path}/"'
  177. for module_dir in $( _plain_git submodule --quiet foreach "'${cmd}'" ); do
  178. [ -f "${module_dir}/.git" ] || continue
  179. relative_dir="$( sed -r -e 's,/+,/,g; s,[^/]+/,../,g' <<<"${module_dir}" )"
  180. sed -r -i -e "s:^gitdir\: $(pwd)/:gitdir\: ${relative_dir}:" "${module_dir}/.git"
  181. done
  182. fi
  183. # If there are large files then fetch them.
  184. if [ ${large_file} -eq 1 ]; then
  185. _git lfs install --local
  186. _git lfs fetch
  187. _git lfs checkout
  188. # If there are also submodules, recurse into them,
  189. # shellcheck disable=SC2086 # We want word-splitting for GIT
  190. if [ ${recurse} -eq 1 ]; then
  191. _git submodule foreach --recursive ${GIT} lfs install --local
  192. _git submodule foreach --recursive ${GIT} lfs fetch
  193. _git submodule foreach --recursive ${GIT} lfs checkout
  194. fi
  195. fi
  196. # Find files that are affected by the export-subst git-attribute.
  197. # There might be a .gitattribute at the root of the repository, as well
  198. # as in any arbitrary sub-directory, whether from the master repository
  199. # or a submodule.
  200. # "git check-attr -z" outputs results using \0 as separator for everything,
  201. # so there is no difference between field or records (but there is a
  202. # trailing \0):
  203. # path_1\0attr_name\0attr_state\0path_2\0attr_name\0attr_state\0....
  204. mapfile -d "" files < <(
  205. set -o pipefail # Constrained to this sub-shell
  206. find . -print0 \
  207. |_plain_git check-attr --stdin -z export-subst \
  208. |(i=0
  209. while read -r -d "" val; do
  210. case "$((i++%3))" in
  211. (0) path="${val}";;
  212. (1) ;; # Attribute name, always "export-subst", as requested
  213. (2)
  214. if [ "${val}" = "set" ]; then
  215. printf "%s\0" "${path}"
  216. fi;;
  217. esac
  218. done
  219. )
  220. )
  221. # Replace format hints in those files. Always use the master repository
  222. # as the source of the git metadata, even for files found in submodules
  223. # as this is the most practical: there is no way to chdir() in (g)awk,
  224. # and recomputing GIT_DIR for each submodule would really be tedious...
  225. # There might be any arbitrary number of hints on each line, so iterate
  226. # over those one by one.
  227. for f in "${files[@]}"; do
  228. TZ=UTC \
  229. LC_ALL=C \
  230. GIT_DIR="${git_cache}/.git" \
  231. awk -v GIT="${GIT}" '
  232. {
  233. l = $(0);
  234. while( (i = match(l, /\$Format:[^\$]+\$/)) > 0 ) {
  235. len = RLENGTH;
  236. printf("%s", substr(l, 1, i-1) );
  237. fmt = substr(l, i, RLENGTH);
  238. pretty = substr(fmt, 9, length(fmt)-9);
  239. cmd = GIT " -c core.abbrev=40 log -s -n1 --pretty=format:'\''" pretty "'\''";
  240. while ( (cmd | getline replace) > 0) {
  241. printf("%s", replace);
  242. }
  243. ret = close(cmd);
  244. if (ret != 0) {
  245. printf("%s:%d: error while executing command \"%s\"\n", FILENAME, NR, cmd) > "/dev/stderr";
  246. exit 1;
  247. }
  248. l = substr(l, i+len);
  249. }
  250. printf("%s\n", l);
  251. }
  252. ' "${f}" >"${f}.br-temp"
  253. mv -f "${f}.br-temp" "${f}"
  254. done
  255. popd >/dev/null
  256. # Generate the archive.
  257. # We do not want the .git dir; we keep other .git files, in case they are the
  258. # only files in their directory.
  259. # The .git dir would generate non reproducible tarballs as it depends on
  260. # the state of the remote server. It also would generate large tarballs
  261. # (gigabytes for some linux trees) when a full clone took place.
  262. mk_tar_gz "${git_cache}" "${basename}" "${date}" "${output}" ".git/*"