<commit_before># vim:ts=4:sw=4:et:
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.


import atexit
import json
import os
import signal
import subprocess
import sys
import tempfile
import threading
import time
import uuid

import pywatchman

from . import TempDir


try:
    import pwd
except ImportError:
    # Windows
    pass

tls = threading.local()


def setSharedInstance(inst) -> None:
    global tls
    # pyre-fixme[16]: `local` has no attribute `instance`.
    tls.instance = inst
    atexit.register(lambda: inst.stop())


def getSharedInstance():
    global tls
    if hasattr(tls, "instance"):
        return tls.instance
    # Ensure that the temporary dir is configured
    TempDir.get_temp_dir().get_dir()
    inst = Instance()
    inst.start()
    setSharedInstance(inst)
    return tls.instance


def hasSharedInstance() -> bool:
    global tls
    return hasattr(tls, "instance")


def mergeTestConfig(config):
    """Merge local config with test config specified via WATCHMAN_TEST_CONFIG"""<commit_msg>make getSharedInstance take an optional config<commit_after># vim:ts=4:sw=4:et:
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.


import atexit
import hashlib
import json
import os
import signal
import subprocess
import sys
import tempfile
import threading
import time
import uuid

import pywatchman

from . import TempDir


try:
    import pwd
except ImportError:
    # Windows
    pass

tls = threading.local()


def getSharedInstance(config=None):
    config_hash = hashlib.sha1(json.dumps(config).encode()).hexdigest()
    attr = f"instance_{config_hash}"
    global tls
    inst = getattr(tls, attr, None)
    if inst is None:
        # Ensure that the temporary dir is configured
        TempDir.get_temp_dir().get_dir()
        inst = Instance(config=config)
        inst.start()
        setattr(tls, attr, inst)
        atexit.register(lambda inst=inst: inst.stop())
    return inst


def mergeTestConfig(config):
    """Merge local config with test config specified via WATCHMAN_TEST_CONFIG"""
{'fraction_non_alphanumeric': 0.08227571115973742, 'fraction_numerical': 0.003063457330415755, 'mean_word_length': 3.6748466257668713, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2641238', 'n_tokens_mistral': 682, 'n_tokens_neox': 671, 'n_words': 239}