Skip to content

Relative paths in lib.pl and playlist.pl #834

Closed

Description

@eljefuri

I mount a remote folder into my home folder, which contains my music collection. I would like to be able to share this lib.pl and playlist.pl file with other computers that I use, without needing to re-scan (because this takes many hours).

In other words, across two machines, these reflect the same directories remotely mounted:

/home/elje/music/J/Jesus, Zola/Versions/06- Sea Talk.mp3
/Users/elje/music/J/Jesus, Zola/Versions/06- Sea Talk.mp3

I'm requesting a feature to make cmus understand relative paths in both lib.pl and playlist.pl so that I can simply share these files across machines. I attempted to grep out the full path name and replace it with $HOME/... but it didn't work.

Thanks for your consideration!

Activity

  1. sigint2 commented on Nov 2, 2018

    @sigint2

    A brief combing through the source code reveals:

    "cmus_config_dir = get_non_empty_env("CMUS_HOME");" on line 230.

    So, export CMUS_HOME in your shell and CMUS will follow that path for loading config data

  2. eljefuri commented on Nov 8, 2018

    @eljefuri
    Author

    Hi @sigint2 I think you may have misunderstood my problem. I am looking to have relative paths in the playlist.pl file. I am not talking about relative paths for the playlist file itself.

  3. sigint2 commented on Nov 8, 2018

    @sigint2

    You can get relative paths in the .pl file, where the directory of the lib.pl / playlist.pl files is the base directory. so if lib.pl is in ~/.config/lib.pl, then to load a song located in your home dir, add ../../song.mp3 to lib.pl and cmus will recognize it

    its not a perfect solution, ideally there would be $HOME / $USER expansion or ~ path expansion, but those are shell features. they could be implemented of course but the above solution works pretty well.

  4. LolnationCH commented on Nov 29, 2018

    @LolnationCH

    You could use a python script to modify your playlist.pl. Something like this :

    with open("playlist.pl") as f:
        lines = f.read().split('\n')
    
    # Modify these to suit your tastes
    CURRENT_HEAD_FOLDER = '/home/elje/music/'
    NEXT_HEAD_FOLDER = ['/home/Steve1/music/', '/home/Steve2/music/', '/home/Steve3/music/']
    
    NEW_PLAYLIST_FILES = ["playlist%d.pl" % i for i in range(len(NEXT_HEAD_FOLDER))]
    
    for i in range(len(NEW_PLAYLIST_FILES)):
        with open(NEW_PLAYLIST_FILES[i], 'w') as f:
            li = [x.replace(CURRENT_HEAD_FOLDER, NEXT_HEAD_FOLDER[i]) for x in lines]
            f.write("\n".join(li))
  5. nefthy commented on Feb 5, 2019

    @nefthy
    Collaborator

    Since this already works by manually mangling the files, maybe someone could come up with a patch.

  6. pgaskin commented on Jan 24, 2021

    @pgaskin
    Member

    @nefthy, do you think it would make more sense to have (in my own order of preference):

    1. An option with similar semantics to bind mounts.
    2. An option to treat a path as the library root.
    3. The first option, but only affecting the internal parts by doing a find/replace in paths passed to open/etc (i.e. the browser would show your local paths).

    And, do you think this option belongs in rc or as a env var/command-line argument. I personally think the latter since this would be a per-computer option and since it would likely be a major source of bugs if this could be changed at runtime.

  7. pgaskin commented on Feb 25, 2021

    @pgaskin
    Member

    I'm going to play around with this sometime in the next few weeks. For the record, I currently use proot as a workaround.

  8. pgaskin commented on Mar 1, 2021

    @pgaskin
    Member

    One thing to consider: How should adding/playing files with cmus-remote or :add work? Should it reject the un-bound path, replace it, or leave it as is? What happens if a file from a directory shadowed by a bind is played directly?

  9. pgaskin commented on Mar 1, 2021

    @pgaskin
    Member

    Also, a few less-intrusive (they don't require intercepting syscalls and/or making error-prone path changes, and they will retain full backwards/forwards compatibility with normal paths) options:

    1. Expand env vars in library/playlist paths, add a setting for a list of env vars to substitute real paths with when adding tracks, add a command to transform the selected tracks' paths. For simplicity (and it also makes more sense), this would be done in the save/add code rather than everywhere a path is used (e.g. the cache would still deal with real paths rather than the ones with env vars). This also means the user should never see the env vars in the UI. There's only one significant problem with this: How should changes to the env var list be handled?
    2. Same as the first option, but have custom variables stored in the cmus config rather than the environment.
    3. Add an option to make all paths relative to the library file (note that I don't like this option due to the implications and potential confusion related to relative paths including .. and their expansion, drive letters on Windows, and moving the config file).
  10. pgaskin commented on Mar 1, 2021

    @pgaskin
    Member

    One somewhat-related note: cmus currently assumes all paths use / as the separator. To avoid breaking things if compiled with MinGW, paths with \ will need to be translated to / on Windows.

  11. pgaskin commented on Mar 1, 2021

    @pgaskin
    Member

    Currently, I believe the first option in the second list will be the least intrusive, most reliable, and most intuitive option to implement.

  12. pgaskin commented on Mar 1, 2021

    @pgaskin
    Member

    I think I've finally managed to track down the essential pl load/save functions (the code was surprisingly convoluted when tracing references starting from ip_new): do_cmus_save and cmus_add+FILE_TYPE_PL. Based on this, I'll have to start with save_playlist_cb and handle_line.

    Based on this, I think I can solve the problem of changes to the env var list by allowing any env var during read, and using the env var list when transforming the written paths. In addition, I don't think I'll need a command to transform paths for existing tracks, since that'll be handled on exit.

  13. self-assigned this
    on Mar 1, 2021
  14. pgaskin commented on Mar 1, 2021

    @pgaskin
    Member

    Here's an initial implementation. It works, but I still need to figure out some edge cases (see the TODO in the patch) and if I'm going to stick with this approach (I probably will):

    Details
    diff --git a/Doc/cmus.txt b/Doc/cmus.txt
    index 6b5d848..358f533 100644
    --- a/Doc/cmus.txt
    +++ b/Doc/cmus.txt
    @@ -1084,6 +1084,10 @@ mpris (true)
     output_plugin [roar, pulse, alsa, arts, oss, sndio, sun, coreaudio]
            Name of output plugin.
     
    +pl_env_vars
    +       Comma separated list of environment variables to substitute when saving
    +       library/playlist files.
    +
     pl_sort () [`Sort Keys`]
            Sort keys for the playlist view (3). Empty value disables sorting and
            enables manually moving tracks.
    diff --git a/cmus.c b/cmus.c
    index ed30db0..95f3251 100644
    --- a/cmus.c
    +++ b/cmus.c
    @@ -206,12 +206,65 @@ static int save_playlist_cb(void *data, struct track_info *ti)
            const char nl = '\n';
            int rc;
     
    -       rc = write_all(fd, ti->filename, strlen(ti->filename));
    +       char *ft = NULL;
    +       if (pl_env_vars && *pl_env_vars && *ti->filename != '\x1F') {
    +               // see handle_line in job.c for more information about how this works
    +
    +               for (char **v = pl_env_vars; *v; v++) {
    +                       if (!**v)
    +                               continue;
    +
    +                       const char *x = getenv(*v);
    +                       if (!x || !*x)
    +                               continue;
    +                       size_t xl = strlen(x);
    +
    +#ifdef _WIN32
    +                       // Windows is case-insensitive and doesn't have strncmp,
    +                       // plus cmus always uses a forward slash for internal
    +                       // paths.
    +                       const char *wna = ti->filename;
    +                       const char *wnb = x;
    +                       size_t wnn = xl;
    +                       while (wnn-- && (tolower(*wna) == tolower(*wnb) || (*wna == '/' && *wnb == '\\'))) {
    +                               if (!wnn || !*wna || !*wnb)
    +                                       break;
    +                               wna++;
    +                               wnb++;
    +                       }
    +                       if (*wna || *wnb)
    +                               continue;
    +#else
    +                       if (strncmp(ti->filename, x, xl) != 0)
    +                               continue;
    +#endif
    +
    +                       // Keep the '/' at the beginning of the path, and only
    +                       // use the env var if it is a dir.
    +                       if (ti->filename[xl-1] == '/')
    +                               xl--;
    +                       if (ti->filename[xl] != '/')
    +                               continue;
    +
    +                       size_t vl = strlen(*v);
    +                       char *fc = ft = xnew(char, 1 + vl + 1 + strlen(ti->filename + xl) + 1);
    +                       *fc++ = '\x1F';
    +                       strncpy(fc, *v, vl);
    +                       fc += vl;
    +                       *fc++ = '\x1F';
    +                       strcpy(fc, ti->filename + xl);
    +               }
    +       }
    +
    +       rc = write_all(fd, ft ? ft : ti->filename, strlen(ft ? ft : ti->filename));
            if (rc == -1)
                    return -1;
            rc = write_all(fd, &nl, 1);
            if (rc == -1)
                    return -1;
    +
    +       free(ft);
    +
            return 0;
     }
     
    diff --git a/job.c b/job.c
    index cd32e0b..0dbdf15 100644
    --- a/job.c
    +++ b/job.c
    @@ -346,7 +346,70 @@ static int handle_line(void *data, const char *line)
            if (is_http_url(line) || is_cue_url(line)) {
                    add_url(line);
            } else {
    -               char *absolute = path_absolute_cwd(line, data);
    +               char *absolute = NULL;
    +               if (*line == '\x1F') {
    +                       // We use \x1F as the variable delimiter since it won't
    +                       // appear in a filename, it won't show up in the
    +                       // console, and it won't require changes to be made
    +                       // elsewhere for the variable handling.
    +
    +                       const char *ve = strchr(line+1, '\x1F');
    +                       char *v = ve
    +                               ? xstrndup(line+1, ve-line-1)
    +                               : xstrdup(line+1);
    +                       ve++;
    +
    +                       // If the env var is not found or is empty, we leave the
    +                       // filename as-is. Even though this will result in
    +                       // errors (the path won't exist, and it'll start with
    +                       // 0x1b), it will allow the env var substitution to be
    +                       // preserved when saving so the playlist isn't
    +                       // destroyed.
    +
    +                       // FIXME: this isn't actually true since it'll discard
    +                       // tracks which aren't found in the cache...
    +
    +                       // TODO: see if there's a way we can preserve the play
    +                       // count info from the cache (speaking of that, does it
    +                       // even belong there in the first place?...)
    +
    +                       // ... maybe the solution to both of these is to use
    +                       // this config option for the cache entries too?
    +
    +                       // Note that when saving, the env var may not be the
    +                       // same as the original one used when loading since the
    +                       // substition is based on the pl_env_vars option in
    +                       // order. This is intentional.
    +
    +                       const char *x = getenv(v);
    +                       if (x && *x) {
    +                               // Note that the remaining filename will always
    +                               // begin with a path separator when saved, just
    +                               // in case the env var doesn't have its own at
    +                               // the end.
    +
    +                               char *fc = absolute = xmalloc(strlen(x) + strlen(ve) + 1);
    +                               for (const char *c = x; *c; c++) {
    +#ifdef _WIN32
    +                                       // cmus always uses forward slashes
    +                                       // internally, and Windows accepts
    +                                       // either.
    +                                       if (*c == '\\')
    +                                               *fc++ = '/';
    +                                       else
    +#endif
    +                                       *fc++ = *c;
    +                               }
    +                               strcpy(fc, ve);
    +
    +                               d_print("substituted filename '%s' => '%s' (%s='%s')\n", line, absolute, v, x);
    +                       }
    +
    +                       free(v);
    +               }
    +               if (!absolute)
    +                       absolute = path_absolute_cwd(line, data);
    +
                    add_file(absolute, 0);
                    free(absolute);
            }
    diff --git a/options.c b/options.c
    index 93b1c35..abb3cfc 100644
    --- a/options.c
    +++ b/options.c
    @@ -155,6 +155,7 @@ char *window_title_alt_format = NULL;
     char *id3_default_charset = NULL;
     char *icecast_default_charset = NULL;
     char *lib_add_filter = NULL;
    +char **pl_env_vars = NULL;
     
     static void buf_int(char *buf, int val, size_t size)
     {
    @@ -261,6 +262,7 @@ static const struct {
            { "pl_sort", "" },
            { "id3_default_charset", "ISO-8859-1" },
            { "icecast_default_charset", "ISO-8859-1" },
    +       { "pl_env_vars", "" },
            { NULL, NULL }
     };
     
    @@ -500,6 +502,51 @@ static void set_tree_width_max(void *data, const char *buf)
            update_size();
     }
     
    +static void get_pl_env_vars(void *data, char *buf, size_t size)
    +{
    +       if (!pl_env_vars) {
    +               strscpy(buf, "", size);
    +               return;
    +       }
    +       char *p = buf;
    +       size_t r = size - 1;
    +       for (char **x = pl_env_vars; *x; x++) {
    +               if (x != pl_env_vars) {
    +                       if (!--r)
    +                               return;
    +                       *p++ = ',';
    +               }
    +               size_t l = strlen(*x);
    +               if (!(r -= l))
    +                       return;
    +               strcpy(p, *x);
    +               p += l;
    +       }
    +       *p = '\0';
    +}
    +
    +static void set_pl_env_vars(void *data, const char *buf)
    +{
    +       if (pl_env_vars) {
    +               free(*pl_env_vars);
    +               free(pl_env_vars);
    +       }
    +       if (!*buf) {
    +               pl_env_vars = NULL;
    +       }
    +       size_t n = 1;
    +       for (const char *x = buf; *x; x++)
    +               if (*x == ',')
    +                       n++;
    +       char **a = pl_env_vars = xnew(char*, n+1);
    +       for (char *x = *a++ = xstrdup(buf); *x; x++)
    +               if (*x == ',') {
    +                       *a++ = x+1;
    +                       *x = '\0';
    +               }
    +       *a = NULL;
    +}
    +
     /* }}} */
     
     /* callbacks for toggle options {{{ */
    @@ -1433,6 +1480,7 @@ static const struct {
            DT(stop_after_queue)
            DN(tree_width_percent)
            DN(tree_width_max)
    +       DN(pl_env_vars)
            { NULL, NULL, NULL, NULL, 0 }
     };
     
    diff --git a/options.h b/options.h
    index 78c5f4e..18e5725 100644
    --- a/options.h
    +++ b/options.h
    @@ -187,6 +187,8 @@ extern char *window_title_alt_format;
     extern char *id3_default_charset;
     extern char *icecast_default_charset;
     
    +extern char **pl_env_vars;
    +
     /* build option list */
     void options_add(void);

    Just apply the patch and :set pl_env_vars=HOME.

  15. pgaskin commented on Jun 1, 2021

    @pgaskin
    Member

    @nefthy, @flyingmutant, any thoughts about the patch so far, specifically what I mentioned in the TODOs?

  16. nefthy commented on Jun 1, 2021

    @nefthy
    Collaborator

    I don't think we will be able to get the play count out of the cache without major open heart surgery.

  17. tonyfischetti commented on Jun 1, 2021

    @tonyfischetti

    Just tested this patch. Works like an absolute charm! Just what I was looking for!
    I tested it on Debian 10. I'll try it on my mac, too

  18. pgaskin commented on Jun 2, 2021

    @pgaskin
    Member

    Yep, it does work in general, but it currently has the following bugs:

    • It will cause cmus to forget tracks if the env var doesn't exist or is otherwise invalid.
    • It will not preserve the play count between env var changes.

    The advantage of doing it this somewhat-hacky way is that:

    • It doesn't requires significant (more bug-prone) changes elsewhere.
    • It gracefully handles different paths since the rest of cmus only sees the real filename.
    • It follows the general convention in cmus of doing stuff on load/exit.
    • It's much shorter than the alternative things I tried.
    • It doesn't have any chance of causing regressions for people not using the config option.

    @nefthy, I just had an idea of how I could deal with that. I'm currently considering either adding an additional cache file mapping the paths to a list of previously known transformed paths. The cache code would use this to try another path if the first one isn't found and the config option is enabled, and this new cache file would be treated the same as the normal cache except that it'd also be invalidated when the env var config changes.
    Edit: I just realized something else: since we aren't keeping track of a file in multiple env card (a single env var counts as a path component), and the cache is also save/restore, we don't even need another cache file. I can probably just mangle the paths used by the cache itself the same way as the main playlist. This should theoretically solve both issues if it works the way I think it does. I'll test this out soon.

    My main priorities when considering different options are:

    • Low risk of regressions for people who haven't used the option.
    • Consistency with the current behaviour.
    • Least amount of code, and as self-contained as possible.
    • Can be enabled/disabled cleanly, and handles config/environment changes properly.
    • Preserves compatibility with older cmus versions when the config option isn't enabled.
  19. nefthy commented on Jun 2, 2021

    @nefthy
    Collaborator

    I'm not sure about that. @flyingmutant?

  20. pgaskin commented on Jun 2, 2021

    @pgaskin
    Member

    I think I've figured out a way to handle this. If I move the dummy-track (for bad env vars) logic into cache.c, I can prevent cmus from discarding those tracks. And, if I also add the filename processing to the cache load/save mechanism, it should also fix the play count issue and keep the cache clean, while keeping the behaviour consistent.

    Edit: I wrote a quick patch for this, and so far, it's working perfectly. Based on my testing so far, it behaves exactly the same as cmus would with normal paths (i.e as if you just bind mounted the dirs and moved them around that way). For example, if you change the env var to point to a nonexistent path, all the old metadata from the cache will still show, and it'll show a not found error when trying to play the track, and it'll still work consistently after restarting cmus in that state. And, if you then remove the env var config from cmus' autosave file, it'll remove the env var on the next run and return the library to how it would have been without the patch in the first place (if the env var was also unset when you did this, it'd preserve the substitutions until the next time the env var was set). Furthermore, if you remove the cache while the env var is not set, it'll still properly remove the contents of the playlists (like what usually happens if a file is missing from both the filesystem and the cache) because the cache is now aware of the substitutions. I'm going to do some more testing, then clean up the patch (I'm going to move most of the code into a separate file with more details about how it works). Also, I'm probably going to make some changes in a few other places to make some errors more clear.

    Edit: TLDR: I've figured out how to make this work perfectly. By substituting all env vars while loading the playlists and the cache, and putting placeholders for configured env vars when saving them again, libraries can be relocated through the values of those env vars while preserving the expected behaviour of cmus, being resilient to errors, and keeping the internal behavior and paths exactly the same if the feature is not enabled. Based on my testing so far, I think I'm ready to open a PR for this after I do a bit of cleanup and documentation.

  21. pgaskin commented on Jun 2, 2021

    @pgaskin
    Member

    I've made a number of improvements and done quite a bit of testing, especially around ensuring paths are handled consistently, ensuring metadata is preserved in all cases, and ensuring it behaves comparably to how cmus usually handles files.

    I've opened a PR with my changes for review and more testing. I've also merged this PR into my Debian and Fedora packages.

  22. tonyfischetti commented on Jun 3, 2021

    @tonyfischetti

    Thanks for your work on this!

  23. pgaskin commented on Jun 3, 2021

    @pgaskin
    Member

    If you have time, can you test the PR, and leave a comment?

  24. tonyfischetti commented on Jun 3, 2021

    @tonyfischetti

    Sure, I think I'll be able to do it in a few hours

  25. tonyfischetti commented on Jun 3, 2021

    @tonyfischetti

    Done. It seems to be working great for me. Comment in the PR

  26. tonyfischetti commented on Jul 23, 2021

    @tonyfischetti

    Any update on getting this merged?
    Right now I'm running this patch but I don't want to drift away from upstream
    and I think a lot of people would like using it

  27. pgaskin commented on Jul 23, 2021

    @pgaskin
    Member

    Yep, I just haven't had time to work on cmus recently. I'll probably get to it sometime within the next month or two.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions