No internet connection
  1. Home
  2. How to

Add or remove items from the Finder sidebar

By Andrew Sherman @Andrew_Sherman
    2024-08-23 07:46:03.960Z

    I use mysides (installed via Homebrew) to automate use of my sidebar, which I use constantly. Mysides is quite simple and offers 3 functions: add, remove, and list. My script is a template which allows me to quickly add specified folders to the sidebar, but I can't get it to work removing folders from the sidebar.
    Can you help me fix it? The add function is working properly. I discovered that the paths needed the spaces replaced with "%20", so that is working properly.
    The template properties are path and user enum (add/remove).
    Error when I try to remove an item: Cannot get item at index 0. Number of items is: 0
    (Sidebar line 5)

    const mySides = '/usr/local/bin/mysides';
    
    // Function to determine if the selected path is a directory or file
    function getSelectedFolderPath() {
        const fullPath = decodeURIComponent(sf.appleScript.finder.selection.getItem(0).asItem.path);
        const isDirectory = fullPath.endsWith('/'); // Basic check: a directory might end with a '/'
        
        if (isDirectory) {
            return fullPath; // Return the folder path directly
        } else {
            return fullPath.split('/').slice(0, -1).join('/'); // Return the parent directory if it's a file
        }
    }
    
    // Function to URL-encode the path
    function encodePath(path) {
        return encodeURI(path).replace(/#/g, '%23').replace(/ /g, '%20');
    }
    
    // Function to extract the folder name from the path
    function getFolderName(path) {
        return path.split('/').slice(-1)[0]; // Get the last part of the path
    }
    
    // Get the folder path from the event props or use the selected folder in Finder
    let folderPath = event.props.folderPath;
    if (folderPath === "SelectedFolder") {
        folderPath = getSelectedFolderPath();
    }
    
    const {change} = event.props;
    
    // Prepare the folder name and URL-encoded path
    const folderName = getFolderName(folderPath);
    const encodedPath = encodePath(folderPath);
    const mysidesCommand = `mysides "${change}" "${folderName}" "file://${encodedPath}"`;
    
    // Log the command to verify it's correct
    // log(`Command to be executed: ${mysidesCommand}`);
    
    // Run the command in the background
    sf.engine.runInBackground(() => {
        sf.system.exec({
            commandLine: mysidesCommand,
            executionMode: 'Background',
        });
    });
    
    • 1 replies
    1. Kitch Membery @Kitch2024-08-23 17:43:16.891Z

      Hi @Andrew_Sherman,

      Have you tried using sf.ui.finder.firstSelectedPath; to get the finder selection path instead?