1#!/usr/bin/env bash 2 3# Copyright (C) 2016 The Android Open Source Project 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16# 17 18# Given a source file, for example Constructor.java, find the patch file for it and apply it. 19# Patch is applied to a copy (as opposed to in-place), for example into a build artifact location. 20 21if [[ $# -lt 3 ]]; then 22 echo "Usage: $(basename $0) <src-file-prefix> <src-file> <dst-file>" 23 exit 1 24fi 25 26DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 27ANDROID_PATCHES_DIR="$DIR/src/patches/android" 28 29src_file_prefix="$1" 30src_file="$2" 31src_file_with_prefix="$2" 32dst_file="$3" 33dst_dir="$(dirname "$dst_file")" 34 35# Sanity checking 36 37if ! [[ -d $ANDROID_PATCHES_DIR ]]; then 38 echo "FATAL: Android patch directory $ANDROID_PATCHES_DIR does not exist." >&2 39 exit 1 40fi 41 42if ! [[ $src_file == $src_file_prefix* ]]; then 43 echo "$src_file_prefix is not a valid prefix of $src_file" >&2 44 exit 1 45fi 46 47if ! [[ -f $src_file ]]; then 48 echo "Source file $src_file does not exist." >&2 49 exit 1 50fi 51 52# Remove the src file prefix, giving us the correct grep target for the .patch files. 53src_file="${src_file#$src_file_prefix}" 54 55patch_file_src=$(grep --files-with-matches -R "diff --git a/$src_file" "$ANDROID_PATCHES_DIR") 56if [[ $? -ne 0 ]]; then 57 echo "Error: Could not find a corresponding .patch file for $src_file" >&2 58 exit 1 59fi 60 61# Parse the source file from the .patch file (assumes exactly one file diff per .patch file) 62src_file_check=$(cat "$patch_file_src" | grep "diff --git a/" | sed -e "s:diff --git a\/::g" | sed -e "s: b\/.*::g") 63 64 65if ! [[ -f $patch_file_src ]]; then 66 echo "Patch file $patch_file_src does not exist." >&2 67 exit 1 68fi 69 70if ! cat "$patch_file_src" | grep "diff --git a/" > /dev/null; then 71 echo "File $patch_file_src is not a valid diff file" >&2 72 exit 1 73fi 74 75if [[ $src_file != $src_file_check ]]; then 76 echo "Check-fail: $src_file was not same as found in patch file ($src_file_check)" >&2 77 exit 1 78fi 79 80set -e 81 82# Copy the src file and then apply the patch to it. 83mkdir -p "$dst_dir" 84cp "$src_file_with_prefix" "$dst_file" 85if ! [[ -f "$dst_file" ]]; then 86 echo "File "$dst_file" does not exist; patching will fail" >&2 87 exit 1 88fi 89cd "$dst_dir" 90patch --quiet "$(basename "$dst_file")" "$patch_file_src" 91