CMake, user running "sudo install", How do I now change the file owner to original user?

105 Views Asked by At

Wrote a CMakeList.txt file. At installation I am copying configuration files into users home directly .application hidden folder.

install(FILES etc/config.tsv DESTINATION ${USER_HIDDEN_DIR} PERMISSIONS OWNER_READ OWNER_WRITE)

Now even though I can copy the file finding the original user's home directory, the files owner remains root:root because he installed it using sudo. Which is not what I want.

Searching I have found way to change the file's read-write permission, but not the owner itself. How do I do it?

Basically I want to run post installation

chown user ~/.app/thefile.conf

Note I figured out the owner and his home from this cmake code snippet.

if($ENV{SUDO_USER})
    # If installed with sudo, use the home directory of the invoking user
    execute_process(
        COMMAND sh -c "eval echo ~$ENV{SUDO_USER}"
        OUTPUT_VARIABLE USER_HOME
        OUTPUT_STRIP_TRAILING_WHITESPACE
    )
else()
    # If not installed with sudo, use the current user's home directory
    execute_process(
        COMMAND sh -c "echo $HOME"
        OUTPUT_VARIABLE USER_HOME
        OUTPUT_STRIP_TRAILING_WHITESPACE
    )
endif()

1

There are 1 best solutions below

0
benblan On

The following seems to works for me. Add this in your CMakefile :

install(CODE "execute_process(COMMAND sh -c \"chown ${USER} ${USER_HOME}/path-to-my-file\" )")

You just have to figure out the USER and USER_HOME.