def pull():
    gist = get_gist_id(editor.get_path())
    if gist is not None:
        fname = os.path.basename(editor.get_path())
        newtxt = load(gist, fname)
        if newtxt is not None:
            editor.replace_text(0, len(editor.get_text()), newtxt)
Esempio n. 2
0
def pull():
	gist = get_gist_id(editor.get_path())
	if gist is not None:
		fname = os.path.basename(editor.get_path())
		newtxt = load(gist,fname)
		if newtxt is not None:
			editor.replace_text(0,len(editor.get_text()),newtxt)
Esempio n. 3
0
def set():
	gist = get_gist_id(editor.get_path())
	if gist == None: gist = ''
	gist = console.input_alert('Assign Gist ID','Enter the gist id for this file',gist)
	try:
		set_gist_id(editor.get_path(),gist)
	except InvalidGistIDError:
		console.alert('Invalid Gist ID', 'That does not appear to be a valid gist id')
Esempio n. 4
0
def pull():
	gist = get_gist_id(editor.get_path())
	if gist is None:
		console.alert('Error', 'There is no gist id set for this file')
	else:
		fname = os.path.basename(editor.get_path())
		newtxt = load(gist,fname)
		if newtxt is not None:
			editor.replace_text(0,len(editor.get_text()),newtxt)
def pull():
    gist = get_gist_id(editor.get_path())
    if gist is None:
        console.alert('Error', 'There is no gist id set for this file')
    else:
        fname = os.path.basename(editor.get_path())
        newtxt = load(gist, fname)
        if newtxt is not None:
            editor.replace_text(0, len(editor.get_text()), newtxt)
Esempio n. 6
0
def test():
    import vdb
    vdb.set_trace()
    # create some variables to try watch window
    a = 1
    b = {'key': {'b': ['c', 'd', 'e']}, 'anotherkey': 'anothervalue'}
    c = 'a string'
    #test stepping over
    test2()
    # step into anothe file
    editor.get_path()
    return 10
Esempio n. 7
0
def commit():
	gist = get_gist_id(editor.get_path())
	if gist is not None:
		token = keychain.get_password('gistcheck','gistcheck')
		if token is None:
			u, p = console.login_alert('GitHub Login')
			r = json.loads(auth(u, p))
			print r
			token = r['token']
			keychain.set_password('gistcheck','gistcheck',token)
		fname = os.path.basename(editor.get_path())
		m = console.input_alert('Edit Description','Enter a new description:','')
		if m == '': m = None
		return edit(gist,{fname:editor.get_text()},token,m)
Esempio n. 8
0
def info():
	documentsDir = os.path.expanduser('~/Documents')
	info = editor.get_path()
	fullPath = info[len(documentsDir)+1:] # get the relative path and remove the leading /
	path = fullPath.split('/',1)[1]
	repo = fullPath.split('/',1)[0]
	return repo,path
Esempio n. 9
0
def pasteDir():
    '''Copy the directory in clipboard to the same directory as the current file
	'''
    # get current directory location
    file = editor.get_path()
    dir = os.path.dirname(file)

    # get source directory from clipboard
    src = clipboard.get()

    # get name of directory
    name = src.split('/')
    name = name[-1]

    # build destination name
    dst = dir + '/' + name

    # short version of destination
    msg = re.match('.*Pythonista3/Documents/(.+)', dst).group(1)

    # if already exists then cancel
    if os.path.exists(dst):
        console.alert(
            'Paste Error',
            'Directory:\n' + msg + '\nalready exists! Paste not possible.')

    # inform user and get confirmation
    ans = console.alert('Paste', 'Create this new directory?\n' + msg, 'yes')

    # if yes, paste
    if ans == 1:
        shutil.copytree(src, dst)
        console.hud_alert('Done!', 'success', 0.5)
Esempio n. 10
0
def info():
	documentsDir = os.path.expanduser('~/Documents')
	info = editor.get_path()
	#documentsDir starts with '/private' whereas info does not
	fullPath = info[len(documentsDir)-7:]
	repo, path = fullPath.split('/',1)
	return repo,path
Esempio n. 11
0
 def __init__(self):
     config = self._load_config()
     self.repo, self.path = None, None
     if config:
         self.repo = config['repo-name']
         # build the path relative to the repo-root
         self.path = editor.get_path()[len(config['repo-root']) + 1:]
Esempio n. 12
0
def commit_authenticated(user, commit_message):
	path = editor.get_path()
	tree_path, blob_name = os.path.split(path)

	repository = get_current_repository(user)

	blob = repository.create_git_blob(editor.get_text(), 'utf-8')

	parent_commit = get_current_head_commit(user)
	
	original_tree = repository.get_git_tree(parent_commit.tree.sha, True)

	tree_elements = []
	for original_element in original_tree.tree:
		element_sha = original_element.sha
		if blob_name == original_element.path:
			element_sha = blob.sha

		element = InputGitTreeElement(
			original_element.path,
			original_element.mode,
			original_element.type,
			sha = element_sha)
		tree_elements.append(element)

	tree = repository.create_git_tree(tree_elements)
	# Need to update all ancestor trees as well
	
	commit = repository.create_git_commit(commit_message, tree, [parent_commit])

	current_branch_head_ref = 'heads/' + get_current_branch_name()
	head_ref = repository.get_git_ref(current_branch_head_ref)
	head_ref.edit(commit.sha)
Esempio n. 13
0
    def edit_file(self, remote_file):
        import tempfile
        import runpy
        import editor

        try:
            temp = tempfile.NamedTemporaryFile(dir=os.path.expanduser("~/Documents"), suffix=".py")
            cur_path = editor.get_path()
            sftp = self.ssh.open_sftp()
            path = self.get_remote_path()
            res = sftp.getfo(path + remote_file, temp)
            # editor.open_file(temp.name)
            temp.seek(0)
            print "***When you are finished editing the file, you must come back to console to confirm changes***"
            editor.open_file(temp.name)
            time.sleep(1.5)
            console.hide_output()
            input = raw_input("Save Changes? Y,N: ")
            editor.open_file(cur_path)
            if input == "y" or input == "Y":
                with open(temp.name, "r") as f:
                    sftp.putfo(f, path + remote_file)
                    print "File transfered."
        except Exception, e:
            print e
Esempio n. 14
0
    def __init__(self):
        global _datasource

        self.name = 'Drag & Drop'

        self.width = min(ui.get_window_size()[0] * 0.8, 700)
        self.height = ui.get_window_size()[1] * 0.8

        path = editor.get_path()
        if path:
            expanded_folder = os.path.dirname(path)
            files = tab.get_paths()
        else:
            expanded_folder = None
            files = None

        root_node = FileNode(os.path.expanduser('~/Documents'), ignore=ignore)
        _datasource = FolderPickerDataSource(root_node, expanded_folder, files)

        tv = ui.TableView(frame=self.bounds, flex='WH')
        tv.delegate = _datasource
        tv.data_source = _datasource
        tv.allows_multiple_selection = False
        tv.allows_selection = True
        tv.allows_multiple_selection_during_editing = False
        tv.allows_selection_during_editing = False
        tv.separator_color = 'clear'
        self.add_subview(tv)

        methods = [tableView_itemsForBeginningDragSession_atIndexPath_]
        protocols = ['UITableViewDragDelegate']
        DragDelegate = create_objc_class('DragDelegate',
                                         methods=methods,
                                         protocols=protocols)
        self._drag_delegate = DragDelegate.alloc().init()

        methods = [
            tableView_canHandleDropSession_,
            tableView_dropSessionDidUpdate_withDestinationIndexPath_,
            tableView_performDropWithCoordinator_
        ]
        protocols = ['UITableViewDropDelegate']
        DropDelegate = create_objc_class('DropDelegate',
                                         methods=methods,
                                         protocols=protocols)
        self._drop_delegate = DropDelegate.alloc().init()

        tv_objc = ObjCInstance(tv)
        tv_objc.setDragDelegate_(self._drag_delegate)
        tv_objc.setDropDelegate_(self._drop_delegate)

        def handle_escape():
            self.close()

        self._handlers = [
            register_key_event_handler(UIEventKeyCode.ESCAPE, handle_escape),
            register_key_event_handler(UIEventKeyCode.DOT,
                                       handle_escape,
                                       modifier=UIKeyModifier.COMMAND)
        ]
 def close_settings(self):
     sPl = plistlib.writePlistToString(self.plSettings)
     sN = self._sA[0:self._iS] + sPl[:-1] + self._sA[self._iF:-1]
     with open(self._f, 'w') as fS:
         fS.write(sN)
     if os.path.split(editor.get_path())[1] == self._f:
         editor.replace_text(0, len(editor.get_text()), sN)
Esempio n. 16
0
def main():
    if not get_config_value('general.jedi', False):
        log.warn(
            'find_usages disabled, you can enable it by setting general.jedi to True'
        )
        return

    path = editor.get_path()
    if path is None:
        return

    if not path.endswith('.py'):
        return

    tab.save()

    text = editor.get_text()
    if not text:
        return

    line = source.get_line_number()
    column = source.get_column_index()

    if line is None or column is None:
        return

    script = jedi.api.Script(text, line, column, path)
    definitions = [d for d in script.usages() if d.module_path and d.line]

    if not definitions:
        console.hud_alert('Definition not found', 'error')
        return

    _select_location(definitions)
Esempio n. 17
0
def main():
    filename = editor.get_path()
    if not filename:
        dialogs.hud_alert('No file selected', 'error')
        return
    pyui_filename = os.path.splitext(filename)[0] + '.pyui'
    if not os.path.exists(pyui_filename):
        folder = os.path.split(filename)[0]
        files = os.listdir(folder)
        files = [f for f in files if f.endswith('.pyui')]
        if not files:
            dialogs.hud_alert('No pyui files found', 'error')
            return
        selected_pyui = dialogs.list_dialog('Select pyui file', files)
        if not selected_pyui:
            return
        pyui_filename = os.path.join(folder, selected_pyui)
    with open(pyui_filename, 'rb') as f:
        pyui = f.read()
    compressed = base64.b64encode(bz2.compress(pyui)).decode('utf-8')
    wrapped = '\n'.join(textwrap.wrap(compressed, 70))
    code = """\
data = '''\\\n%s
'''
import ui
import bz2
from base64 import b64decode
pyui = bz2.decompress(b64decode(data))
v = ui.load_view_str(pyui.decode('utf-8'))
""" % (wrapped, )
    clipboard.set(code)
    dialogs.hud_alert('Code copied', 'success')
Esempio n. 18
0
def commit():
    token = get_token()
    fpath = editor.get_path()
    fname = os.path.basename(fpath)
    m = console.input_alert('Edit Description', 'Enter a new description:', '')
    if m == '': m = None
    gist_id = get_gist_id()
    res = commit_or_create(gist_id, {fpath: editor.get_text()}, token, m)
    try:
        id = res['id']
    except KeyError:
        if gist_id:
            f = console.alert(
                'Commit Failed',
                'Do you have permission to commit? Would you like to fork?',
                'Fork')
            if f == 1:
                res = fork(gist_id, token)
                try:
                    id = res['id']
                except KeyError:
                    console.alert('Fork Error',
                                  'There was a problem with the fork')
                else:
                    set_gist_id(id)
                    res = commit_or_create(id, {fpath: editor.get_text()},
                                           token, m)
                    try:
                        id = res['id']
                    except KeyError:
                        console.alert('Commit Error',
                                      'Commit still failed, maybe fork too')
    else:
        if gist_id is None:
            set_gist_id(id)
def install_actions():
    ''' Installs shortcuts in the wrench menu
	'''
    # get current location
    file = editor.get_path()
    file = re.match('.+Pythonista3/Documents(/.+)', file).group(1)

    lst = get_actions()
    titles = {}
    for dct in lst:
        titles[str(dct['title'])] = True

    cmd = 'paste_dir'
    if cmd not in titles:
        add_action(arguments='paste',
                   iconName="Primaries_Paste",
                   scriptName=file,
                   title=cmd)

    cmd = 'copy_dir'
    if cmd not in titles:
        add_action(arguments='copy',
                   iconName="ios7-copy-outline",
                   scriptName=file,
                   title=cmd)

    save_defaults()
Esempio n. 20
0
def main():
    filename = editor.get_path()
    if not filename:
        return

    if not filename.endswith('.py'):
        return

    text = editor.get_text()
    if not text:
        return

    def scroll_to_node(node, shift_enter):
        source.scroll_to_line(node.line)

    v = PickerView()
    v.name = 'Outline'
    v.datasource = OutlineDataSource(text, os.path.basename(filename))
    v.shift_enter_enabled = False
    v.help_label.text = (
        '⇅ - select • Enter - scroll to location'
        '\n'
        'Esc - close • Cmd . - close with Apple smart keyboard')
    v.textfield.placeholder = 'Start typing to filter nodes...'
    v.did_select_item_action = scroll_to_node
    v.present('sheet')
    v.wait_modal()
Esempio n. 21
0
def replace():
    steps = {
        1: 'Extracting content',
        2: 'Starting edition',
        3: 'Getting cuantity'
    }
    actual = 1
    try:
        file = get_path()
        print(steps[1])
        content = open(file).read()

        line = [x for x in content.split('\n') if ' ' in x[:1]][0]
        actual = 2
        print(steps[2])
        actual = 3
        print(steps[3])
        cuantity = count_spaces(line)
        with open(file, 'w') as file:
            file.write(content.replace(' ' * cuantity, '\t'))
            file.close()
        print('Done')
    except Exception as e:
        print('++{}++'.format(e))
        print('Error in step {}'.format(actual))
        print('({})'.format(steps[actual]))
Esempio n. 22
0
def get_path():
	regex= r"\/Documents\/(.+)$"

	path = editor.get_path()
	matches = re.findall(regex, path)
	
	return matches[0]
Esempio n. 23
0
def edit_file(file_to_edit):
    '''Open file in a temp text page to allow editing'''
    
    cur_path = editor.get_path()
    #with open('tmp.txt', 'w') as file:
    try:
        file = open(TEMP_DIR+'/tmp.txt','w')
        file.write(file_to_edit.read())
        file.close()
        editor.reload_files()
        raw_input('*When you are finished editing the file, you must come back to console to confim changes*\n[Press Enter]')
        editor.open_file(TEMP)
        console.hide_output()
        while True:
            input = raw_input('Save Changes? Y,N: ')
            if input=='Y' or input=='y':
                editor.open_file(cur_path)
                return open(TEMP_DIR+'/tmp.txt','r')
            elif input=='N' or input=='n':
                editor.open_file(cur_path)
                return False

        
    except Exception, e:
        print e
        return False
Esempio n. 24
0
def download(gist_url):
	num = 0
	try:
		for num, (filename, content) in enumerate(download_gist(gist_url), start=1):
			if os.path.isfile(filename):
				i = console.alert('File exists', 'A file with the name ' + filename + 
								  ' already exists in your library.',
								  'Auto Rename', 'Skip')
				if i == 1:
					editor.make_new_file(filename, content)
			else:
				editor.make_new_file(filename, content)
				try:
					set_gist_id(editor.get_path(), gist_url)
				except InvalidGistIDError:
					# console.alert('Gist ID not set', filename + '\n' + gist_url)
					pass
	except InvalidGistURLError:
		console.alert('No Gist URL',
					  'Invalid Gist URL.',
					  'OK')
	except GistDownloadError:
		console.alert('Error', 'The Gist could not be downloaded.')
	if not num:
		console.alert('No Python Files', 'This Gist contains no Python files.')
Esempio n. 25
0
File: ssh.py Progetto: jsbain/stash
    def edit_file(self, remote_file):
        import tempfile
        import runpy
        import editor

        try:
            temp = tempfile.NamedTemporaryFile(
                dir=os.path.expanduser('~/Documents'), suffix='.py')
            cur_path = editor.get_path()
            sftp = self.ssh.open_sftp()
            path = self.get_remote_path()
            res = sftp.getfo(path + remote_file, temp)
            #editor.open_file(temp.name)
            temp.seek(0)
            print '***When you are finished editing the file, you must come back to console to confirm changes***'
            editor.open_file(temp.name)
            time.sleep(1.5)
            console.hide_output()
            input = raw_input('Save Changes? Y,N: ')
            editor.open_file(cur_path)
            if input == 'y' or input == 'Y':
                with open(temp.name, 'r') as f:
                    sftp.putfo(f, path + remote_file)
                    print 'File transfered.'
        except Exception, e:
            print e
Esempio n. 26
0
def main():
    title = os.path.split(editor.get_path())[1]
    html = editor.get_text()

    webview = ui.WebView(title)
    webview.load_html(html)
    webview.present()
Esempio n. 27
0
def commit():
	token = get_token()
	fpath = editor.get_path()
	fname = os.path.basename(fpath)
	m = console.input_alert('Edit Description','Enter a new description:','')
	if m == '': m = None
	gist_id = get_gist_id()
	res = commit_or_create(gist_id,{fpath:editor.get_text()},token,m)
	try:
		id = res['id']
	except KeyError:
		if gist_id:
			f = console.alert('Commit Failed',
			'Do you have permission to commit? Would you like to fork?','Fork')
			if f == 1:
				res = fork(gist_id,token)
				try:
					id = res['id']
				except KeyError:
					console.alert('Fork Error', 'There was a problem with the fork')
				else:
					set_gist_id(id)
					res = commit_or_create(id,{fpath:editor.get_text()},token,m)
					try:
						id = res['id']
					except KeyError:
						console.alert('Commit Error',
						'Commit still failed, maybe fork too')
	else:
		if gist_id is None:
			set_gist_id(id)
	print('success!')
Esempio n. 28
0
def main():
	filename = editor.get_path()
	if not filename:
		dialogs.hud_alert('No file selected', 'error')
		return
	pyui_filename = os.path.splitext(filename)[0] + '.pyui'
	if not os.path.exists(pyui_filename):
		folder = os.path.split(filename)[0]
		files = os.listdir(folder)
		files = [f for f in files if f.endswith('.pyui')]
		if not files:
			dialogs.hud_alert('No pyui files found', 'error')
			return
		selected_pyui = dialogs.list_dialog('Select pyui file', files)
		if not selected_pyui:
			return
		pyui_filename = os.path.join(folder, selected_pyui)
	with open(pyui_filename, 'rb') as f:
		pyui = f.read()
	compressed = base64.b64encode(bz2.compress(pyui)).decode('utf-8')
	wrapped = '\n'.join(textwrap.wrap(compressed, 70))
	code = """\
data = '''\\\n%s
'''
import ui
import bz2
from base64 import b64decode
pyui = bz2.decompress(b64decode(data))
v = ui.load_view_str(pyui.decode('utf-8'))
""" % (wrapped,)
	clipboard.set(code)
	dialogs.hud_alert('Code copied', 'success')
Esempio n. 29
0
 def edit_file(self,remote_file):
     import tempfile
     import runpy
     import editor
 
     try:
         temp = tempfile.NamedTemporaryFile(dir=os.path.expanduser('~/Documents') , suffix='.py')
         cur_path = editor.get_path()
         sftp = self.ssh.open_sftp()
         path = self.get_remote_path()
         res = sftp.getfo(path+remote_file,temp)
         #editor.open_file(temp.name)
         temp.seek(0)
         print '***When you are finished editing the file, you must come back to console to confim changes***'
         editor.open_file(temp.name)
         time.sleep(1.5)
         console.hide_output()
         input = raw_input('Save Changes? Y,N: ')
         editor.open_file(cur_path)
         if input == 'y' or input =='Y':
             with open(temp.name,'r') as f:
                 sftp.putfo(f,path+remote_file)
                 print 'File transfered.'
     except exception, e:
         print e
Esempio n. 30
0
class LoggingPrinter:
    scriptname = editor.get_path().split("/")[-1]

    def __init__(
            self,
            filename=str(
                "/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/logs/"
                + scriptname + " - " + "logged_printer.txt"),
            submodule=None):

        if submodule != None:
            filename = str(submodule)
            self.out_file = open(filename, "a")
        else:
            self.out_file = open(filename, "w")
        self.old_stdout = sys.stdout
        #this object will take over `stdout`'s job
        sys.stdout = self

    #executed when the user does a `print`
    def write(self, text):
        self.old_stdout.write(text)
        self.out_file.write(text)

    #executed when `with` block begins
    def __enter__(self):
        return self

    #executed when `with` block ends
    def __exit__(self, type, value, traceback):
        #we don't want to log anymore. Restore the original stdout object.
        sys.stdout = self.old_stdout
Esempio n. 31
0
    def open_url(self,sender):
        sv=self.sv
        d=self.d
        current_path = editor.get_path()
        button_title = sender.title
    
        #unselect current tab
        current_tab = self.get_current_tab(current_path)
        if current_tab:
            sv[current_tab['name']].background_color = 'white'
            d[current_tab['name']]['selection']=editor.get_selection()
        
        if not d.has_key(button_title):
            console.hud_alert('missing tab entry for this tab.. ')
        
        new_tab=d[button_title]
        path=new_tab['path']
        if not os.path.isfile(path):
            console.hud_alert('The file for this tab has been moved, renamed, or deleted. the tab will now be removed.', icon = 'error', duration = 3)
            self.close_button(sender)

        else:
            editor.open_file(path)
            def setsel():
                sel=new_tab['selection']

                while editor.get_selection()[0] < sel[0]:
                    import time
                    editor.replace_text(sel[0],sel[0],'')
                    editor.replace_text(sel[0]+400,sel[0]+400,'')
                    time.sleep(0.25)
                editor.set_selection(*sel)
            ui.delay(setsel,1.0)
            sender.background_color = 'orange'
Esempio n. 32
0
def analyze():
    path = editor.get_path()

    if not path:
        return

    if not path.endswith('.py'):
        return

    editor.clear_annotations()

    text = editor.get_text()
    annotations = _pep8_annotations(
        text,
        ignore=settings.ANALYZER_PEP8_IGNORE,
        max_line_length=settings.ANALYZER_PEP8_MAX_LINE_LENGTH)

    annotations += _pyflakes_annotations(path, text)

    if not annotations:
        console.hud_alert('No Issues Found', 'iob:checkmark_32',
                          settings.ANALYZER_HUD_DELAY)
        return None

    scroll = True
    by_line = sorted(annotations, key=lambda x: x.line)
    for l, a in groupby(by_line, lambda x: x.line):
        _annotate(l, a, scroll)
        scroll = False
Esempio n. 33
0
def get_configuration():
    '''
  Reads the docstring in the open file and finds AWS configuration information, starting with the magic string followed by JSON formatted key-value pairs. Remember that JSON uses double quotes for strings.
  '''
    lambda_function_name = os.path.basename(current_dir)
    current_file = os.path.basename(editor.get_path())
    if current_file.endswith('.py'):
        handler_first_part = current_file[:-3]
    file_text = editor.get_text()
    tree = ast.parse(file_text)

    conf = None
    for func in top_level_functions(tree.body):
        docstr = ast.get_docstring(func)
        if docstr:
            if conf_strings.awslambda in docstr:
                conf = {
                    'function_name': lambda_function_name,
                    'handler': handler_first_part + '.' + func.name
                }
                if conf_strings.noapi in docstr:
                    conf['no-api'] = True
                    print('** Will not update API endpoint')
                if conf_strings.html in docstr:
                    conf['html'] = True
                return conf
    return None
def main():
    try:
        choice = console.alert("Copy what?", "Choose...", "File (full)", "File (~/Documents)", "Dir")
    except:
        choice = 1
    fn = editor.get_path()
    fn = fn[fn.find("/Documents"):] if choice == 2 else os.path.split(fn)[0][8:] if choice == 3 else fn[8:]
    clipboard.set(fn)
Esempio n. 35
0
def info():
	documentsDir = os.path.expanduser('~/Documents')
	info = editor.get_path()
	#documentsDir starts with '/private' whereas info does not
	fullPath = info[len(documentsDir)-7:]
	path = fullPath.split('/',1)[1]
	repo = fullPath.split('/',1)[0]
	return repo,path
	def _get_repo_info(self):
		documentsDir = os.path.expanduser('~/Documents')
		info = editor.get_path()
		fullPath = info[len(documentsDir)+1:] # get the relative path and remove the leading /
		print(fullPath)
		path = fullPath.split('/',1)[1]
		repo = fullPath.split('/',1)[0]
		return repo, path			
Esempio n. 37
0
    def run_script(sender):
        '''run a script without clearing glbals'''
        import editor
        editor.reload_files()
        execfile(editor.get_path(), globals())

    #create_toolbar_button(run_script,'iow:play_32',0,'execfile')

    #remove_toolbar_button(0)
Esempio n. 38
0
 def __init__(self):
     self.key = self._get_key()
     self.install_path = self._find_install_path()
     self.config = self._get_config()
     self.repo, self.path = None, None
     if self.config:
         self.repo = self.config['repo-name']
         # build the path relative to the repo-root
         self.path = editor.get_path()[len(self.config['repo-root']) + 1:]
def pyui2json2pyui():
    srce_file = editor.get_path()
    root, ext = os.path.splitext(srce_file)
    assert ext in file_types, "'{}' must be in {}".format(ext, file_types)
    other_ext = [file_type for file_type in file_types if file_type != ext][0]
    dest_file = root + other_ext
    os.rename(srce_file, dest_file)
    fmt = '{} was renamed to {}.'
    print(fmt.format(os.path.basename(srce_file), os.path.basename(dest_file)))
Esempio n. 40
0
	def __init__(self):
		self.key = self._get_key()
		self.install_path = self._find_install_path()
		self.config = self._get_config()
		self.repo, self.path = None, None
		if self.config: 
			self.repo = self.config['repo-name']
			# build the path relative to the repo-root
			self.path = editor.get_path()[len(self.config['repo-root'])+1:]
Esempio n. 41
0
	def run_script(sender):
		'''run a script without clearing glbals'''
		import editor
		editor.reload_files()
		execfile(editor.get_path(),globals())

	#create_toolbar_button(run_script,'iow:play_32',0,'execfile')
	
	#remove_toolbar_button(0)
Esempio n. 42
0
	def overwrite_with_wc_copy(self):
		action = 'read'
		fmt = 'pythonista3://{install_path}/{wc_file}?action=run&argv=overwrite_file&argv={path}&argv='
		payload = {
			'repo': self.repo,
			'path': self.path,
			'base64': '1',
			'x-success': fmt.format(install_path=self.install_path, path=editor.get_path(), wc_file=WC_FILENAME)
		}
		self._send_to_working_copy(action, payload)
Esempio n. 43
0
 def checkout(self,sender):
     repo =self._get_repo()
     cwd=os.path.abspath('.')
     os.chdir(r._get_repo().path)
     #repo.clean_working()
     repo.switch_branch(self.view['branch'].text)
     self.refresh()
     os.chdir(cwd)
     editor.open_file(editor.get_path())
     console.hud_alert('checked out')
Esempio n. 44
0
 def checkout(self, sender):
     repo = self._get_repo()
     cwd = os.path.abspath('.')
     os.chdir(r._get_repo().path)
     #repo.clean_working()
     repo.switch_branch(self.view['branch'].text)
     self.refresh()
     os.chdir(cwd)
     editor.open_file(editor.get_path())
     console.hud_alert('checked out')
Esempio n. 45
0
 def add_button_tapped(self, sender):
     # Bookmarks a file from the file picker dialog
     if selection == 1:
         path = editor.get_path()
     elif selection == 2:
         # TODO
         # Show file picker dialog
         pass
     self.bm_manager.add(path=path)
     self.reload()
Esempio n. 46
0
 def check_tab(self):
     open_path = editor.get_path()
     for tab in self.sv.subviews:
         try:
             if self.d[tab.name]['path'] != open_path:
                 tab.background_color = 'white'
             else:
                 tab.background_color = 'orange'
         except KeyError:
             pass
Esempio n. 47
0
 def check_tab(self):
     open_path = editor.get_path()
     for tab in self.sv.subviews:
         try:
             if self.d[tab.name]['path'] != open_path:
                 tab.background_color = 'white'
             else:
                 tab.background_color = 'orange'
         except KeyError:
             pass
Esempio n. 48
0
def pasteboardChanged_(_self, _cmd, _n):
    import clipboard
    from datetime import datetime
    import editor
    if editor.get_path().endswith('/Scrapbook.txt'):
        # Don't add to ScrapBook when copying from it...
        return
    timestamp = datetime.strftime(datetime.now(), '%Y-%m-%d - %H:%M')
    text = clipboard.get()
    with open('Scrapbook.txt', 'a') as f:
        f.write('\n\n=== %s\n%s' % (timestamp, text))
Esempio n. 49
0
def pyui2json():
    python_file = editor.get_path()
    root,ext = os.path.splitext(python_file)
    ui_file = root+'.pyui'
    backup_folder = python_file+'backup'
    try:
        os.makedirs(backup_folder)
    except:
        None
    shutil.copy(ui_file,backup_folder)
    os.rename(ui_file,root+'.json')
Esempio n. 50
0
def refresh_editor():
    #reload current file in editor
    # TODO: only reload if the file was recently updated...
    try:
        sel=editor.get_selection()
        editor.open_file(editor.get_path())
        import time
        time.sleep(0.5) #let the file load
        editor.replace_text(sel[0],sel[0],'') #force scroll
        editor.set_selection(sel[0],sel[1])
    except:
        print 'Could not refresh editor.  continuing anyway'
Esempio n. 51
0
def pull():
	gist_id = get_gist_id()
	if gist_id is None:
		console.alert('Error', 'There is no gist id set for this file')
	else:
		fname = os.path.basename(editor.get_path())
		gist_data = requests.get(api_url + gist_id).json()
		try:
			newtext = gist_data['files'][fname]['content']
		except:
			console.alert('Pull Error', 'There was a problem with the pull',gist_data)
		if newtext is not None:
			editor.replace_text(0,len(editor.get_text()),newtext)
Esempio n. 52
0
 def add_file(self,sender):
     d=self.d
     current_path = str(editor.get_path())
     name = os.path.split(current_path)[1]
     for item in self.d.itervalues():
         if current_path==item['path']:
             console.hud_alert('There is already a tab for this file', duration = 1)
             return None
     if self.d.has_key(name): #has name, but diff path, still create the tab, but append !#
         suffix_list=[(k+'!').split('!')[1] or '0' for k in self.d.keys() if k.startswith(name) ]
         new_suffix='!'+max([int(m) for m in suffix_list])+1
         name=name+new_suffix
     d[name]={'name':name,'path':current_path,'selection':editor.get_selection()}
     self.add_new_button(name, new = True)
Esempio n. 53
0
 def close_settings(self):
     while self.__iR != 0: pass
     if self.settings_file[:7] == 'http://':
         pass
     else:
         sPl = plistlib.writePlistToString(self.settings_dict)
         sN = self.__sA[0:self.__iS] + sPl[:-1] + self.__sA[self.__iF:]
         with open(self.settings_file, 'w') as fS: fS.write(sN)
         if editor.get_path() == self.settings_file:
             tS = editor.get_selection()
             iD = 0 if tS[0] <= self.__iF else len(sN) - len(self.__sA)
             editor.replace_text(0, len(editor.get_text()), sN[:-1])
             editor.set_selection(tS[0] + iD, tS[1] + iD)
         return True
     self.settings_dict = None
Esempio n. 54
0
	def _get_config(self, path=None):
		''' Dind the config file for the repo recursively.
				Don't look beyond the docs directory.
		'''
		config = None
		if not path: 
			path = os.path.dirname(editor.get_path())	
		config_path = os.path.join(path, CONFIG_FILE)
		if os.path.exists(config_path):
			with open(config_path) as f:
				config = json.loads(f.read())
				config['repo-root'] = path
		elif path != DOCS_DIR:
			new_path = os.path.abspath(os.path.join(path, '..'))
			config = self._get_config(new_path)
		return config
Esempio n. 55
0
File: edit.py Progetto: BBOOXX/stash
def open_temp(file='', new_tab=True):
    try:
        file_to_edit = file
        temp = tempfile.NamedTemporaryFile(dir=os.path.expanduser('~/Documents') , suffix='.py')
        cur_path = editor.get_path()
        if file_to_edit != '':
            try:
                to_edit = open(file_to_edit,'r')
            except:
                to_edit = open(file_to_edit,'w+')

            temp.write(to_edit.read())
            temp.flush()
            to_edit.close()
            
        print('***When you are finished editing the file, you must come back to console to confim changes***')
        editor.open_file(temp.name, new_tab)
        time.sleep(1.5)
        console.hide_output()
        input = raw_input('Save Changes? Y,N: ')
    
        if input=='Y' or input=='y':
            while True:
                try:
                    save_as = raw_input('Save file as [Enter to confirm]: %s' % file_to_edit) or file_to_edit
                except:
                    save_as = file_to_edit
                if save_as:
                    break

            if not new_tab:
                editor.open_file(cur_path) # restore previous script in editor
            with open(save_as,'w') as f:
                with open(temp.name,'r') as tmp:
                    f.write(tmp.read())
                    
            print('File Saved.')
        elif input=='N' or input=='n':
            if not new_tab:
                editor.open_file(cur_path) # restore previous script in editor
    
    except Exception as e:
        print(e)
        
    finally:
        temp.close()
Esempio n. 56
0
 def did_load(self):
     sv=self['scrollview1']
     self.sv=sv
     self.add_button = sv['add_button']
     self.add_button.action=self.add_file
     self.remove = sv['remove']
     self.edit = sv['edit']
     self.edit.action=edit_menu
     
     d=shelve.open(os.path.expanduser('~/Documents/.tabs'),writeback=True )
 
     current_path = editor.get_path()
 
     for tab in d.itervalues():
         self.add_new_button(tab['name'])
     self.d=d
     self.present('sidebar')
     self.check_tab()
     type(self)._lastinstance=self