From 510cf8059af7c0fb77c256df8f62cf9bcb03b19a Mon Sep 17 00:00:00 2001 From: Oliver Ford Date: Wed, 9 Dec 2020 01:48:25 +0000 Subject: [PATCH] Fix reading incorrect APK versions from device --- android/resource_android_apk.go | 68 ++++++++++++++++++++++++++------- 1 file changed, 54 insertions(+), 14 deletions(-) diff --git a/android/resource_android_apk.go b/android/resource_android_apk.go index 7f6565c..a15a439 100644 --- a/android/resource_android_apk.go +++ b/android/resource_android_apk.go @@ -4,6 +4,8 @@ import ( "fmt" "log" "os/exec" + "regexp" + "strconv" "strings" "github.com/OJFord/terraform-provider-android/android/apk" @@ -263,28 +265,66 @@ func resourceAndroidApkRead(d *schema.ResourceData, m interface{}) error { return fmt.Errorf("Device %s is not ready, in state: %s", serial, stdout) } - installed, err := device.Installed() + // Seems to be an upstream bug here, they report ABI versions or other incorrect numbers + /* + installed, err := device.Installed() + if err != nil { + return fmt.Errorf("Failed to read %s's packages", device.Model) + } + + pkg := d.Get("name").(string) + var pkg_info *adb.Package + for installed_pkg, installed_pkg_info := range installed { + log.Printf("%s has %s", device.Model, installed_pkg) + if installed_pkg == pkg { + pkg_info = &installed_pkg_info + } + } + + if pkg_info == nil { + d.SetId("") + d.Set("version", -1) + d.Set("version_name", "") + } else { + d.SetId(fmt.Sprint(serial, "-", pkg)) + + d.Set("version", pkg_info.VersCode) + d.Set("version_name", pkg_info.VersName) + } + */ + + pkg := d.Get("name").(string) + cmd = device.AdbShell("dumpsys", "package", pkg) + stdout, err = cmd.Output() if err != nil { - return fmt.Errorf("Failed to read %s's packages", device.Model) + return fmt.Errorf("Failed to read %s from %s", pkg, serial) } - pkg := d.Get("name").(string) - var pkg_info *adb.Package - for installed_pkg, installed_pkg_info := range installed { - log.Printf("%s has %s", device.Model, installed_pkg) - if installed_pkg == pkg { - pkg_info = &installed_pkg_info - } + if !strings.Contains(string(stdout), fmt.Sprint("Unable to find package:", pkg)) { + d.SetId("") } - if pkg_info == nil { + re_vcode := regexp.MustCompile(`versionCode=(\d+)`) + matches := re_vcode.FindStringSubmatch(string(stdout)) + if len(matches) > 0 { + v, err := strconv.ParseInt(string(matches[1]), 10, 32) + if err != nil { + return err + } + + d.SetId(fmt.Sprint(serial, "-", pkg)) + d.Set("version", v) + } else { d.SetId("") d.Set("version", -1) - d.Set("version_name", "") + } + + re_vname := regexp.MustCompile(`versionName=(.+) `) + matches = re_vname.FindStringSubmatch(string(stdout)) + if len(matches) > 0 { + d.Set("version_name", string(matches[1])) } else { - d.SetId(fmt.Sprint(serial, "-", pkg)) - d.Set("version", pkg_info.VersCode) - d.Set("version_name", pkg_info.VersName) + d.Set("version_name", -1) } return nil