<commit_before>#!/usr/bin/python3
import os
import sys
import requests
import subprocess
import json
import argparse
from urllib.parse import urlencode
import webbrowser

def get_config_dir():
    if os.name == 'nt':
        return os.path.join(os.environ['APPDATA'], 'twitch-cli')
    elif os.name == 'posix':
        home = os.environ.get('XDG_CONFIG_HOME', '~/.config')
        return os.path.expanduser(os.path.join(home, 'twitch-cli'))

# The configuration file is located at $HOME/.config/twitch-cli/config.json.
CONFIG_DIR = get_config_dir()
CONFIG_FILE = os.path.join(CONFIG_DIR, 'config.json')

TWITCH_CLIENT_ID = 'e0fm2z7ufk73k2jnkm21y0gp1h9q2o'

def save_config(config):
    with open(CONFIG_FILE, 'w') as f:
        json.dump(config, f, sort_keys=True, indent=4)

def load_config():
    """Load the configuration file at ~/.config/twitch-cli/config.json and
    return a dict with configuration options."""

    if not os.path.isdir(CONFIG_DIR):
        os.makedirs(CONFIG_DIR)

    if not os.path.isfile(CONFIG_FILE):
        with open(CONFIG_FILE, 'a') as f:
            f.write('{}')
        print('Configuration file created at {}'.format(CONFIG_FILE))

    with open(CONFIG_FILE, 'r') as f:
        config = json.load(f)

    config.setdefault('oauth', '')

    save_config(config)

    return config

config = load_config()

def main():
    parser = argparse.ArgumentParser(description='List or play Twitch streams.')
    subparsers = parser.add_subparsers(metavar='COMMAND')

    parser_list = subparsers.add_parser('list', help='List followed channels')
    parser_list.add_argument('--flat', '-f', action='store_true',
                             help='Don\'t show detailed information or prompt')
    parser_list.add_argument('--game', help='List streams playing a game')
    parser_list.add_argument('--followed', action='store_true',
                             help='List followed streams')
    parser_list.set_defaults(func=cmd_list)

    parser_play = subparsers.add_parser('play', help='Play a stream')
    parser_play.add_argument('channel', help='Channel name')
    parser_play.set_defaults(func=cmd_play)

    parser_follow = subparsers.add_parser('follow', help='Follow a channel')
    parser_follow.add_argument('channel', help='The channel you want to follow')
    parser_follow.set_defaults(func=cmd_follow)

    parser_unfollow = subparsers.add_parser('unfollow',
                                            help='Unfollow a channel')
    parser_unfollow.add_argument('channel', help='The channel you don\'t want '
                                            'to follow anymore')
    parser_unfollow.set_defaults(func=cmd_unfollow)

    parser_auth = subparsers.add_parser('auth', help='Authenticate with Twitch')
    parser_auth.set_defaults(func=cmd_auth)

    args = parser.parse_args()

    if not hasattr(args, 'func'):
        args = parser.parse_args(['list'])

    args.func(args)

# The cmd_* functions get called when their respective subcommand is executed
# Example: "python3 twitch-cli list" calls "cmd_list"

def cmd_list(args):
    list_streams(args)

def cmd_play(args):
    play_stream(args.channel)

def cmd_follow(args):
    follow_channel(args.channel)

def cmd_unfollow(args):
    unfollow_channel(args.channel)

def cmd_auth(args):
    if config['oauth'] != '':
        print('You are already authenticated.')
        return

    token = authenticate()

    if token != '':
        config['oauth'] = token
        save_config(config)
        print('Authentication complete.')
    else:
        print('Authentication cancelled.')

def play_stream(channel):
    """Load a stream and open the player"""

    command = 'streamlink twitch.tv/{} best '.format(channel)

    process = subprocess.Popen(command.split(), stdout=None, stderr=None)
    output, error = process.communicate()

def list_streams(args):
    """Load the list of streams and prompt the user to chose one."""

    if config['oauth'] == '':
        print('You have to provide a Twitch OAuth token to list followed '
              'streams.')
        print('Look at the configuration file at {}'.format(CONFIG_FILE))
        sys.exit(1)

    if args.game is not None:
        streams = get_game_streams(args.game)<commit_msg>Added --force switch to twitch-cli auth<commit_after>#!/usr/bin/python3
import os
import sys
import requests
import subprocess
import json
import argparse
from urllib.parse import urlencode
import webbrowser

def get_config_dir():
    if os.name == 'nt':
        return os.path.join(os.environ['APPDATA'], 'twitch-cli')
    elif os.name == 'posix':
        home = os.environ.get('XDG_CONFIG_HOME', '~/.config')
        return os.path.expanduser(os.path.join(home, 'twitch-cli'))

# The configuration file is located at $HOME/.config/twitch-cli/config.json.
CONFIG_DIR = get_config_dir()
CONFIG_FILE = os.path.join(CONFIG_DIR, 'config.json')

TWITCH_CLIENT_ID = 'e0fm2z7ufk73k2jnkm21y0gp1h9q2o'

def save_config(config):
    with open(CONFIG_FILE, 'w') as f:
        json.dump(config, f, sort_keys=True, indent=4)

def load_config():
    """Load the configuration file at ~/.config/twitch-cli/config.json and
    return a dict with configuration options."""

    if not os.path.isdir(CONFIG_DIR):
        os.makedirs(CONFIG_DIR)

    if not os.path.isfile(CONFIG_FILE):
        with open(CONFIG_FILE, 'a') as f:
            f.write('{}')
        print('Configuration file created at {}'.format(CONFIG_FILE))

    with open(CONFIG_FILE, 'r') as f:
        config = json.load(f)

    config.setdefault('oauth', '')

    save_config(config)

    return config

config = load_config()

def main():
    parser = argparse.ArgumentParser(description='List or play Twitch streams.')
    subparsers = parser.add_subparsers(metavar='COMMAND')

    parser_list = subparsers.add_parser('list', help='List followed channels')
    parser_list.add_argument('--flat', '-f', action='store_true',
                             help='Don\'t show detailed information or prompt')
    parser_list.add_argument('--game', help='List streams playing a game')
    parser_list.add_argument('--followed', action='store_true',
                             help='List followed streams')
    parser_list.set_defaults(func=cmd_list)

    parser_play = subparsers.add_parser('play', help='Play a stream')
    parser_play.add_argument('channel', help='Channel name')
    parser_play.set_defaults(func=cmd_play)

    parser_follow = subparsers.add_parser('follow', help='Follow a channel')
    parser_follow.add_argument('channel', help='The channel you want to follow')
    parser_follow.set_defaults(func=cmd_follow)

    parser_unfollow = subparsers.add_parser('unfollow',
                                            help='Unfollow a channel')
    parser_unfollow.add_argument('channel', help='The channel you don\'t want '
                                            'to follow anymore')
    parser_unfollow.set_defaults(func=cmd_unfollow)

    parser_auth = subparsers.add_parser('auth', help='Authenticate with Twitch')
    parser_auth.add_argument('--force', '-f', action='store_true', help='Overwrite the existing OAuth token')
    parser_auth.set_defaults(func=cmd_auth)

    args = parser.parse_args()

    if not hasattr(args, 'func'):
        args = parser.parse_args(['list'])

    args.func(args)

# The cmd_* functions get called when their respective subcommand is executed
# Example: "python3 twitch-cli list" calls "cmd_list"

def cmd_list(args):
    list_streams(args)

def cmd_play(args):
    play_stream(args.channel)

def cmd_follow(args):
    follow_channel(args.channel)

def cmd_unfollow(args):
    unfollow_channel(args.channel)

def cmd_auth(args):
    if (config['oauth'] != '') and (not args.force):
        print('You are already authenticated.')
        return

    token = authenticate()

    if token != '':
        config['oauth'] = token
        save_config(config)
        print('Authentication complete.')
    else:
        print('Authentication cancelled.')

def play_stream(channel):
    """Load a stream and open the player"""

    command = 'streamlink twitch.tv/{} best '.format(channel)

    process = subprocess.Popen(command.split(), stdout=None, stderr=None)
    output, error = process.communicate()

def list_streams(args):
    """Load the list of streams and prompt the user to chose one."""

    if config['oauth'] == '':
        print('You have to provide a Twitch OAuth token to list followed '
              'streams.')
        print('Look at the configuration file at {}'.format(CONFIG_FILE))
        sys.exit(1)

    if args.game is not None:
        streams = get_game_streams(args.game)
{'fraction_non_alphanumeric': 0.12305025996533796, 'fraction_numerical': 0.0036972848064702486, 'mean_word_length': 3.3258370814592704, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2178012', 'n_tokens_mistral': 2663, 'n_tokens_neox': 2613, 'n_words': 633}