Ejemplo n.º 1
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description="Wifi status",
        detailed_description="Wifi status bar components",
        knobs=[],
        exemplar="wifi  | ▁▂▄ | ",
        update_cadence=5,
        identifier="take.wifi")

    @iterm2.StatusBarRPC
    async def wifi_status(knobs):
        signal = ""

        output = subprocess.check_output(args=[airport_path, "-I"]).decode()
        info = re.findall(
            "[\s]*(agrCtlRSSI|agrCtlNoise|state|lastTxRate|SSID):[\s]([!-~\ ]*)",
            output)
        rssi = int(info[0][1])
        noise = int(info[1][1])
        rate = info[3][1]
        ssid = info[5][1]
        snr = rssi - noise

        if int(rate) == 0:
            signal = "🙅‍♂️"
            status = "{0}".format(signal)
        else:
            # 25dB SNR -> 5 bars
            power = min(snr // 5, 5)
            signal = "".join(signals[:power])
            status = "{0}  | {1} |".format(ssid, signal)
        # print(f"rssi: {rssi}, noise: {noise}, snr: {snr}, ssid: {ssid}")
        return status

    await component.async_register(connection, wifi_status)
Ejemplo n.º 2
0
async def main(connection):
    await iterm2.async_get_app(connection)

    icon2x = iterm2.StatusBarComponent.Icon(
        2,
        "iVBORw0KGgoAAAANSUhEUgAAACAAAAAiCAYAAAA+stv/AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAlmVYSWZNTQAqAAAACAAFARIAAwAAAAEAAQAAARoABQAAAAEAAABKARsABQAAAAEAAABSATEAAgAAABEAAABah2kABAAAAAEAAABsAAAAAAAAAGAAAAABAAAAYAAAAAF3d3cuaW5rc2NhcGUub3JnAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIgAAAADJGjVWAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAComlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS40LjAiPgogICA8c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PKNN1MpKL2JEcA0RiN8lDaR8B2sVEwAozQazErLFbZUcsVQOvKoVQ5Ag4KFuc7sVrMiRsCAZ5KZYc2joBh6yJnQT/k7hVrBGsF413MDwrjow8BMR75j+WCJp9hyzWLdupthn9KPBF3xH1xRXA2YF4rhZeeDjJS2OAwpOx5zKv/jfKUw13BVHwSdMxp+UVgvP/LcgQQgK/dJzhsVgi25DpBZ5wJlxJKulmOABbTKlE+CemJr0TgLuFtyEH0QlwXtZYjgCAeRr7W24pRYZuxntgFu4W3IevglmC6XF/ZoeUKcEvalQMy9/sFU+OtR5nN4u0P0nEFjASRgxibF6f9xjRnGzbV5euY8/PipXgongsuLm/TKFLFhXUZATpmjjnf6wwBbL3b4oPgMGIqEOFpoE62WTU/LM4JgiCG1Ng/o7J/Zpxw5Q6rfG9Rhh0m+kXkr9/R0HmViC2qj7l94Y3xtPpZtaUjtpY7rEr9/qLqYU2LtqjR8LR6hnFB5AjgMsI6CWirxA9Nb6NB1A4P7gWObBanP6S2WZuA92rpU602SOkFFxRbls4ZuUarE0BD3nHJ8Cckx+ZS5davbwvqANxwXgPe8/iRWL61LwFR4EzqkI442YCpcd5iTqgMs/jCm+DpQEzHWeGOyinCToZ+3C4UjZ+NwXYqDBcMl828eCAui23CFuu7bOKUoDHwtPz1ggvHVq7j8l5TpsInpANzo9btJtepTf8ANYnL9fLxNg8AAAAASUVORK5CYII="
    )
    icon1x = iterm2.StatusBarComponent.Icon(
        1,
        "iVBORw0KGgoAAAANSUhEUgAAABAAAAARCAYAAADUryzEAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAlmVYSWZNTQAqAAAACAAFARIAAwAAAAEAAQAAARoABQAAAAEAAABKARsABQAAAAEAAABSATEAAgAAABEAAABah2kABAAAAAEAAABsAAAAAAAAAGAAAAABAAAAYAAAAAF3d3cuaW5rc2NhcGUub3JnAAAAA6ABAAMAAAABAAEAAKACAA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/iEBvzCEf4sJKBkCyYwhyH04BbeQGK2iTejJboUreEVtGsHZN6deIGsLjngTUxH/nEo/s9iAiqqu8oqXnUV5104czEBHXsKLzCAD9Du3gmkGrJvgnfQhBXs4CIBza2Z287jkhvQJSpXg6jZpWnmZ5CQffdZrsvqcqHs1f6JPss95AXeWUvYaw5dopq/QCYR2Rb0KW2tWNBM8Imsio2xq/ZOUAxobbs88n4PC1jCxVYUVWModhaMJsjaODbGuaH4OAEUkzSDoz1zAAAAAABJRU5ErkJggg=="
    )

    component = iterm2.StatusBarComponent(
        short_description="Temp CPU",
        detailed_description="Shows the temperature of the CPU",
        knobs=[],
        exemplar=GetTemp(),
        update_cadence=10,
        identifier="com.iterm2.example.cpu-temp",
        icons=[icon1x, icon2x])

    # This function gets called once per second.
    @iterm2.StatusBarRPC
    async def coro(knobs, cputemp=iterm2.Reference("iterm2.user.cputemp?")):
        return GetTemp() + "    ☢  " + GetFan()

    # Register the component.
    await component.async_register(connection, coro)
Ejemplo n.º 3
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description="Vagrant Counter",
        detailed_description="Show Number of Vagrant VM",
        knobs=[],
        exemplar="[Vagrant Counter]",
        update_cadence=30,
        identifier="koh-sh.vagrant-counter")

    @iterm2.StatusBarRPC
    async def vagrant_counter(knobs):
        # TODO: find better emojis
        up = "🔵 "
        down = "âš« "

        try:
            fpath = os.environ["HOME"] + "/.vagrant.d/data/machine-index/index"
            with open(fpath, "r") as f:
                d = json.loads(f.read())
            vms = d["machines"]
            up_vms = [x for x in vms if vms[x]["state"] == "running"]
            all_machines = len(vms)
            up_machines = len(up_vms)
            return (up * up_machines) + (down * (all_machines - up_machines))
        except Exception:
            return "Cannot find Vagrant info"

    await component.async_register(connection, vagrant_counter)
Ejemplo n.º 4
0
async def main(connection):
    app = await iterm2.async_get_app(connection)
    asyncio.create_task(poll(app))

    icon1x = iterm2.StatusBarComponent.Icon(1, ICON1X)
    icon2x = iterm2.StatusBarComponent.Icon(2, ICON2X)

    # Register the status bar component.
    component = iterm2.StatusBarComponent(
        short_description="Disk IO",
        detailed_description="Shows your overall disk read/write speed",
        knobs=[],
        exemplar="🆁1.2MB/s 🆆️10.5MB/",
        update_cadence=None,
        identifier="catj.moe.disk_io",
        icons=[icon1x, icon2x])

    @iterm2.StatusBarRPC
    async def disk_io_coroutine(knobs, value=iterm2.Reference("iterm2.user." + DISK_IO_VARIABLE + "?")):
        """This function returns the value to show in a status bar."""
        if value:
            return value
        return "Loading…"

    # Register the component.
    await component.async_register(connection, disk_io_coroutine)
Ejemplo n.º 5
0
async def main(connection):
    fmt = 'fmt'
    default_fmt = '%m/%d %a %H:%M:%S'
    knobs = [
        iterm2.StringKnob(name='format',
                          placeholder=default_fmt,
                          default_value=default_fmt,
                          key=fmt)
    ]
    component = iterm2.StatusBarComponent(
        short_description='Clock',
        detailed_description='A customized clock.',
        knobs=knobs,
        exemplar=' 08/03 Sat 01:56:48',
        update_cadence=1,
        identifier='peinan.clock')

    @iterm2.StatusBarRPC
    async def clock(knobs):
        n = datetime.now()
        clock_char = ''
        if fmt in knobs and knobs[fmt]:
            clock_face = f'{clock_char} {n.strftime(knobs[fmt])}'
        else:
            clock_face = f'{clock_char} {n.strftime(default_fmt)}'

        return clock_face

    await component.async_register(connection, clock)
Ejemplo n.º 6
0
async def main(connection):
    # Define the configuration knobs:
    ds = "docker_status"
    knobs = []
    component = iterm2.StatusBarComponent(
        short_description="Docker Status",
        detailed_description=
        "Show docker status and number or running containers",
        knobs=knobs,
        exemplar=" Docker status",
        update_cadence=60,
        identifier="fr.gabrielpichot.iterm2.statusbarcomponent.docker_status")

    @iterm2.StatusBarRPC
    async def coro(knobs):
        try:
            running = get_docker_info('ContainersRunning')
            paused = get_docker_info('ContainersPaused')
            stopped = get_docker_info('ContainersStopped')
        except DockerNotRunning as e:
            print(e)
            return " Stopped"
        except Exception as e:
            print(e)
            return " Errored"

        return " {}   {}   {} ".format(running, stopped, paused)

    # Register the component.
    await component.async_register(connection, coro)
Ejemplo n.º 7
0
async def main(connection):
    icon1x = iterm2.StatusBarComponent.Icon(1, ICON1X)
    icon2x = iterm2.StatusBarComponent.Icon(2, ICON2X)

    component = iterm2.StatusBarComponent(
        short_description="Enhanced Time",
        detailed_description="Display current tme with extra information",
        knobs=[],
        exemplar=local_time(),
        update_cadence=1,
        identifier="catj.moe.localtime",
        icons=[icon1x, icon2x])

    @iterm2.StatusBarRPC
    async def localtime(knobs):
        return local_time()

    @iterm2.RPC
    async def onclick(session_id):
        word_time = "Loading"
        try:
            word_time = get_world_time()
        except:
            word_time = "Loading"
        if word_time is not None:
            await component.async_open_popover(session_id, word_time,
                                               iterm2.util.Size(256, 340))

    # Register the component.
    await component.async_register(connection, localtime, onclick=onclick)
Ejemplo n.º 8
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description='pyenv',
        detailed_description='The currently active Python',
        exemplar='🐍 3.7.2',
        update_cadence=2,
        identifier='engineering.dane.iterm-components.pyenv',
        knobs=[],
    )

    @iterm2.StatusBarRPC
    async def pyenv_coroutine(knobs):
        proc = await asyncio.create_subprocess_shell(
            'pyenv local',
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
        stdout, stderr = await proc.communicate()

        if stderr:
            return stderr.decode().strip()

        env = stdout.decode().strip()
        return f'🐍 {env}'

    await component.async_register(connection, pyenv_coroutine)
Ejemplo n.º 9
0
async def main(connection):
    api_key = "atlas_api_key"
    knobs = [iterm2.StringKnob("API key", "API KEY", "", api_key)]
    component = iterm2.StatusBarComponent(
        short_description="RIPE Atlas Credits",
        detailed_description="Shows credits balance at atlas.ripe.net",
        knobs=knobs,
        exemplar="0.0 / 34,000.0 / 4,000,000.0",
        update_cadence=300,
        identifier="com.iterm2.example.status-bar")

    @iterm2.StatusBarRPC
    async def coro(knobs):
        URL = 'https://atlas.ripe.net/api/v2/credits/'
        PARAMS = {'key': knobs[api_key]}
        try:
            r = requests.get(url=URL, params=PARAMS)
            data = r.json()
            daily = data['estimated_daily_income']
            total = data['current_balance']
            expenditure = data['estimated_daily_expenditure']
        except:
            raise
        else:
            return f'{float(expenditure):,.1f} / {float(daily):,.1f} / {float(total):,.1f}'

    await component.async_register(connection, coro)
Ejemplo n.º 10
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description='GitHub stars',
        detailed_description='How many stars a GitHub repository has',
        exemplar='some-user/project ★ 103',
        update_cadence=300,
        identifier='engineering.dane.iterm-components.github-stars',
        knobs=[
            iterm2.StringKnob('Repository', 'some-user/project', 'some-user/project', REPO_KNOB_NAME),
            iterm2.StringKnob('Personal access token', 'token value (optional, for rate limiting or private repos)', '', TOKEN_KNOB_NAME)
        ],
    )

    @iterm2.StatusBarRPC
    async def github_stars_coroutine(knobs):
        github_repo = knobs[REPO_KNOB_NAME]
        token = knobs[TOKEN_KNOB_NAME]
        info_url = f'https://api.github.com/repos/{github_repo}'

        try:
            request = urllib.request.Request(
                info_url,
                headers={'Authorization': f'token {token}'} if token else {},
            )
            stars = json.loads(
                urllib.request.urlopen(request).read().decode()
            )['stargazers_count']
            stars = human_number(stars)
        except:
            raise
        else:
            return f'{github_repo} ★ {stars}'

    await component.async_register(connection, github_stars_coroutine)
Ejemplo n.º 11
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description='rvm gemset',
        detailed_description='The currently active rvm gemset',
        exemplar='♦ gemset',
        update_cadence=2,
        identifier='engineering.dane.iterm-components.rvm-gemset',
        knobs=[],
    )

    @iterm2.StatusBarRPC
    async def rvm_gemset_coroutine(knobs):
        proc = await asyncio.create_subprocess_shell(
            '${HOME}/.rvm/bin/rvm-prompt g',
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
        stdout, stderr = await proc.communicate()

        if stderr:
            return '♦ rvm not installed!'

        gemset = stdout.decode().strip().replace('@', '') or 'default'
        return f'♦ {gemset}'

    await component.async_register(connection, rvm_gemset_coroutine)
Ejemplo n.º 12
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description='Execute a user defined command',
        detailed_description='A component that displays the output of an arbitrary command with an optional prefix',
        exemplar='> hello world',
        update_cadence=7,
        identifier='engineering.dane.iterm-components.generic-command',
        knobs=[
           iterm2.StringKnob('Script', 'echo "hello world"', '', SCRIPT),
           iterm2.StringKnob('Prefix', '>', '', PREFIX)
        ],
    )

    @iterm2.StatusBarRPC
    async def generic_command_coroutine(knobs):
        proc = await asyncio.create_subprocess_shell(
            knobs[SCRIPT],
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
        stdout, stderr = await proc.communicate()
        prefix = knobs[PREFIX]
        prefix = f'{prefix} ' if prefix else ''
        return f'{prefix}{stdout.decode().strip()}' if not stderr else 'Command failed!'

    await component.async_register(connection, generic_command_coroutine)
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description='Bitcoin Mempool Stats',
        detailed_description=
        'Displays BTC mempool size and unconfirmed transactions count',
        exemplar='BTC Mempool 4,239 txs @ 1.03 MB',
        update_cadence=60,
        identifier='schnogz.iterm-crypto-components.btc-mempool',
        knobs=[],
    )

    @iterm2.StatusBarRPC
    async def btc_mempool_coroutine(knobs):
        stats_url = 'https://api.blockchair.com/bitcoin/stats'

        try:
            context = ssl._create_unverified_context()
            request = urllib.request.Request(
                stats_url,
                headers={},
            )
            stats = json.loads(
                urllib.request.urlopen(request,
                                       context=context).read().decode())
            unconfirmed_tx_count = format(
                stats['data']['mempool_transactions'], ',')
            mempool_size = round(stats['data']['mempool_size'] / 1000000, 2)
        except:
            raise
        else:
            return f'BTC Mempool {unconfirmed_tx_count} txs @ {mempool_size} MB'

    await component.async_register(connection, btc_mempool_coroutine)
Ejemplo n.º 14
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description='Weather',
        detailed_description='Display weather by using darksky-weather',
        exemplar='🌧️8°C',
        update_cadence=900,
        identifier='vxider.iterm-components.weather',
        knobs=[],
    )

    @iterm2.StatusBarRPC
    async def weather_coroutine(knobs):
        try:
            output = check_output(["/usr/local/bin/weather", "-json"],
                                  stderr=STDOUT,
                                  timeout=10)
            data = json.loads(output.decode().strip())
            weather = data['currently']['temperature']
            icon_text = data['currently']['icon']
            unit = data['flags']['units']
            return f'{get_weather_icon(icon_text)}{int(weather)}{get_temperature(unit)}'
        except Exception as e:
            print(e)
            return '☁️ N/A'

    await component.async_register(connection, weather_coroutine, timeout=15)
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description='Ethereum Price',
        detailed_description='Displays current price of Ethereum',
        exemplar='ETH $321.50',
        update_cadence=30,
        identifier='schnogz.iterm-crypto-components.eth-price',
        knobs=[],
    )

    @iterm2.StatusBarRPC
    async def ethereum_price_coroutine(knobs):
        price_url = 'https://api.blockchair.com/ethereum/stats'

        try:
            context = ssl._create_unverified_context()
            request = urllib.request.Request(
                price_url,
                headers={},
            )
            price = format(
                round(
                    json.loads(
                        urllib.request.urlopen(
                            request, context=context).read().decode())['data']
                    ['market_price_usd'], 2), ',')
        except:
            raise
        else:
            return f'ETH ${price}'

    await component.async_register(connection, ethereum_price_coroutine)
Ejemplo n.º 16
0
async def main(connection):
    app = await iterm2.async_get_app(connection)
    # Start fetching the URL
    asyncio.create_task(updater(app, type='current'))
    asyncio.create_task(updater(app, type='forecast'))

    location_knob = "weather_location"
    update_interval_knob = "weather_update_interval"
    knobs = [
        iterm2.StringKnob("Location", "Hangzhou", "Hangzhou", location_knob),
        iterm2.StringKnob("Update Interval", "60", "60", update_interval_knob)
    ]

    # icon1x = iterm2.StatusBarComponent.Icon(1, ICON1X)
    # icon2x = iterm2.StatusBarComponent.Icon(2, ICON2X)

    # Register the status bar component.
    component = iterm2.StatusBarComponent(
        short_description="Weather",
        detailed_description="Shows your local weather",
        knobs=knobs,
        exemplar="☁️Weather",
        update_cadence=None,
        identifier="catj.moe.weather")

    @iterm2.StatusBarRPC
    async def weather(knobs,
                      value=iterm2.Reference("iterm2.user." +
                                             CURRENT_VARIABLE + "?")):
        """This function returns the value to show in a status bar."""
        global city
        global update_interval
        if location_knob in knobs and knobs[location_knob]:
            city = knobs[location_knob]
        if update_interval_knob in knobs and knobs[update_interval_knob]:
            update_interval = int(knobs[update_interval_knob])

        if value:
            return value
        return "Loading…"

    @iterm2.RPC
    async def onclick(session_id):
        session = app.get_session_by_id(session_id)
        forecast_weather = "Loading"
        try:
            forecast_weather = await format_weather(app)
        except:
            forecast_weather = "Loading"
        if forecast_weather is not None:
            await component.async_open_popover(session_id, forecast_weather,
                                               iterm2.util.Size(480, 520))

    # Register the component.
    await component.async_register(connection, weather, onclick=onclick)
Ejemplo n.º 17
0
async def main(connection):
    knob_icons = KnobOption('icons', '')
    knob_free = KnobOption('free', True)
    knob_usedtotal = KnobOption('usedtotal', True)
    knob_usedpercent = KnobOption('usedpercent', True)
    knobs = [
        iterm2.StringKnob(name='Icons',
                          default_value=knob_icons.v,
                          placeholder=knob_icons.v,
                          key=knob_icons.name),
        iterm2.CheckboxKnob(name='Show Free Space',
                            default_value=knob_free.v,
                            key=knob_free.name),
        iterm2.CheckboxKnob(name='Show Used/Total Space',
                            default_value=knob_usedtotal.v,
                            key=knob_usedtotal.name),
        iterm2.CheckboxKnob(name='Show Used Space (%)',
                            default_value=knob_usedpercent.v,
                            key=knob_usedpercent.name),
    ]

    component = iterm2.StatusBarComponent(
        short_description='Disk Usage',
        detailed_description='Display the usage of disk.',
        knobs=knobs,
        exemplar=' 44.1 GB  179.7/233.5 GB (81.0%)',
        update_cadence=2,
        identifier='peinan.diskusage')

    def is_true_knob(knobs, knob_option: KnobOption):
        return knob_option.name in knobs and knobs[knob_option.name]

    @iterm2.StatusBarRPC
    async def diskusage(knobs):
        true_icons = is_true_knob(knobs, knob_icons)
        true_free = is_true_knob(knobs, knob_free)
        true_usedtotal = is_true_knob(knobs, knob_usedtotal)
        true_usedpercent = is_true_knob(knobs, knob_usedpercent)

        char_header = knobs[knob_icons.name][0] if true_icons else ''
        char_usedtotal = f' {knobs[knob_icons.name][-1]}' if true_icons and true_free and true_usedtotal else ''
        disk = shutil.disk_usage('/')
        unit = sizeof_fmt(disk.total)[1]

        v_free = f' {" ".join(sizeof_fmt(disk.free))}' if true_free else ''
        v_usedtotal = f' {sizeof_fmt(disk.used)[0]}/{sizeof_fmt(disk.total)[0]} {unit}' if true_usedtotal else ''
        v_usedp = f' ({100 * disk.used / disk.total:.1f}%)' if (true_free or true_usedtotal) and true_usedpercent\
                  else f' {100 * disk.used / disk.total:.1f}%' if true_usedpercent else ''

        usage = f'{char_header}{v_free}{char_usedtotal}{v_usedtotal}{v_usedp}'

        return usage

    await component.async_register(connection, diskusage)
Ejemplo n.º 18
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description="spotify",
        detailed_description="This Component shows the current spotfiy song",
        knobs=[],
        exemplar="spotify",
        update_cadence=1,
        identifier="com.iterm2.spotify")

    @iterm2.StatusBarRPC
    async def coro(knobs,
                   rows=iterm2.Reference("rows"),
                   cols=iterm2.Reference("columns")):
        status_delimiter = '-~`/='
        ascript = '''
          tell application "System Events"
            set process_list to (name of every process)
          end tell

          if process_list contains "Spotify" then
            tell application "Spotify"
              if player state is playing or player state is paused then
                set track_name to name of current track
                set artist_name to artist of current track
                set album_name to album of current track
                set track_length to duration of current track
                set now_playing to "" & player state & "{0}" & album_name & "{0}" & artist_name & "{0}" & track_name & "{0}" & track_length & "{0}" & player position
                return now_playing
              else
                return player state
              end if
            end tell
          end if
        '''.format(status_delimiter)
        spotify = asrun(ascript)
        if not spotify:
            return ""

        spotify_status = spotify.split(status_delimiter)
        state = _convert_state(spotify_status[0])
        if state == 'stop':
            return None

        artist = spotify_status[2]
        title = spotify_status[3]
        total = _convert_seconds(
            int(spotify_status[4].replace(',', '.')) / 1000)
        elapsed = _convert_seconds(spotify_status[5].replace(',', '.'))
        return "{} {} - {} {}/{}".format(state, artist, title, elapsed, total)

    # Register the component.
    await component.async_register(connection, coro)
Ejemplo n.º 19
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description='Hello, world!',
        detailed_description='Says hello in a random language periodically',
        exemplar='¡Hola, mundo!',
        update_cadence=5,
        identifier='engineering.dane.iterm-components.sentinel',
        knobs=[],
    )

    @iterm2.StatusBarRPC
    async def hello_world_coroutine(knobs):
        return random.choice(GREETINGS)

    await component.async_register(connection, hello_world_coroutine)
Ejemplo n.º 20
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description='Sprint',
        detailed_description='show Sprint days',
        exemplar='Sprint',
        update_cadence=5,
        identifier='engineering.paulomcnally.iterm-components.sprint',
        knobs=[],
    )

    @iterm2.StatusBarRPC
    async def sprint_coroutine(knobs):
        return '🗓️ Sprint %d: %s' % (SPRINT_NUMBER, message(days))

    await component.async_register(connection, sprint_coroutine)
Ejemplo n.º 21
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description="Unix Time",
        detailed_description="Show Unix Time",
        knobs=[],
        exemplar="[Unix Time]",
        update_cadence=1,
        identifier="koh-sh.iterm2-statusbar-scripts.unixtime"
    )

    @iterm2.StatusBarRPC
    async def showunixtime(knobs):
        return "UnixTime: " + str(int(time.time()))

    await component.async_register(connection, showunixtime)
Ejemplo n.º 22
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description="Load Average",
        detailed_description="Show Load Average",
        knobs=[],
        exemplar="[Load Average]",
        update_cadence=1,
        identifier="koh-sh.iterm2-statusbar-scripts.loadaverage")

    @iterm2.StatusBarRPC
    async def showloadaverage(knobs):
        la = os.getloadavg()
        return ("LoadAvg: " + " ".join([str(round(x, 2)) for x in la]))

    await component.async_register(connection, showloadaverage)
Ejemplo n.º 23
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description="Current song playing",
        detailed_description=
        "Show the current song playing in iTunes or Spotify",
        exemplar="Spotify: ▶️ Danzig - Mother",
        update_cadence=1,
        identifier="dev.djordje.iterm-components.current-song",
        knobs=[])

    @iterm2.StatusBarRPC
    async def current_song_coroutine(knobs):
        current_song = get_current_song()
        return current_song

    await component.async_register(connection, current_song_coroutine)
Ejemplo n.º 24
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description='Days until Christmas',
        detailed_description='Display the number of days until christmas.',
        knobs=[],
        exemplar='🎄 93',
        update_cadence=1,
        identifier='xmas.counter')

    @iterm2.StatusBarRPC
    async def christmas_counter(knobs):
        christmas = datetime.datetime.now()
        christmas = christmas.replace(month=12, day=25)
        return "🎄 {}".format((christmas - datetime.datetime.now()).days)

    await component.async_register(connection, christmas_counter)
Ejemplo n.º 25
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description='NodeJS Version',
        detailed_description='show nodejs version',
        exemplar='NodeJS Version',
        update_cadence=5,
        identifier='engineering.paulomcnally.iterm-components.node',
        knobs=[],
    )

    @iterm2.StatusBarRPC
    async def node_coroutine(knobs):
        output = subprocess.check_output(['bash', '-c', bashCommand]).strip()
        return 'Node: %s' % output[1:]

    await component.async_register(connection, node_coroutine)
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description='Days employed',
        detailed_description='Display the number of days at Kubra.',
        knobs=[],
        exemplar='💼 93',
        update_cadence=1,
        identifier='employment.counter'
    )

    @iterm2.StatusBarRPC
    async def days_employed_counter(knobs):
        employed_at = datetime.datetime(month=6, day=24, year=2019)
        return "💼 {}".format((datetime.datetime.now() - employed_at).days)

    await component.async_register(connection, days_employed_counter)
Ejemplo n.º 27
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description='pyenv',
        detailed_description='The currently active Python',
        exemplar='🐍 3.7.2',
        update_cadence=2,
        identifier='engineering.dane.iterm-components.pyenv',
        knobs=[],
    )

    @iterm2.StatusBarRPC
    async def pyenv_coroutine(knobs, python=iterm2.Reference('user.python_version?')):
        python = python or '☠️'
        return f'🐍 {python}'

    await component.async_register(connection, pyenv_coroutine)
Ejemplo n.º 28
0
async def main(connection):
    component = iterm2.StatusBarComponent(
            short_description="iTunes",
            detailed_description="This Component shows the current itunes song",
            knobs=[],
            exemplar="iTunes",
            update_cadence=1,
            identifier="com.iterm2.iTunes")

    @iterm2.StatusBarRPC
    async def coro(
            knobs,
            rows=iterm2.Reference("rows"),
            cols=iterm2.Reference("columns")):
        status_delimiter = '-~`/='
        ascript = '''
            tell application "System Events"
                set process_list to (name of every process)
            end tell

            if process_list contains "Music" then
                tell application "Music"
                    set t_title to name of current track
                    set t_artist to artist of current track
                    set t_album to album of current track
                    set t_duration to duration of current track
                    set t_elapsed to player position
                    set t_state to player state
                    return t_title & "{0}" & t_artist & "{0}" & t_album & "{0}" & t_elapsed & "{0}" & t_duration & "{0}" & t_state
                    end tell
            end if
        '''.format(status_delimiter)
        now_playing = asrun(ascript)
        if not now_playing:
            return ""
        now_playing = now_playing.split(status_delimiter)
        if len(now_playing) != 6:
            return
        title, artist, album = now_playing[0], now_playing[1], now_playing[2]
        state = _convert_state(now_playing[5])
        total = _convert_seconds(now_playing[4].replace(',', '.'))
        elapsed = _convert_seconds(now_playing[3].replace(',', '.'))

        return "{} {} - {} {}/{}".format(state, artist, title, elapsed, total)

    # Register the component.
    await component.async_register(connection, coro)
Ejemplo n.º 29
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description="Kubernetes Configuration",
        detailed_description=
        "This tells you what your current kubernetes context and namespace are",
        exemplar="⎈ context:staging namespace:my-cluster",
        update_cadence=5,
        identifier="com.iterm2.jebentier.iterm2-kubernetes-context",
        knobs=[])

    @iterm2.StatusBarRPC
    async def coro(knobs):
        current_config = config.list_kube_config_contexts()[1]
        return "⎈ context:{} namespace:{}".format(
            current_config['name'], current_config['context']['namespace'])

    await component.async_register(connection, coro)
Ejemplo n.º 30
0
async def main(connection):
    component = iterm2.StatusBarComponent(
        short_description="GMT Clock",
        detailed_description="Shows the time in jolly old England",
        knobs=[],
        exemplar="[12:00 GMT]",
        update_cadence=1,
        identifier="com.iterm2.example.gmt-clock")

    # This function gets called once per second.
    @iterm2.StatusBarRPC
    async def coro(knobs):
        return datetime.datetime.now(
            datetime.timezone.utc).strftime("%H:%M:%S GMT")

    # Register the component.
    await component.async_register(connection, coro)