DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (2028a9d7ce91)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
import test_valid
from ConfigParser import ConfigParser
import errno
import json
import os
import os.path
import sys

from fabric.api import task, sudo, run, local, lcd, cd, env,hosts
from fabric.contrib.console import confirm

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST:
            pass
        else: raise

# TODO:  this should list all profiles if called without argument
def find_profile_dir(name):
    """
    Given the name of a Firefox profile, attempts to find the absolute
    path to its directory.  If it can't be found, None is returned.
    """

    base_path = None
    if sys.platform == "darwin":
        base_path = os.path.expanduser(
            "~/Library/Application Support/Firefox/"
            )
    elif sys.platform.startswith("win"):
        # TODO: This only works on 2000/XP/Vista, not 98/Me.
        appdata = os.environ["APPDATA"]
        base_path = os.path.join(appdata, "Mozilla\\Firefox")
    elif sys.platform == "cygwin":
        appdata = os.environ["APPDATA"]
        base_path = os.path.join(appdata, "Mozilla\\Firefox")
    else:
        base_path = os.path.expanduser("~/.mozilla/firefox/")
    inifile = os.path.join(base_path, "profiles.ini")
    config = ConfigParser()
    config.read(inifile)
    profiles = [section for section in config.sections()
                if section.startswith("Profile")]
    for profile in profiles:
        if config.get(profile, "Name") == name:
            # TODO: Look at IsRelative?
            path = config.get(profile, "Path")
            if not os.path.isabs(path):
                path = os.path.join(base_path, path)
            return path
    return None

@task
def profile(string='default'):
    """ print the path to a profile.  call:  fab profile:profile_name"""
    print find_profile_dir(string)

@task
def simplesurvey(url="",name="",summary="",fn="",minroll='1',maxroll='2'):
    """ create a simple survey

    usage:

    """

    t = """
"use strict";

exports.surveyInfo = {{
  surveyId: "{surveyId}",
  surveyName: "{name}",
  surveyUrl: "{url}",
  summary: {summary},
  thumbnail: "https://testpilot.mozillalabs.com/testcases/pilot-survey-thumbnail.png",
  randomDeployment: {{
    minRoll: {minroll},
    maxRoll: {maxroll},
    rolloutCode: "{surveyId}"
  }}
}};
""".strip()
    surveyId = name_to_id(name)
    if not fn:
        fn = os.path.join(surveyId,surveyId + ".js")

    mkdir_p(surveyId)
    with open(fn,'w') as fh:
        print "# writing to: " + fn
        print >> fh, t.format(url=url,surveyId=surveyId,name=(name or surveyId),
            summary=json.dumps(summary),minroll=int(minroll),maxroll=int(maxroll))
        print """
    # edit: {fn}
    # then:
    fab package:{surveyId}""".format(**locals())


# TODO:  tree isn't a built-in...
@task
def clear(profile):
    """ clear:profile.  removes downloaded experiments, logs, manifests from profile <profile>"""
    p = find_profile_dir(profile)
    d = "%s/TestPilotExperimentFiles" % p
    local('rm -rf "%s"/TestPilotErrorLog.log' % p)
    local('rm -rf "%s"/*' % (d,))
    local('tree "%s"' % (d,))

@task
@hosts(['testpilot1.webapp.scl3.mozilla.com'])
def push():
    """
    sudo hg pull;  call:  fab push -u user.name
    """
    if confirm("You did 'hg ci; hg pull; hg up; hg push' right?"):
        if confirm("You did change the sample size and turn of debugging, right?"):
            with cd("/data/www/testpilotweb/"):
                sudo("hg pull")
                result = sudo("hg tip")
                print "###### hg tip #####"
                print result
                if confirm("Upgrade to that tip?"):
                    sudo("hg update")

def rollback(rev_or_id):
    pass
    """ rollback upstream?"""

def guess_name(path,extension='.js'):
    files = os.listdir(path)
    print files
    guesses = [x for x in files if x.endswith(extension)]
    if len(guesses) == 1:
        return guesses[0]
    else:
        return None

def replace_in_json(name,newjson,manifest):
    """
    Args:
        name:  name of the study to match/replace
        newjson:  that studies json
        manifest:  the whole old shebang

    Returns:
        manifest, which replaces the orig (gross!)
        TODO, decide this for real.

    """
    print name
    for k,v in manifest.iteritems():
        for ii,study in enumerate(v):
            cand = study.get('default',{}).get('name',None)
            if cand == name:
                manifest[k][ii] = newjson
                return manifest

    # else fall back...
    manifest.setdefault('new_experiments',[])
    manifest['new_experiments'].append(newjson)
    return manifest


@task
def package(path,name=None,jsonfile=None):
    """ package:path,name,jsonfile.  jar, sign, and dump the snippet.  assumes one .js file -> jar.  path from root

    Args:
        path: dir containing code.
        name: name of the study, if not, it gets the base of the js file
        jsonfile:  if there, replace the json with the created one.
    """
    # be wary, lcd only changes how local and sudo and such are called.  the path
    # is still really the caller path.

    studyfile = guess_name(path) or os.path.split(path)[-1]
    with lcd(path):
        if studyfile:
            if studyfile.endswith('.js'):
                base = studyfile[:-3]
            else:
                base = studyfile

            if not name:
                name=base

            # for unclear reasons, old formating was messing up bash on windows.
            print local('jar -cvf %s.jar *' % (base),capture=True)
            # this is a place where we really want '/'... urls!
            ini("/".join([path,base+ ".jar"]),name=name,studyfile=base + ".js")
        else:
            print "unable to guess name for packaging."

    if jsonfile:
        D = json.load(file(jsonfile))
        newjson = ini('/'.join([path,base+ ".jar"]),name=name,studyfile=base + ".js", prints=False)
        D =replace_in_json(name,newjson,D)
        print "revising json!"
        json.dump(D,open(jsonfile,'w'),indent=2)

import hashlib


def sign(fn):
    """ sign a file """
    # 'rb', for windows!
    with open(fn,'rb') as fh:
        return hashlib.sha256(fh.read()).hexdigest()

@task(alias='sign')
def print_sign(fn):
    print sign(fn)

@task
def ini(path,name=None,studyfile=None,prints=True):
    """ path,name,studyfile.  ini snippet

    {"default":
    {"name": "exploring_satisfaction_survey_v2",
     "jarfile": "exploring_satisfaction_survey//exploring_satisfaction_survey.jar",
     "studyfile": "exploring_satisfaction_survey_v2.js",
     "hash": "59a28d941c24ff8ac55c632f0b65aece29de03dc858ff4b53a9ee71deab34ebb"
    }
    """
    jarfile=path
    if studyfile is None:
        studyfile=os.path.basename(path)
        studyfile=os.path.splitext(studyfile)[0] + ".js"
    if name is None:
        name = studyfile
    hash=sign(jarfile)
    d = dict(name=name,jarfile=jarfile,studyfile=studyfile,hash=hash)
    if prints:
        print json.dumps({"new_experiments":[{'default':d}]},indent=2)
    else:
        return {'default':d}

def fakejson():
    pass

def name_to_id(name):
    return name.strip().lower().replace(" ","_")

@task(alias="test_valid")
def _test_valid(*args):
    test_valid.main(args)

"""
exports.surveyInfo = {
  surveyId: "firefox_upgrade_survey",
  surveyName: "Firefox Upgrade Survey",
  surveyUrl: "http://www.surveygizmo.com/s3/569257/TestPilot-Firefox-Upgrade-Survey",
  summary: "If you see this survey, most likely you are using Firefox 3.6 currently.  There is also a completely new version of Firefox which was released in March this year. Through this survey, We're interested to understand why you have not upgraded so that we can better meet your needs in our future products. ",
  thumbnail: "https://testpilot.mozillalabs.com/testcases/pilot-survey-thumbnail.png",

  runOrNotFunc: function() {
    let Application = Cc["@mozilla.org/fuel/application;1"]
                      .getService(Ci.fuelIApplication);
    let versionComparator = Cc["@mozilla.org/xpcom/version-comparator;1"]
                            .getService(Ci.nsIVersionComparator);
    let ver = Application.version;
    if( versionComparator.compare(ver, "3.6")>=0 && versionComparator.compare(ver, "3.7")<0 )
        return true;
    else
        return false;
  }
};


## a sample session.
pwd
NAME="firefox_apps_usage_survey"
NICE="Firefox Apps Usage Survey"
mkdir testcases/$NAME && \
cd testcases/$NAME
cat << DONE > $NAME.js
exports.surveyInfo = {
  surveyId: "$NAME",
  surveyName: "$NICE",
  surveyUrl: "http://qsurvey.mozilla.com/s3/apps_tp",
  summary: "Mozilla is currently exploring an apps initiaitive that aims to make more apps available across more devices. We would love your help with a brief survey to understand how you currently use apps. Thanks for helping us make the Web better.",
  thumbnail: "https://testpilot.mozillalabs.com/testcases/pilot-survey-thumbnail.png",

  randomDeployment: {
    maxRoll: 0,
    minRoll: 19,
    rolloutCode: "sample1",
  },

  runOrNotFunc: function() {
    let Application = Cc["@mozilla.org/fuel/application;1"]
                      .getService(Ci.fuelIApplication);
    let versionComparator = Cc["@mozilla.org/xpcom/version-comparator;1"]
                            .getService(Ci.nsIVersionComparator);
    let ver = Application.version;
    /* this is the sort of thing you can use to decide who gets to run it.
    if( versionComparator.compare(ver, "3.6")>=0 && versionComparator.compare(ver, "3.7")<0 )
        return true;
    else
        return false; */

    return true;
  }
};
DONE

# jar and sign
jar -cf $NAME.jar $NAME.js
SIGN=`python ~/testpilot/codesigning/signer.py $NAME.jar | awk '{print $NF}'`

cat <<DONE
  {"default":
    {"name": "$NICE",
     "jarfile": "$NAME/$NAME.jar",
     "studyfile": "$NAME.js",
     "hash": "$SIGN"
    }
  },
DONE
echo "^ append this into ../index-dev.json  'new_experiments'"

hg add $NAME.jar $NAME.js ../index-dev.json
hg commit
hg push
ssh lm-app-testpilot01.labs.mozilla.org
cd /var/www/testcases
sudo hg pull -u



F=TestPilotExperimentFiles
rm -rf "$F"
I=~/hgs/testpilotweb/testcases/
mkdir $F
cp $I/index-fake.json $F/index.json
cp $I/broken-extensions/broken-extensions-survey.jar $F/




"""