def compile_waxsim():
    previous_dir = os.getcwd()
    os.chdir(os.path.join(os.path.realpath(os.path.split(__file__)[0]), "Contributed", "WaxSim"))
    subprocess.call(
        ["xcodebuild", "-target", "WaxSim", "-configuration", "Release", "SYMROOT=build"], stdout=open("/dev/null", "w")
    )
    os.chdir(previous_dir)
Example #2
1
 def build_egg(self, egg_root, target):
     """Build an egg containing the files at egg_root for the specified target.
 There must be an egg_root/setup.py file."""
     # TODO(Brian Wickman): Do a sanity check somewhere to ensure that
     # setuptools is on the path?
     args = [sys.executable, "setup.py", "bdist_egg", "--dist-dir=dist", "--bdist-dir=build.%s" % target.name]
     cwd = os.getcwd()
     os.chdir(egg_root)
     print "EggBuilder executing: %s" % " ".join(args)
     try:
         oldenv = os.getenv("PYTHONPATH")
         os.putenv("PYTHONPATH", ":".join(sys.path))
         po = subprocess.Popen(args, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
         rv = po.wait()
         if oldenv:
             os.putenv("PYTHONPATH", oldenv)
         else:
             os.unsetenv("PYTHONPATH")
         eggs = os.path.abspath(os.path.join("dist", "*.egg"))
         eggs = glob.glob(eggs)
         if rv != 0 or len(eggs) != 1:
             comm = po.communicate()
             print >> sys.stderr, "egg generation failed (return value=%d, num eggs=%d)" % (rv, len(eggs))
             print >> sys.stderr, "STDOUT"
             print >> sys.stderr, comm[0]
             print >> sys.stderr, "STDERR"
             print >> sys.stderr, comm[1]
             raise EggBuilder.EggBuildingException("Generation of eggs failed for target = %s" % target)
         egg_path = eggs[0]
     finally:
         os.chdir(cwd)
     return egg_path
Example #3
1
def test_backup_projects(server, tmpdir, loop):
    Config.instance().set("Server", "projects_path", str(tmpdir))

    os.makedirs(str(tmpdir / "a"))
    with open(str(tmpdir / "a" / "a.gns3"), "w+") as f:
        f.write("hello")
    os.makedirs(str(tmpdir / "b"))
    with open(str(tmpdir / "b" / "b.gns3"), "w+") as f:
        f.write("world")

    response = server.get("/backup/projects.tar", api_version=None, raw=True)
    assert response.status == 200
    assert response.headers["CONTENT-TYPE"] == "application/x-gtar"

    with open(str(tmpdir / "projects.tar"), "wb+") as f:
        print(len(response.body))
        f.write(response.body)

    tar = tarfile.open(str(tmpdir / "projects.tar"), "r")
    os.makedirs(str(tmpdir / "extract"))
    os.chdir(str(tmpdir / "extract"))
    # Extract to current working directory
    tar.extractall()
    tar.close()

    assert os.path.exists(os.path.join("a", "a.gns3"))
    open(os.path.join("a", "a.gns3")).read() == "hello"

    assert os.path.exists(os.path.join("b", "b.gns3"))
    open(os.path.join("b", "b.gns3")).read() == "world"
Example #4
1
    def run(self, module, post_check):
        try:
            # Simulate the sys.path behaviour decribed here:
            #
            # https://docs.python.org/2/library/sys.html#sys.path
            _cwd = os.getcwd()
            _sys_path = list(sys.path)
            _sys_argv = list(sys.argv)
            sys.path.insert(0, os.path.dirname(self._path))
            sys.argv = [os.path.basename(self._path)] + self._argv

            exec(self._code, module.__dict__)
            post_check()

        except Exception as e:
            self._failed = True
            self._error_detail = traceback.format_exc()

            exc_type, exc_value, exc_traceback = sys.exc_info()
            filename, line_number, func, txt = traceback.extract_tb(exc_traceback)[-1]

            self._error = '%s\nFile "%s", line %d, in %s:\n%s' % (
                str(e),
                os.path.basename(filename),
                line_number,
                func,
                txt,
            )

        finally:
            # undo sys.path, CWD fixups
            os.chdir(_cwd)
            sys.path = _sys_path
            sys.argv = _sys_argv
            self.ran = True
Example #5
1
def daemonize(aDaemonCurDir="/"):
    """
    Detach the process from the controlling terminal and run it in the background
    """
    try:
        myPid = os.fork()
    except OSError as e:
        raise Exception("%s. Errno: %d" % (e.strerror, e.errno))
    if myPid == 0:
        # child
        os.setsid()
        try:
            # second fork is to guarantee that the child is no longer a session
            # leader, preventing the daemon from ever acquiring a controlling
            # terminal.
            myPid = os.fork()
        except OSError as e:
            raise Exception("%s. Errno: %d" % (e.strerror, e.errno))
        if myPid == 0:
            # child
            os.chdir(aDaemonCurDir)
            os.umask(0)

            _close_all_fds()
            dev_null = os.devnull if hasattr(os, "devnull") else "/dev/null"
            os.open(dev_null, os.O_RDWR)  # STDIN
            os.dup2(0, 1)  # STDOUT
            os.dup2(0, 2)  # STDERR

        else:
            os._exit(0)  # Exit parent (the first child) of the second child.
    else:
        os._exit(0)  # Exit parent of the first child.
Example #6
1
 def to_work_dir(self):
     wd = self.work_dir
     if str(wd) != os.getcwd():
         os.chdir(wd)
         self.log.info("Changing to working dir: %s" % wd)
     # This is the working dir by now.
     sys.path.insert(0, "")
Example #7
1
def installTrove():
    foo = "target" + os.sep + "dependency"
    src_fi = "jcore-mstparser-ae-2.*.jar"
    os.chdir(foo)
    mst = glob.glob(src_fi)[0]

    # extract trove jar from mst repo
    subprocess.call(["jar", "xf", mst, "repo/de/julielab/jules-trove/1.3/jules-trove-1.3.jar"])
    # move trove jar to current dir
    shutil.copy2("repo/de/julielab/jules-trove/1.3/jules-trove-1.3.jar", "./")

    # delete old folder
    shutil.rmtree("repo/")

    # install jules-trove using maven as well?
    subprocess.call(
        [
            "mvn",
            "install:install-file",
            "-Dfile=jules-trove-1.3.jar",
            "-DgroupId=de.julielab",
            "-DartifactId=jules-trove",
            "-Dversion=1.3",
            "-Dpackaging=jar",
        ]
    )
def wrapper():
    dtype_dict = {
        "bathrooms": float,
        "waterfront": int,
        "sqft_above": int,
        "sqft_living15": float,
        "grade": int,
        "yr_renovated": int,
        "price": float,
        "bedrooms": float,
        "zipcode": str,
        "long": float,
        "sqft_lot15": float,
        "sqft_living": float,
        "floors": float,
        "condition": int,
        "lat": float,
        "date": str,
        "sqft_basement": int,
        "yr_built": int,
        "id": str,
        "sqft_lot": int,
        "view": int,
    }
    os.chdir("..")
    sales = pd.read_csv("kc_house_data.csv")
    testing = pd.read_csv("kc_house_test_data.csv", dtype=dtype_dict)
    training = pd.read_csv("kc_house_train_data.csv", dtype=dtype_dict)
    question1(sales)
    question2(sales)
    question3(training, testing)
def set_up():  # Kan zijn dat je alles binnen deze functie moet bevrijden.
    # Dit deel hieronder regelt de user accounts. Iedere gebruiker krijgt zijn eigen map met daarin zijn eigen SAVE_FILE
    folders = filter(os.path.isdir, os.listdir(os.getcwd()))
    mappen = []
    print("Users\n\n")
    for x in folders:
        if not x.startswith("."):  # Zorgt dat hidden folders niet zichtbaar zijn.
            print("- %s" % (x))
            mappen.append(x)  # DIT IS NODIG VOOR p3
    print("Type name to continue\nTo add a new user, enter their name")
    user = input("> ")
    user = user.capitalize()

    # DIT MOLT MIJN PROGRAMMA, (DE EXCEPT OM DE EEN OF ANDERE REDEN)
    # try:
    if user in mappen:  # IS ANDERS EN NODIG VOOR p3
        # Bestaat al, ingetypt
        print("Welcome back %s\n" % user)  # < beleefd #INCORPEREER JORENDEEL VERDER
        os.chdir(user)
        doorgaan = 1
        main_loop()
    elif not os.path.exists(user):
        # Bestaat niet, maakt hem
        os.makedirs(user)
        os.chdir(user)
        doorgaan = 1
        main_loop()
    else:
        print("er gaat iets mis yo")
Example #10
0
        def inhibit(self, *a):
            """inhibit a gluster filesystem

            Mount glusterfs over a temporary mountpoint,
            change into the mount, and lazy unmount the
            filesystem.
            """
            mounted = False
            try:
                po = Popen(self.make_mount_argv(*a), **self.mountkw)
                self.handle_mounter(po)
                po.terminate_geterr()
                d = self.mntpt
                mounted = True
                logging.debug("auxiliary glusterfs mount in place")
                os.chdir(d)
                self.umount_l(d).terminate_geterr()
                mounted = False
            finally:
                try:
                    if mounted:
                        self.umount_l(d).terminate_geterr(fail_on_err=False)
                    self.cleanup_mntpt()
                except:
                    logging.warn("stale mount possibly left behind on " + d)
            logging.debug("auxiliary glusterfs mount prepared")
Example #11
0
    def on_inbox_delete_clicked(self, widget, data=None):

        if self.filename == None:
            message = "There are no Files to Delete"
            print "delete dialog being generated"
            dialog = gtk.MessageDialog(
                self.window,
                gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                gtk.MESSAGE_INFO,
                gtk.BUTTONS_OK,
                message,
            )
            dialog.run()
            dialog.destroy()
        else:

            os.chdir("./download")
            os.remove(self.filename)
            os.chdir("..")
            message = "File Deleted"
            print "delete dialog being generated"
            dialog = gtk.MessageDialog(
                self.window,
                gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                gtk.MESSAGE_INFO,
                gtk.BUTTONS_OK,
                message,
            )
            dialog.run()
            dialog.destroy()
            buff = self.user_inbox_textview.get_buffer()
            buff.set_text("")
Example #12
0
def in_dir(dir):
    old_cwd = os.getcwd()
    try:
        os.chdir(dir)
        yield
    finally:
        os.chdir(old_cwd)
def onSelect(val):
    SListValue = []
    sender = val.widget
    idx = sender.curselection()
    value = sender.get(idx)
    SList.delete(0, END)
    # Read Second List Value
    filepath = "V:\\09-Final Price Data Bank"
    # filepath=unicode(filepath,'utf8')
    secondPath = "%s\\%s" % (filepath, value)
    print secondPath

    os.chdir(secondPath)
    for root, dirs, files in os.walk(".", topdown=False):
        for name in files:
            matchObj = re.match("(^[A-Z]{1}[0-9]{2}[-])", name)
            if matchObj:
                # text1=name.decode("BIG5")

                SListValue.append(name[0:3])
    Unique = sets.Set(SListValue)
    Unique = sorted(Unique)
    for Sval in Unique:
        SList.insert(END, Sval)

    var.set(secondPath)
def GetPath(val):
    anchor = val.widget
    index = anchor.curselection()
    value = anchor.get(index)
    TList.delete(0, END)
    # Find Fist Stage Path
    filepath = "V:\\09-Final Price Data Bank"
    filepath = unicode(filepath, "utf8")
    print filepath
    dirs = os.listdir(filepath)
    for file in dirs:
        matchObj = re.match("(^[A-Z]{1}[-])", file)
        if matchObj:
            find = str(file[0:1])
            befind = str(value[0:1])
            # Generate Second Stage Path
            if find == befind:
                FilterPath = "%s\\%s" % (filepath, file)
                os.chdir(FilterPath)
                for root, dirs, files in os.walk(".", topdown=False):
                    for targets in files:
                        if targets[0:3] == value:
                            print targets
                            target = targets.decode("BIG5")
                            TList.insert(END, target)
    print value

    var.set(value)
    return
Example #15
0
def initialize_release(version, path, top_level):
    """
    Clone the Flocker repo and install a new virtual environment for
    a release.

    :param bytes version: The version to release.
    :param FilePath path: The path in which the release branch
        will be created.
    :param FilePath top_level: The top-level of the flocker repository.

    """
    REMOTE_URL = "https://github.com/ClusterHQ/flocker"
    release_path = path.child("flocker-release-{}".format(version))
    sys.stdout.write("Cloning repo in {}...\n".format(release_path.path))

    release_repo = Repo.init(release_path.path)
    release_origin = release_repo.create_remote("origin", REMOTE_URL)
    release_origin.fetch()

    sys.stdout.write("Checking out master...\n")
    release_repo.git.checkout("master")

    sys.stdout.write("Updating repo...\n")
    release_repo.git.pull("origin", "master")

    sys.stdout.write("Creating release branch for version {}...\n".format(version))
    release_repo.active_branch.checkout(b="release/flocker-{}".format(version))

    sys.stdout.write("Creating virtual environment...\n")
    virtualenv.create_environment(release_path.child("flocker-{}".format(version)).path, site_packages=False)

    sys.stdout.write("Activating virtual environment...\n")
    virtualenv_file = release_path.child("flocker-{}".format(version))
    virtualenv_file = virtualenv_file.child("bin").child("activate_this.py")
    execfile(virtualenv_file.path, dict(__file__=virtualenv_file.path))

    sys.stdout.write("Installing dependencies...\n")
    os.chdir(release_path.path)
    if _platform == "darwin":
        brew_openssl = check_output(["brew", "--prefix", "openssl"])
        os.environ["LDFLAGS"] = '-L{}/lib" CFLAGS="-I{}/include'.format(brew_openssl, brew_openssl)
    check_call(["pip install --process-dependency-links -e .[dev]"], shell=True, stdout=open(os.devnull, "w"))

    sys.stdout.write("Updating LICENSE file...\n")
    update_license_file(list(), top_level)

    sys.stdout.write("Committing result (no push)...\n")
    try:
        release_repo.git.commit(a=True, m="'Updated copyright in LICENSE file'")
    except GitCommandError:
        # This will happen when the LICENSE file has not changed, so we'll
        # ignore the error.
        pass

    sys.stdout.write(
        "\nCompleted.\n\nPlease copy and paste the following commands "
        "in your shell to enter the release environment and continue "
        "the pre-tag release process:\n\n"
        "export VERSION={};\ncd {};\nsource flocker-{}/bin/activate;\n\n".format(version, release_path.path, version)
    )
Example #16
0
    def _git_sync_files(self, project_checkout):
        """
        Copy files from our git into each git build branch and add them.

        A list of safe files is used to protect critical files both from
        being overwritten by a git file of the same name, as well as being
        deleted after.
        """

        # Build the list of all files we will copy:
        debug("Searching for files to copy to build system git:")
        files_to_copy = self._list_files_to_copy()

        os.chdir(project_checkout)

        # TODO:
        # for branch in self.cvs_branches:
        # print("Syncing files with git branch [%s]" % branch)
        new, copied, old = self._sync_files(files_to_copy, project_checkout)

        os.chdir(project_checkout)

        # Git add everything:
        for add_file in new + copied:
            run_command("git add %s" % add_file)

        # Cleanup obsolete files:
        for cleanup_file in old:
            # Can't delete via full path, must not chdir:
            run_command("git rm %s" % cleanup_file)
Example #17
0
    def tearDown(self):
        for dirname in ["en_US", "ja_JP", "lv_LV"]:
            locale_dir = os.path.join(self._i18n_dir(), dirname)
            if os.path.isdir(locale_dir):
                shutil.rmtree(locale_dir)

        os.chdir(self.olddir)
Example #18
0
    def cvs_sync_files(self):
        """
        Copy files from git into each CVS branch and add them. Extra files
        found in CVS will then be deleted.

        A list of CVS safe files is used to protect critical files both from
        being overwritten by a git file of the same name, as well as being
        deleted after.
        """

        # Build the list of all files we will copy from git to CVS.
        debug("Searching for git files to copy to CVS:")
        files_to_copy = self._list_files_to_copy()

        for branch in self.cvs_branches:
            print ("Syncing files with CVS branch [%s]" % branch)
            branch_dir = os.path.join(self.working_dir, self.project_name, branch)

            new, copied, old = self._sync_files(files_to_copy, branch_dir)

            os.chdir(branch_dir)

            # For entirely new files we need to cvs add:
            for add_file in new:
                commands.getstatusoutput("cvs add %s" % add_file)

            # Cleanup obsolete files:
            for cleanup_file in old:
                # Can't delete via full path, must not chdir:
                run_command("cvs rm -Rf %s" % cleanup_file)
 def test_init_manifest_packageid(self):
     comm.setUp()
     os.chdir(comm.XwalkPath)
     comm.clear("org.xwalk.test")
     os.mkdir("org.xwalk.test")
     cmd = (
         comm.HOST_PREFIX
         + comm.PackTools
         + "crosswalk-app manifest "
         + comm.XwalkPath
         + "org.xwalk.test --platforms=android --package-id=org.xwalk.test"
     )
     os.system(cmd)
     with open(comm.ConstPath + "/../tools/org.xwalk.test/manifest.json") as json_file:
         data = json.load(json_file)
     updatecmd = (
         comm.HOST_PREFIX
         + comm.PackTools
         + "crosswalk-app manifest "
         + comm.XwalkPath
         + "org.xwalk.test --platforms=android --package-id=org.test.foo"
     )
     os.system(updatecmd)
     with open(comm.ConstPath + "/../tools/org.xwalk.test/manifest.json") as json_file_update:
         updatedata = json.load(json_file_update)
     comm.clear("org.xwalk.test")
     self.assertEquals(data["xwalk_package_id"].strip(os.linesep), "org.xwalk.test")
     self.assertEquals(updatedata["xwalk_package_id"].strip(os.linesep), "org.test.foo")
 def start_monitor(self, event):
     print(os.getcwd())
     os.chdir("../activity_monitor/")
     print(os.getcwd())
     cmd = ["sudo", "python3", "main.py"]
     self.monitor_pro = subprocess.Popen(cmd, preexec_fn=os.setsid)
     os.chdir("../administrator_program")
Example #21
0
 def run_generated_code(
     self, engine, filename, args=[], check_timeout=True, output_nicerizer=None, assert_returncode=0
 ):
     stdout = os.path.join(self.get_dir(), "stdout")  # use files, as PIPE can get too full and hang us
     stderr = os.path.join(self.get_dir(), "stderr")
     try:
         cwd = os.getcwd()
     except:
         cwd = None
     os.chdir(self.get_dir())
     assert (
         check_line_endings(filename) == 0
     )  # Make sure that we produced proper line endings to the .js file we are about to run.
     run_js(
         filename,
         engine,
         args,
         check_timeout,
         stdout=open(stdout, "w"),
         stderr=open(stderr, "w"),
         assert_returncode=assert_returncode,
     )
     if cwd is not None:
         os.chdir(cwd)
     out = open(stdout, "r").read()
     err = open(stderr, "r").read()
     if engine == SPIDERMONKEY_ENGINE and Settings.ASM_JS == 1:
         err = self.validate_asmjs(err)
     if output_nicerizer:
         ret = output_nicerizer(out, err)
     else:
         ret = out + err
     assert "strict warning:" not in ret, "We should pass all strict mode checks: " + ret
     return ret
 def delete_images(self, event):
     print("deleting images")
     os.chdir("../flaskServer/static/camera/")
     filelist = [f for f in os.listdir(".") if f.endswith(".jpg")]
     for f in filelist:
         os.remove(f)
     os.chdir("../../../administrator_program")
Example #23
0
 def _run_remote(self, opts, suite_name):
     """rose suite-run --remote=KEY=VALUE,..."""
     suite_dir_rel = self._suite_dir_rel(suite_name)
     r_opts = {}
     for item in opts.remote.split(","):
         key, val = item.split("=", 1)
         r_opts[key] = val
     uuid_file = os.path.join(suite_dir_rel, r_opts["uuid"])
     if os.path.exists(uuid_file):
         self.handle_event("/" + r_opts["uuid"] + "\n", level=0)
     elif opts.new_mode:
         self.fs_util.delete(suite_dir_rel)
     if opts.run_mode == "run" or not os.path.exists(suite_dir_rel):
         self._run_init_dir(opts, suite_name, r_opts=r_opts)
     os.chdir(suite_dir_rel)
     for name in ["share", "share/cycle", "work"]:
         uuid_file = os.path.join(name, r_opts["uuid"])
         if os.path.exists(uuid_file):
             self.handle_event(name + "/" + r_opts["uuid"] + "\n", level=0)
         else:
             self._run_init_dir_work(opts, suite_name, name, r_opts=r_opts)
     if not opts.install_only_mode:
         uuid_file = os.path.join("log", r_opts["uuid"])
         if os.path.exists(uuid_file):
             self.handle_event("log/" + r_opts["uuid"] + "\n", level=0)
         else:
             self._run_init_dir_log(opts)
     self.fs_util.makedirs("log/suite")
Example #24
0
def align_combine(fitsdir, myfilter, examine=True):
    from pyraf import iraf

    iraf.noao(_doprint=0)
    iraf.digiphot(_doprint=0)
    iraf.apphot(_doprint=0)

    os.chdir(fitsdir)
    listfiles = glob.glob(myfilter)
    listfiles.sort()

    if examine:
        print "Opening ", listfiles[0], " to examine."
        iraf.imexamine(input=listfiles[0], logfile="coords.dat", keeplog="yes")

        with open("align.list", "w") as f:
            for i in listfiles:
                f.write(i + "\n")

    print "Aligning with reference:", listfiles[0]
    iraf.imalign(input="@align.list", referenc=listfiles[0], coords="coords.dat", output="a_@align.list")

    listfiles = glob.glob("a_" + myfilter)
    listfiles.sort()
    with open("comb.list", "w") as f:
        for i in listfiles:
            f.write(i + "\n")

    print "Combining"
    iraf.imcombine(input="@comb.list", output="out.fits", combine="median")
Example #25
0
    def __init__(self, server_path):
        self.server_path = server_path
        self.memory = memory_overrides.get(self.server_path, memory_default)
        self.server = None

        # Gives us the width
        self.term = Terminal()

        # Handles input nicely
        self.prompt = prompt.Prompt(self.run_command_from_prompt)

        # Queued server output
        self.server_output_queue = Queue()

        # Stuff to output (includes server output)
        self.console_output = []

        # Move to server directory
        os.chdir(os.path.join(servers_dir, self.server_path))

        # In case of any residual logs...
        self.backup()

        # Read random messages
        self.messages = open("messages.txt").read().splitlines()

        # Read triggers
        self.triggers = open("triggers.txt").read().splitlines()
        self.triggers = [x.split(",", 1) for x in self.triggers]

        # Start
        self.start_server()
    def setup(self, tarball="connectathon.tar.bz2"):
        connectathon_tarball = utils.unmap_url(self.bindir, tarball, self.tmpdir)
        utils.extract_tarball_to_dir(connectathon_tarball, self.srcdir)

        os.chdir(self.srcdir)
        utils.system("make clean")
        utils.system("make")
Example #27
0
def do_download(packages):
    try:
        os.chdir(download_dir)
    except:
        print >> sys.stderr, "Failed to change to directory %s, do you need to init?" % download_dir

    for p in packages:
        if p.check_download():
            print "Already have %s with md5sum %s" % (p.get_download(), p.get_download_md5())
            continue

        if p.get_download_md5() != None:
            print "Existing file %s has wrong md5 %s" % (p.get_download(), p.get_download_md5())

        print "Downloading %s to %s" % (p.url, p.get_download())
        try:
            urllib.urlretrieve(p.url, p.get_download(), download_progress_hook)
        except Exception, e:
            print >> sys.stderr, "Failed to download %s: %s" % (p.get_filename(), e)
        sys.stdout.write("\n")

        if p.check_download():
            print "Successfully downloaded %s with md5sum %s" % (p.get_download(), p.get_download_md5())
        else:
            print >> sys.stderr, "Failed to download %s (expected md5 %s downloaded file hashes to %s)" % (
                p.get_filename(),
                p.md5,
                p.get_download_md5(),
            )
Example #28
0
    def test_get_configs_cwd(self):
        """config.in_cwd() finds config in shell's current working directory"""

        current_dir = os.getcwd()

        configs_found = config.in_cwd()

        # create a temporary folder and change dir into it
        tmp_dir = tempfile.mkdtemp(suffix="tmuxp")
        os.chdir(tmp_dir)

        try:
            config1 = open(".tmuxp.json", "w+b")
            config1.close()

            configs_found = config.in_cwd()
        finally:
            os.remove(config1.name)

        self.assertEqual(len(configs_found), 1)
        self.assertIn(".tmuxp.json", configs_found)

        # clean up
        os.chdir(current_dir)
        if os.path.isdir(tmp_dir):
            shutil.rmtree(tmp_dir)
Example #29
0
def test_upload_projects_backup(server, tmpdir):
    Config.instance().set("Server", "projects_path", str(tmpdir / "projects"))
    os.makedirs(str(tmpdir / "projects" / "b"))
    # An old b image that we need to replace
    with open(str(tmpdir / "projects" / "b" / "b.img"), "w+") as f:
        f.write("bad")

    os.makedirs(str(tmpdir / "old" / "a"))
    with open(str(tmpdir / "old" / "a" / "a.img"), "w+") as f:
        f.write("hello")
    os.makedirs(str(tmpdir / "old" / "b"))
    with open(str(tmpdir / "old" / "b" / "b.img"), "w+") as f:
        f.write("world")

    os.chdir(str(tmpdir / "old"))
    with tarfile.open(str(tmpdir / "test.tar"), "w") as tar:
        tar.add(".", recursive=True)

    body = aiohttp.FormData()
    body.add_field("type", "PROJECTS")
    body.add_field("file", open(str(tmpdir / "test.tar"), "rb"), content_type="application/x-gtar", filename="test.tar")
    response = server.post("/upload", api_version=None, body=body, raw=True)
    assert response.status == 200

    with open(str(tmpdir / "projects" / "a" / "a.img")) as f:
        assert f.read() == "hello"
    with open(str(tmpdir / "projects" / "b" / "b.img")) as f:
        assert f.read() == "world"

    assert "a.img" not in response.body.decode("utf-8")
    assert "b.img" not in response.body.decode("utf-8")
    assert not os.path.exists(str(tmpdir / "projects" / "archive.tar"))
Example #30
0
def project(universe, options, config):
    """Project a copy of all the files in each checkout'ed repository
    into a plain, non-version-controlled directory in
    the projection directory, at (TODO) the latest tag specified in data.

    """
    space_key = "node"  # FIXME hardcoded
    space = universe[space_key]

    checkout_dir = os.path.abspath(config[space_key]["checkout_dir"])
    projection_dir = os.path.abspath(config[space_key]["projection_dir"])
    try:
        os.makedirs(projection_dir)
    except OSError:
        pass

    cwd = os.getcwd()
    for (key, user, repo) in sorted(space.github_repos()):
        repo_path = os.path.join(checkout_dir, repo)
        os.chdir(repo_path)
        distname = get_distname(space[key])
        proj_path = os.path.join(projection_dir, distname)
        command = "rm -rf %s && git archive --format=tar --prefix=%s/ HEAD | (cd %s && tar xf -)" % (
            proj_path,
            distname,
            projection_dir,
        )
        print command
        os.system(command)

    os.chdir(cwd)