def fix_tfvars_symlinks()

in fix_tfvars_symlinks.py [0:0]


def fix_tfvars_symlinks(src_fname, dirpath):
    global fixed_fake_symlinked_count
    global fix_symlink_error_count
    global pat_find_symlink
    # normalize just in case if src_fname is a path
    fname = os.path.basename(src_fname)
    fname_abs_path = os.path.join(dirpath,fname)

    if re.match(pat_find_tfvars,fname):
        if not os.path.islink(fname_abs_path):
            tfvars_path_above = None
            symlink_path = None
            lines = None
            try:
                with open(fname_abs_path,'r') as f:
                    lines = f.readlines()
                    f.close()
            except:
                print("can't open file {}".format(fname_abs_path))
                fix_symlink_error_count += 1
                return
            if len(lines) == 1 and re.match(pat_find_symlink, lines[0]):
                symlink_path = lines[0]
                tfvars_path_above = os.path.join(dirpath,symlink_path)
            else:
                return
            # exit if error
            if tfvars_path_above is None or not os.path.exists(tfvars_path_above):
                print("missing source tfvars file" + "" if tfvars_path_above is None else tfvars_path_above)
                fix_symlink_error_count += 1
                return
            # rename source file and try to create symlink, otherwise hard copy
            print("renaming " + fname_abs_path + "\n to " + fname_abs_path + ".delete_me")
            os.rename(fname_abs_path,  fname_abs_path +'.delete_me')
            if create_symlink_or_hardcopy(tfvars_path_above,fname_abs_path) is not None:
               print("symlinked " + tfvars_path_above + "\n to " + fname_abs_path)
               fixed_fake_symlinked_count += 1
            else:
               fix_symlink_error_count += 1
               print("error symlinking " + tfvars_path_above + "\n to " + fname_abs_path)

        else:
            try:
                tfvars_path_above = os.readlink(fname_abs_path)
                if not os.path.isabs(tfvars_path_above):
                    tfvars_path_above = os.path.join(dirpath,tfvars_path_above)
                if tfvars_path_above is not None and os.path.exists(tfvars_path_above):
                    return
                print("Broken symlink {} to {}".format(fname_abs_path,tfvars_path_above) if tfvars_path_above is not None else "" )
                print("Broken symlink in {}".format(fname_abs_path) if tfvars_path_above is None else "")
            except:
                 print("can't get symlink from file {}".format( fname_abs_path))
                 fix_symlink_error_count += 1