hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 5, "code_window": [ "\t\treturn this.session.setVariable({\n", "\t\t\tname: variable.name,\n", "\t\t\tvalue,\n", "\t\t\tvariablesReference: (<model.Variable>variable).parent.reference\n", "\t\t}).then(response => {\n", "\t\t\tvariable.value = response.body.value;\n", "\t\t\t// Evaluate all watch expressions again since changing variable value might have changed some #8118.\n", "\t\t\treturn this.setFocusedStackFrameAndEvaluate(this.viewModel.getFocusedStackFrame());\n", "\t\t}, err => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (response && response.body) {\n", "\t\t\t\tvariable.value = response.body.value;\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 510 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "tags.a": "Wenn das a-Element ein href-Attribut besitzt, stellt es einen Link (einen Hypertextanker) dar, der durch seinen Inhalt bezeichnet wird.", "tags.abbr": "Das abbr-Element stellt eine Abkürzung oder ein Akronym dar, optional mit der entsprechenden Erweiterung. Das title-Attribut kann zum Bereitstellen einer Erweiterung der Abkürzung verwendet werden. Das Attribut muss (wenn es angegeben wird) eine Erweiterung der Abkürzung und darf nichts anderes enthalten.", "tags.address": "Das address-Element stellt die Kontaktinformationen für seinen nächsten Artikel oder body-Element-Vorgänger dar. Wenn es sich um das body-Element handelt, gelten die Kontaktinformationen für das gesamte Dokument.", "tags.area": "Das area-Element stellt einen Link mit Text und einem entsprechenden Bereich für eine Imagemap oder einen toten Bereich für eine Imagemap dar.", "tags.article": "Das article-Element stellt eine vollständige (oder eigenständige) Komposition in einem Dokument, auf einer Seite, in einer Anwendung oder auf einer Website dar, die im Prinzip unabhängig verteilt oder erneut verwendet werden kann, z. B. bei der Veröffentlichung. Dabei kann es sich um einen Beitrag in einem Forum, in einem Magazin oder um einen Zeitungsartikel, einen Blogeintrag, ein von einem Benutzer übermittelten Kommentar, ein interaktives Widget oder Gadget oder um ein beliebiges anderes unabhängiges Inhaltselement handeln. Jedes article-Element sollte identifiziert werden. Dies geschieht normalerweise durch eine Überschrift (h1- bis h6-Element) als untergeordnetes Element eines article-Elements.", "tags.aside": "Das aside-Element stellt einen Abschnitt einer Seite dar, der aus Inhalt besteht, der indirekt mit dem Inhalt um das aside-Element in Beziehung steht, und der als separat von diesem Inhalt betrachtet werden kann. Solche Abschnitte werden in Druckerzeugnissen häufig in einem Kasten dargestellt.", "tags.audio": "Ein audio-Element stellt einen Sound- oder Audiodatenstrom dar.", "tags.b": "Das b-Element stellt eine Textpassage dar, auf die aus praktischen Gründen die Aufmerksamkeit gelenkt werden soll, ohne Wichtigkeit zu vermitteln oder einen anderen Stil oder Ton zu verwenden, z. B. Stichwörter in einer Dokumentzusammenfassung, Produktnamen in einer Bewertung, Aktionswörter in einer interaktiven textgesteuerten Software oder führende Sätze der Absätze eines Artikels.", "tags.base": "Das base-Element ermöglicht Autoren das Angeben der Dokumentbasis-URL zum Auflösen relativer URLs sowie des Namens des Standardbrowserkontexts zum Folgen von Links. Das Element stellt keinen Inhalt dar, der über diese Informationen hinausgeht.", "tags.bdi": "Das bdi-Element stellt eine Textpassage dar, die von ihrer Umgebung isoliert werden soll, um bidirektionale Textformatierung zu ermöglichen. [BIDI]", "tags.blockquote": "Das blockquote-Element stellt Inhalt dar, der aus einer anderen Quelle zitiert wird, optional mit einem Zitat, das sich in einem footer- oder cite-Element befinden muss, und optional mit Inlineänderungen (z. B. Anmerkungen und Abkürzungen).", "tags.body": "Das body-Element stellt den Inhalt des Dokuments dar.", "tags.br": "Das br-Element stellt einen Zeilenumbruch dar.", "tags.button": "Das button-Element stellt eine Schaltfläche dar, die durch ihren Inhalt beschriftet wird.", "tags.canvas": "Das canvas-Element stellt Skripts mit einem auflösungsabhängigen Bitmapzeichenbereich bereit, der während des Betriebs zum Rendern von Diagrammen, Spielegrafiken, Bildern oder anderen visuellen Effekten verwendet werden kann.", "tags.caption": "Das caption-Element stellt den Titel der Tabelle dar, die sein übergeordnetes Element ist, wenn es ein übergeordnetes Element besitzt und dieses ein table-Element ist.", "tags.cite": "Das cite-Element stellt einen Verweis auf eine kreative Arbeit dar. Es muss den Titel der Arbeit oder den Namen des Autors (Person, Personen oder Organisation) oder einen URL-Verweis umfassen, der in abgekürzter Form gemäß den Konventionen vorliegen kann, die für die Hinzufügung von Zitatmetadaten verwendet werden.", "tags.code": "Das code-Element stellt ein Fragment von Computercode dar. Es kann sich um den Namen eines XML-Elements, einen Dateinamen, ein Computerprogramm oder eine andere Zeichenfolge handeln, die ein Computer erkennen kann.", "tags.col": "Wenn ein col-Element ein übergeordnetes Element besitzt und dieses ein colgroup-Element ist, das seinerseits ein übergeordnetes Element besitzt, das ein table-Element ist, stellt das col-Element mindestens eine Spalte in der Spaltengruppe dar, die durch dieses colgroup-Element dargestellt wird.", "tags.colgroup": "Das colgroup-Element stellt eine Gruppe aus mindestens einer Spalte in der Tabelle dar, die sein übergeordnetes Element ist, wenn es ein übergeordnetes Element besitzt und dieses ein table-Element ist.", "tags.datalist": "Das datalist-Element stellt eine Sammlung von option-Elementen dar, die vordefinierte Optionen für andere Steuerelemente darstellen. Beim Rendern stellt das datalist-Element nichts dar und sollte (zusammen mit seinen untergeordneten Elementen) verborgen werden.", "tags.dbo": "Das bdo-Element stellt eine explizite Formatierungssteuerung der Textrichtung für seine untergeordneten Elemente dar. Es ermöglicht Autoren die Außerkraftsetzung des bidirektionalen Unicode-Algorithmus durch explizites Angeben einer Richtungsaußerkraftsetzung. [BIDI]", "tags.dd": "Das dd-Element stellt den Beschreibungs-, Definitions- oder Wertteil einer Ausdrucks-Beschreibungs-Gruppe in einer Beschreibungsliste (dl-Element) dar.", "tags.del": "Das del-Element stellt eine Entfernung aus dem Dokument dar.", "tags.details": "Das details-Element stellt ein Anzeigewidget dar, aus dem der Benutzer zusätzliche Informationen oder Steuerelemente abrufen kann.", "tags.dfn": "Das dfn-Element stellt die definierende Instanz eines Ausdrucks dar. Der Absatz, die Beschreibungslistengruppe oder der Abschnitt, der bzw. die der nächste Vorgänger des dfn-Elements ist, muss außerdem die Definition(en) für den durch das dfn-Element angegebenen Ausdruck enthalten.", "tags.dialog": "Das dialog-Element stellt einen Teil einer Anwendung dar, mit der ein Benutzer interagiert, um eine Aufgabe auszuführen, z. B. ein Dialogfeld, eine Überprüfung oder ein Fenster.", "tags.div": "Das div-Element besitzt keine besondere Bedeutung. Es stellt seine untergeordneten Elemente dar. Es kann mit den class-, lang- und title-Attributen als Markup für Semantik verwendet werden, die einer Gruppe aufeinanderfolgender Elemente gemeinsam ist.", "tags.dl": "Das dl-Element stellt eine Zuordnungsliste dar, die aus mindestens null Name-Wert-Gruppen (einer Beschreibungsliste) besteht. Eine Name-Wert-Gruppe besteht aus mindestens einem Namen (dt-Elemente), gefolgt von mindestens einem Wert (dd-Elemente). Dabei werden alle anderen Knoten als dt- und dd-Elemente ignoriert. In einem einzelnen dl-Element sollten nicht mehrere dt-Elemente für jeden Namen vorhanden sein.", "tags.dt": "Das dt-Element stellt den Ausdrucksteil (oder Namensteil) einer Ausdrucks-Beschreibungs-Gruppe in einer Beschreibungsliste (dl-Element) dar.", "tags.em": "Das em-Element stellt eine Hervorhebung seiner Inhalte dar.", "tags.embed": "Das embed-Element stellt einen Einbindungspunkt für eine externe Anwendung (normalerweise Nicht-HTML) oder interaktiven Inhalt bereit.", "tags.fieldset": "Das fieldset-Element stellt eine Sammlung von Formularsteuerelementen dar, die optional unter einem gemeinsamen Namen gruppiert sind.", "tags.figcaption": "Das figcaption-Element stellt einen Titel oder eine Legende für den restlichen Inhalt des übergeordneten figure-Elements des figcaption-Elements dar (wenn vorhanden).", "tags.figure": "Das figure-Element stellt Flussinhalt (optional mit einem Titel) dar, der eigenständig ist (wie ein vollständiger Satz) und auf den normalerweise aus dem Hauptfluss des Dokuments als einzelne Einheit verwiesen wird.", "tags.footer": "Das footer-Element stellt eine Fußzeile für seinen nächsten Vorgänger mit unterteilendem Inhalt oder das unterteilende Stammelement dar. Ein footer-Element enthält normalerweise Informationen zu seinem Abschnitt, z. B. zum Autor, Links zu verwandten Dokumenten, Copyrightinformationen usw.", "tags.form": "Das form-Element stellt eine Sammlung von Elementen dar, die einem Formular zugeordnet sind. Einige dieser Elemente können bearbeitbare Werte darstellen, die an einen Server für die Verarbeitung übermittelt werden können.", "tags.h1": "Das h1-Element stellt eine Abschnittsüberschrift dar.", "tags.h2": "Das h2-Element stellt eine Abschnittsüberschrift dar.", "tags.h3": "Das h3-Element stellt eine Abschnittsüberschrift dar.", "tags.h4": "Das h4-Element stellt eine Abschnittsüberschrift dar.", "tags.h5": "Das h5-Element stellt eine Abschnittsüberschrift dar.", "tags.h6": "Das h6-Element stellt eine Abschnittsüberschrift dar.", "tags.head": "Das head-Element stellt eine Sammlung von Metadaten für das Dokument dar.", "tags.header": "Das header-Element stellt einführenden Inhalt für seinen nächsten Vorgänger mit unterteilendem Inhalt oder das unterteilende Stammelement dar. Ein header-Element enthält normalerweise eine Gruppe von Einführungs- oder Navigationshilfen. Wenn der nächste Vorgänger mit unterteilendem Inhalt oder das unterteilende Stammelement das body-Element ist, gilt es für die ganze Seite.", "tags.hr": "Das hr-Element stellt einen Themawechsel auf Absatzebene (z. B. den Wechsel des Handlungsorts in einer Geschichte) oder den Übergang in ein anderes Thema innerhalb eines Abschnitts eines Referenzdokuments dar.", "tags.html": "Das html-Element stellt den Stamm eines HTML-Dokuments dar.", "tags.i": "Das i-Element stellt eine Textpassage in einem anderen Stil, Ton oder anderweitig vom normalen Text abweichende Textpassage dar. Es gibt eine andere Qualität des Texts an, z. B. eine taxonomische Bezeichnung, einen technischen Begriff, einen idiomatischen Ausdruck aus einer anderen Sprache, eine Transkription, einen Gedanken oder einen Schiffsnamen in westlichen Texten.", "tags.iframe": "Das iframe-Element stellt einen geschachtelten Browserkontext dar.", "tags.img": "Ein img-Element stellt ein Bild dar.", "tags.input": "Das input-Element stellt ein typisiertes Datenfeld dar und besitzt normalerweise ein Formularsteuerelement, damit Benutzer die Daten bearbeiten können.", "tags.ins": "Das ins-Element stellt eine Hinzufügung zum Dokument dar.", "tags.ion.checkbox": "\"checkbox\" unterscheidet sich nicht von der HTML-Kontrollkästcheneingabe. Das Element verwendet nur einen anderen Stil. \"checkbox\" verhält sich wie jedes Kontrollkästchen von AngularJS.", "tags.ion.content": "Die ionContent-Direktive stellt einen einfach zu verwendenden Inhaltsbereich bereit, der für die Verwendung der benutzerdefinierten Scroll View von Ionic oder des integrierten Überlaufbildlaufs des Browsers konfiguriert werden kann.", "tags.ion.deletebutton": "Ein untergeordnetes Element von \"ionItem\".", "tags.ion.footerbar": "Fügt eine feste Fußzeilenleiste unter Inhalt hinzu. Es kann sich auch um einen \"subfooter\" (weiter oben) handeln, wenn die Klasse \"bar-subfooter\" angewendet wird.", "tags.ion.headerbar": "Fügt eine feste Kopfzeilenleiste über Inhalt hinzu. Es kann sich auch um einen \"subheader\" (weiter unten) handeln, wenn die Klasse \"bar-subheader\" angewendet wird.", "tags.ion.infinitescroll": "Ein untergeordnetes Element von \"ionContent\" oder \"ionScroll\". Die Direktive \"ionInfiniteScroll\" ermöglicht den Aufruf einer Funktion, sobald der Benutzer den unteren Seitenrand erreicht oder sich diesem nähert.", "tags.ion.input": "\"ionInput\" ist nur für Texttypeingaben vorgesehen. Ionic verwendet ein <input Type=\"Text\">-HTML-Element innerhalb der Komponente. Dabei führt Ionic einen Zeilenumbruch aus, um Benutzeroberfläche und Interaktivität besser zu verarbeiten.", "tags.ion.item": "Ein untergeordnetes Element von \"ionList\".", "tags.ion.list": "Das List-Element ist ein häufig verwendetes Schnittstellenelement in fast jedem mobilen App. Der Inhalt kann Basistext bis hin zu Schaltflächen, Umschaltflächen, Symbolen und Miniaturansichten sein.", "tags.ion.modalview": "Das Modal-Element ist ein Inhaltsbereich, der die Hauptansicht des Benutzers vorübergehend verdecken kann. Es wird normalerweise verwendet, um eine Auswahl zu treffen oder ein Element zu bearbeiten.", "tags.ion.navbackbutton": "Ein untergeordnetes Element von \"ionNavBar\". Es erstellt eine Schaltfläche \"Zurück\" in einer \"ionNavBar\". Die Schaltfläche \"Zurück\" wird angezeigt, wenn der Benutzer im aktuellen Navigationsstapel zurückgehen kann.", "tags.ion.navbar": "Wenn Sie eine ionNavView-Direktive verwenden, können Sie auch eine <ion-nav-bar> erstellen. Auf diese Weise wird eine obere Leiste erstellt, die aktualisiert wird, wenn sich der Zustand der Anwendung ändert.", "tags.ion.navbuttons": "Ein untergeordnetes Element von \"ionNavView\". Verwenden Sie \"ionNavButtons\", um die Schaltflächen auf der \"ionNavBar\" aus einer \"ionView\" festzulegen.", "tags.ion.navtitle": "Ein untergeordnetes Element von \"ionNavView\". Die ionNavTitle-Direktive ersetzt einen ionNavBar-Titeltext durch benutzerdefinierten HTML-Text aus in einer ionView Vorlage.", "tags.ion.navview": "Die ionNavView-Direktive wird zum Rendern von Vorlagen in Ihrer Anwendung verwendet. Jede Vorlage ist Teil eines Zustands. Zustände werden normalerweise einer URL zugeordnet und programmgesteuert mithilfe von \"angular-ui-router\" definiert.", "tags.ion.optionbutton": "Ein untergeordnetes Element von \"ionItem\". Erstellt ein Optionsfeld in einem Listenelement, das angezeigt wird, wenn der Benutzer das Element nach links wischt.", "tags.ion.pane": "Ein einfacher Container, der Inhalt ohne Nebenwirkungen aufnimmt. Fügt dem Element die Klasse \"pane\" hinzu.", "tags.ion.popoverview": "Das Popover-Element ist eine Ansicht, die über dem Inhalt einer App frei angeordnet ist. Mit Popover-Elementen können auf einfache Weise Informationen für Benutzer bereitgestellt oder von Benutzern erfasst werden.", "tags.ion.radio": "Die ionRadio-Direktive unterscheidet sich nicht von der HTML-Optionsfeldeingabe. Das Element verwendet nur einen anderen Stil. \"ionRadio\" verhält sich wie jede Optionsfeldeingabe von AngularJS.", "tags.ion.refresher": "Ein untergeordnetes Element von \"ionContent\" oder \"ionScroll\". Ermöglicht das Hinzufügen von \"pull-to-refresh\" zu einer \"scrollView\". Platzieren Sie dieses Element als erstes untergeordnetes Element des Elements \"ionContent\" oder \"ionScroll\".", "tags.ion.reorderbutton": "Ein untergeordnetes Element von \"ionItem\".", "tags.ion.scroll": "Erstellt einen bildlauffähigen Container für alle darin enthaltenen Inhalte.", "tags.ion.sidemenu": "Ein untergeordnetes Element von \"ionSideMenus\". Ein Container für ein Seitenmenü. Ein gleichgeordnetes Element einer ionSideMenuContent-Direktive.", "tags.ion.sidemenucontent": "Ein untergeordnetes Element von \"ionSideMenus\". Ein Container für den sichtbaren Hauptinhalt. Ein gleichgeordnetes Element von mindestens einer ionSideMenu-Direktive.", "tags.ion.sidemenus": "Ein Containerelement für mindestens ein Seitenmenü und den Hauptinhalt. Ermöglicht das Umschalten des Menüs auf der linken und/oder rechten Seite durch Nebeneinanderziehen des Hauptinhaltsbereichs.", "tags.ion.slide": "Ein untergeordnetes Element von \"ionSlideBox\". Zeigt eine Folie innerhalb eines slidebox-Elements an.", "tags.ion.slidebox": "Eine SlideBox ist ein mehrseitiger Container, in dem jede Seite gewischt oder gezogen werden kann.", "tags.ion.spinner": "Die ionSpinner-Direktive stellt eine Vielzahl von animierten Drehfeldern bereit.", "tags.ion.tab": "Ein untergeordnetes Element von \"ionTabs\". Es enthält den Inhalt einer Registerkarte. Der Inhalt ist nur vorhanden, während die angegebene Registerkarte ausgewählt ist.", "tags.ion.tabs": "Stellt eine Benutzeroberfläche mit mehreren Registerkarten, einer Registerkartenleiste und einer Sammlung von \"Seiten\" bereit, die mit der TAB-TASTE durchlaufen werden kann.", "tags.ion.title": "\"ion-title\" ist eine Komponente, die den Titel von \"ionNavbar\" festlegt.", "tags.ion.toggle": "Ein toggle-Element ist ein animierter Schalter, der ein angegebenes Modell an einen booleschen Wert bindet. Ermöglicht das Ziehen des Schalterknopfs. Das toggle-Element verhält sich wie jedes andere Kontrollkästchen von AngularJS.", "tags.ion.view": "Ein untergeordnetes Element von \"ionNavView\". Ein Container für Anzeigeinhalt und alle Navigations- und Kopfzeilenleisten-Informationen.", "tags.kbd": "Das kbd-Element stellt eine Benutzereingabe dar (normalerweise eine Eingabe über die Tastatur, es kann jedoch auch zum Darstellen anderer Eingaben (z. B. Sprachbefehle) verwendet werden).", "tags.label": "Das label-Element stellt eine Beschriftung in einer Benutzeroberfläche dar. Die Beschriftung kann einem bestimmten Formularsteuerelement zugeordnet werden, das als das Beschriftungssteuerelement des label-Elements bezeichnet wird. Dies geschieht mithilfe des for-Attributs oder durch Positionieren des Formularsteuerelements im label-Element selbst.", "tags.legend": "Das legend-Element stellt eine Beschriftung für den restlichen Inhalt des übergeordneten fieldset-Elements des legend-Elements dar, wenn vorhanden.", "tags.li": "Das li-Element stellt ein Listenelement dar. Wenn sein übergeordnetes Element ein ol-, ul- oder menu-Element ist, ist das Element ein Element der Liste des übergeordneten Elements wie für diese Elemente definiert. Andernfalls besitzt das Listenelement keine definierte listenbezogene Beziehung zu einem anderen li-Element.", "tags.link": "Das link-Element ermöglicht Autoren das Verknüpfen Ihres Dokuments mit anderen Ressourcen.", "tags.main": "Das main-Element stellt den Hauptinhalt des Textkörpers eines Dokuments oder einer Anwendung dar. Der Hauptinhaltsbereich besteht aus Inhalt, der sich unmittelbar auf das zentrale Thema eines Dokuments oder die zentrale Funktion einer Anwendung bezieht oder diese(s) erweitert.", "tags.map": "Das map-Element definiert (zusammen mit einem img-Element und ggf. Nachfolgern des area-Elements) eine Imagemap. Das Element stellt deren untergeordnete Elemente dar.", "tags.mark": "Das mark-Element stellt eine Textpassage in einem Dokument dar, die zu Referenzzwecken aufgrund ihrer Relevanz in einem anderen Kontext markiert oder hervorgehoben wird. Wenn dieses Element in einem Zitat oder anderem Textblock verwendet wird, auf das bzw. den im Text verwiesen wird, gibt es eine Hervorhebung an, die ursprünglich nicht vorhanden war, dann jedoch hinzugefügt wurde, um die Aufmerksamkeit des Lesers auf einen Textteil zu lenken, der vom ursprünglichen Autor beim Schreiben des Texts ggf. nicht als wichtig betrachtet wurde, jetzt aber unerwarteterweise genauer überprüft wird. Wenn dieses Element im Haupttext eines Dokuments verwendet wird, gibt es einen Teils des Dokuments an, der aufgrund seiner Relevanz für die aktuelle Aktivität des Benutzers hervorgehoben wird.", "tags.meta": "Das meta-Element stellt verschiedene Typen von Metadaten dar, die nicht mithilfe der title-, base-, link-, style- und script-Elemente ausgedrückt werden können.", "tags.meter": "Das meter-Element stellt eine skalare Messgröße in einem bekannten Bereich oder einen Teilwert dar. Beispiele: Datenträgerauslastung, die Relevanz eines Abfrageergebnisses oder der Prozentsatz der Wähler, die für einen bestimmten Kandidaten gestimmt haben.", "tags.nav": "Das nav-Element stellt einen Abschnitt einer Seite dar, der mit anderen Seiten oder mit Parts innerhalb der Seite verknüpft ist: ein Abschnitt mit Navigationslinks.", "tags.noscript": "Das noscript-Element stellt nichts dar, wenn Skripting aktiviert ist. Es stellt seine untergeordneten Elemente dar, wenn Skripting deaktiviert ist. Es wird zum Darstellen von verschiedenem Markup für Benutzer-Agents verwendet, die Skripting unterstützen bzw. nicht unterstützen, indem die Analyse des Dokuments beeinflusst wird.", "tags.object": "Das object-Element kann eine externe Ressource darstellen, die abhängig vom Typ der Ressource als Bild, als geschachtelter Browserkontext oder als externe Ressource behandelt wird, die von einem Plug-In verarbeitet werden soll.", "tags.ol": "Das ol-Element stellt eine Liste mit Elementen dar. Dabei wurden die Elemente bewusst so sortiert, dass eine Änderung der Reihenfolge die Bedeutung des Dokuments ändern würde.", "tags.optgroup": "Das optgroup-Element stellt eine Gruppe von option-Elementen mit einer gemeinsamen Beschriftung dar.", "tags.option": "Das option-Element stellt eine Option in einem select-Element oder als Teil einer Liste der Vorschläge in einem datalist-Element dar.", "tags.output": "Das output-Element stellt das Ergebnis einer Berechnung dar, die von der Anwendung ausgeführt wurde, oder das Ergebnis einer Benutzeraktion.", "tags.p": "Das p-Element stellt einen Absatz dar.", "tags.param": "Das param-Element definiert Parameter für Plug-Ins, die von Objektelementen aufgerufen werden. Es selbst stellt nichts dar.", "tags.picture": "Das picture-Element ist ein Container, der seinem enthaltenen img-Element mehrere Quellen bereitstellt, damit Autoren den Benutzer-Agent deklarativ steuern oder ihm Hinweise geben können, welche Bildressource basierend auf der Bildschirm-Pixeldichte, der Viewportgröße, den Bildformat und anderen Faktoren verwendet werden sollen. Es stellt die untergeordneten Elemente dar.", "tags.pre": "Das pre-Element stellt einen Block von vorformatiertem Text dar, in dem die Struktur durch typografische Konventionen und nicht durch Elemente dargestellt wird.", "tags.progress": "Das progress-Element stellt den Fortschritt eines Tasks dar. Der Fortschritt ist unbestimmt – er findet statt, es ist jedoch nicht klar, welche Aufgaben bis zum Abschluss des Tasks verbleiben (z. B., weil der Task auf die Antwort eines Remotehosts wartet) –, oder der Fortschritt ist eine Zahl in einem Bereich zwischen null und einem Maximalwert. Im letztgenannten Fall wird angegeben, welcher Prozentsatz der Aufgaben bis jetzt abgeschlossen wurde.", "tags.q": "Das q-Element stellt Formulierungsinhalt dar, der aus einer anderen Quelle zitiert wird.", "tags.rb": "Das rb-Element markiert die Basistextkomponente einer Ruby-Anmerkung. Wenn es sich um ein untergeordnetes Element eines Ruby-Elements handelt, stellt es selbst nichts dar, sein übergeordnetes Ruby-Element verwendet es aber bei der Bestimmung dessen, was es darstellt.", "tags.rp": "Das rp-Element stellt Fallbacktext bereit, der von Benutzer-Agents angezeigt werden soll, die keine Ruby-Anmerkungen unterstützen. Eine weit verbreitete Konvention besteht darin, die Ruby-Textkomponente einer Ruby-Anmerkung in runde Klammern einzuschließen.", "tags.rt": "Das rt-Element markiert die Ruby-Textkomponente einer Ruby-Anmerkung. Wenn es sich um ein untergeordnetes Element eines Ruby-Elements oder eines rtc-Elements handelt, das selbst das untergeordnete Element eines Ruby-Elements ist, stellt es selbst nichts dar, sein Ruby-Vorgängerelement verwendet es aber bei der Bestimmung dessen, was es darstellt.", "tags.ruby": "Das ruby-Element ermöglicht, dass mindestens ein Bereich von Formulierungsinhalt mit Ruby-Anmerkungen markiert wird. Ruby-Anmerkungen sind kurze Texte, die neben dem Basistext angezeigt werden. Sie werden hauptsächlich in ostasiatischer Typografie als Hinweise für die Aussprache verwendet oder enthalten andere Anmerkungen. Im Japanischen wird diese Form der Typografie als Furigana bezeichnet. Ruby-Text kann auf jeder Seite (manchmal auch auf beiden Seiten) des Basistexts angezeigt werden, und seine Position kann mithilfe von CSS gesteuert werden. Eine umfassendere Einführung in Ruby finden Sie in den Anwendungsfällen, im Dokument \"Exploratory Approaches for Ruby Markup\" sowie in \"CSS Ruby Module Level 1\". [RUBY-UC] [CSSRUBY]", "tags.s": "Das s-Element stellt Inhalte dar, die nicht mehr richtig oder nicht mehr relevant sind.", "tags.samp": "Das samp-Element stellt Beispieldaten oder Ausgabe in Anführungszeichen aus einem anderen Programm oder Computersystem dar.", "tags.script": "Das script-Element ermöglicht Autoren das Einschließen von dynamischen Skript- und Datenblöcken in ihre Dokumente. Das Element stellt keinen Inhalt für den Benutzer dar.", "tags.section": "Das section-Element stellt einen generischen Abschnitt eines Dokuments oder einer Anwendung dar. Ein Abschnitt ist in diesem Kontext eine thematische Gruppierung von Inhalten. Das Thema jedes Abschnitts sollte identifiziert werden – normalerweise durch Einschließen einer Überschrift (h1- bis h6-Element) als untergeordnetes Element des section-Elements.", "tags.select": "Das select-Element stellt ein Steuerelement für die Auswahl aus einer Sammlung von Optionen dar.", "tags.small": "Das small-Element stellt seitliche Kommentare dar, z. B. mit einem kleinen Schriftgrad.", "tags.source": "Das source-Element ermöglicht Autoren das Angeben mehrerer alternativer Medienressourcen für media-Elemente. Es stellt selbst nichts dar.", "tags.span": "Das span-Element bedeutet selbst nichts. Es kann jedoch nützlich sein, wenn es zusammen mit den globalen Attributen verwendet wird, z. B. mit class, lang oder dir. Es stellt deren untergeordneten Elemente dar.", "tags.strong": "Das strong-Element stellt hohe Wichtigkeit, große Bedeutung oder Dringlichkeit seiner Inhalte dar.", "tags.style": "Das style-Element ermöglicht Autoren das Einbetten von Formatierungsinformationen in ihre Dokumente. Das style-Element ist eine von mehreren Eingaben für das Formatierungsverarbeitungsmodell. Das Element stellt keinen Inhalt für den Benutzer dar.", "tags.sub": "Das sub-Element stellt ein tiefgestelltes Zeichen dar.", "tags.summary": "Das summary-Element stellt eine Zusammenfassung, eine Beschriftung oder eine Legende für den restlichen Inhalt des übergeordneten details-Elements (wenn vorhanden) des summary-Elements dar.", "tags.sup": "Das sup-Element stellt ein hochgestelltes Zeichen dar.", "tags.table": "Das table-Element stellt Daten mit mehreren Dimensionen in der Form einer Tabelle dar.", "tags.tbody": "Das tbody-Element stellt einen Zeilenblock dar, der aus Datentext für das übergeordnete Tabellenelement besteht, wenn das tbody-Element ein übergeordnetes Element besitzt und eine Tabelle ist.", "tags.td": "Das td-Element stellt eine Datenzelle in einer Tabelle dar.", "tags.template": "Das template-Element wird zum Deklarieren von HTML-Fragmenten verwendet, die geklont und mithilfe von Skript in das Dokument eingefügt werden können.", "tags.textarea": "Das textarea-Element stellt ein Bearbeitungssteuerelement für mehrzeiligen unformatierten Text für den raw-Wert des Elements dar. Der Inhalt des Steuerelements stellt den Standardwert des Steuerelements dar.", "tags.tfoot": "Das tfoot-Element stellt den Zeilenblock dar, der aus den Spaltenzusammenfassungen (Fußzeilen) für das übergeordnete Tabellenelement besteht, wenn das tfoot-Element ein übergeordnetes Element besitzt und eine Tabelle ist.", "tags.th": "Das th-Element stellt eine Kopfzeilenzelle in einer Tabelle dar.", "tags.thead": "Das thead-Element stellt einen Zeilenblock dar, der aus den Spaltenbeschriftungen (Kopfzeilen) für das übergeordnete Tabellenelement besteht, wenn das thead-Element ein übergeordnetes Element besitzt und eine Tabelle ist.", "tags.time": "Das time-Element stellt seinen Inhalt zusammen mit einer maschinenlesbaren Form dieses Inhalts im datetime-Attribut dar. Die Art des Inhalts ist wie unten beschrieben auf verschiedene Arten von Datumsangaben, Uhrzeitangaben, Zeitzonenoffsets und Dauerangaben eingeschränkt.", "tags.title": "Das title-Element stellt den Titel oder Namen des Dokuments dar. Autoren sollten Titel verwenden, die ihre Dokumente selbst dann identifizieren, wenn sie außerhalb des Kontexts verwendet werden, z. B. im Verlauf oder den Lesezeichen eines Benutzers oder in Suchergebnissen. Der Titel eines Dokuments unterscheidet sich häufig von seiner ersten Überschrift, da die erste Überschrift außerhalb des Kontexts nicht eigenständig sein muss.", "tags.tr": "Das tr-Element stellt eine Zeile mit Zellen in einer Tabelle dar.", "tags.track": "Das track-Element ermöglicht Autoren das Angeben expliziter Textspuren mit externer Zeitsteuerung für media-Elemente. Es stellt selbst nichts dar.", "tags.u": "Das u-Element stellt eine Textpassage mit einer unartikulierten, jedoch ausdrücklich gerenderten Anmerkung dar, die kein Text ist, z. B. ein Eigenname in chinesischem Text (eine Markierung eines chinesischen Eigennamens) oder orthografisch falscher Text.", "tags.ul": "Das ul-Element stellt eine Liste von Elementen dar. Dabei ist die Reihenfolge der Elemente unwichtig – eine Änderung der Reihenfolge würde die Bedeutung des Dokuments nicht wesentlich ändern.", "tags.var": "Das var-Element stellt eine Variable dar. Dabei kann es sich um eine tatsächliche Variable in einem mathematischen Ausdruck oder Programmierkontext, einen Bezeichner, der eine Konstante darstellt, ein Symbol, das eine physische Menge identifiziert, einen Funktionsparameter oder einfach um einen Ausdruck handeln, der als Platzhalter im Text verwendet wird.", "tags.video": "Ein video-Element wird für die Wiedergabe von Videos oder Filmen sowie Audiodateien mit Untertiteln verwendet.", "tags.wbr": "Das wbr-Element stellt eine Gelegenheit für einen Zeilenumbruch dar." }
i18n/deu/src/vs/languages/html/common/htmlTags.i18n.json
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.000261490058619529, 0.00017266024951823056, 0.00016297602269332856, 0.00016451282135676593, 0.000024402974304393865 ]
{ "id": 5, "code_window": [ "\t\treturn this.session.setVariable({\n", "\t\t\tname: variable.name,\n", "\t\t\tvalue,\n", "\t\t\tvariablesReference: (<model.Variable>variable).parent.reference\n", "\t\t}).then(response => {\n", "\t\t\tvariable.value = response.body.value;\n", "\t\t\t// Evaluate all watch expressions again since changing variable value might have changed some #8118.\n", "\t\t\treturn this.setFocusedStackFrameAndEvaluate(this.viewModel.getFocusedStackFrame());\n", "\t\t}, err => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (response && response.body) {\n", "\t\t\t\tvariable.value = response.body.value;\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 510 }
If you intend to install Octicons locally, install `octicons-local.ttf`. It should appear as “github-octicons” in your font list. It is specially designed not to conflict with GitHub's web fonts.
src/vs/base/browser/ui/octiconLabel/octicons/README.md
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017149123596027493, 0.00017149123596027493, 0.00017149123596027493, 0.00017149123596027493, 0 ]
{ "id": 6, "code_window": [ "\t\tif (source.inMemory) {\n", "\t\t\t// internal module\n", "\t\t\tif (source.reference !== 0 && this.session && source.available) {\n", "\t\t\t\treturn this.session.source({ sourceReference: source.reference }).then(response => {\n", "\t\t\t\t\tconst mime = response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0];\n", "\t\t\t\t\treturn this.getDebugStringEditorInput(source, response.body.content, mime);\n", "\t\t\t\t}, (err: DebugProtocol.ErrorResponse) => {\n", "\t\t\t\t\t// Display the error from debug adapter using a temporary editor #8836\n", "\t\t\t\t\treturn this.getDebugErrorEditorInput(source, err.message);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tconst mime = response && response.body && response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0];\n", "\t\t\t\t\tconst inputValue = response && response.body ? response.body.content : '';\n", "\t\t\t\t\treturn this.getDebugStringEditorInput(source, inputValue, mime);\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 840 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import nls = require('vs/nls'); import lifecycle = require('vs/base/common/lifecycle'); import {guessMimeTypes} from 'vs/base/common/mime'; import Event, {Emitter} from 'vs/base/common/event'; import uri from 'vs/base/common/uri'; import {RunOnceScheduler} from 'vs/base/common/async'; import {Action} from 'vs/base/common/actions'; import arrays = require('vs/base/common/arrays'); import types = require('vs/base/common/types'); import errors = require('vs/base/common/errors'); import severity from 'vs/base/common/severity'; import {TPromise} from 'vs/base/common/winjs.base'; import aria = require('vs/base/browser/ui/aria/aria'); import editorbrowser = require('vs/editor/browser/editorBrowser'); import {ISuggestion} from 'vs/editor/common/modes'; import {Position} from 'vs/editor/common/core/position'; import {IContextKeyService, IContextKey} from 'vs/platform/contextkey/common/contextkey'; import {IMarkerService} from 'vs/platform/markers/common/markers'; import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle'; import {IExtensionService} from 'vs/platform/extensions/common/extensions'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {IFileService, FileChangesEvent, FileChangeType, EventType} from 'vs/platform/files/common/files'; import {IEventService} from 'vs/platform/event/common/event'; import {IMessageService, CloseAction} from 'vs/platform/message/common/message'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {TelemetryService} from 'vs/platform/telemetry/common/telemetryService'; import {TelemetryAppenderClient} from 'vs/platform/telemetry/common/telemetryIpc'; import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage'; import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService'; import {asFileEditorInput} from 'vs/workbench/common/editor'; import debug = require('vs/workbench/parts/debug/common/debug'); import {RawDebugSession} from 'vs/workbench/parts/debug/electron-browser/rawDebugSession'; import model = require('vs/workbench/parts/debug/common/debugModel'); import {DebugStringEditorInput, DebugErrorEditorInput} from 'vs/workbench/parts/debug/browser/debugEditorInputs'; import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel'); import debugactions = require('vs/workbench/parts/debug/browser/debugActions'); import {ConfigurationManager} from 'vs/workbench/parts/debug/node/debugConfigurationManager'; import {Source} from 'vs/workbench/parts/debug/common/debugSource'; import {ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary} from 'vs/workbench/parts/tasks/common/taskService'; import {TaskError, TaskErrors} from 'vs/workbench/parts/tasks/common/taskSystem'; import {IViewletService} from 'vs/workbench/services/viewlet/common/viewletService'; import {IPanelService} from 'vs/workbench/services/panel/common/panelService'; import {IPartService} from 'vs/workbench/services/part/common/partService'; import {ITextFileService} from 'vs/workbench/parts/files/common/files'; import {IConfigurationService} from 'vs/platform/configuration/common/configuration'; import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {IWindowService, IBroadcast} from 'vs/workbench/services/window/electron-browser/windowService'; import {ILogEntry, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL} from 'vs/workbench/services/thread/electron-browser/threadService'; import {ipcRenderer as ipc} from 'electron'; import {Client} from 'vs/base/parts/ipc/node/ipc.cp'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname'; export class DebugService implements debug.IDebugService { public _serviceBrand: any; private _state: debug.State; private _onDidChangeState: Emitter<debug.State>; private session: RawDebugSession; private model: model.Model; private viewModel: viewmodel.ViewModel; private configurationManager: ConfigurationManager; private customTelemetryService: ITelemetryService; private lastTaskEvent: TaskEvent; private toDispose: lifecycle.IDisposable[]; private toDisposeOnSessionEnd: lifecycle.IDisposable[]; private inDebugMode: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: { [uri: string]: boolean }; constructor( @IStorageService private storageService: IStorageService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @ITextFileService private textFileService: ITextFileService, @IViewletService private viewletService: IViewletService, @IPanelService private panelService: IPanelService, @IFileService private fileService: IFileService, @IMessageService private messageService: IMessageService, @IPartService private partService: IPartService, @IWindowService private windowService: IWindowService, @ITelemetryService private telemetryService: ITelemetryService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IEventService eventService: IEventService, @ILifecycleService private lifecycleService: ILifecycleService, @IInstantiationService private instantiationService: IInstantiationService, @IExtensionService private extensionService: IExtensionService, @IMarkerService private markerService: IMarkerService, @ITaskService private taskService: ITaskService, @IConfigurationService private configurationService: IConfigurationService ) { this.toDispose = []; this.toDisposeOnSessionEnd = []; this.session = null; this.breakpointsToSendOnResourceSaved = {}; this._state = debug.State.Inactive; this._onDidChangeState = new Emitter<debug.State>(); if (!this.contextService.getWorkspace()) { this._state = debug.State.Disabled; } this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, 'null')); this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadWatchExpressions()); this.toDispose.push(this.model); this.viewModel = new viewmodel.ViewModel(); this.registerListeners(eventService, lifecycleService); } private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void { this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e))); if (this.taskService) { this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => { this.lastTaskEvent = e; })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => { if (e.type === TaskType.SingleRun) { this.lastTaskEvent = null; } })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => { this.lastTaskEvent = null; })); } lifecycleService.onShutdown(this.store, this); lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.windowService.onBroadcast(this.onBroadcast, this)); } private onBroadcast(broadcast: IBroadcast): void { // attach: PH is ready to be attached to if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) { this.rawAttach(broadcast.payload.port); return; } if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) { this.onSessionEnd(); return; } // from this point on we require an active session let session = this.getActiveSession(); if (!session || session.configuration.type !== 'extensionHost') { return; // we are only intersted if we have an active debug session for extensionHost } // a plugin logged output, show it inside the REPL if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) { let extensionOutput: ILogEntry = broadcast.payload; let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info; let args: any[] = []; try { let parsed = JSON.parse(extensionOutput.arguments); args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o])); } catch (error) { args.push(extensionOutput.arguments); } // add output for each argument logged let simpleVals: any[] = []; for (let i = 0; i < args.length; i++) { let a = args[i]; // undefined gets printed as 'undefined' if (typeof a === 'undefined') { simpleVals.push('undefined'); } // null gets printed as 'null' else if (a === null) { simpleVals.push('null'); } // objects & arrays are special because we want to inspect them in the REPL else if (types.isObject(a) || Array.isArray(a)) { // flush any existing simple values logged if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); simpleVals = []; } // show object this.logToRepl(a, sev); } // string: watch out for % replacement directive // string substitution and formatting @ https://developer.chrome.com/devtools/docs/console else if (typeof a === 'string') { let buf = ''; for (let j = 0, len = a.length; j < len; j++) { if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) { i++; // read over substitution buf += !types.isUndefinedOrNull(args[i]) ? args[i] : ''; // replace j++; // read over directive } else { buf += a[j]; } } simpleVals.push(buf); } // number or boolean is joined together else { simpleVals.push(a); } } // flush simple values if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); } } } private registerSessionListeners(): void { this.toDisposeOnSessionEnd.push(this.session); this.toDisposeOnSessionEnd.push(this.session.onDidInitialize(event => { aria.status(nls.localize('debuggingStarted', "Debugging started.")); this.sendAllBreakpoints().then(() => { if (this.session.configuration.capabilities.supportsConfigurationDoneRequest) { this.session.configurationDone().done(null, e => { // Disconnect the debug session on configuration done error #10596 if (this.session) { this.session.disconnect().done(null, errors.onUnexpectedError); } this.messageService.show(severity.Error, e.message); }); } }); })); this.toDisposeOnSessionEnd.push(this.session.onDidStop(event => { this.setStateAndEmit(debug.State.Stopped); const threadId = event.body.threadId; this.getThreadData().done(() => { this.model.rawUpdate({ threadId, stoppedDetails: event.body, allThreadsStopped: event.body.allThreadsStopped }); const thread = this.model.getThreads()[threadId]; thread.getCallStack(this).then(callStack => { if (callStack.length > 0) { // focus first stack frame from top that has source location const stackFrameToFocus = arrays.first(callStack, sf => sf.source && sf.source.available, callStack[0]); this.setFocusedStackFrameAndEvaluate(stackFrameToFocus, thread).done(null, errors.onUnexpectedError); this.windowService.getWindow().focus(); aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber)); return this.openOrRevealSource(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false); } else { this.setFocusedStackFrameAndEvaluate(null, thread).done(null, errors.onUnexpectedError); } }); }, errors.onUnexpectedError); })); this.toDisposeOnSessionEnd.push(this.session.onDidThread(event => { if (event.body.reason === 'started') { this.getThreadData().done(null, errors.onUnexpectedError); } else if (event.body.reason === 'exited') { this.model.clearThreads(true, event.body.threadId); } })); this.toDisposeOnSessionEnd.push(this.session.onDidTerminateDebugee(event => { aria.status(nls.localize('debuggingStopped', "Debugging stopped.")); if (this.session && this.session.getId() === event.body.sessionId) { if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) { this.restartSession().done(null, err => this.messageService.show(severity.Error, err.message)); } else { this.session.disconnect().done(null, errors.onUnexpectedError); } } })); this.toDisposeOnSessionEnd.push(this.session.onDidContinued(event => { this.lazyTransitionToRunningState(event.body.allThreadsContinued ? undefined : event.body.threadId); })); this.toDisposeOnSessionEnd.push(this.session.onDidOutput(event => { if (event.body && event.body.category === 'telemetry') { // only log telemetry events from debug adapter if the adapter provided the telemetry key // and the user opted in telemetry if (this.customTelemetryService && this.telemetryService.isOptedIn) { this.customTelemetryService.publicLog(event.body.output, event.body.data); } } else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) { this.onOutput(event); } })); this.toDisposeOnSessionEnd.push(this.session.onDidBreakpoint(event => { const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined; const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (breakpoint) { this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint }); } else { const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (functionBreakpoint) { this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint }); } } })); this.toDisposeOnSessionEnd.push(this.session.onDidExitAdapter(event => { // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (this.session.configuration.type === 'extensionHost' && this._state === debug.State.RunningNoDebug) { ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath); } if (this.session && this.session.getId() === event.body.sessionId) { this.onSessionEnd(); } })); } private onOutput(event: DebugProtocol.OutputEvent): void { const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info; this.appendReplOutput(event.body.output, outputSeverity); } private getThreadData(): TPromise<void> { return this.session.threads().then(response => { response.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread })); }); } private loadBreakpoints(): debug.IBreakpoint[] { let result: debug.IBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }), breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] { let result: debug.IFunctionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new model.FunctionBreakpoint(fb.name, fb.enabled); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] { let result: debug.IExceptionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadWatchExpressions(): model.Expression[] { let result: model.Expression[]; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string } ) => { return new model.Expression(watchStoredData.name, false, watchStoredData.id); }); } catch (e) { } return result || []; } public get state(): debug.State { return this._state; } public get onDidChangeState(): Event<debug.State> { return this._onDidChangeState.event; } private setStateAndEmit(newState: debug.State): void { this._state = newState; this._onDidChangeState.fire(newState); } public get enabled(): boolean { return !!this.contextService.getWorkspace(); } public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame, thread?: debug.IThread): TPromise<void> { if (!thread && focusedStackFrame) { thread = this.model.getThreads()[focusedStackFrame.threadId]; } this.viewModel.setFocusedStackFrame(focusedStackFrame, thread); if (focusedStackFrame) { return this.model.evaluateWatchExpressions(this.session, focusedStackFrame); } else { this.model.clearWatchExpressionValues(); return TPromise.as(null); } } public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof model.Breakpoint) { return this.sendBreakpoints((<model.Breakpoint>breakpoint).source.uri); } else if (breakpoint instanceof model.FunctionBreakpoint) { return this.sendFunctionBreakpoints(); } return this.sendExceptionBreakpoints(); } this.model.enableOrDisableAllBreakpoints(enable); return this.sendAllBreakpoints(); } public addBreakpoints(rawBreakpoints: debug.IRawBreakpoint[]): TPromise<void[]> { this.model.addBreakpoints(rawBreakpoints); const uris = arrays.distinct(rawBreakpoints, raw => raw.uri.toString()).map(raw => raw.uri); rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, rbp.uri.fsPath))); return TPromise.join(uris.map(uri => this.sendBreakpoints(uri))); } public removeBreakpoints(id?: string): TPromise<any> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.source.uri.fsPath))); const urisToClear = arrays.distinct(toRemove, bp => bp.source.uri.toString()).map(bp => bp.source.uri); this.model.removeBreakpoints(toRemove); return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri))); } public setBreakpointsActivated(activated: boolean): TPromise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } public addFunctionBreakpoint(): void { this.model.addFunctionBreakpoint(''); } public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> { this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } }); return this.sendFunctionBreakpoints(); } public removeFunctionBreakpoints(id?: string): TPromise<void> { this.model.removeFunctionBreakpoints(id); return this.sendFunctionBreakpoints(); } public addReplExpression(name: string): TPromise<void> { this.telemetryService.publicLog('debugService/addReplExpression'); const focussedStackFrame = this.viewModel.getFocusedStackFrame(); return this.model.addReplExpression(this.session, focussedStackFrame, name) // Evaluate all watch expressions again since repl evaluation might have changed some. .then(() => this.setFocusedStackFrameAndEvaluate(focussedStackFrame)); } public logToRepl(value: string | { [key: string]: any }, severity?: severity): void { this.model.logToRepl(value, severity); } public appendReplOutput(value: string, severity?: severity): void { this.model.appendReplOutput(value, severity); } public removeReplExpressions(): void { this.model.removeReplExpressions(); } public setVariable(variable: debug.IExpression, value: string): TPromise<any> { if (!this.session || !(variable instanceof model.Variable)) { return TPromise.as(null); } return this.session.setVariable({ name: variable.name, value, variablesReference: (<model.Variable>variable).parent.reference }).then(response => { variable.value = response.body.value; // Evaluate all watch expressions again since changing variable value might have changed some #8118. return this.setFocusedStackFrameAndEvaluate(this.viewModel.getFocusedStackFrame()); }, err => { (<model.Variable>variable).errorMessage = err.message; }); } public addWatchExpression(name: string): TPromise<void> { return this.model.addWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), name); } public renameWatchExpression(id: string, newName: string): TPromise<void> { return this.model.renameWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), id, newName); } public removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); } public createSession(noDebug: boolean, configuration?: debug.IConfig): TPromise<any> { this.removeReplExpressions(); return this.textFileService.saveAll() // make sure all dirty files are saved .then(() => this.configurationService.reloadConfiguration() // make sure configuration is up to date .then(() => this.extensionService.onReady() .then(() => this.configurationManager.setConfiguration(configuration || this.configurationManager.configurationName) .then(() => this.configurationManager.resolveInteractiveVariables()) .then(resolvedConfiguration => { configuration = resolvedConfiguration; if (!configuration) { return this.configurationManager.openConfigFile(false).then(openend => { if (openend) { this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application.")); } }); } if (configuration.silentlyAbort) { return; } configuration.noDebug = noDebug; if (!this.configurationManager.adapter) { return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type))) : TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."), { actions: [this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), CloseAction] })); } return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => { const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0; if (successExitCode || (errorCount === 0 && !failureExitCode)) { return this.doCreateSession(configuration); } this.messageService.show(severity.Error, { message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode), actions: [new Action('debug.continue', nls.localize('debugAnyway', "Debug Anyway"), null, true, () => { this.messageService.hideAll(); return this.doCreateSession(configuration); }), CloseAction] }); }, (err: TaskError) => { if (err.code !== TaskErrors.NotConfigured) { throw err; } this.messageService.show(err.severity, { message: err.message, actions: [this.taskService.configureAction(), CloseAction] }); }); })))); } private doCreateSession(configuration: debug.IExtHostConfig): TPromise<any> { this.setStateAndEmit(debug.State.Initializing); return this.telemetryService.getTelemetryInfo().then(info => { const telemetryInfo: { [key: string]: string } = Object.create(null); telemetryInfo['common.vscodemachineid'] = info.machineId; telemetryInfo['common.vscodesessionid'] = info.sessionId; return telemetryInfo; }).then(data => { const { aiKey, type } = this.configurationManager.adapter; const publisher = this.configurationManager.adapter.extensionDescription.publisher; this.customTelemetryService = null; if (aiKey) { const client = new Client( uri.parse(require.toUrl('bootstrap')).fsPath, { serverName: 'Debug Telemetry', timeout: 1000 * 60 * 5, args: [`${ publisher }.${ type }`, JSON.stringify(data), aiKey], env: { ELECTRON_RUN_AS_NODE: 1, PIPE_LOGGING: 'true', AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp' } } ); const channel = client.getChannel('telemetryAppender'); const appender = new TelemetryAppenderClient(channel); this.toDisposeOnSessionEnd.push(client); this.customTelemetryService = new TelemetryService({ appender }, this.configurationService); } this.session = this.instantiationService.createInstance(RawDebugSession, configuration.debugServer, this.configurationManager.adapter, this.customTelemetryService); this.registerSessionListeners(); return this.session.initialize({ adapterID: configuration.type, pathFormat: 'path', linesStartAt1: true, columnsStartAt1: true, supportsVariableType: true, // #8858 supportsVariablePaging: true, // #9537 supportsRunInTerminalRequest: true // #10574 }).then((result: DebugProtocol.InitializeResponse) => { if (!this.session) { return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly"))); } this.model.setExceptionBreakpoints(this.session.configuration.capabilities.exceptionBreakpointFilters); return configuration.request === 'attach' ? this.session.attach(configuration) : this.session.launch(configuration); }).then((result: DebugProtocol.Response) => { if (!this.session) { return TPromise.as(null); } if (configuration.internalConsoleOptions === 'openOnSessionStart' || (!this.viewModel.changedWorkbenchViewState && configuration.internalConsoleOptions !== 'neverOpen')) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } if (!this.viewModel.changedWorkbenchViewState && !this.partService.isSideBarHidden()) { // We only want to change the workbench view state on the first debug session #5738 and if the side bar is not hidden this.viewModel.changedWorkbenchViewState = true; this.viewletService.openViewlet(debug.VIEWLET_ID); } // Do not change status bar to orange if we are just running without debug. if (!configuration.noDebug) { this.partService.addClass('debugging'); } this.extensionService.activateByEvent(`onDebug:${configuration.type}`).done(null, errors.onUnexpectedError); this.inDebugMode.set(true); this.lazyTransitionToRunningState(); this.telemetryService.publicLog('debugSessionStart', { type: configuration.type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: `${ this.configurationManager.adapter.extensionDescription.publisher }.${ this.configurationManager.adapter.extensionDescription.name }`, isBuiltin: this.configurationManager.adapter.extensionDescription.isBuiltin }); }).then(undefined, (error: any) => { if (error instanceof Error && error.message === 'Canceled') { // Do not show 'canceled' error messages to the user #7906 return TPromise.as(null); } this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined }); this.setStateAndEmit(debug.State.Inactive); if (this.session) { this.session.disconnect().done(null, errors.onUnexpectedError); } // Show the repl if some error got logged there #5870 if (this.model.getReplElements().length > 0) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction]; return TPromise.wrapError(errors.create(error.message, { actions })); }); }); } private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> { if (!taskName) { return TPromise.as(null); } // run a task before starting a debug session return this.taskService.tasks().then(descriptions => { const filteredTasks = descriptions.filter(task => task.name === taskName); if (filteredTasks.length !== 1) { return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), { actions: [ this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), this.taskService.configureAction(), CloseAction ] })); } // task is already running - nothing to do. if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) { return TPromise.as(null); } if (this.lastTaskEvent) { // there is a different task running currently. return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName))); } // no task running, execute the preLaunchTask. const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => { this.lastTaskEvent = null; return result; }, err => { this.lastTaskEvent = null; }); if (filteredTasks[0].isWatching) { return new TPromise((c, e) => this.taskService.addOneTimeDisposableListener(TaskServiceEvents.Inactive, () => c(null))); } return taskPromise; }); } private rawAttach(port: number): TPromise<any> { if (this.session) { return this.session.attach({ port }); } this.setStateAndEmit(debug.State.Initializing); const configuration = <debug.IExtHostConfig>this.configurationManager.configuration; return this.doCreateSession({ type: configuration.type, request: 'attach', port, sourceMaps: configuration.sourceMaps, outDir: configuration.outDir, debugServer: configuration.debugServer }); } public restartSession(): TPromise<any> { return this.session ? this.session.disconnect(true).then(() => new TPromise<void>((c, e) => { setTimeout(() => { this.createSession(false, null).then(() => c(null), err => e(err)); }, 300); }) ) : this.createSession(false, null); } public getActiveSession(): debug.IRawDebugSession { return this.session; } private onSessionEnd(): void { if (this.session) { const bpsExist = this.model.getBreakpoints().length > 0; this.telemetryService.publicLog('debugSessionStop', { type: this.session.configuration.type, success: this.session.emittedStopped || !bpsExist, sessionLengthInSeconds: this.session.getLengthInSeconds(), breakpointCount: this.model.getBreakpoints().length, watchExpressionsCount: this.model.getWatchExpressions().length }); } this.session = null; try { this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd); } catch (e) { // an internal module might be open so the dispose can throw -> ignore and continue with stop session. } this.partService.removeClass('debugging'); this.model.clearThreads(true); this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); this.setStateAndEmit(debug.State.Inactive); // set breakpoints back to unverified since the session ended. // source reference changes across sessions, so we do not use it to persist the source. const data: { [id: string]: { line: number, verified: boolean } } = {}; this.model.getBreakpoints().forEach(bp => { delete bp.source.raw.sourceReference; data[bp.getId()] = { line: bp.lineNumber, verified: false }; }); this.model.updateBreakpoints(data); this.inDebugMode.reset(); } public getModel(): debug.IModel { return this.model; } public getViewModel(): debug.IViewModel { return this.viewModel; } public openOrRevealSource(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> { const visibleEditors = this.editorService.getVisibleEditors(); for (let i = 0; i < visibleEditors.length; i++) { const fileInput = asFileEditorInput(visibleEditors[i].input); if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) || (visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) { const control = <editorbrowser.ICodeEditor>visibleEditors[i].getControl(); if (control) { control.revealLineInCenterIfOutsideViewport(lineNumber); control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }); this.editorGroupService.activateGroup(i); if (!preserveFocus) { this.editorGroupService.focusGroup(i); } } return TPromise.as(null); } } if (source.inMemory) { // internal module if (source.reference !== 0 && this.session && source.available) { return this.session.source({ sourceReference: source.reference }).then(response => { const mime = response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0]; return this.getDebugStringEditorInput(source, response.body.content, mime); }, (err: DebugProtocol.ErrorResponse) => { // Display the error from debug adapter using a temporary editor #8836 return this.getDebugErrorEditorInput(source, err.message); }).then(editorInput => { return this.editorService.openEditor(editorInput, { preserveFocus, selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 } }, sideBySide); }); } return this.sourceIsUnavailable(source, sideBySide); } return this.fileService.resolveFile(source.uri).then(() => this.editorService.openEditor({ resource: source.uri, options: { selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }, preserveFocus: preserveFocus } }, sideBySide), err => this.sourceIsUnavailable(source, sideBySide) ); } private sourceIsUnavailable(source: Source, sideBySide: boolean): TPromise<any> { this.model.sourceIsUnavailable(source); const editorInput = this.getDebugErrorEditorInput(source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.name)); return this.editorService.openEditor(editorInput, { preserveFocus: true }, sideBySide); } public getConfigurationManager(): debug.IConfigurationManager { return this.configurationManager; } public next(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.next({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public stepIn(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.stepIn({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public stepOut(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.stepOut({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public stepBack(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.stepBack({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public continue(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.continue({ threadId }).then(response => { const allThreadsContinued = response.body ? response.body.allThreadsContinued !== false : true; this.lazyTransitionToRunningState(allThreadsContinued ? undefined : threadId); }); } public pause(threadId: number): TPromise<any> { if (!this.session) { return TPromise.as(null); } return this.session.pause({ threadId }); } public restartFrame(frameId: number): TPromise<any> { if (!this.session) { return TPromise.as(null); } return this.session.restartFrame({ frameId }); } public completions(text: string, position: Position): TPromise<ISuggestion[]> { if (!this.session || !this.session.configuration.capabilities.supportsCompletionsRequest) { return TPromise.as([]); } const focussedStackFrame = this.viewModel.getFocusedStackFrame(); return this.session.completions({ frameId: focussedStackFrame ? focussedStackFrame.frameId : undefined, text, column: position.column, line: position.lineNumber }).then(response => { return !response ? [] : response.body.targets.map(item => ({ label: item.label, insertText: item.text || item.label, type: item.type })); }, err => []); } private lazyTransitionToRunningState(threadId?: number): void { let setNewFocusedStackFrameScheduler: RunOnceScheduler; const toDispose = this.session.onDidStop(e => { if (e.body.threadId === threadId || e.body.allThreadsStopped || !threadId) { setNewFocusedStackFrameScheduler.cancel(); } }); this.model.clearThreads(false, threadId); // Get a top stack frame of a stopped thread if there is any. const threads = this.model.getThreads(); const stoppedReference = Object.keys(threads).filter(ref => threads[ref].stopped).pop(); const stoppedThread = stoppedReference ? threads[parseInt(stoppedReference)] : null; const callStack = stoppedThread ? stoppedThread.getCachedCallStack() : null; const stackFrameToFocus = callStack && callStack.length > 0 ? callStack[0] : null; if (!stoppedThread) { this.setStateAndEmit(this.configurationManager.configuration.noDebug ? debug.State.RunningNoDebug : debug.State.Running); } // Do not immediatly set a new focused stack frame since that might cause unnecessery flickering // of the tree in the debug viewlet. Only set focused stack frame if no stopped event has arrived in 500ms. setNewFocusedStackFrameScheduler = new RunOnceScheduler(() => { toDispose.dispose(); aria.status(nls.localize('debuggingContinued', "Debugging continued.")); this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError); }, 500); setNewFocusedStackFrameScheduler.schedule(); } private getDebugStringEditorInput(source: Source, value: string, mtype: string): DebugStringEditorInput { const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0); this.toDisposeOnSessionEnd.push(result); return result; } private getDebugErrorEditorInput(source: Source, value: string): DebugErrorEditorInput { const result = this.instantiationService.createInstance(DebugErrorEditorInput, source.name, value); this.toDisposeOnSessionEnd.push(result); return result; } private sendAllBreakpoints(): TPromise<any> { return TPromise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri))) .then(() => this.sendFunctionBreakpoints()) // send exception breakpoints at the end since some debug adapters rely on the order .then(() => this.sendExceptionBreakpoints()); } private sendBreakpoints(modelUri: uri, sourceModified = false): TPromise<void> { if (!this.session || !this.session.readyForBreakpoints) { return TPromise.as(null); } if (this.textFileService.isDirty(modelUri)) { // Only send breakpoints for a file once it is not dirty #8077 this.breakpointsToSendOnResourceSaved[modelUri.toString()] = true; return TPromise.as(null); } const breakpointsToSend = arrays.distinct( this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()), bp => `${bp.desiredLineNumber}` ); const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, this.model); return this.session.setBreakpoints({ source: rawSource, lines: breakpointsToSend.map(bp => bp.desiredLineNumber), breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition })), sourceModified }).then(response => { const data: { [id: string]: { line?: number, verified: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateBreakpoints(data); }); } private sendFunctionBreakpoints(): TPromise<void> { if (!this.session || !this.session.readyForBreakpoints || !this.session.configuration.capabilities.supportsFunctionBreakpoints) { return TPromise.as(null); } const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => { const data: { [id: string]: { name?: string, verified?: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateFunctionBreakpoints(data); }); } private sendExceptionBreakpoints(): TPromise<any> { if (!this.session || !this.session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) { return TPromise.as(null); } const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return this.session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) }); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED))); fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved[event.resource.toString()]) { this.breakpointsToSendOnResourceSaved[event.resource.toString()] = false; this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError); } }); } private store(): void { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE); this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.configurationManager.configurationName, StorageScope.WORKSPACE); this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions().map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } public dispose(): void { this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd); this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/parts/debug/electron-browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.9984728693962097, 0.01789684034883976, 0.000161567673785612, 0.00017450755694881082, 0.13004463911056519 ]
{ "id": 6, "code_window": [ "\t\tif (source.inMemory) {\n", "\t\t\t// internal module\n", "\t\t\tif (source.reference !== 0 && this.session && source.available) {\n", "\t\t\t\treturn this.session.source({ sourceReference: source.reference }).then(response => {\n", "\t\t\t\t\tconst mime = response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0];\n", "\t\t\t\t\treturn this.getDebugStringEditorInput(source, response.body.content, mime);\n", "\t\t\t\t}, (err: DebugProtocol.ErrorResponse) => {\n", "\t\t\t\t\t// Display the error from debug adapter using a temporary editor #8836\n", "\t\t\t\t\treturn this.getDebugErrorEditorInput(source, err.message);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tconst mime = response && response.body && response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0];\n", "\t\t\t\t\tconst inputValue = response && response.body ? response.body.content : '';\n", "\t\t\t\t\treturn this.getDebugStringEditorInput(source, inputValue, mime);\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 840 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "altKey": "Alt", "altKey.long": "Alt", "cmdKey": "コマンド", "cmdKey.long": "コマンド", "ctrlKey": "Ctrl", "ctrlKey.long": "コントロール", "shiftKey": "Shift", "shiftKey.long": "Shift", "windowsKey": "Windows", "windowsKey.long": "Windows" }
i18n/jpn/src/vs/base/common/keyCodes.i18n.json
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017429172294214368, 0.0001719341380521655, 0.00016957655316218734, 0.0001719341380521655, 0.0000023575848899781704 ]
{ "id": 6, "code_window": [ "\t\tif (source.inMemory) {\n", "\t\t\t// internal module\n", "\t\t\tif (source.reference !== 0 && this.session && source.available) {\n", "\t\t\t\treturn this.session.source({ sourceReference: source.reference }).then(response => {\n", "\t\t\t\t\tconst mime = response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0];\n", "\t\t\t\t\treturn this.getDebugStringEditorInput(source, response.body.content, mime);\n", "\t\t\t\t}, (err: DebugProtocol.ErrorResponse) => {\n", "\t\t\t\t\t// Display the error from debug adapter using a temporary editor #8836\n", "\t\t\t\t\treturn this.getDebugErrorEditorInput(source, err.message);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tconst mime = response && response.body && response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0];\n", "\t\t\t\t\tconst inputValue = response && response.body ? response.body.content : '';\n", "\t\t\t\t\treturn this.getDebugStringEditorInput(source, inputValue, mime);\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 840 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as assert from 'assert'; import {renderLine, RenderLineInput} from 'vs/editor/common/viewLayout/viewLineRenderer'; import {ViewLineToken} from 'vs/editor/common/core/viewLineToken'; import {CharCode} from 'vs/base/common/charCode'; suite('viewLineRenderer.renderLine', () => { function createPart(startIndex: number, type:string): ViewLineToken { return new ViewLineToken(startIndex, type); } function assertCharacterReplacement(lineContent:string, tabSize:number, expected:string, expectedCharOffsetInPart: number[]): void { let _actual = renderLine(new RenderLineInput( lineContent, tabSize, 0, -1, 'none', false, [createPart(0, '')] )); assert.equal(_actual.output, '<span><span class="token ">' + expected + '</span></span>'); assert.deepEqual(_actual.charOffsetInPart, expectedCharOffsetInPart); } test('replaces spaces', () => { assertCharacterReplacement(' ', 4, '&nbsp;', [0, 1]); assertCharacterReplacement(' ', 4, '&nbsp;&nbsp;', [0, 1, 2]); assertCharacterReplacement('a b', 4, 'a&nbsp;&nbsp;b', [0, 1, 2, 3, 4]); }); test('escapes HTML markup', () => { assertCharacterReplacement('a<b', 4, 'a&lt;b', [0, 1, 2, 3]); assertCharacterReplacement('a>b', 4, 'a&gt;b', [0, 1, 2, 3]); assertCharacterReplacement('a&b', 4, 'a&amp;b', [0, 1, 2, 3]); }); test('replaces some bad characters', () => { assertCharacterReplacement('a\0b', 4, 'a&#00;b', [0, 1, 2, 3]); assertCharacterReplacement('a' + String.fromCharCode(CharCode.UTF8_BOM) + 'b', 4, 'a\ufffdb', [0, 1, 2, 3]); assertCharacterReplacement('a\u2028b', 4, 'a\ufffdb', [0, 1, 2, 3]); assertCharacterReplacement('a\rb', 4, 'a&#8203b', [0, 1, 2, 3]); }); test('handles tabs', () => { assertCharacterReplacement('\t', 4, '&nbsp;&nbsp;&nbsp;&nbsp;', [0, 4]); assertCharacterReplacement('x\t', 4, 'x&nbsp;&nbsp;&nbsp;', [0, 1, 4]); assertCharacterReplacement('xx\t', 4, 'xx&nbsp;&nbsp;', [0, 1, 2, 4]); assertCharacterReplacement('xxx\t', 4, 'xxx&nbsp;', [0, 1, 2, 3, 4]); assertCharacterReplacement('xxxx\t', 4, 'xxxx&nbsp;&nbsp;&nbsp;&nbsp;', [0, 1, 2, 3, 4, 8]); }); function assertParts(lineContent:string, tabSize:number, parts: ViewLineToken[], expected:string, expectedCharOffsetInPart:number[]): void { let _actual = renderLine(new RenderLineInput( lineContent, tabSize, 0, -1, 'none', false, parts )); assert.equal(_actual.output, '<span>' + expected + '</span>'); assert.deepEqual(_actual.charOffsetInPart, expectedCharOffsetInPart); } test('empty line', () => { assertParts('', 4, [], '<span>&nbsp;</span>', []); }); test('uses part type', () => { assertParts('x', 4, [createPart(0, 'y')], '<span class="token y">x</span>', [0, 1]); assertParts('x', 4, [createPart(0, 'aAbBzZ0123456789-cC')], '<span class="token aAbBzZ0123456789-cC">x</span>', [0, 1]); assertParts('x', 4, [createPart(0, '"~!@#$%^&*()\'')], '<span class="token ">x</span>', [0, 1]); }); test('two parts', () => { assertParts('xy', 4, [createPart(0, 'a'), createPart(1, 'b')], '<span class="token a">x</span><span class="token b">y</span>', [0, 0, 1]); assertParts('xyz', 4, [createPart(0, 'a'), createPart(1, 'b')], '<span class="token a">x</span><span class="token b">yz</span>', [0, 0, 1, 2]); assertParts('xyz', 4, [createPart(0, 'a'), createPart(2, 'b')], '<span class="token a">xy</span><span class="token b">z</span>', [0, 1, 0, 1]); }); test('overflow', () => { let _actual = renderLine(new RenderLineInput( 'Hello world!', 4, 10, 6, 'boundary', false, [ createPart( 0, '0'), createPart( 1, '1'), createPart( 2, '2'), createPart( 3, '3'), createPart( 4, '4'), createPart( 5, '5'), createPart( 6, '6'), createPart( 7, '7'), createPart( 8, '8'), createPart( 9, '9'), createPart(10, '10'), createPart(11, '11'), ] )); let expectedOutput = [ '<span class="token 0">H</span>', '<span class="token 1">e</span>', '<span class="token 2">l</span>', '<span class="token 3">l</span>', '<span class="token 4">o</span>', '<span class="token 5">&nbsp;&hellip;</span>' ].join(''); assert.equal(_actual.output, '<span>' + expectedOutput + '</span>'); assert.deepEqual(_actual.charOffsetInPart, [ 0, 0, 0, 0, 0, 1 ]); }); test('typical line', () => { let lineText = '\t export class Game { // http://test.com '; let lineParts = [ createPart( 0, 'block meta ts leading whitespace'), createPart( 5, 'block declaration meta modifier object storage ts'), createPart(11, 'block declaration meta object ts'), createPart(12, 'block declaration meta object storage type ts'), createPart(17, 'block declaration meta object ts'), createPart(18, 'block class declaration entity meta name object ts'), createPart(22, 'block declaration meta object ts'), createPart(23, 'delimiter curly typescript'), createPart(24, 'block body declaration meta object ts'), createPart(25, 'block body comment declaration line meta object ts'), createPart(28, 'block body comment declaration line meta object ts detected-link'), createPart(43, 'block body comment declaration line meta object ts trailing whitespace'), ]; let expectedOutput = [ '<span class="token block meta ts leading whitespace" style="width:80px">&rarr;&nbsp;&nbsp;&nbsp;&middot;&middot;&middot;&middot;</span>', '<span class="token block declaration meta modifier object storage ts">export</span>', '<span class="token block declaration meta object ts">&nbsp;</span>', '<span class="token block declaration meta object storage type ts">class</span>', '<span class="token block declaration meta object ts">&nbsp;</span>', '<span class="token block class declaration entity meta name object ts">Game</span>', '<span class="token block declaration meta object ts">&nbsp;</span>', '<span class="token delimiter curly typescript">{</span>', '<span class="token block body declaration meta object ts">&nbsp;</span>', '<span class="token block body comment declaration line meta object ts">//&nbsp;</span>', '<span class="token block body comment declaration line meta object ts detected-link">http://test.com</span>', '<span class="token block body comment declaration line meta object ts trailing whitespace" style="width:50px">&middot;&middot;&middot;&middot;&middot;</span>' ].join(''); let expectedOffsetsArr = [ [0, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5], [0], [0, 1, 2, 3, 4], [0], [0, 1, 2, 3], [0], [0], [0], [0, 1, 2], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], [0, 1, 2, 3, 4, 5], ]; let expectedOffsets = expectedOffsetsArr.reduce((prev, curr) => prev.concat(curr), []); let _actual = renderLine(new RenderLineInput( lineText, 4, 10, -1, 'boundary', false, lineParts )); assert.equal(_actual.output, '<span>' + expectedOutput + '</span>'); assert.deepEqual(_actual.charOffsetInPart, expectedOffsets); }); test('issue #2255: Weird line rendering part 1', () => { let lineText = '\t\t\tcursorStyle:\t\t\t\t\t\t(prevOpts.cursorStyle !== newOpts.cursorStyle),'; let lineParts = [ createPart( 0, 'block body decl declaration meta method object ts'), // 3 chars createPart( 3, 'block body decl declaration member meta method object ts'), // 12 chars createPart(15, 'block body decl declaration member meta method object ts'), // 6 chars createPart(21, 'delimiter paren typescript'), // 1 char createPart(22, 'block body decl declaration member meta method object ts'), // 21 chars createPart(43, 'block body comparison decl declaration keyword member meta method object operator ts'), // 2 chars createPart(45, 'block body comparison decl declaration keyword member meta method object operator ts'), // 1 char createPart(46, 'block body decl declaration member meta method object ts'), // 20 chars createPart(66, 'delimiter paren typescript'), // 1 char createPart(67, 'block body decl declaration meta method object ts'), // 2 chars ]; let expectedOutput = [ '<span class="token block body decl declaration meta method object ts">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>', '<span class="token block body decl declaration member meta method object ts">cursorStyle:</span>', '<span class="token block body decl declaration member meta method object ts">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>', '<span class="token delimiter paren typescript">(</span>', '<span class="token block body decl declaration member meta method object ts">prevOpts.cursorStyle&nbsp;</span>', '<span class="token block body comparison decl declaration keyword member meta method object operator ts">!=</span>', '<span class="token block body comparison decl declaration keyword member meta method object operator ts">=</span>', '<span class="token block body decl declaration member meta method object ts">&nbsp;newOpts.cursorStyle</span>', '<span class="token delimiter paren typescript">)</span>', '<span class="token block body decl declaration meta method object ts">,</span>', ].join(''); let expectedOffsetsArr = [ [0, 4, 8], // 3 chars [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], // 12 chars [0, 4, 8, 12, 16, 20], // 6 chars [0], // 1 char [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], // 21 chars [0, 1], // 2 chars [0], // 1 char [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19], // 20 chars [0], // 1 char [0, 1] // 2 chars ]; let expectedOffsets = expectedOffsetsArr.reduce((prev, curr) => prev.concat(curr), []); let _actual = renderLine(new RenderLineInput( lineText, 4, 10, -1, 'none', false, lineParts )); assert.equal(_actual.output, '<span>' + expectedOutput + '</span>'); assert.deepEqual(_actual.charOffsetInPart, expectedOffsets); }); test('issue #2255: Weird line rendering part 2', () => { let lineText = ' \t\t\tcursorStyle:\t\t\t\t\t\t(prevOpts.cursorStyle !== newOpts.cursorStyle),'; let lineParts = [ createPart( 0, 'block body decl declaration meta method object ts'), // 4 chars createPart( 4, 'block body decl declaration member meta method object ts'), // 12 chars createPart(16, 'block body decl declaration member meta method object ts'), // 6 chars createPart(22, 'delimiter paren typescript'), // 1 char createPart(23, 'block body decl declaration member meta method object ts'), // 21 chars createPart(44, 'block body comparison decl declaration keyword member meta method object operator ts'), // 2 chars createPart(46, 'block body comparison decl declaration keyword member meta method object operator ts'), // 1 char createPart(47, 'block body decl declaration member meta method object ts'), // 20 chars createPart(67, 'delimiter paren typescript'), // 1 char createPart(68, 'block body decl declaration meta method object ts'), // 2 chars ]; let expectedOutput = [ '<span class="token block body decl declaration meta method object ts">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>', '<span class="token block body decl declaration member meta method object ts">cursorStyle:</span>', '<span class="token block body decl declaration member meta method object ts">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>', '<span class="token delimiter paren typescript">(</span>', '<span class="token block body decl declaration member meta method object ts">prevOpts.cursorStyle&nbsp;</span>', '<span class="token block body comparison decl declaration keyword member meta method object operator ts">!=</span>', '<span class="token block body comparison decl declaration keyword member meta method object operator ts">=</span>', '<span class="token block body decl declaration member meta method object ts">&nbsp;newOpts.cursorStyle</span>', '<span class="token delimiter paren typescript">)</span>', '<span class="token block body decl declaration meta method object ts">,</span>', ].join(''); let expectedOffsetsArr = [ [0, 1, 4, 8], // 4 chars [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], // 12 chars [0, 4, 8, 12, 16, 20], // 6 chars [0], // 1 char [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], // 21 chars [0, 1], // 2 chars [0], // 1 char [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19], // 20 chars [0], // 1 char [0, 1] // 2 chars ]; let expectedOffsets = expectedOffsetsArr.reduce((prev, curr) => prev.concat(curr), []); let _actual = renderLine(new RenderLineInput( lineText, 4, 10, -1, 'none', false, lineParts )); assert.equal(_actual.output, '<span>' + expectedOutput + '</span>'); assert.deepEqual(_actual.charOffsetInPart, expectedOffsets); }); });
src/vs/editor/test/common/viewLayout/viewLineRenderer.test.ts
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017656524141784757, 0.0001711928052827716, 0.00016422991757281125, 0.0001716391125228256, 0.0000030558164780813968 ]
{ "id": 6, "code_window": [ "\t\tif (source.inMemory) {\n", "\t\t\t// internal module\n", "\t\t\tif (source.reference !== 0 && this.session && source.available) {\n", "\t\t\t\treturn this.session.source({ sourceReference: source.reference }).then(response => {\n", "\t\t\t\t\tconst mime = response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0];\n", "\t\t\t\t\treturn this.getDebugStringEditorInput(source, response.body.content, mime);\n", "\t\t\t\t}, (err: DebugProtocol.ErrorResponse) => {\n", "\t\t\t\t\t// Display the error from debug adapter using a temporary editor #8836\n", "\t\t\t\t\treturn this.getDebugErrorEditorInput(source, err.message);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\t\tconst mime = response && response.body && response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0];\n", "\t\t\t\t\tconst inputValue = response && response.body ? response.body.content : '';\n", "\t\t\t\t\treturn this.getDebugStringEditorInput(source, inputValue, mime);\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 840 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- * Please make sure to make edits in the .ts file at https://github.com/Microsoft/vscode-loader/ *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------- *--------------------------------------------------------------------------------------------*/ 'use strict'; var _nlsPluginGlobal = this; var NLSLoaderPlugin; (function (NLSLoaderPlugin) { var global = _nlsPluginGlobal || {}; var Resources = global.Plugin && global.Plugin.Resources ? global.Plugin.Resources : undefined; var DEFAULT_TAG = 'i-default'; var IS_PSEUDO = (global && global.document && global.document.location && global.document.location.hash.indexOf('pseudo=true') >= 0); var slice = Array.prototype.slice; function _format(message, args) { var result; if (args.length === 0) { result = message; } else { result = message.replace(/\{(\d+)\}/g, function (match, rest) { var index = rest[0]; return typeof args[index] !== 'undefined' ? args[index] : match; }); } if (IS_PSEUDO) { // FF3B and FF3D is the Unicode zenkaku representation for [ and ] result = '\uFF3B' + result.replace(/[aouei]/g, '$&$&') + '\uFF3D'; } return result; } function findLanguageForModule(config, name) { var result = config[name]; if (result) return result; result = config['*']; if (result) return result; return null; } function localize(data, message) { var args = []; for (var _i = 0; _i < (arguments.length - 2); _i++) { args[_i] = arguments[_i + 2]; } return _format(message, args); } function createScopedLocalize(scope) { return function (idx, defaultValue) { var restArgs = slice.call(arguments, 2); return _format(scope[idx], restArgs); }; } var NLSPlugin = (function () { function NLSPlugin() { this.localize = localize; } NLSPlugin.prototype.setPseudoTranslation = function (value) { IS_PSEUDO = value; }; NLSPlugin.prototype.create = function (key, data) { return { localize: createScopedLocalize(data[key]) }; }; NLSPlugin.prototype.load = function (name, req, load, config) { config = config || {}; if (!name || name.length === 0) { load({ localize: localize }); } else { var suffix = void 0; if (Resources && Resources.getString) { suffix = '.nls.keys'; req([name + suffix], function (keyMap) { load({ localize: function (moduleKey, index) { if (!keyMap[moduleKey]) return 'NLS error: unknown key ' + moduleKey; var mk = keyMap[moduleKey].keys; if (index >= mk.length) return 'NLS error unknow index ' + index; var subKey = mk[index]; var args = []; args[0] = moduleKey + '_' + subKey; for (var _i = 0; _i < (arguments.length - 2); _i++) { args[_i + 1] = arguments[_i + 2]; } return Resources.getString.apply(Resources, args); } }); }); } else { if (config.isBuild) { req([name + '.nls', name + '.nls.keys'], function (messages, keys) { NLSPlugin.BUILD_MAP[name] = messages; NLSPlugin.BUILD_MAP_KEYS[name] = keys; load(messages); }); } else { var pluginConfig = config['vs/nls'] || {}; var language = pluginConfig.availableLanguages ? findLanguageForModule(pluginConfig.availableLanguages, name) : null; suffix = '.nls'; if (language !== null && language !== DEFAULT_TAG) { suffix = suffix + '.' + language; } req([name + suffix], function (messages) { if (Array.isArray(messages)) { messages.localize = createScopedLocalize(messages); } else { messages.localize = createScopedLocalize(messages[name]); } load(messages); }); } } } }; NLSPlugin.prototype._getEntryPointsMap = function () { global.nlsPluginEntryPoints = global.nlsPluginEntryPoints || {}; return global.nlsPluginEntryPoints; }; NLSPlugin.prototype.write = function (pluginName, moduleName, write) { // getEntryPoint is a Monaco extension to r.js var entryPoint = write.getEntryPoint(); // r.js destroys the context of this plugin between calling 'write' and 'writeFile' // so the only option at this point is to leak the data to a global var entryPointsMap = this._getEntryPointsMap(); entryPointsMap[entryPoint] = entryPointsMap[entryPoint] || []; entryPointsMap[entryPoint].push(moduleName); if (moduleName !== entryPoint) { write.asModule(pluginName + '!' + moduleName, 'define([\'vs/nls\', \'vs/nls!' + entryPoint + '\'], function(nls, data) { return nls.create("' + moduleName + '", data); });'); } }; NLSPlugin.prototype.writeFile = function (pluginName, moduleName, req, write, config) { var entryPointsMap = this._getEntryPointsMap(); if (entryPointsMap.hasOwnProperty(moduleName)) { var fileName = req.toUrl(moduleName + '.nls.js'); var contents = [ '/*---------------------------------------------------------', ' * Copyright (c) Microsoft Corporation. All rights reserved.', ' *--------------------------------------------------------*/' ], entries = entryPointsMap[moduleName]; var data = {}; for (var i = 0; i < entries.length; i++) { data[entries[i]] = NLSPlugin.BUILD_MAP[entries[i]]; } contents.push('define("' + moduleName + '.nls", ' + JSON.stringify(data, null, '\t') + ');'); write(fileName, contents.join('\r\n')); } }; NLSPlugin.prototype.finishBuild = function (write) { write('nls.metadata.json', JSON.stringify({ keys: NLSPlugin.BUILD_MAP_KEYS, messages: NLSPlugin.BUILD_MAP, bundles: this._getEntryPointsMap() }, null, '\t')); }; ; NLSPlugin.BUILD_MAP = {}; NLSPlugin.BUILD_MAP_KEYS = {}; return NLSPlugin; }()); NLSLoaderPlugin.NLSPlugin = NLSPlugin; (function () { define('vs/nls', new NLSPlugin()); })(); })(NLSLoaderPlugin || (NLSLoaderPlugin = {}));
src/vs/nls.js
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.0001742531603667885, 0.00016941764624789357, 0.00016413112462032586, 0.0001699182321317494, 0.0000031215713534038514 ]
{ "id": 7, "code_window": [ "\t\t\treturn TPromise.as(null);\n", "\t\t}\n", "\n", "\t\treturn this.session.continue({ threadId }).then(response => {\n", "\t\t\tconst allThreadsContinued = response.body ? response.body.allThreadsContinued !== false : true;\n", "\t\t\tthis.lazyTransitionToRunningState(allThreadsContinued ? undefined : threadId);\n", "\t\t});\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst allThreadsContinued = response && response.body ? response.body.allThreadsContinued !== false : true;\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 926 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import {TPromise} from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import lifecycle = require('vs/base/common/lifecycle'); import Event, {Emitter} from 'vs/base/common/event'; import uuid = require('vs/base/common/uuid'); import objects = require('vs/base/common/objects'); import severity from 'vs/base/common/severity'; import types = require('vs/base/common/types'); import arrays = require('vs/base/common/arrays'); import debug = require('vs/workbench/parts/debug/common/debug'); import {Source} from 'vs/workbench/parts/debug/common/debugSource'; const MAX_REPL_LENGTH = 10000; const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source"); function massageValue(value: string): string { return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value; } export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> { if (!session) { expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE; expression.available = false; expression.reference = 0; return TPromise.as(expression); } return session.evaluate({ expression: expression.name, frameId: stackFrame ? stackFrame.frameId : undefined, context }).then(response => { expression.available = !!(response && response.body); if (response && response.body) { expression.value = response.body.result; expression.reference = response.body.variablesReference; expression.namedVariables = response.body.namedVariables; expression.indexedVariables = response.body.indexedVariables; expression.type = response.body.type; } return expression; }, err => { expression.value = err.message; expression.available = false; expression.reference = 0; return expression; }); } const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/; const arrayElementSyntax = /\[.*\]$/; export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string { let names = [expression.name]; if (expression instanceof Variable) { let v = (<Variable> expression).parent; while (v instanceof Variable || v instanceof Expression) { names.push((<Variable> v).name); v = (<Variable> v).parent; } } names = names.reverse(); let result = null; names.forEach(name => { if (!result) { result = name; } else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) { // use safe way to access node properties a['property_name']. Also handles array elements. result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`; } else { result = `${ result }.${ name }`; } }); return result; } export class Thread implements debug.IThread { private promisedCallStack: TPromise<debug.IStackFrame[]>; private cachedCallStack: debug.IStackFrame[]; public stoppedDetails: debug.IRawStoppedDetails; public stopped: boolean; constructor(public name: string, public threadId: number) { this.promisedCallStack = undefined; this.stoppedDetails = undefined; this.cachedCallStack = undefined; this.stopped = false; } public getId(): string { return `thread:${ this.name }:${ this.threadId }`; } public clearCallStack(): void { this.promisedCallStack = undefined; this.cachedCallStack = undefined; } public getCachedCallStack(): debug.IStackFrame[] { return this.cachedCallStack; } public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> { if (!this.stopped) { return TPromise.as([]); } if (!this.promisedCallStack) { this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => { this.cachedCallStack = callStack; return callStack; }); } else if (getAdditionalStackFrames) { this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => { this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart); return this.cachedCallStack; })); } return this.promisedCallStack; } private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> { let session = debugService.getActiveSession(); return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => { this.stoppedDetails.totalFrames = response.body.totalFrames; return response.body.stackFrames.map((rsf, level) => { if (!rsf) { return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined); } return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column); }); }, (err: Error) => { this.stoppedDetails.framesErrorMessage = err.message; return []; }); } } export class OutputElement implements debug.ITreeElement { private static ID_COUNTER = 0; constructor(private id = OutputElement.ID_COUNTER++) { // noop } public getId(): string { return `outputelement:${ this.id }`; } } export class ValueOutputElement extends OutputElement { constructor( public value: string, public severity: severity, public category?: string, public counter: number = 1 ) { super(); } } export class KeyValueOutputElement extends OutputElement { private static MAX_CHILDREN = 1000; // upper bound of children per value private children: debug.ITreeElement[]; private _valueName: string; constructor(public key: string, public valueObj: any, public annotation?: string) { super(); this._valueName = null; } public get value(): string { if (this._valueName === null) { if (this.valueObj === null) { this._valueName = 'null'; } else if (Array.isArray(this.valueObj)) { this._valueName = `Array[${this.valueObj.length}]`; } else if (types.isObject(this.valueObj)) { this._valueName = 'Object'; } else if (types.isString(this.valueObj)) { this._valueName = `"${massageValue(this.valueObj)}"`; } else { this._valueName = String(this.valueObj); } if (!this._valueName) { this._valueName = ''; } } return this._valueName; } public getChildren(): debug.ITreeElement[] { if (!this.children) { if (Array.isArray(this.valueObj)) { this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null)); } else if (types.isObject(this.valueObj)) { this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null)); } else { this.children = []; } } return this.children; } } export abstract class ExpressionContainer implements debug.IExpressionContainer { public static allValues: { [id: string]: string } = {}; // Use chunks to support variable paging #9537 private static BASE_CHUNK_SIZE = 100; public valueChanged: boolean; private children: TPromise<debug.IExpression[]>; private _value: string; constructor( public reference: number, private id: string, private cacheChildren: boolean, public namedVariables: number, public indexedVariables: number, private startOfVariables = 0 ) { // noop } public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> { if (!this.cacheChildren || !this.children) { const session = debugService.getActiveSession(); // only variables with reference > 0 have children. if (!session || this.reference <= 0) { this.children = TPromise.as([]); } else { // Check if object has named variables, fetch them independent from indexed variables #9670 this.children = (!!this.namedVariables ? this.fetchVariables(session, undefined, undefined, 'named') : TPromise.as([])).then(childrenArray => { // Use a dynamic chunk size based on the number of elements #9774 let chunkSize = ExpressionContainer.BASE_CHUNK_SIZE; while (this.indexedVariables > chunkSize * ExpressionContainer.BASE_CHUNK_SIZE) { chunkSize *= ExpressionContainer.BASE_CHUNK_SIZE; } if (this.indexedVariables > chunkSize) { // There are a lot of children, create fake intermediate values that represent chunks #9537 const numberOfChunks = Math.ceil(this.indexedVariables / chunkSize); for (let i = 0; i < numberOfChunks; i++) { const start = this.startOfVariables + i * chunkSize; const count = Math.min(chunkSize, this.indexedVariables - i * chunkSize); childrenArray.push(new Variable(this, this.reference, `[${start}..${start + count - 1}]`, '', null, count, null, true, start)); } return childrenArray; } const start = this.getChildrenInChunks ? this.startOfVariables : undefined; const count = this.getChildrenInChunks ? this.indexedVariables : undefined; return this.fetchVariables(session, start, count, 'indexed').then(variables => childrenArray.concat(variables)); }); } } return this.children; } public getId(): string { return this.id; } public get value(): string { return this._value; } private fetchVariables(session: debug.IRawDebugSession, start: number, count: number, filter: 'indexed'|'named'): TPromise<Variable[]> { return session.variables({ variablesReference: this.reference, start, count, filter }).then(response => { return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map( v => new Variable(this, v.variablesReference, v.name, v.value, v.namedVariables, v.indexedVariables, v.type) ); }, (e: Error) => [new Variable(this, 0, null, e.message, 0, 0, null, false)]); } // The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked. private get getChildrenInChunks(): boolean { return !!this.indexedVariables; } public set value(value: string) { this._value = massageValue(value); this.valueChanged = ExpressionContainer.allValues[this.getId()] && ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value; ExpressionContainer.allValues[this.getId()] = value; } } export class Expression extends ExpressionContainer implements debug.IExpression { static DEFAULT_VALUE = 'not available'; public available: boolean; public type: string; constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) { super(0, id, cacheChildren, 0, 0); this.value = Expression.DEFAULT_VALUE; this.available = false; } } export class Variable extends ExpressionContainer implements debug.IExpression { // Used to show the error message coming from the adapter when setting the value #7807 public errorMessage: string; constructor( public parent: debug.IExpressionContainer, reference: number, public name: string, value: string, namedVariables: number, indexedVariables: number, public type: string = null, public available = true, startOfVariables = 0 ) { super(reference, `variable:${parent.getId()}:${name}:${reference}`, true, namedVariables, indexedVariables, startOfVariables); this.value = massageValue(value); } } export class Scope extends ExpressionContainer implements debug.IScope { constructor( private threadId: number, public name: string, reference: number, public expensive: boolean, namedVariables: number, indexedVariables: number ) { super(reference, `scope:${threadId}:${name}:${reference}`, true, namedVariables, indexedVariables); } } export class StackFrame implements debug.IStackFrame { private scopes: TPromise<Scope[]>; constructor( public threadId: number, public frameId: number, public source: Source, public name: string, public lineNumber: number, public column: number ) { this.scopes = null; } public getId(): string { return `stackframe:${ this.threadId }:${ this.frameId }`; } public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> { if (!this.scopes) { this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => { return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables)); }, err => []); } return this.scopes; } } export class Breakpoint implements debug.IBreakpoint { public lineNumber: number; public verified: boolean; public idFromAdapter: number; public message: string; private id: string; constructor( public source: Source, public desiredLineNumber: number, public enabled: boolean, public condition: string ) { if (enabled === undefined) { this.enabled = true; } this.lineNumber = this.desiredLineNumber; this.verified = false; this.id = uuid.generateUuid(); } public getId(): string { return this.id; } } export class FunctionBreakpoint implements debug.IFunctionBreakpoint { private id: string; public verified: boolean; public idFromAdapter: number; constructor(public name: string, public enabled: boolean) { this.verified = false; this.id = uuid.generateUuid(); } public getId(): string { return this.id; } } export class ExceptionBreakpoint implements debug.IExceptionBreakpoint { private id: string; constructor(public filter: string, public label: string, public enabled: boolean) { this.id = uuid.generateUuid(); } public getId(): string { return this.id; } } export class Model implements debug.IModel { private threads: { [reference: number]: debug.IThread; }; private toDispose: lifecycle.IDisposable[]; private replElements: debug.ITreeElement[]; private _onDidChangeBreakpoints: Emitter<void>; private _onDidChangeCallStack: Emitter<void>; private _onDidChangeWatchExpressions: Emitter<debug.IExpression>; private _onDidChangeREPLElements: Emitter<void>; constructor( private breakpoints: debug.IBreakpoint[], private breakpointsActivated: boolean, private functionBreakpoints: debug.IFunctionBreakpoint[], private exceptionBreakpoints: debug.IExceptionBreakpoint[], private watchExpressions: Expression[] ) { this.threads = {}; this.replElements = []; this.toDispose = []; this._onDidChangeBreakpoints = new Emitter<void>(); this._onDidChangeCallStack = new Emitter<void>(); this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>(); this._onDidChangeREPLElements = new Emitter<void>(); } public getId(): string { return 'root'; } public get onDidChangeBreakpoints(): Event<void> { return this._onDidChangeBreakpoints.event; } public get onDidChangeCallStack(): Event<void> { return this._onDidChangeCallStack.event; } public get onDidChangeWatchExpressions(): Event<debug.IExpression> { return this._onDidChangeWatchExpressions.event; } public get onDidChangeReplElements(): Event<void> { return this._onDidChangeREPLElements.event; } public getThreads(): { [reference: number]: debug.IThread; } { return this.threads; } public clearThreads(removeThreads: boolean, reference: number = undefined): void { if (reference) { if (this.threads[reference]) { this.threads[reference].clearCallStack(); this.threads[reference].stoppedDetails = undefined; this.threads[reference].stopped = false; if (removeThreads) { delete this.threads[reference]; } } } else { Object.keys(this.threads).forEach(ref => { this.threads[ref].clearCallStack(); this.threads[ref].stoppedDetails = undefined; this.threads[ref].stopped = false; }); if (removeThreads) { this.threads = {}; ExpressionContainer.allValues = {}; } } this._onDidChangeCallStack.fire(); } public getBreakpoints(): debug.IBreakpoint[] { return this.breakpoints; } public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] { return this.functionBreakpoints; } public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] { return this.exceptionBreakpoints; } public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void { if (data) { this.exceptionBreakpoints = data.map(d => { const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop(); return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default); }); } } public areBreakpointsActivated(): boolean { return this.breakpointsActivated; } public setBreakpointsActivated(activated: boolean): void { this.breakpointsActivated = activated; this._onDidChangeBreakpoints.fire(); } public addBreakpoints(rawData: debug.IRawBreakpoint[]): void { this.breakpoints = this.breakpoints.concat(rawData.map(rawBp => new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition))); this.breakpointsActivated = true; this._onDidChangeBreakpoints.fire(); } public removeBreakpoints(toRemove: debug.IBreakpoint[]): void { this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId())); this._onDidChangeBreakpoints.fire(); } public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void { this.breakpoints.forEach(bp => { const bpData = data[bp.getId()]; if (bpData) { bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber; bp.verified = bpData.verified; bp.idFromAdapter = bpData.id; bp.message = bpData.message; } }); this._onDidChangeBreakpoints.fire(); } public setEnablement(element: debug.IEnablement, enable: boolean): void { element.enabled = enable; if (element instanceof Breakpoint && !element.enabled) { var breakpoint = <Breakpoint> element; breakpoint.lineNumber = breakpoint.desiredLineNumber; breakpoint.verified = false; } this._onDidChangeBreakpoints.fire(); } public enableOrDisableAllBreakpoints(enable: boolean): void { this.breakpoints.forEach(bp => { bp.enabled = enable; if (!enable) { bp.lineNumber = bp.desiredLineNumber; bp.verified = false; } }); this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable); this.functionBreakpoints.forEach(fbp => fbp.enabled = enable); this._onDidChangeBreakpoints.fire(); } public addFunctionBreakpoint(functionName: string): void { this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true)); this._onDidChangeBreakpoints.fire(); } public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void { this.functionBreakpoints.forEach(fbp => { const fbpData = data[fbp.getId()]; if (fbpData) { fbp.name = fbpData.name || fbp.name; fbp.verified = fbpData.verified; fbp.idFromAdapter = fbpData.id; } }); this._onDidChangeBreakpoints.fire(); } public removeFunctionBreakpoints(id?: string): void { this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : []; this._onDidChangeBreakpoints.fire(); } public getReplElements(): debug.ITreeElement[] { return this.replElements; } public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> { const expression = new Expression(name, true); this.addReplElements([expression]); return evaluateExpression(session, stackFrame, expression, 'repl') .then(() => this._onDidChangeREPLElements.fire()); } public logToRepl(value: string | { [key: string]: any }, severity?: severity): void { let elements:OutputElement[] = []; let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]); // string message if (typeof value === 'string') { if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) { previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter } else { let lines = value.trim().split('\n'); lines.forEach((line, index) => { elements.push(new ValueOutputElement(line, severity)); }); } } // key-value output else { elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object."))); } if (elements.length) { this.addReplElements(elements); } this._onDidChangeREPLElements.fire(); } public appendReplOutput(value: string, severity?: severity): void { const elements: OutputElement[] = []; let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]); let lines = value.split('\n'); let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity); if (groupTogether) { // append to previous line if same group previousOutput.value += lines.shift(); } else if (previousOutput && previousOutput.value === '') { // remove potential empty lines between different output types this.replElements.pop(); } // fill in lines as output value elements lines.forEach((line, index) => { elements.push(new ValueOutputElement(line, severity, 'output')); }); this.addReplElements(elements); this._onDidChangeREPLElements.fire(); } private addReplElements(newElements: debug.ITreeElement[]): void { this.replElements.push(...newElements); if (this.replElements.length > MAX_REPL_LENGTH) { this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH); } } public removeReplExpressions(): void { if (this.replElements.length > 0) { this.replElements = []; this._onDidChangeREPLElements.fire(); } } public getWatchExpressions(): Expression[] { return this.watchExpressions; } public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> { const we = new Expression(name, false); this.watchExpressions.push(we); if (!name) { this._onDidChangeWatchExpressions.fire(we); return TPromise.as(null); } return this.evaluateWatchExpressions(session, stackFrame, we.getId()); } public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> { const filtered = this.watchExpressions.filter(we => we.getId() === id); if (filtered.length === 1) { filtered[0].name = newName; return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => { this._onDidChangeWatchExpressions.fire(filtered[0]); }); } return TPromise.as(null); } public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> { if (id) { const filtered = this.watchExpressions.filter(we => we.getId() === id); if (filtered.length !== 1) { return TPromise.as(null); } return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => { this._onDidChangeWatchExpressions.fire(filtered[0]); }); } return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => { this._onDidChangeWatchExpressions.fire(); }); } public clearWatchExpressionValues(): void { this.watchExpressions.forEach(we => { we.value = Expression.DEFAULT_VALUE; we.available = false; we.reference = 0; }); this._onDidChangeWatchExpressions.fire(); } public removeWatchExpressions(id: string = null): void { this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : []; this._onDidChangeWatchExpressions.fire(); } public sourceIsUnavailable(source: Source): void { Object.keys(this.threads).forEach(key => { if (this.threads[key].getCachedCallStack()) { this.threads[key].getCachedCallStack().forEach(stackFrame => { if (stackFrame.source.uri.toString() === source.uri.toString()) { stackFrame.source.available = false; } }); } }); this._onDidChangeCallStack.fire(); } public rawUpdate(data: debug.IRawModelUpdate): void { if (data.thread && !this.threads[data.threadId]) { // A new thread came in, initialize it. this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id); } if (data.stoppedDetails) { // Set the availability of the threads' callstacks depending on // whether the thread is stopped or not if (data.allThreadsStopped) { Object.keys(this.threads).forEach(ref => { // Only update the details if all the threads are stopped // because we don't want to overwrite the details of other // threads that have stopped for a different reason this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails); this.threads[ref].stopped = true; this.threads[ref].clearCallStack(); }); } else { // One thread is stopped, only update that thread. this.threads[data.threadId].stoppedDetails = data.stoppedDetails; this.threads[data.threadId].clearCallStack(); this.threads[data.threadId].stopped = true; } } this._onDidChangeCallStack.fire(); } public dispose(): void { this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/parts/debug/common/debugModel.ts
1
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.006578113883733749, 0.00030948748462833464, 0.00016496631724294275, 0.00017151198699139059, 0.000727450184058398 ]
{ "id": 7, "code_window": [ "\t\t\treturn TPromise.as(null);\n", "\t\t}\n", "\n", "\t\treturn this.session.continue({ threadId }).then(response => {\n", "\t\t\tconst allThreadsContinued = response.body ? response.body.allThreadsContinued !== false : true;\n", "\t\t\tthis.lazyTransitionToRunningState(allThreadsContinued ? undefined : threadId);\n", "\t\t});\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst allThreadsContinued = response && response.body ? response.body.allThreadsContinued !== false : true;\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 926 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "ColonExpected": "Signe des deux points attendu", "DisallowedExtraPropWarning": "La propriété {0} n'est pas autorisée", "DoubleQuotesExpected": "Les clés de propriété doivent être entre guillemets doubles", "DuplicateKeyWarning": "Clé d'objet en double", "End of file expected": "Fin de fichier attendue", "ExpectedCloseBrace": "Virgule ou accolade fermante attendue", "ExpectedCloseBracket": "Virgule ou crochet fermant attendu", "Invalid symbol": "Littéral, tableau ou objet JSON attendu", "InvalidEscapeCharacter": "Caractère d'échappement non valide dans la chaîne", "InvalidNumberFormat": "Format de nombre non valide", "InvalidUnicode": "Séquence unicode non valide dans la chaîne", "MaxPropWarning": "L'objet a plus de propriétés que la limite {0}", "MinPropWarning": "L'objet a moins de propriétés que le nombre requis {0}", "MissingRequiredPropWarning": "Propriété manquante \"{0}\"", "PropertyExpected": "Propriété attendue", "RequiredDependentPropWarning": "La propriété {0} requise par la propriété {1} est manquante pour l'objet", "UnexpectedEndOfComment": "Fin de commentaire inattendue", "UnexpectedEndOfNumber": "Fin de nombre inattendue", "UnexpectedEndOfString": "Fin de chaîne inattendue", "ValueExpected": "Valeur attendue", "additionalItemsWarning": "Le tableau comporte trop d'éléments selon le schéma. {0} maximum sont attendus", "enumWarning": "La valeur n'est pas acceptée. Valeurs valides : {0}", "exclusiveMaximumWarning": "La valeur est supérieure au maximum exclusif {0}", "exclusiveMinimumWarning": "La valeur est inférieur au minimum exclusif {0}", "maxItemsWarning": "Le tableau contient trop d'éléments. {0} éléments au maximum sont attendus", "maxLengthWarning": "La chaîne est plus courte que la longueur maximum", "maximumWarning": "La valeur est supérieure au maximum {0}", "minItemsWarning": "Le tableau ne contient pas assez d'éléments. {0} minimum sont attendus", "minLengthWarning": "La chaîne est plus courte que la longueur minimum", "minimumWarning": "La valeur est inférieure au minimum {0}", "multipleOfWarning": "La valeur n'est pas divisible par {0}", "notSchemaWarning": "Correspond à un schéma non autorisé.", "oneOfWarning": "Correspond à plusieurs schémas alors qu'un seul doit exister pour la validation.", "patternWarning": "La chaîne ne correspond pas au modèle \"{0}\"", "typeArrayMismatchWarning": "Type incorrect. {0} était attendu.", "typeMismatchWarning": "Type incorrect. \"{0}\" était attendu", "uniqueItemsWarning": "Le tableau comporte des doublons" }
i18n/fra/src/vs/languages/json/common/parser/jsonParser.i18n.json
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017437779752071947, 0.00017352185386698693, 0.0001722112501738593, 0.00017368783301208168, 7.927158094389597e-7 ]
{ "id": 7, "code_window": [ "\t\t\treturn TPromise.as(null);\n", "\t\t}\n", "\n", "\t\treturn this.session.continue({ threadId }).then(response => {\n", "\t\t\tconst allThreadsContinued = response.body ? response.body.allThreadsContinued !== false : true;\n", "\t\t\tthis.lazyTransitionToRunningState(allThreadsContinued ? undefined : threadId);\n", "\t\t});\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst allThreadsContinued = response && response.body ? response.body.allThreadsContinued !== false : true;\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 926 }
[ { "c": "function", "t": "function.meta.storage.ts.type", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.storage.type rgb(86, 156, 214)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.storage.type rgb(0, 0, 255)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.storage.type rgb(86, 156, 214)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.storage.type rgb(0, 0, 255)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.storage.type rgb(86, 156, 214)" } }, { "c": " ", "t": "function.meta.ts", "r": { "dark_plus": ".vs-dark .token rgb(212, 212, 212)", "light_plus": ".vs .token rgb(0, 0, 0)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": "foo3", "t": "entity.function.meta.name.ts", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.entity.name.function rgb(220, 220, 170)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.entity.name.function rgb(121, 94, 38)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.entity.name.function rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": "()", "t": "brace.function.meta.parameter.round.ts.type", "r": { "dark_plus": ".vs-dark .token rgb(212, 212, 212)", "light_plus": ".vs .token rgb(0, 0, 0)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": " ", "t": "function.meta.ts", "r": { "dark_plus": ".vs-dark .token rgb(212, 212, 212)", "light_plus": ".vs .token rgb(0, 0, 0)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": "{", "t": "block.brace.curly.decl.function.meta.ts", "r": { "dark_plus": ".vs-dark .token rgb(212, 212, 212)", "light_plus": ".vs .token rgb(0, 0, 0)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": "\t", "t": "block.decl.expr.function.meta.ts.var", "r": { "dark_plus": ".vs-dark .token rgb(212, 212, 212)", "light_plus": ".vs .token rgb(0, 0, 0)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": "const", "t": "block.decl.expr.function.meta.storage.ts.type.var", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.storage.type rgb(86, 156, 214)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.storage.type rgb(0, 0, 255)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.storage.type rgb(86, 156, 214)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.storage.type rgb(0, 0, 255)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.storage.type rgb(86, 156, 214)" } }, { "c": " ", "t": "block.decl.expr.function.meta.ts.var", "r": { "dark_plus": ".vs-dark .token rgb(212, 212, 212)", "light_plus": ".vs .token rgb(0, 0, 0)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": "foo", "t": "block.decl.expr.function.meta.ts.var.var-single-variable.variable", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.variable rgb(156, 220, 254)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.variable rgb(0, 16, 128)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": " = ", "t": "block.decl.expr.function.meta.ts.var.var-single-variable", "r": { "dark_plus": ".vs-dark .token rgb(212, 212, 212)", "light_plus": ".vs .token rgb(0, 0, 0)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": "()", "t": "block.brace.decl.expr.function.meta.paren.ts.var.var-single-variable", "r": { "dark_plus": ".vs-dark .token rgb(212, 212, 212)", "light_plus": ".vs .token rgb(0, 0, 0)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": ": ", "t": "annotation.block.decl.expr.function.meta.ts.type.var.var-single-variable", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.meta.type.annotation rgb(78, 201, 176)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.meta.type.annotation rgb(38, 127, 153)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": "any", "t": "annotation.block.decl.expr.function.meta.primitive.support.ts.type.var.var-single-variable", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.meta.type.annotation rgb(78, 201, 176)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.meta.type.annotation rgb(38, 127, 153)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": " ", "t": "annotation.block.decl.expr.function.meta.ts.type.var.var-single-variable", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.meta.type.annotation rgb(78, 201, 176)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.meta.type.annotation rgb(38, 127, 153)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": "=>", "t": "annotation.block.decl.expr.function.keyword.meta.operator.return.ts.type.var.var-single-variable", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.meta.type.annotation rgb(78, 201, 176)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.meta.type.annotation rgb(38, 127, 153)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.keyword.operator rgb(212, 212, 212)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.keyword.operator rgb(0, 0, 0)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.keyword.operator rgb(212, 212, 212)" } }, { "c": " (", "t": "annotation.block.cover.decl.expr.function.meta.paren.return.ts.type.var.var-single-variable", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.meta.type.annotation rgb(78, 201, 176)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.meta.type.annotation rgb(38, 127, 153)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": "{", "t": "annotation.block.brace.cover.curly.decl.expr.function.meta.object.paren.return.ts.type.var.var-single-variable", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.meta.type.annotation rgb(78, 201, 176)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.meta.type.annotation rgb(38, 127, 153)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": " ", "t": "annotation.block.cover.decl.declaration.expr.field.function.meta.object.paren.return.ts.type.var.var-single-variable", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.meta.type.annotation rgb(78, 201, 176)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.meta.type.annotation rgb(38, 127, 153)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": "'bar'", "t": "annotation.block.cover.decl.declaration.expr.field.function.meta.object.paren.return.ts.type.var.var-single-variable.variable", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.meta.type.annotation rgb(78, 201, 176)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.meta.type.annotation rgb(38, 127, 153)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": ": ", "t": "annotation.block.cover.decl.declaration.expr.field.function.meta.object.paren.return.ts.type.var.var-single-variable", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.meta.type.annotation rgb(78, 201, 176)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.meta.type.annotation rgb(38, 127, 153)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": "'baz'", "t": "annotation.block.cover.decl.declaration.expr.field.function.meta.object.paren.return.single.string.ts.type.var.var-single-variable", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.meta.type.annotation rgb(78, 201, 176)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.meta.type.annotation rgb(38, 127, 153)", "dark_vs": ".vs-dark.vscode-theme-defaults-themes-dark_vs-json .token.string rgb(206, 145, 120)", "light_vs": ".vs.vscode-theme-defaults-themes-light_vs-json .token.string rgb(163, 21, 21)", "hc_black": ".hc-black.vscode-theme-defaults-themes-hc_black-json .token.string rgb(206, 145, 120)" } }, { "c": " ", "t": "annotation.block.cover.decl.declaration.expr.field.function.meta.object.paren.return.ts.type.var.var-single-variable", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.meta.type.annotation rgb(78, 201, 176)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.meta.type.annotation rgb(38, 127, 153)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": "}", "t": "annotation.block.brace.cover.curly.decl.expr.function.meta.object.paren.return.ts.type.var.var-single-variable", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.meta.type.annotation rgb(78, 201, 176)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.meta.type.annotation rgb(38, 127, 153)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": ")", "t": "annotation.block.cover.decl.expr.function.meta.paren.return.ts.type.var.var-single-variable", "r": { "dark_plus": ".vs-dark.vscode-theme-defaults-themes-dark_plus-json .token.meta.type.annotation rgb(78, 201, 176)", "light_plus": ".vs.vscode-theme-defaults-themes-light_plus-json .token.meta.type.annotation rgb(38, 127, 153)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } }, { "c": "}", "t": "block.brace.curly.decl.function.meta.ts", "r": { "dark_plus": ".vs-dark .token rgb(212, 212, 212)", "light_plus": ".vs .token rgb(0, 0, 0)", "dark_vs": ".vs-dark .token rgb(212, 212, 212)", "light_vs": ".vs .token rgb(0, 0, 0)", "hc_black": ".hc-black .token rgb(255, 255, 255)" } } ]
extensions/typescript/test/colorize-results/test-issue5566_ts.json
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017497208318673074, 0.0001724267058307305, 0.00017021434905473143, 0.00017240017768926919, 0.000001238002141690231 ]
{ "id": 7, "code_window": [ "\t\t\treturn TPromise.as(null);\n", "\t\t}\n", "\n", "\t\treturn this.session.continue({ threadId }).then(response => {\n", "\t\t\tconst allThreadsContinued = response.body ? response.body.allThreadsContinued !== false : true;\n", "\t\t\tthis.lazyTransitionToRunningState(allThreadsContinued ? undefined : threadId);\n", "\t\t});\n", "\t}\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst allThreadsContinued = response && response.body ? response.body.allThreadsContinued !== false : true;\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 926 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "filesCategory": "文件" }
i18n/chs/src/vs/workbench/parts/files/electron-browser/files.electron.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017695558199193329, 0.00017695558199193329, 0.00017695558199193329, 0.00017695558199193329, 0 ]
{ "id": 8, "code_window": [ "\t\t\tframeId: focussedStackFrame ? focussedStackFrame.frameId : undefined,\n", "\t\t\ttext,\n", "\t\t\tcolumn: position.column,\n", "\t\t\tline: position.lineNumber\n", "\t\t}).then(response => {\n", "\t\t\treturn !response ? [] : response.body.targets.map(item => ({\n", "\t\t\t\tlabel: item.label,\n", "\t\t\t\tinsertText: item.text || item.label,\n", "\t\t\t\ttype: item.type\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\treturn response && response.body && response.body.targets ? response.body.targets.map(item => ({\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 959 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import nls = require('vs/nls'); import lifecycle = require('vs/base/common/lifecycle'); import {guessMimeTypes} from 'vs/base/common/mime'; import Event, {Emitter} from 'vs/base/common/event'; import uri from 'vs/base/common/uri'; import {RunOnceScheduler} from 'vs/base/common/async'; import {Action} from 'vs/base/common/actions'; import arrays = require('vs/base/common/arrays'); import types = require('vs/base/common/types'); import errors = require('vs/base/common/errors'); import severity from 'vs/base/common/severity'; import {TPromise} from 'vs/base/common/winjs.base'; import aria = require('vs/base/browser/ui/aria/aria'); import editorbrowser = require('vs/editor/browser/editorBrowser'); import {ISuggestion} from 'vs/editor/common/modes'; import {Position} from 'vs/editor/common/core/position'; import {IContextKeyService, IContextKey} from 'vs/platform/contextkey/common/contextkey'; import {IMarkerService} from 'vs/platform/markers/common/markers'; import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle'; import {IExtensionService} from 'vs/platform/extensions/common/extensions'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {IFileService, FileChangesEvent, FileChangeType, EventType} from 'vs/platform/files/common/files'; import {IEventService} from 'vs/platform/event/common/event'; import {IMessageService, CloseAction} from 'vs/platform/message/common/message'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {TelemetryService} from 'vs/platform/telemetry/common/telemetryService'; import {TelemetryAppenderClient} from 'vs/platform/telemetry/common/telemetryIpc'; import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage'; import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService'; import {asFileEditorInput} from 'vs/workbench/common/editor'; import debug = require('vs/workbench/parts/debug/common/debug'); import {RawDebugSession} from 'vs/workbench/parts/debug/electron-browser/rawDebugSession'; import model = require('vs/workbench/parts/debug/common/debugModel'); import {DebugStringEditorInput, DebugErrorEditorInput} from 'vs/workbench/parts/debug/browser/debugEditorInputs'; import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel'); import debugactions = require('vs/workbench/parts/debug/browser/debugActions'); import {ConfigurationManager} from 'vs/workbench/parts/debug/node/debugConfigurationManager'; import {Source} from 'vs/workbench/parts/debug/common/debugSource'; import {ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary} from 'vs/workbench/parts/tasks/common/taskService'; import {TaskError, TaskErrors} from 'vs/workbench/parts/tasks/common/taskSystem'; import {IViewletService} from 'vs/workbench/services/viewlet/common/viewletService'; import {IPanelService} from 'vs/workbench/services/panel/common/panelService'; import {IPartService} from 'vs/workbench/services/part/common/partService'; import {ITextFileService} from 'vs/workbench/parts/files/common/files'; import {IConfigurationService} from 'vs/platform/configuration/common/configuration'; import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {IWindowService, IBroadcast} from 'vs/workbench/services/window/electron-browser/windowService'; import {ILogEntry, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL} from 'vs/workbench/services/thread/electron-browser/threadService'; import {ipcRenderer as ipc} from 'electron'; import {Client} from 'vs/base/parts/ipc/node/ipc.cp'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname'; export class DebugService implements debug.IDebugService { public _serviceBrand: any; private _state: debug.State; private _onDidChangeState: Emitter<debug.State>; private session: RawDebugSession; private model: model.Model; private viewModel: viewmodel.ViewModel; private configurationManager: ConfigurationManager; private customTelemetryService: ITelemetryService; private lastTaskEvent: TaskEvent; private toDispose: lifecycle.IDisposable[]; private toDisposeOnSessionEnd: lifecycle.IDisposable[]; private inDebugMode: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: { [uri: string]: boolean }; constructor( @IStorageService private storageService: IStorageService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @ITextFileService private textFileService: ITextFileService, @IViewletService private viewletService: IViewletService, @IPanelService private panelService: IPanelService, @IFileService private fileService: IFileService, @IMessageService private messageService: IMessageService, @IPartService private partService: IPartService, @IWindowService private windowService: IWindowService, @ITelemetryService private telemetryService: ITelemetryService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IEventService eventService: IEventService, @ILifecycleService private lifecycleService: ILifecycleService, @IInstantiationService private instantiationService: IInstantiationService, @IExtensionService private extensionService: IExtensionService, @IMarkerService private markerService: IMarkerService, @ITaskService private taskService: ITaskService, @IConfigurationService private configurationService: IConfigurationService ) { this.toDispose = []; this.toDisposeOnSessionEnd = []; this.session = null; this.breakpointsToSendOnResourceSaved = {}; this._state = debug.State.Inactive; this._onDidChangeState = new Emitter<debug.State>(); if (!this.contextService.getWorkspace()) { this._state = debug.State.Disabled; } this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, 'null')); this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadWatchExpressions()); this.toDispose.push(this.model); this.viewModel = new viewmodel.ViewModel(); this.registerListeners(eventService, lifecycleService); } private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void { this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e))); if (this.taskService) { this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => { this.lastTaskEvent = e; })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => { if (e.type === TaskType.SingleRun) { this.lastTaskEvent = null; } })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => { this.lastTaskEvent = null; })); } lifecycleService.onShutdown(this.store, this); lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.windowService.onBroadcast(this.onBroadcast, this)); } private onBroadcast(broadcast: IBroadcast): void { // attach: PH is ready to be attached to if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) { this.rawAttach(broadcast.payload.port); return; } if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) { this.onSessionEnd(); return; } // from this point on we require an active session let session = this.getActiveSession(); if (!session || session.configuration.type !== 'extensionHost') { return; // we are only intersted if we have an active debug session for extensionHost } // a plugin logged output, show it inside the REPL if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) { let extensionOutput: ILogEntry = broadcast.payload; let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info; let args: any[] = []; try { let parsed = JSON.parse(extensionOutput.arguments); args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o])); } catch (error) { args.push(extensionOutput.arguments); } // add output for each argument logged let simpleVals: any[] = []; for (let i = 0; i < args.length; i++) { let a = args[i]; // undefined gets printed as 'undefined' if (typeof a === 'undefined') { simpleVals.push('undefined'); } // null gets printed as 'null' else if (a === null) { simpleVals.push('null'); } // objects & arrays are special because we want to inspect them in the REPL else if (types.isObject(a) || Array.isArray(a)) { // flush any existing simple values logged if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); simpleVals = []; } // show object this.logToRepl(a, sev); } // string: watch out for % replacement directive // string substitution and formatting @ https://developer.chrome.com/devtools/docs/console else if (typeof a === 'string') { let buf = ''; for (let j = 0, len = a.length; j < len; j++) { if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) { i++; // read over substitution buf += !types.isUndefinedOrNull(args[i]) ? args[i] : ''; // replace j++; // read over directive } else { buf += a[j]; } } simpleVals.push(buf); } // number or boolean is joined together else { simpleVals.push(a); } } // flush simple values if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); } } } private registerSessionListeners(): void { this.toDisposeOnSessionEnd.push(this.session); this.toDisposeOnSessionEnd.push(this.session.onDidInitialize(event => { aria.status(nls.localize('debuggingStarted', "Debugging started.")); this.sendAllBreakpoints().then(() => { if (this.session.configuration.capabilities.supportsConfigurationDoneRequest) { this.session.configurationDone().done(null, e => { // Disconnect the debug session on configuration done error #10596 if (this.session) { this.session.disconnect().done(null, errors.onUnexpectedError); } this.messageService.show(severity.Error, e.message); }); } }); })); this.toDisposeOnSessionEnd.push(this.session.onDidStop(event => { this.setStateAndEmit(debug.State.Stopped); const threadId = event.body.threadId; this.getThreadData().done(() => { this.model.rawUpdate({ threadId, stoppedDetails: event.body, allThreadsStopped: event.body.allThreadsStopped }); const thread = this.model.getThreads()[threadId]; thread.getCallStack(this).then(callStack => { if (callStack.length > 0) { // focus first stack frame from top that has source location const stackFrameToFocus = arrays.first(callStack, sf => sf.source && sf.source.available, callStack[0]); this.setFocusedStackFrameAndEvaluate(stackFrameToFocus, thread).done(null, errors.onUnexpectedError); this.windowService.getWindow().focus(); aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber)); return this.openOrRevealSource(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false); } else { this.setFocusedStackFrameAndEvaluate(null, thread).done(null, errors.onUnexpectedError); } }); }, errors.onUnexpectedError); })); this.toDisposeOnSessionEnd.push(this.session.onDidThread(event => { if (event.body.reason === 'started') { this.getThreadData().done(null, errors.onUnexpectedError); } else if (event.body.reason === 'exited') { this.model.clearThreads(true, event.body.threadId); } })); this.toDisposeOnSessionEnd.push(this.session.onDidTerminateDebugee(event => { aria.status(nls.localize('debuggingStopped', "Debugging stopped.")); if (this.session && this.session.getId() === event.body.sessionId) { if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) { this.restartSession().done(null, err => this.messageService.show(severity.Error, err.message)); } else { this.session.disconnect().done(null, errors.onUnexpectedError); } } })); this.toDisposeOnSessionEnd.push(this.session.onDidContinued(event => { this.lazyTransitionToRunningState(event.body.allThreadsContinued ? undefined : event.body.threadId); })); this.toDisposeOnSessionEnd.push(this.session.onDidOutput(event => { if (event.body && event.body.category === 'telemetry') { // only log telemetry events from debug adapter if the adapter provided the telemetry key // and the user opted in telemetry if (this.customTelemetryService && this.telemetryService.isOptedIn) { this.customTelemetryService.publicLog(event.body.output, event.body.data); } } else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) { this.onOutput(event); } })); this.toDisposeOnSessionEnd.push(this.session.onDidBreakpoint(event => { const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined; const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (breakpoint) { this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint }); } else { const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (functionBreakpoint) { this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint }); } } })); this.toDisposeOnSessionEnd.push(this.session.onDidExitAdapter(event => { // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (this.session.configuration.type === 'extensionHost' && this._state === debug.State.RunningNoDebug) { ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath); } if (this.session && this.session.getId() === event.body.sessionId) { this.onSessionEnd(); } })); } private onOutput(event: DebugProtocol.OutputEvent): void { const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info; this.appendReplOutput(event.body.output, outputSeverity); } private getThreadData(): TPromise<void> { return this.session.threads().then(response => { response.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread })); }); } private loadBreakpoints(): debug.IBreakpoint[] { let result: debug.IBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }), breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] { let result: debug.IFunctionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new model.FunctionBreakpoint(fb.name, fb.enabled); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] { let result: debug.IExceptionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadWatchExpressions(): model.Expression[] { let result: model.Expression[]; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string } ) => { return new model.Expression(watchStoredData.name, false, watchStoredData.id); }); } catch (e) { } return result || []; } public get state(): debug.State { return this._state; } public get onDidChangeState(): Event<debug.State> { return this._onDidChangeState.event; } private setStateAndEmit(newState: debug.State): void { this._state = newState; this._onDidChangeState.fire(newState); } public get enabled(): boolean { return !!this.contextService.getWorkspace(); } public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame, thread?: debug.IThread): TPromise<void> { if (!thread && focusedStackFrame) { thread = this.model.getThreads()[focusedStackFrame.threadId]; } this.viewModel.setFocusedStackFrame(focusedStackFrame, thread); if (focusedStackFrame) { return this.model.evaluateWatchExpressions(this.session, focusedStackFrame); } else { this.model.clearWatchExpressionValues(); return TPromise.as(null); } } public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof model.Breakpoint) { return this.sendBreakpoints((<model.Breakpoint>breakpoint).source.uri); } else if (breakpoint instanceof model.FunctionBreakpoint) { return this.sendFunctionBreakpoints(); } return this.sendExceptionBreakpoints(); } this.model.enableOrDisableAllBreakpoints(enable); return this.sendAllBreakpoints(); } public addBreakpoints(rawBreakpoints: debug.IRawBreakpoint[]): TPromise<void[]> { this.model.addBreakpoints(rawBreakpoints); const uris = arrays.distinct(rawBreakpoints, raw => raw.uri.toString()).map(raw => raw.uri); rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, rbp.uri.fsPath))); return TPromise.join(uris.map(uri => this.sendBreakpoints(uri))); } public removeBreakpoints(id?: string): TPromise<any> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.source.uri.fsPath))); const urisToClear = arrays.distinct(toRemove, bp => bp.source.uri.toString()).map(bp => bp.source.uri); this.model.removeBreakpoints(toRemove); return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri))); } public setBreakpointsActivated(activated: boolean): TPromise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } public addFunctionBreakpoint(): void { this.model.addFunctionBreakpoint(''); } public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> { this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } }); return this.sendFunctionBreakpoints(); } public removeFunctionBreakpoints(id?: string): TPromise<void> { this.model.removeFunctionBreakpoints(id); return this.sendFunctionBreakpoints(); } public addReplExpression(name: string): TPromise<void> { this.telemetryService.publicLog('debugService/addReplExpression'); const focussedStackFrame = this.viewModel.getFocusedStackFrame(); return this.model.addReplExpression(this.session, focussedStackFrame, name) // Evaluate all watch expressions again since repl evaluation might have changed some. .then(() => this.setFocusedStackFrameAndEvaluate(focussedStackFrame)); } public logToRepl(value: string | { [key: string]: any }, severity?: severity): void { this.model.logToRepl(value, severity); } public appendReplOutput(value: string, severity?: severity): void { this.model.appendReplOutput(value, severity); } public removeReplExpressions(): void { this.model.removeReplExpressions(); } public setVariable(variable: debug.IExpression, value: string): TPromise<any> { if (!this.session || !(variable instanceof model.Variable)) { return TPromise.as(null); } return this.session.setVariable({ name: variable.name, value, variablesReference: (<model.Variable>variable).parent.reference }).then(response => { variable.value = response.body.value; // Evaluate all watch expressions again since changing variable value might have changed some #8118. return this.setFocusedStackFrameAndEvaluate(this.viewModel.getFocusedStackFrame()); }, err => { (<model.Variable>variable).errorMessage = err.message; }); } public addWatchExpression(name: string): TPromise<void> { return this.model.addWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), name); } public renameWatchExpression(id: string, newName: string): TPromise<void> { return this.model.renameWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), id, newName); } public removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); } public createSession(noDebug: boolean, configuration?: debug.IConfig): TPromise<any> { this.removeReplExpressions(); return this.textFileService.saveAll() // make sure all dirty files are saved .then(() => this.configurationService.reloadConfiguration() // make sure configuration is up to date .then(() => this.extensionService.onReady() .then(() => this.configurationManager.setConfiguration(configuration || this.configurationManager.configurationName) .then(() => this.configurationManager.resolveInteractiveVariables()) .then(resolvedConfiguration => { configuration = resolvedConfiguration; if (!configuration) { return this.configurationManager.openConfigFile(false).then(openend => { if (openend) { this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application.")); } }); } if (configuration.silentlyAbort) { return; } configuration.noDebug = noDebug; if (!this.configurationManager.adapter) { return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type))) : TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."), { actions: [this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), CloseAction] })); } return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => { const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0; if (successExitCode || (errorCount === 0 && !failureExitCode)) { return this.doCreateSession(configuration); } this.messageService.show(severity.Error, { message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode), actions: [new Action('debug.continue', nls.localize('debugAnyway', "Debug Anyway"), null, true, () => { this.messageService.hideAll(); return this.doCreateSession(configuration); }), CloseAction] }); }, (err: TaskError) => { if (err.code !== TaskErrors.NotConfigured) { throw err; } this.messageService.show(err.severity, { message: err.message, actions: [this.taskService.configureAction(), CloseAction] }); }); })))); } private doCreateSession(configuration: debug.IExtHostConfig): TPromise<any> { this.setStateAndEmit(debug.State.Initializing); return this.telemetryService.getTelemetryInfo().then(info => { const telemetryInfo: { [key: string]: string } = Object.create(null); telemetryInfo['common.vscodemachineid'] = info.machineId; telemetryInfo['common.vscodesessionid'] = info.sessionId; return telemetryInfo; }).then(data => { const { aiKey, type } = this.configurationManager.adapter; const publisher = this.configurationManager.adapter.extensionDescription.publisher; this.customTelemetryService = null; if (aiKey) { const client = new Client( uri.parse(require.toUrl('bootstrap')).fsPath, { serverName: 'Debug Telemetry', timeout: 1000 * 60 * 5, args: [`${ publisher }.${ type }`, JSON.stringify(data), aiKey], env: { ELECTRON_RUN_AS_NODE: 1, PIPE_LOGGING: 'true', AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp' } } ); const channel = client.getChannel('telemetryAppender'); const appender = new TelemetryAppenderClient(channel); this.toDisposeOnSessionEnd.push(client); this.customTelemetryService = new TelemetryService({ appender }, this.configurationService); } this.session = this.instantiationService.createInstance(RawDebugSession, configuration.debugServer, this.configurationManager.adapter, this.customTelemetryService); this.registerSessionListeners(); return this.session.initialize({ adapterID: configuration.type, pathFormat: 'path', linesStartAt1: true, columnsStartAt1: true, supportsVariableType: true, // #8858 supportsVariablePaging: true, // #9537 supportsRunInTerminalRequest: true // #10574 }).then((result: DebugProtocol.InitializeResponse) => { if (!this.session) { return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly"))); } this.model.setExceptionBreakpoints(this.session.configuration.capabilities.exceptionBreakpointFilters); return configuration.request === 'attach' ? this.session.attach(configuration) : this.session.launch(configuration); }).then((result: DebugProtocol.Response) => { if (!this.session) { return TPromise.as(null); } if (configuration.internalConsoleOptions === 'openOnSessionStart' || (!this.viewModel.changedWorkbenchViewState && configuration.internalConsoleOptions !== 'neverOpen')) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } if (!this.viewModel.changedWorkbenchViewState && !this.partService.isSideBarHidden()) { // We only want to change the workbench view state on the first debug session #5738 and if the side bar is not hidden this.viewModel.changedWorkbenchViewState = true; this.viewletService.openViewlet(debug.VIEWLET_ID); } // Do not change status bar to orange if we are just running without debug. if (!configuration.noDebug) { this.partService.addClass('debugging'); } this.extensionService.activateByEvent(`onDebug:${configuration.type}`).done(null, errors.onUnexpectedError); this.inDebugMode.set(true); this.lazyTransitionToRunningState(); this.telemetryService.publicLog('debugSessionStart', { type: configuration.type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: `${ this.configurationManager.adapter.extensionDescription.publisher }.${ this.configurationManager.adapter.extensionDescription.name }`, isBuiltin: this.configurationManager.adapter.extensionDescription.isBuiltin }); }).then(undefined, (error: any) => { if (error instanceof Error && error.message === 'Canceled') { // Do not show 'canceled' error messages to the user #7906 return TPromise.as(null); } this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined }); this.setStateAndEmit(debug.State.Inactive); if (this.session) { this.session.disconnect().done(null, errors.onUnexpectedError); } // Show the repl if some error got logged there #5870 if (this.model.getReplElements().length > 0) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction]; return TPromise.wrapError(errors.create(error.message, { actions })); }); }); } private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> { if (!taskName) { return TPromise.as(null); } // run a task before starting a debug session return this.taskService.tasks().then(descriptions => { const filteredTasks = descriptions.filter(task => task.name === taskName); if (filteredTasks.length !== 1) { return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), { actions: [ this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), this.taskService.configureAction(), CloseAction ] })); } // task is already running - nothing to do. if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) { return TPromise.as(null); } if (this.lastTaskEvent) { // there is a different task running currently. return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName))); } // no task running, execute the preLaunchTask. const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => { this.lastTaskEvent = null; return result; }, err => { this.lastTaskEvent = null; }); if (filteredTasks[0].isWatching) { return new TPromise((c, e) => this.taskService.addOneTimeDisposableListener(TaskServiceEvents.Inactive, () => c(null))); } return taskPromise; }); } private rawAttach(port: number): TPromise<any> { if (this.session) { return this.session.attach({ port }); } this.setStateAndEmit(debug.State.Initializing); const configuration = <debug.IExtHostConfig>this.configurationManager.configuration; return this.doCreateSession({ type: configuration.type, request: 'attach', port, sourceMaps: configuration.sourceMaps, outDir: configuration.outDir, debugServer: configuration.debugServer }); } public restartSession(): TPromise<any> { return this.session ? this.session.disconnect(true).then(() => new TPromise<void>((c, e) => { setTimeout(() => { this.createSession(false, null).then(() => c(null), err => e(err)); }, 300); }) ) : this.createSession(false, null); } public getActiveSession(): debug.IRawDebugSession { return this.session; } private onSessionEnd(): void { if (this.session) { const bpsExist = this.model.getBreakpoints().length > 0; this.telemetryService.publicLog('debugSessionStop', { type: this.session.configuration.type, success: this.session.emittedStopped || !bpsExist, sessionLengthInSeconds: this.session.getLengthInSeconds(), breakpointCount: this.model.getBreakpoints().length, watchExpressionsCount: this.model.getWatchExpressions().length }); } this.session = null; try { this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd); } catch (e) { // an internal module might be open so the dispose can throw -> ignore and continue with stop session. } this.partService.removeClass('debugging'); this.model.clearThreads(true); this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); this.setStateAndEmit(debug.State.Inactive); // set breakpoints back to unverified since the session ended. // source reference changes across sessions, so we do not use it to persist the source. const data: { [id: string]: { line: number, verified: boolean } } = {}; this.model.getBreakpoints().forEach(bp => { delete bp.source.raw.sourceReference; data[bp.getId()] = { line: bp.lineNumber, verified: false }; }); this.model.updateBreakpoints(data); this.inDebugMode.reset(); } public getModel(): debug.IModel { return this.model; } public getViewModel(): debug.IViewModel { return this.viewModel; } public openOrRevealSource(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> { const visibleEditors = this.editorService.getVisibleEditors(); for (let i = 0; i < visibleEditors.length; i++) { const fileInput = asFileEditorInput(visibleEditors[i].input); if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) || (visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) { const control = <editorbrowser.ICodeEditor>visibleEditors[i].getControl(); if (control) { control.revealLineInCenterIfOutsideViewport(lineNumber); control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }); this.editorGroupService.activateGroup(i); if (!preserveFocus) { this.editorGroupService.focusGroup(i); } } return TPromise.as(null); } } if (source.inMemory) { // internal module if (source.reference !== 0 && this.session && source.available) { return this.session.source({ sourceReference: source.reference }).then(response => { const mime = response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0]; return this.getDebugStringEditorInput(source, response.body.content, mime); }, (err: DebugProtocol.ErrorResponse) => { // Display the error from debug adapter using a temporary editor #8836 return this.getDebugErrorEditorInput(source, err.message); }).then(editorInput => { return this.editorService.openEditor(editorInput, { preserveFocus, selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 } }, sideBySide); }); } return this.sourceIsUnavailable(source, sideBySide); } return this.fileService.resolveFile(source.uri).then(() => this.editorService.openEditor({ resource: source.uri, options: { selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }, preserveFocus: preserveFocus } }, sideBySide), err => this.sourceIsUnavailable(source, sideBySide) ); } private sourceIsUnavailable(source: Source, sideBySide: boolean): TPromise<any> { this.model.sourceIsUnavailable(source); const editorInput = this.getDebugErrorEditorInput(source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.name)); return this.editorService.openEditor(editorInput, { preserveFocus: true }, sideBySide); } public getConfigurationManager(): debug.IConfigurationManager { return this.configurationManager; } public next(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.next({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public stepIn(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.stepIn({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public stepOut(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.stepOut({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public stepBack(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.stepBack({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public continue(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.continue({ threadId }).then(response => { const allThreadsContinued = response.body ? response.body.allThreadsContinued !== false : true; this.lazyTransitionToRunningState(allThreadsContinued ? undefined : threadId); }); } public pause(threadId: number): TPromise<any> { if (!this.session) { return TPromise.as(null); } return this.session.pause({ threadId }); } public restartFrame(frameId: number): TPromise<any> { if (!this.session) { return TPromise.as(null); } return this.session.restartFrame({ frameId }); } public completions(text: string, position: Position): TPromise<ISuggestion[]> { if (!this.session || !this.session.configuration.capabilities.supportsCompletionsRequest) { return TPromise.as([]); } const focussedStackFrame = this.viewModel.getFocusedStackFrame(); return this.session.completions({ frameId: focussedStackFrame ? focussedStackFrame.frameId : undefined, text, column: position.column, line: position.lineNumber }).then(response => { return !response ? [] : response.body.targets.map(item => ({ label: item.label, insertText: item.text || item.label, type: item.type })); }, err => []); } private lazyTransitionToRunningState(threadId?: number): void { let setNewFocusedStackFrameScheduler: RunOnceScheduler; const toDispose = this.session.onDidStop(e => { if (e.body.threadId === threadId || e.body.allThreadsStopped || !threadId) { setNewFocusedStackFrameScheduler.cancel(); } }); this.model.clearThreads(false, threadId); // Get a top stack frame of a stopped thread if there is any. const threads = this.model.getThreads(); const stoppedReference = Object.keys(threads).filter(ref => threads[ref].stopped).pop(); const stoppedThread = stoppedReference ? threads[parseInt(stoppedReference)] : null; const callStack = stoppedThread ? stoppedThread.getCachedCallStack() : null; const stackFrameToFocus = callStack && callStack.length > 0 ? callStack[0] : null; if (!stoppedThread) { this.setStateAndEmit(this.configurationManager.configuration.noDebug ? debug.State.RunningNoDebug : debug.State.Running); } // Do not immediatly set a new focused stack frame since that might cause unnecessery flickering // of the tree in the debug viewlet. Only set focused stack frame if no stopped event has arrived in 500ms. setNewFocusedStackFrameScheduler = new RunOnceScheduler(() => { toDispose.dispose(); aria.status(nls.localize('debuggingContinued', "Debugging continued.")); this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError); }, 500); setNewFocusedStackFrameScheduler.schedule(); } private getDebugStringEditorInput(source: Source, value: string, mtype: string): DebugStringEditorInput { const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0); this.toDisposeOnSessionEnd.push(result); return result; } private getDebugErrorEditorInput(source: Source, value: string): DebugErrorEditorInput { const result = this.instantiationService.createInstance(DebugErrorEditorInput, source.name, value); this.toDisposeOnSessionEnd.push(result); return result; } private sendAllBreakpoints(): TPromise<any> { return TPromise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri))) .then(() => this.sendFunctionBreakpoints()) // send exception breakpoints at the end since some debug adapters rely on the order .then(() => this.sendExceptionBreakpoints()); } private sendBreakpoints(modelUri: uri, sourceModified = false): TPromise<void> { if (!this.session || !this.session.readyForBreakpoints) { return TPromise.as(null); } if (this.textFileService.isDirty(modelUri)) { // Only send breakpoints for a file once it is not dirty #8077 this.breakpointsToSendOnResourceSaved[modelUri.toString()] = true; return TPromise.as(null); } const breakpointsToSend = arrays.distinct( this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()), bp => `${bp.desiredLineNumber}` ); const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, this.model); return this.session.setBreakpoints({ source: rawSource, lines: breakpointsToSend.map(bp => bp.desiredLineNumber), breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition })), sourceModified }).then(response => { const data: { [id: string]: { line?: number, verified: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateBreakpoints(data); }); } private sendFunctionBreakpoints(): TPromise<void> { if (!this.session || !this.session.readyForBreakpoints || !this.session.configuration.capabilities.supportsFunctionBreakpoints) { return TPromise.as(null); } const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => { const data: { [id: string]: { name?: string, verified?: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateFunctionBreakpoints(data); }); } private sendExceptionBreakpoints(): TPromise<any> { if (!this.session || !this.session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) { return TPromise.as(null); } const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return this.session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) }); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED))); fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved[event.resource.toString()]) { this.breakpointsToSendOnResourceSaved[event.resource.toString()] = false; this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError); } }); } private store(): void { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE); this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.configurationManager.configurationName, StorageScope.WORKSPACE); this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions().map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } public dispose(): void { this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd); this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/parts/debug/electron-browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.9831526279449463, 0.01088389940559864, 0.00016091426368802786, 0.000172589483554475, 0.09457749873399734 ]
{ "id": 8, "code_window": [ "\t\t\tframeId: focussedStackFrame ? focussedStackFrame.frameId : undefined,\n", "\t\t\ttext,\n", "\t\t\tcolumn: position.column,\n", "\t\t\tline: position.lineNumber\n", "\t\t}).then(response => {\n", "\t\t\treturn !response ? [] : response.body.targets.map(item => ({\n", "\t\t\t\tlabel: item.label,\n", "\t\t\t\tinsertText: item.text || item.label,\n", "\t\t\t\ttype: item.type\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\treturn response && response.body && response.body.targets ? response.body.targets.map(item => ({\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 959 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { createConnection, IConnection, Range, TextDocuments, TextDocument, InitializeParams, InitializeResult, RequestType } from 'vscode-languageserver'; import {getCSSLanguageService, getSCSSLanguageService, getLESSLanguageService, LanguageSettings, LanguageService, Stylesheet} from 'vscode-css-languageservice'; import {getLanguageModelCache} from './languageModelCache'; namespace ColorSymbolRequest { export const type: RequestType<string, Range[], any> = { get method() { return 'css/colorSymbols'; } }; } export interface Settings { css: LanguageSettings; less: LanguageSettings; scss: LanguageSettings; } // Create a connection for the server. let connection: IConnection = createConnection(); console.log = connection.console.log.bind(connection.console); console.error = connection.console.error.bind(connection.console); // Create a simple text document manager. The text document manager // supports full document sync only let documents: TextDocuments = new TextDocuments(); // Make the text document manager listen on the connection // for open, change and close text document events documents.listen(connection); let stylesheets = getLanguageModelCache<Stylesheet>(10, 60, document => getLanguageService(document).parseStylesheet(document)); documents.onDidClose(e => { stylesheets.onDocumentRemoved(e.document); }); connection.onShutdown(() => { stylesheets.dispose(); }); // After the server has started the client sends an initilize request. The server receives // in the passed params the rootPath of the workspace plus the client capabilities. connection.onInitialize((params: InitializeParams): InitializeResult => { return { capabilities: { // Tell the client that the server works in FULL text document sync mode textDocumentSync: documents.syncKind, completionProvider: { resolveProvider: false }, hoverProvider: true, documentSymbolProvider: true, referencesProvider: true, definitionProvider: true, documentHighlightProvider: true, codeActionProvider: true, renameProvider: true } }; }); let languageServices : { [id:string]: LanguageService} = { css: getCSSLanguageService(), scss: getSCSSLanguageService(), less: getLESSLanguageService() }; function getLanguageService(document: TextDocument) { let service = languageServices[document.languageId]; if (!service) { connection.console.log('Document type is ' + document.languageId + ', using css instead.'); service = languageServices['css']; } return service; } // The settings have changed. Is send on server activation as well. connection.onDidChangeConfiguration(change => { updateConfiguration(<Settings>change.settings); }); function updateConfiguration(settings: Settings) { for (let languageId in languageServices) { languageServices[languageId].configure(settings[languageId]); } // Revalidate any open text documents documents.all().forEach(triggerValidation); } let pendingValidationRequests : { [uri:string]: NodeJS.Timer } = {}; const validationDelayMs = 200; // The content of a text document has changed. This event is emitted // when the text document first opened or when its content has changed. documents.onDidChangeContent(change => { triggerValidation(change.document); }); // a document has closed: clear all diagnostics documents.onDidClose(event => { cleanPendingValidation(event.document); connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] }); }); function cleanPendingValidation(textDocument: TextDocument): void { let request = pendingValidationRequests[textDocument.uri]; if (request) { clearTimeout(request); delete pendingValidationRequests[textDocument.uri]; } } function triggerValidation(textDocument: TextDocument): void { cleanPendingValidation(textDocument); pendingValidationRequests[textDocument.uri] = setTimeout(() => { delete pendingValidationRequests[textDocument.uri]; validateTextDocument(textDocument); }, validationDelayMs); } function validateTextDocument(textDocument: TextDocument): void { let stylesheet = stylesheets.get(textDocument); let diagnostics = getLanguageService(textDocument).doValidation(textDocument, stylesheet); // Send the computed diagnostics to VSCode. connection.sendDiagnostics({ uri: textDocument.uri, diagnostics }); } connection.onCompletion(textDocumentPosition => { let document = documents.get(textDocumentPosition.textDocument.uri); let stylesheet = stylesheets.get(document); return getLanguageService(document).doComplete(document, textDocumentPosition.position, stylesheet); }); connection.onHover(textDocumentPosition => { let document = documents.get(textDocumentPosition.textDocument.uri); let styleSheet = stylesheets.get(document); return getLanguageService(document).doHover(document, textDocumentPosition.position, styleSheet); }); connection.onDocumentSymbol(documentSymbolParams => { let document = documents.get(documentSymbolParams.textDocument.uri); let stylesheet = stylesheets.get(document); return getLanguageService(document).findDocumentSymbols(document, stylesheet); }); connection.onDefinition(documentSymbolParams => { let document = documents.get(documentSymbolParams.textDocument.uri); let stylesheet = stylesheets.get(document); return getLanguageService(document).findDefinition(document, documentSymbolParams.position, stylesheet); }); connection.onDocumentHighlight(documentSymbolParams => { let document = documents.get(documentSymbolParams.textDocument.uri); let stylesheet = stylesheets.get(document); return getLanguageService(document).findDocumentHighlights(document, documentSymbolParams.position, stylesheet); }); connection.onReferences(referenceParams => { let document = documents.get(referenceParams.textDocument.uri); let stylesheet = stylesheets.get(document); return getLanguageService(document).findReferences(document, referenceParams.position, stylesheet); }); connection.onCodeAction(codeActionParams => { let document = documents.get(codeActionParams.textDocument.uri); let stylesheet = stylesheets.get(document); return getLanguageService(document).doCodeActions(document, codeActionParams.range, codeActionParams.context, stylesheet); }); connection.onRequest(ColorSymbolRequest.type, uri => { let document = documents.get(uri); let stylesheet = stylesheets.get(document); return getLanguageService(document).findColorSymbols(document, stylesheet); }); connection.onRenameRequest(renameParameters => { let document = documents.get(renameParameters.textDocument.uri); let stylesheet = stylesheets.get(document); return getLanguageService(document).doRename(document, renameParameters.position, renameParameters.newName, stylesheet); }); // Listen on the connection connection.listen();
extensions/css/server/src/cssServerMain.ts
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00020643624884542078, 0.00017374925664626062, 0.0001650866906857118, 0.000172351865330711, 0.00000828682732390007 ]
{ "id": 8, "code_window": [ "\t\t\tframeId: focussedStackFrame ? focussedStackFrame.frameId : undefined,\n", "\t\t\ttext,\n", "\t\t\tcolumn: position.column,\n", "\t\t\tline: position.lineNumber\n", "\t\t}).then(response => {\n", "\t\t\treturn !response ? [] : response.body.targets.map(item => ({\n", "\t\t\t\tlabel: item.label,\n", "\t\t\t\tinsertText: item.text || item.label,\n", "\t\t\t\ttype: item.type\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\treturn response && response.body && response.body.targets ? response.body.targets.map(item => ({\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 959 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "format.endWithNewline": "Endet mit einer neuen Zeile.", "format.extraLiners": "Die Liste der Tags (durch Kommas getrennt), vor denen eine zusätzliche neue Zeile eingefügt werden soll. \"null\" verwendet standardmäßig \"head, body, /HTML\".", "format.indentHandlebars": "Formatiert {{#foo}} und {{/foo}} und nimmt einen Einzug vor.", "format.indentInnerHtml": "Nimmt einen Einzug für <head>- und <body>-Abschnitte vor.", "format.maxPreserveNewLines": "Die maximale Anzahl von Zeilenumbrüchen, die in einem Block beibehalten werden soll. Verwenden Sie \"null\" für eine unbegrenzte Anzahl.", "format.preserveNewLines": "Gibt an, ob vorhandene Zeilenumbrüche vor Elemente beibehalten werden sollen. Funktioniert nur vor Elementen, nicht in Tags oder für Text.", "format.unformatted": "Die Liste der Tags (durch Kommas getrennt), die nicht erneut formatiert werden sollen. \"null\" bezieht sich standardmäßig auf alle Tags, die unter https://www.w3.org/TR/html5/dom.html#phrasing-content aufgeführt werden.", "format.wrapLineLength": "Die maximale Anzahl von Zeichen pro Zeile (0 = deaktiviert).", "htmlConfigurationTitle": "HTML" }
i18n/deu/src/vs/languages/html/common/html.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017024404951371253, 0.0001676222454989329, 0.00016500044148415327, 0.0001676222454989329, 0.0000026218040147796273 ]
{ "id": 8, "code_window": [ "\t\t\tframeId: focussedStackFrame ? focussedStackFrame.frameId : undefined,\n", "\t\t\ttext,\n", "\t\t\tcolumn: position.column,\n", "\t\t\tline: position.lineNumber\n", "\t\t}).then(response => {\n", "\t\t\treturn !response ? [] : response.body.targets.map(item => ({\n", "\t\t\t\tlabel: item.label,\n", "\t\t\t\tinsertText: item.text || item.label,\n", "\t\t\t\ttype: item.type\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\t\treturn response && response.body && response.body.targets ? response.body.targets.map(item => ({\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 959 }
# Header 1 # ## Header 2 ## ### Header 3 ### (Hashes on right are optional) ## Markdown plus h2 with a custom ID ## {#id-goes-here} [Link back to H2](#id-goes-here) <!-- html madness --> <div class="custom-class" markdown="1"> <div> nested div </div> <script type='text/x-koka'> function( x: int ) { return x*x; } </script> This is a div _with_ underscores and a & <b class="bold">bold</b> element. <style> body { font: "Consolas" } </style> </div> * Bullet lists are easy too - Another one + Another one This is a paragraph, which is text surrounded by whitespace. Paragraphs can be on one line (or many), and can drone on for hours. Now some inline markup like _italics_, **bold**, and `code()`. Note that underscores in_words_are ignored. ````application/json { value: ["or with a mime type"] } ```` > Blockquotes are like quoted text in email replies >> And, they can be nested 1. A numbered list 2. Which is numbered 3. With periods and a space And now some code: // Code is just text indented a bit which(is_easy) to_remember(); And a block ~~~ // Markdown extra adds un-indented code blocks too if (this_is_more_code == true && !indented) { // tild wrapped code blocks, also not indented } ~~~ Text with two trailing spaces (on the right) can be used for things like poems ### Horizontal rules * * * * **** -------------------------- ![picture alt](/images/photo.jpeg "Title is optional") ## Markdown plus tables ## | Header | Header | Right | | ------ | ------ | -----: | | Cell | Cell | $10 | | Cell | Cell | $20 | * Outer pipes on tables are optional * Colon used for alignment (right versus left) ## Markdown plus definition lists ## Bottled water : $ 1.25 : $ 1.55 (Large) Milk Pop : $ 1.75 * Multiple definitions and terms are possible * Definitions can include multiple paragraphs too *[ABBR]: Markdown plus abbreviations (produces an <abbr> tag)
extensions/markdown/test/colorize-fixtures/test.md
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00018034738604910672, 0.00016984142712317407, 0.00016501350910402834, 0.0001680586428847164, 0.0000049150521590490825 ]
{ "id": 9, "code_window": [ "\t\t\t\tlabel: item.label,\n", "\t\t\t\tinsertText: item.text || item.label,\n", "\t\t\t\ttype: item.type\n", "\t\t\t}));\n", "\t\t}, err => []);\n", "\t}\n", "\n", "\tprivate lazyTransitionToRunningState(threadId?: number): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t})) : [];\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 963 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import {TPromise} from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import lifecycle = require('vs/base/common/lifecycle'); import Event, {Emitter} from 'vs/base/common/event'; import uuid = require('vs/base/common/uuid'); import objects = require('vs/base/common/objects'); import severity from 'vs/base/common/severity'; import types = require('vs/base/common/types'); import arrays = require('vs/base/common/arrays'); import debug = require('vs/workbench/parts/debug/common/debug'); import {Source} from 'vs/workbench/parts/debug/common/debugSource'; const MAX_REPL_LENGTH = 10000; const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source"); function massageValue(value: string): string { return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value; } export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> { if (!session) { expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE; expression.available = false; expression.reference = 0; return TPromise.as(expression); } return session.evaluate({ expression: expression.name, frameId: stackFrame ? stackFrame.frameId : undefined, context }).then(response => { expression.available = !!(response && response.body); if (response && response.body) { expression.value = response.body.result; expression.reference = response.body.variablesReference; expression.namedVariables = response.body.namedVariables; expression.indexedVariables = response.body.indexedVariables; expression.type = response.body.type; } return expression; }, err => { expression.value = err.message; expression.available = false; expression.reference = 0; return expression; }); } const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/; const arrayElementSyntax = /\[.*\]$/; export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string { let names = [expression.name]; if (expression instanceof Variable) { let v = (<Variable> expression).parent; while (v instanceof Variable || v instanceof Expression) { names.push((<Variable> v).name); v = (<Variable> v).parent; } } names = names.reverse(); let result = null; names.forEach(name => { if (!result) { result = name; } else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) { // use safe way to access node properties a['property_name']. Also handles array elements. result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`; } else { result = `${ result }.${ name }`; } }); return result; } export class Thread implements debug.IThread { private promisedCallStack: TPromise<debug.IStackFrame[]>; private cachedCallStack: debug.IStackFrame[]; public stoppedDetails: debug.IRawStoppedDetails; public stopped: boolean; constructor(public name: string, public threadId: number) { this.promisedCallStack = undefined; this.stoppedDetails = undefined; this.cachedCallStack = undefined; this.stopped = false; } public getId(): string { return `thread:${ this.name }:${ this.threadId }`; } public clearCallStack(): void { this.promisedCallStack = undefined; this.cachedCallStack = undefined; } public getCachedCallStack(): debug.IStackFrame[] { return this.cachedCallStack; } public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> { if (!this.stopped) { return TPromise.as([]); } if (!this.promisedCallStack) { this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => { this.cachedCallStack = callStack; return callStack; }); } else if (getAdditionalStackFrames) { this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => { this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart); return this.cachedCallStack; })); } return this.promisedCallStack; } private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> { let session = debugService.getActiveSession(); return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => { this.stoppedDetails.totalFrames = response.body.totalFrames; return response.body.stackFrames.map((rsf, level) => { if (!rsf) { return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined); } return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column); }); }, (err: Error) => { this.stoppedDetails.framesErrorMessage = err.message; return []; }); } } export class OutputElement implements debug.ITreeElement { private static ID_COUNTER = 0; constructor(private id = OutputElement.ID_COUNTER++) { // noop } public getId(): string { return `outputelement:${ this.id }`; } } export class ValueOutputElement extends OutputElement { constructor( public value: string, public severity: severity, public category?: string, public counter: number = 1 ) { super(); } } export class KeyValueOutputElement extends OutputElement { private static MAX_CHILDREN = 1000; // upper bound of children per value private children: debug.ITreeElement[]; private _valueName: string; constructor(public key: string, public valueObj: any, public annotation?: string) { super(); this._valueName = null; } public get value(): string { if (this._valueName === null) { if (this.valueObj === null) { this._valueName = 'null'; } else if (Array.isArray(this.valueObj)) { this._valueName = `Array[${this.valueObj.length}]`; } else if (types.isObject(this.valueObj)) { this._valueName = 'Object'; } else if (types.isString(this.valueObj)) { this._valueName = `"${massageValue(this.valueObj)}"`; } else { this._valueName = String(this.valueObj); } if (!this._valueName) { this._valueName = ''; } } return this._valueName; } public getChildren(): debug.ITreeElement[] { if (!this.children) { if (Array.isArray(this.valueObj)) { this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null)); } else if (types.isObject(this.valueObj)) { this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null)); } else { this.children = []; } } return this.children; } } export abstract class ExpressionContainer implements debug.IExpressionContainer { public static allValues: { [id: string]: string } = {}; // Use chunks to support variable paging #9537 private static BASE_CHUNK_SIZE = 100; public valueChanged: boolean; private children: TPromise<debug.IExpression[]>; private _value: string; constructor( public reference: number, private id: string, private cacheChildren: boolean, public namedVariables: number, public indexedVariables: number, private startOfVariables = 0 ) { // noop } public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> { if (!this.cacheChildren || !this.children) { const session = debugService.getActiveSession(); // only variables with reference > 0 have children. if (!session || this.reference <= 0) { this.children = TPromise.as([]); } else { // Check if object has named variables, fetch them independent from indexed variables #9670 this.children = (!!this.namedVariables ? this.fetchVariables(session, undefined, undefined, 'named') : TPromise.as([])).then(childrenArray => { // Use a dynamic chunk size based on the number of elements #9774 let chunkSize = ExpressionContainer.BASE_CHUNK_SIZE; while (this.indexedVariables > chunkSize * ExpressionContainer.BASE_CHUNK_SIZE) { chunkSize *= ExpressionContainer.BASE_CHUNK_SIZE; } if (this.indexedVariables > chunkSize) { // There are a lot of children, create fake intermediate values that represent chunks #9537 const numberOfChunks = Math.ceil(this.indexedVariables / chunkSize); for (let i = 0; i < numberOfChunks; i++) { const start = this.startOfVariables + i * chunkSize; const count = Math.min(chunkSize, this.indexedVariables - i * chunkSize); childrenArray.push(new Variable(this, this.reference, `[${start}..${start + count - 1}]`, '', null, count, null, true, start)); } return childrenArray; } const start = this.getChildrenInChunks ? this.startOfVariables : undefined; const count = this.getChildrenInChunks ? this.indexedVariables : undefined; return this.fetchVariables(session, start, count, 'indexed').then(variables => childrenArray.concat(variables)); }); } } return this.children; } public getId(): string { return this.id; } public get value(): string { return this._value; } private fetchVariables(session: debug.IRawDebugSession, start: number, count: number, filter: 'indexed'|'named'): TPromise<Variable[]> { return session.variables({ variablesReference: this.reference, start, count, filter }).then(response => { return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map( v => new Variable(this, v.variablesReference, v.name, v.value, v.namedVariables, v.indexedVariables, v.type) ); }, (e: Error) => [new Variable(this, 0, null, e.message, 0, 0, null, false)]); } // The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked. private get getChildrenInChunks(): boolean { return !!this.indexedVariables; } public set value(value: string) { this._value = massageValue(value); this.valueChanged = ExpressionContainer.allValues[this.getId()] && ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value; ExpressionContainer.allValues[this.getId()] = value; } } export class Expression extends ExpressionContainer implements debug.IExpression { static DEFAULT_VALUE = 'not available'; public available: boolean; public type: string; constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) { super(0, id, cacheChildren, 0, 0); this.value = Expression.DEFAULT_VALUE; this.available = false; } } export class Variable extends ExpressionContainer implements debug.IExpression { // Used to show the error message coming from the adapter when setting the value #7807 public errorMessage: string; constructor( public parent: debug.IExpressionContainer, reference: number, public name: string, value: string, namedVariables: number, indexedVariables: number, public type: string = null, public available = true, startOfVariables = 0 ) { super(reference, `variable:${parent.getId()}:${name}:${reference}`, true, namedVariables, indexedVariables, startOfVariables); this.value = massageValue(value); } } export class Scope extends ExpressionContainer implements debug.IScope { constructor( private threadId: number, public name: string, reference: number, public expensive: boolean, namedVariables: number, indexedVariables: number ) { super(reference, `scope:${threadId}:${name}:${reference}`, true, namedVariables, indexedVariables); } } export class StackFrame implements debug.IStackFrame { private scopes: TPromise<Scope[]>; constructor( public threadId: number, public frameId: number, public source: Source, public name: string, public lineNumber: number, public column: number ) { this.scopes = null; } public getId(): string { return `stackframe:${ this.threadId }:${ this.frameId }`; } public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> { if (!this.scopes) { this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => { return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables)); }, err => []); } return this.scopes; } } export class Breakpoint implements debug.IBreakpoint { public lineNumber: number; public verified: boolean; public idFromAdapter: number; public message: string; private id: string; constructor( public source: Source, public desiredLineNumber: number, public enabled: boolean, public condition: string ) { if (enabled === undefined) { this.enabled = true; } this.lineNumber = this.desiredLineNumber; this.verified = false; this.id = uuid.generateUuid(); } public getId(): string { return this.id; } } export class FunctionBreakpoint implements debug.IFunctionBreakpoint { private id: string; public verified: boolean; public idFromAdapter: number; constructor(public name: string, public enabled: boolean) { this.verified = false; this.id = uuid.generateUuid(); } public getId(): string { return this.id; } } export class ExceptionBreakpoint implements debug.IExceptionBreakpoint { private id: string; constructor(public filter: string, public label: string, public enabled: boolean) { this.id = uuid.generateUuid(); } public getId(): string { return this.id; } } export class Model implements debug.IModel { private threads: { [reference: number]: debug.IThread; }; private toDispose: lifecycle.IDisposable[]; private replElements: debug.ITreeElement[]; private _onDidChangeBreakpoints: Emitter<void>; private _onDidChangeCallStack: Emitter<void>; private _onDidChangeWatchExpressions: Emitter<debug.IExpression>; private _onDidChangeREPLElements: Emitter<void>; constructor( private breakpoints: debug.IBreakpoint[], private breakpointsActivated: boolean, private functionBreakpoints: debug.IFunctionBreakpoint[], private exceptionBreakpoints: debug.IExceptionBreakpoint[], private watchExpressions: Expression[] ) { this.threads = {}; this.replElements = []; this.toDispose = []; this._onDidChangeBreakpoints = new Emitter<void>(); this._onDidChangeCallStack = new Emitter<void>(); this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>(); this._onDidChangeREPLElements = new Emitter<void>(); } public getId(): string { return 'root'; } public get onDidChangeBreakpoints(): Event<void> { return this._onDidChangeBreakpoints.event; } public get onDidChangeCallStack(): Event<void> { return this._onDidChangeCallStack.event; } public get onDidChangeWatchExpressions(): Event<debug.IExpression> { return this._onDidChangeWatchExpressions.event; } public get onDidChangeReplElements(): Event<void> { return this._onDidChangeREPLElements.event; } public getThreads(): { [reference: number]: debug.IThread; } { return this.threads; } public clearThreads(removeThreads: boolean, reference: number = undefined): void { if (reference) { if (this.threads[reference]) { this.threads[reference].clearCallStack(); this.threads[reference].stoppedDetails = undefined; this.threads[reference].stopped = false; if (removeThreads) { delete this.threads[reference]; } } } else { Object.keys(this.threads).forEach(ref => { this.threads[ref].clearCallStack(); this.threads[ref].stoppedDetails = undefined; this.threads[ref].stopped = false; }); if (removeThreads) { this.threads = {}; ExpressionContainer.allValues = {}; } } this._onDidChangeCallStack.fire(); } public getBreakpoints(): debug.IBreakpoint[] { return this.breakpoints; } public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] { return this.functionBreakpoints; } public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] { return this.exceptionBreakpoints; } public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void { if (data) { this.exceptionBreakpoints = data.map(d => { const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop(); return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default); }); } } public areBreakpointsActivated(): boolean { return this.breakpointsActivated; } public setBreakpointsActivated(activated: boolean): void { this.breakpointsActivated = activated; this._onDidChangeBreakpoints.fire(); } public addBreakpoints(rawData: debug.IRawBreakpoint[]): void { this.breakpoints = this.breakpoints.concat(rawData.map(rawBp => new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition))); this.breakpointsActivated = true; this._onDidChangeBreakpoints.fire(); } public removeBreakpoints(toRemove: debug.IBreakpoint[]): void { this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId())); this._onDidChangeBreakpoints.fire(); } public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void { this.breakpoints.forEach(bp => { const bpData = data[bp.getId()]; if (bpData) { bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber; bp.verified = bpData.verified; bp.idFromAdapter = bpData.id; bp.message = bpData.message; } }); this._onDidChangeBreakpoints.fire(); } public setEnablement(element: debug.IEnablement, enable: boolean): void { element.enabled = enable; if (element instanceof Breakpoint && !element.enabled) { var breakpoint = <Breakpoint> element; breakpoint.lineNumber = breakpoint.desiredLineNumber; breakpoint.verified = false; } this._onDidChangeBreakpoints.fire(); } public enableOrDisableAllBreakpoints(enable: boolean): void { this.breakpoints.forEach(bp => { bp.enabled = enable; if (!enable) { bp.lineNumber = bp.desiredLineNumber; bp.verified = false; } }); this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable); this.functionBreakpoints.forEach(fbp => fbp.enabled = enable); this._onDidChangeBreakpoints.fire(); } public addFunctionBreakpoint(functionName: string): void { this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true)); this._onDidChangeBreakpoints.fire(); } public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void { this.functionBreakpoints.forEach(fbp => { const fbpData = data[fbp.getId()]; if (fbpData) { fbp.name = fbpData.name || fbp.name; fbp.verified = fbpData.verified; fbp.idFromAdapter = fbpData.id; } }); this._onDidChangeBreakpoints.fire(); } public removeFunctionBreakpoints(id?: string): void { this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : []; this._onDidChangeBreakpoints.fire(); } public getReplElements(): debug.ITreeElement[] { return this.replElements; } public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> { const expression = new Expression(name, true); this.addReplElements([expression]); return evaluateExpression(session, stackFrame, expression, 'repl') .then(() => this._onDidChangeREPLElements.fire()); } public logToRepl(value: string | { [key: string]: any }, severity?: severity): void { let elements:OutputElement[] = []; let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]); // string message if (typeof value === 'string') { if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) { previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter } else { let lines = value.trim().split('\n'); lines.forEach((line, index) => { elements.push(new ValueOutputElement(line, severity)); }); } } // key-value output else { elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object."))); } if (elements.length) { this.addReplElements(elements); } this._onDidChangeREPLElements.fire(); } public appendReplOutput(value: string, severity?: severity): void { const elements: OutputElement[] = []; let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]); let lines = value.split('\n'); let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity); if (groupTogether) { // append to previous line if same group previousOutput.value += lines.shift(); } else if (previousOutput && previousOutput.value === '') { // remove potential empty lines between different output types this.replElements.pop(); } // fill in lines as output value elements lines.forEach((line, index) => { elements.push(new ValueOutputElement(line, severity, 'output')); }); this.addReplElements(elements); this._onDidChangeREPLElements.fire(); } private addReplElements(newElements: debug.ITreeElement[]): void { this.replElements.push(...newElements); if (this.replElements.length > MAX_REPL_LENGTH) { this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH); } } public removeReplExpressions(): void { if (this.replElements.length > 0) { this.replElements = []; this._onDidChangeREPLElements.fire(); } } public getWatchExpressions(): Expression[] { return this.watchExpressions; } public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> { const we = new Expression(name, false); this.watchExpressions.push(we); if (!name) { this._onDidChangeWatchExpressions.fire(we); return TPromise.as(null); } return this.evaluateWatchExpressions(session, stackFrame, we.getId()); } public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> { const filtered = this.watchExpressions.filter(we => we.getId() === id); if (filtered.length === 1) { filtered[0].name = newName; return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => { this._onDidChangeWatchExpressions.fire(filtered[0]); }); } return TPromise.as(null); } public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> { if (id) { const filtered = this.watchExpressions.filter(we => we.getId() === id); if (filtered.length !== 1) { return TPromise.as(null); } return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => { this._onDidChangeWatchExpressions.fire(filtered[0]); }); } return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => { this._onDidChangeWatchExpressions.fire(); }); } public clearWatchExpressionValues(): void { this.watchExpressions.forEach(we => { we.value = Expression.DEFAULT_VALUE; we.available = false; we.reference = 0; }); this._onDidChangeWatchExpressions.fire(); } public removeWatchExpressions(id: string = null): void { this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : []; this._onDidChangeWatchExpressions.fire(); } public sourceIsUnavailable(source: Source): void { Object.keys(this.threads).forEach(key => { if (this.threads[key].getCachedCallStack()) { this.threads[key].getCachedCallStack().forEach(stackFrame => { if (stackFrame.source.uri.toString() === source.uri.toString()) { stackFrame.source.available = false; } }); } }); this._onDidChangeCallStack.fire(); } public rawUpdate(data: debug.IRawModelUpdate): void { if (data.thread && !this.threads[data.threadId]) { // A new thread came in, initialize it. this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id); } if (data.stoppedDetails) { // Set the availability of the threads' callstacks depending on // whether the thread is stopped or not if (data.allThreadsStopped) { Object.keys(this.threads).forEach(ref => { // Only update the details if all the threads are stopped // because we don't want to overwrite the details of other // threads that have stopped for a different reason this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails); this.threads[ref].stopped = true; this.threads[ref].clearCallStack(); }); } else { // One thread is stopped, only update that thread. this.threads[data.threadId].stoppedDetails = data.stoppedDetails; this.threads[data.threadId].clearCallStack(); this.threads[data.threadId].stopped = true; } } this._onDidChangeCallStack.fire(); } public dispose(): void { this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/parts/debug/common/debugModel.ts
1
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.0007115585030987859, 0.00018799054669216275, 0.00016196438809856772, 0.00016949282144196332, 0.00008669672388350591 ]
{ "id": 9, "code_window": [ "\t\t\t\tlabel: item.label,\n", "\t\t\t\tinsertText: item.text || item.label,\n", "\t\t\t\ttype: item.type\n", "\t\t\t}));\n", "\t\t}, err => []);\n", "\t}\n", "\n", "\tprivate lazyTransitionToRunningState(threadId?: number): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t})) : [];\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 963 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import {IDisposable} from 'vs/base/common/lifecycle'; import {TPromise} from 'vs/base/common/winjs.base'; import {EditorModel, IEncodingSupport} from 'vs/workbench/common/editor'; import {StringEditorModel} from 'vs/workbench/common/editor/stringEditorModel'; import URI from 'vs/base/common/uri'; import {EndOfLinePreference} from 'vs/editor/common/editorCommon'; import {IFilesConfiguration} from 'vs/platform/files/common/files'; import {IConfigurationService} from 'vs/platform/configuration/common/configuration'; import {IModeService} from 'vs/editor/common/services/modeService'; import {IModelService} from 'vs/editor/common/services/modelService'; import {IMode} from 'vs/editor/common/modes'; import {isUnspecific} from 'vs/base/common/mime'; import Event, {Emitter} from 'vs/base/common/event'; export class UntitledEditorModel extends StringEditorModel implements IEncodingSupport { private textModelChangeListener: IDisposable; private configurationChangeListener: IDisposable; private dirty: boolean; private _onDidChangeDirty: Emitter<void>; private _onDidChangeEncoding: Emitter<void>; private configuredEncoding: string; private preferredEncoding: string; private hasAssociatedFilePath: boolean; constructor( value: string, mime: string, resource: URI, hasAssociatedFilePath: boolean, @IModeService modeService: IModeService, @IModelService modelService: IModelService, @IConfigurationService private configurationService: IConfigurationService ) { super(value, mime, resource, modeService, modelService); this.hasAssociatedFilePath = hasAssociatedFilePath; this.dirty = hasAssociatedFilePath; // untitled associated to file path are dirty right away this._onDidChangeDirty = new Emitter<void>(); this._onDidChangeEncoding = new Emitter<void>(); this.registerListeners(); } public get onDidChangeDirty(): Event<void> { return this._onDidChangeDirty.event; } public get onDidChangeEncoding(): Event<void> { return this._onDidChangeEncoding.event; } protected getOrCreateMode(modeService: IModeService, mime: string, firstLineText?: string): TPromise<IMode> { if (isUnspecific(mime)) { return modeService.getOrCreateModeByFilenameOrFirstLine(this.resource.fsPath, firstLineText); // lookup mode via resource path if the provided mime is unspecific } return super.getOrCreateMode(modeService, mime, firstLineText); } private registerListeners(): void { // Config Changes this.configurationChangeListener = this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationChange(e.config)); } private onConfigurationChange(configuration: IFilesConfiguration): void { this.configuredEncoding = configuration && configuration.files && configuration.files.encoding; } public getValue(): string { if (this.textEditorModel) { return this.textEditorModel.getValue(EndOfLinePreference.TextDefined, true /* Preserve BOM */); } return null; } public getModeId(): string { if (this.textEditorModel) { return this.textEditorModel.getModeId(); } return null; } public getEncoding(): string { return this.preferredEncoding || this.configuredEncoding; } public setEncoding(encoding: string): void { const oldEncoding = this.getEncoding(); this.preferredEncoding = encoding; // Emit if it changed if (oldEncoding !== this.preferredEncoding) { this._onDidChangeEncoding.fire(); } } public isDirty(): boolean { return this.dirty; } public revert(): void { this.dirty = false; this._onDidChangeDirty.fire(); } public load(): TPromise<EditorModel> { return super.load().then((model) => { const configuration = this.configurationService.getConfiguration<IFilesConfiguration>(); // Encoding this.configuredEncoding = configuration && configuration.files && configuration.files.encoding; // Listen to content changes this.textModelChangeListener = this.textEditorModel.onDidChangeContent(e => this.onModelContentChanged()); // Emit initial dirty event if we are if (this.dirty) { setTimeout(() => { this._onDidChangeDirty.fire(); }, 0 /* prevent race condition between creating model and emitting dirty event */); } return model; }); } private onModelContentChanged(): void { // turn dirty if we were not if (!this.dirty) { this.dirty = true; this._onDidChangeDirty.fire(); } // mark the untitled editor as non-dirty once its content becomes empty and we do // not have an associated path set else if (!this.hasAssociatedFilePath && this.textEditorModel.getLineCount() === 1 && this.textEditorModel.getLineContent(1) === '') { this.dirty = false; this._onDidChangeDirty.fire(); } } public dispose(): void { super.dispose(); if (this.textModelChangeListener) { this.textModelChangeListener.dispose(); this.textModelChangeListener = null; } if (this.configurationChangeListener) { this.configurationChangeListener.dispose(); this.configurationChangeListener = null; } this._onDidChangeDirty.dispose(); this._onDidChangeEncoding.dispose(); } }
src/vs/workbench/common/editor/untitledEditorModel.ts
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017548118194099516, 0.00017032591858878732, 0.00016613476327620447, 0.0001703152374830097, 0.00000227320288104238 ]
{ "id": 9, "code_window": [ "\t\t\t\tlabel: item.label,\n", "\t\t\t\tinsertText: item.text || item.label,\n", "\t\t\t\ttype: item.type\n", "\t\t\t}));\n", "\t\t}, err => []);\n", "\t}\n", "\n", "\tprivate lazyTransitionToRunningState(threadId?: number): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t})) : [];\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 963 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import { PPromise, TPromise } from 'vs/base/common/winjs.base'; import glob = require('vs/base/common/glob'); import { IProgress, ILineMatch, IPatternInfo, ISearchStats } from 'vs/platform/search/common/search'; export interface IRawSearch { rootFolders: string[]; extraFiles?: string[]; filePattern?: string; excludePattern?: glob.IExpression; includePattern?: glob.IExpression; contentPattern?: IPatternInfo; maxResults?: number; sortByScore?: boolean; cacheKey?: string; maxFilesize?: number; fileEncoding?: string; } export interface IRawSearchService { fileSearch(search: IRawSearch): PPromise<ISerializedSearchComplete, ISerializedSearchProgressItem>; textSearch(search: IRawSearch): PPromise<ISerializedSearchComplete, ISerializedSearchProgressItem>; clearCache(cacheKey: string): TPromise<void>; } export interface IRawFileMatch { base?: string; relativePath: string; basename: string; size?: number; } export interface ISearchEngine<T> { search: (onResult: (match: T) => void, onProgress: (progress: IProgress) => void, done: (error: Error, complete: ISerializedSearchComplete) => void) => void; cancel: () => void; } export interface ISerializedSearchComplete { limitHit: boolean; stats: ISearchStats; } export interface ISerializedFileMatch { path: string; lineMatches?: ILineMatch[]; } // Type of the possible values for progress calls from the engine export type ISerializedSearchProgressItem = ISerializedFileMatch | ISerializedFileMatch[] | IProgress;
src/vs/workbench/services/search/node/search.ts
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017422292148694396, 0.0001695992104941979, 0.0001677011896390468, 0.00016903544019442052, 0.0000021475318590091774 ]
{ "id": 9, "code_window": [ "\t\t\t\tlabel: item.label,\n", "\t\t\t\tinsertText: item.text || item.label,\n", "\t\t\t\ttype: item.type\n", "\t\t\t}));\n", "\t\t}, err => []);\n", "\t}\n", "\n", "\tprivate lazyTransitionToRunningState(threadId?: number): void {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t})) : [];\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 963 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "diff.days": "{0} j", "diff.days.month": "il y a un mois", "diff.days.verbose": "Il y a {0} jours", "diff.days.week": "il y a une semaine", "diff.days.yesterday": "hier", "diff.hour.verbose": "Il y a 1 heure", "diff.hours": "{0} h", "diff.hours.verbose": "Il y a {0} heures", "diff.minute.verbose": "Il y 1 minute", "diff.minutes": "{0} m", "diff.minutes.verbose": "Il y a {0} minutes", "diff.seconds": "{0} s", "diff.seconds.verbose": "maintenant", "format.date": "{0}-{1}-{2} {3}:{4}:{5}", "format.time": "{0}:{1}:{2}" }
i18n/fra/src/vs/base/common/strings.i18n.json
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.0001742853783071041, 0.00017265515634790063, 0.0001717715640552342, 0.0001719085412332788, 0.0000011540931836862 ]
{ "id": 10, "code_window": [ "\t\t\tbreakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition })),\n", "\t\t\tsourceModified\n", "\t\t}).then(response => {\n", "\t\t\tconst data: { [id: string]: { line?: number, verified: boolean } } = {};\n", "\t\t\tfor (let i = 0; i < breakpointsToSend.length; i++) {\n", "\t\t\t\tdata[breakpointsToSend[i].getId()] = response.body.breakpoints[i];\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!response || !response.body) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "add", "edit_start_line_idx": 1043 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import nls = require('vs/nls'); import lifecycle = require('vs/base/common/lifecycle'); import {guessMimeTypes} from 'vs/base/common/mime'; import Event, {Emitter} from 'vs/base/common/event'; import uri from 'vs/base/common/uri'; import {RunOnceScheduler} from 'vs/base/common/async'; import {Action} from 'vs/base/common/actions'; import arrays = require('vs/base/common/arrays'); import types = require('vs/base/common/types'); import errors = require('vs/base/common/errors'); import severity from 'vs/base/common/severity'; import {TPromise} from 'vs/base/common/winjs.base'; import aria = require('vs/base/browser/ui/aria/aria'); import editorbrowser = require('vs/editor/browser/editorBrowser'); import {ISuggestion} from 'vs/editor/common/modes'; import {Position} from 'vs/editor/common/core/position'; import {IContextKeyService, IContextKey} from 'vs/platform/contextkey/common/contextkey'; import {IMarkerService} from 'vs/platform/markers/common/markers'; import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle'; import {IExtensionService} from 'vs/platform/extensions/common/extensions'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {IFileService, FileChangesEvent, FileChangeType, EventType} from 'vs/platform/files/common/files'; import {IEventService} from 'vs/platform/event/common/event'; import {IMessageService, CloseAction} from 'vs/platform/message/common/message'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {TelemetryService} from 'vs/platform/telemetry/common/telemetryService'; import {TelemetryAppenderClient} from 'vs/platform/telemetry/common/telemetryIpc'; import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage'; import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService'; import {asFileEditorInput} from 'vs/workbench/common/editor'; import debug = require('vs/workbench/parts/debug/common/debug'); import {RawDebugSession} from 'vs/workbench/parts/debug/electron-browser/rawDebugSession'; import model = require('vs/workbench/parts/debug/common/debugModel'); import {DebugStringEditorInput, DebugErrorEditorInput} from 'vs/workbench/parts/debug/browser/debugEditorInputs'; import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel'); import debugactions = require('vs/workbench/parts/debug/browser/debugActions'); import {ConfigurationManager} from 'vs/workbench/parts/debug/node/debugConfigurationManager'; import {Source} from 'vs/workbench/parts/debug/common/debugSource'; import {ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary} from 'vs/workbench/parts/tasks/common/taskService'; import {TaskError, TaskErrors} from 'vs/workbench/parts/tasks/common/taskSystem'; import {IViewletService} from 'vs/workbench/services/viewlet/common/viewletService'; import {IPanelService} from 'vs/workbench/services/panel/common/panelService'; import {IPartService} from 'vs/workbench/services/part/common/partService'; import {ITextFileService} from 'vs/workbench/parts/files/common/files'; import {IConfigurationService} from 'vs/platform/configuration/common/configuration'; import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {IWindowService, IBroadcast} from 'vs/workbench/services/window/electron-browser/windowService'; import {ILogEntry, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL} from 'vs/workbench/services/thread/electron-browser/threadService'; import {ipcRenderer as ipc} from 'electron'; import {Client} from 'vs/base/parts/ipc/node/ipc.cp'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname'; export class DebugService implements debug.IDebugService { public _serviceBrand: any; private _state: debug.State; private _onDidChangeState: Emitter<debug.State>; private session: RawDebugSession; private model: model.Model; private viewModel: viewmodel.ViewModel; private configurationManager: ConfigurationManager; private customTelemetryService: ITelemetryService; private lastTaskEvent: TaskEvent; private toDispose: lifecycle.IDisposable[]; private toDisposeOnSessionEnd: lifecycle.IDisposable[]; private inDebugMode: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: { [uri: string]: boolean }; constructor( @IStorageService private storageService: IStorageService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @ITextFileService private textFileService: ITextFileService, @IViewletService private viewletService: IViewletService, @IPanelService private panelService: IPanelService, @IFileService private fileService: IFileService, @IMessageService private messageService: IMessageService, @IPartService private partService: IPartService, @IWindowService private windowService: IWindowService, @ITelemetryService private telemetryService: ITelemetryService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IEventService eventService: IEventService, @ILifecycleService private lifecycleService: ILifecycleService, @IInstantiationService private instantiationService: IInstantiationService, @IExtensionService private extensionService: IExtensionService, @IMarkerService private markerService: IMarkerService, @ITaskService private taskService: ITaskService, @IConfigurationService private configurationService: IConfigurationService ) { this.toDispose = []; this.toDisposeOnSessionEnd = []; this.session = null; this.breakpointsToSendOnResourceSaved = {}; this._state = debug.State.Inactive; this._onDidChangeState = new Emitter<debug.State>(); if (!this.contextService.getWorkspace()) { this._state = debug.State.Disabled; } this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, 'null')); this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadWatchExpressions()); this.toDispose.push(this.model); this.viewModel = new viewmodel.ViewModel(); this.registerListeners(eventService, lifecycleService); } private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void { this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e))); if (this.taskService) { this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => { this.lastTaskEvent = e; })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => { if (e.type === TaskType.SingleRun) { this.lastTaskEvent = null; } })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => { this.lastTaskEvent = null; })); } lifecycleService.onShutdown(this.store, this); lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.windowService.onBroadcast(this.onBroadcast, this)); } private onBroadcast(broadcast: IBroadcast): void { // attach: PH is ready to be attached to if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) { this.rawAttach(broadcast.payload.port); return; } if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) { this.onSessionEnd(); return; } // from this point on we require an active session let session = this.getActiveSession(); if (!session || session.configuration.type !== 'extensionHost') { return; // we are only intersted if we have an active debug session for extensionHost } // a plugin logged output, show it inside the REPL if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) { let extensionOutput: ILogEntry = broadcast.payload; let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info; let args: any[] = []; try { let parsed = JSON.parse(extensionOutput.arguments); args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o])); } catch (error) { args.push(extensionOutput.arguments); } // add output for each argument logged let simpleVals: any[] = []; for (let i = 0; i < args.length; i++) { let a = args[i]; // undefined gets printed as 'undefined' if (typeof a === 'undefined') { simpleVals.push('undefined'); } // null gets printed as 'null' else if (a === null) { simpleVals.push('null'); } // objects & arrays are special because we want to inspect them in the REPL else if (types.isObject(a) || Array.isArray(a)) { // flush any existing simple values logged if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); simpleVals = []; } // show object this.logToRepl(a, sev); } // string: watch out for % replacement directive // string substitution and formatting @ https://developer.chrome.com/devtools/docs/console else if (typeof a === 'string') { let buf = ''; for (let j = 0, len = a.length; j < len; j++) { if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) { i++; // read over substitution buf += !types.isUndefinedOrNull(args[i]) ? args[i] : ''; // replace j++; // read over directive } else { buf += a[j]; } } simpleVals.push(buf); } // number or boolean is joined together else { simpleVals.push(a); } } // flush simple values if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); } } } private registerSessionListeners(): void { this.toDisposeOnSessionEnd.push(this.session); this.toDisposeOnSessionEnd.push(this.session.onDidInitialize(event => { aria.status(nls.localize('debuggingStarted', "Debugging started.")); this.sendAllBreakpoints().then(() => { if (this.session.configuration.capabilities.supportsConfigurationDoneRequest) { this.session.configurationDone().done(null, e => { // Disconnect the debug session on configuration done error #10596 if (this.session) { this.session.disconnect().done(null, errors.onUnexpectedError); } this.messageService.show(severity.Error, e.message); }); } }); })); this.toDisposeOnSessionEnd.push(this.session.onDidStop(event => { this.setStateAndEmit(debug.State.Stopped); const threadId = event.body.threadId; this.getThreadData().done(() => { this.model.rawUpdate({ threadId, stoppedDetails: event.body, allThreadsStopped: event.body.allThreadsStopped }); const thread = this.model.getThreads()[threadId]; thread.getCallStack(this).then(callStack => { if (callStack.length > 0) { // focus first stack frame from top that has source location const stackFrameToFocus = arrays.first(callStack, sf => sf.source && sf.source.available, callStack[0]); this.setFocusedStackFrameAndEvaluate(stackFrameToFocus, thread).done(null, errors.onUnexpectedError); this.windowService.getWindow().focus(); aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber)); return this.openOrRevealSource(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false); } else { this.setFocusedStackFrameAndEvaluate(null, thread).done(null, errors.onUnexpectedError); } }); }, errors.onUnexpectedError); })); this.toDisposeOnSessionEnd.push(this.session.onDidThread(event => { if (event.body.reason === 'started') { this.getThreadData().done(null, errors.onUnexpectedError); } else if (event.body.reason === 'exited') { this.model.clearThreads(true, event.body.threadId); } })); this.toDisposeOnSessionEnd.push(this.session.onDidTerminateDebugee(event => { aria.status(nls.localize('debuggingStopped', "Debugging stopped.")); if (this.session && this.session.getId() === event.body.sessionId) { if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) { this.restartSession().done(null, err => this.messageService.show(severity.Error, err.message)); } else { this.session.disconnect().done(null, errors.onUnexpectedError); } } })); this.toDisposeOnSessionEnd.push(this.session.onDidContinued(event => { this.lazyTransitionToRunningState(event.body.allThreadsContinued ? undefined : event.body.threadId); })); this.toDisposeOnSessionEnd.push(this.session.onDidOutput(event => { if (event.body && event.body.category === 'telemetry') { // only log telemetry events from debug adapter if the adapter provided the telemetry key // and the user opted in telemetry if (this.customTelemetryService && this.telemetryService.isOptedIn) { this.customTelemetryService.publicLog(event.body.output, event.body.data); } } else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) { this.onOutput(event); } })); this.toDisposeOnSessionEnd.push(this.session.onDidBreakpoint(event => { const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined; const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (breakpoint) { this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint }); } else { const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (functionBreakpoint) { this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint }); } } })); this.toDisposeOnSessionEnd.push(this.session.onDidExitAdapter(event => { // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (this.session.configuration.type === 'extensionHost' && this._state === debug.State.RunningNoDebug) { ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath); } if (this.session && this.session.getId() === event.body.sessionId) { this.onSessionEnd(); } })); } private onOutput(event: DebugProtocol.OutputEvent): void { const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info; this.appendReplOutput(event.body.output, outputSeverity); } private getThreadData(): TPromise<void> { return this.session.threads().then(response => { response.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread })); }); } private loadBreakpoints(): debug.IBreakpoint[] { let result: debug.IBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }), breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] { let result: debug.IFunctionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new model.FunctionBreakpoint(fb.name, fb.enabled); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] { let result: debug.IExceptionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadWatchExpressions(): model.Expression[] { let result: model.Expression[]; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string } ) => { return new model.Expression(watchStoredData.name, false, watchStoredData.id); }); } catch (e) { } return result || []; } public get state(): debug.State { return this._state; } public get onDidChangeState(): Event<debug.State> { return this._onDidChangeState.event; } private setStateAndEmit(newState: debug.State): void { this._state = newState; this._onDidChangeState.fire(newState); } public get enabled(): boolean { return !!this.contextService.getWorkspace(); } public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame, thread?: debug.IThread): TPromise<void> { if (!thread && focusedStackFrame) { thread = this.model.getThreads()[focusedStackFrame.threadId]; } this.viewModel.setFocusedStackFrame(focusedStackFrame, thread); if (focusedStackFrame) { return this.model.evaluateWatchExpressions(this.session, focusedStackFrame); } else { this.model.clearWatchExpressionValues(); return TPromise.as(null); } } public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof model.Breakpoint) { return this.sendBreakpoints((<model.Breakpoint>breakpoint).source.uri); } else if (breakpoint instanceof model.FunctionBreakpoint) { return this.sendFunctionBreakpoints(); } return this.sendExceptionBreakpoints(); } this.model.enableOrDisableAllBreakpoints(enable); return this.sendAllBreakpoints(); } public addBreakpoints(rawBreakpoints: debug.IRawBreakpoint[]): TPromise<void[]> { this.model.addBreakpoints(rawBreakpoints); const uris = arrays.distinct(rawBreakpoints, raw => raw.uri.toString()).map(raw => raw.uri); rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, rbp.uri.fsPath))); return TPromise.join(uris.map(uri => this.sendBreakpoints(uri))); } public removeBreakpoints(id?: string): TPromise<any> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.source.uri.fsPath))); const urisToClear = arrays.distinct(toRemove, bp => bp.source.uri.toString()).map(bp => bp.source.uri); this.model.removeBreakpoints(toRemove); return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri))); } public setBreakpointsActivated(activated: boolean): TPromise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } public addFunctionBreakpoint(): void { this.model.addFunctionBreakpoint(''); } public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> { this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } }); return this.sendFunctionBreakpoints(); } public removeFunctionBreakpoints(id?: string): TPromise<void> { this.model.removeFunctionBreakpoints(id); return this.sendFunctionBreakpoints(); } public addReplExpression(name: string): TPromise<void> { this.telemetryService.publicLog('debugService/addReplExpression'); const focussedStackFrame = this.viewModel.getFocusedStackFrame(); return this.model.addReplExpression(this.session, focussedStackFrame, name) // Evaluate all watch expressions again since repl evaluation might have changed some. .then(() => this.setFocusedStackFrameAndEvaluate(focussedStackFrame)); } public logToRepl(value: string | { [key: string]: any }, severity?: severity): void { this.model.logToRepl(value, severity); } public appendReplOutput(value: string, severity?: severity): void { this.model.appendReplOutput(value, severity); } public removeReplExpressions(): void { this.model.removeReplExpressions(); } public setVariable(variable: debug.IExpression, value: string): TPromise<any> { if (!this.session || !(variable instanceof model.Variable)) { return TPromise.as(null); } return this.session.setVariable({ name: variable.name, value, variablesReference: (<model.Variable>variable).parent.reference }).then(response => { variable.value = response.body.value; // Evaluate all watch expressions again since changing variable value might have changed some #8118. return this.setFocusedStackFrameAndEvaluate(this.viewModel.getFocusedStackFrame()); }, err => { (<model.Variable>variable).errorMessage = err.message; }); } public addWatchExpression(name: string): TPromise<void> { return this.model.addWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), name); } public renameWatchExpression(id: string, newName: string): TPromise<void> { return this.model.renameWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), id, newName); } public removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); } public createSession(noDebug: boolean, configuration?: debug.IConfig): TPromise<any> { this.removeReplExpressions(); return this.textFileService.saveAll() // make sure all dirty files are saved .then(() => this.configurationService.reloadConfiguration() // make sure configuration is up to date .then(() => this.extensionService.onReady() .then(() => this.configurationManager.setConfiguration(configuration || this.configurationManager.configurationName) .then(() => this.configurationManager.resolveInteractiveVariables()) .then(resolvedConfiguration => { configuration = resolvedConfiguration; if (!configuration) { return this.configurationManager.openConfigFile(false).then(openend => { if (openend) { this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application.")); } }); } if (configuration.silentlyAbort) { return; } configuration.noDebug = noDebug; if (!this.configurationManager.adapter) { return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type))) : TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."), { actions: [this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), CloseAction] })); } return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => { const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0; if (successExitCode || (errorCount === 0 && !failureExitCode)) { return this.doCreateSession(configuration); } this.messageService.show(severity.Error, { message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode), actions: [new Action('debug.continue', nls.localize('debugAnyway', "Debug Anyway"), null, true, () => { this.messageService.hideAll(); return this.doCreateSession(configuration); }), CloseAction] }); }, (err: TaskError) => { if (err.code !== TaskErrors.NotConfigured) { throw err; } this.messageService.show(err.severity, { message: err.message, actions: [this.taskService.configureAction(), CloseAction] }); }); })))); } private doCreateSession(configuration: debug.IExtHostConfig): TPromise<any> { this.setStateAndEmit(debug.State.Initializing); return this.telemetryService.getTelemetryInfo().then(info => { const telemetryInfo: { [key: string]: string } = Object.create(null); telemetryInfo['common.vscodemachineid'] = info.machineId; telemetryInfo['common.vscodesessionid'] = info.sessionId; return telemetryInfo; }).then(data => { const { aiKey, type } = this.configurationManager.adapter; const publisher = this.configurationManager.adapter.extensionDescription.publisher; this.customTelemetryService = null; if (aiKey) { const client = new Client( uri.parse(require.toUrl('bootstrap')).fsPath, { serverName: 'Debug Telemetry', timeout: 1000 * 60 * 5, args: [`${ publisher }.${ type }`, JSON.stringify(data), aiKey], env: { ELECTRON_RUN_AS_NODE: 1, PIPE_LOGGING: 'true', AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp' } } ); const channel = client.getChannel('telemetryAppender'); const appender = new TelemetryAppenderClient(channel); this.toDisposeOnSessionEnd.push(client); this.customTelemetryService = new TelemetryService({ appender }, this.configurationService); } this.session = this.instantiationService.createInstance(RawDebugSession, configuration.debugServer, this.configurationManager.adapter, this.customTelemetryService); this.registerSessionListeners(); return this.session.initialize({ adapterID: configuration.type, pathFormat: 'path', linesStartAt1: true, columnsStartAt1: true, supportsVariableType: true, // #8858 supportsVariablePaging: true, // #9537 supportsRunInTerminalRequest: true // #10574 }).then((result: DebugProtocol.InitializeResponse) => { if (!this.session) { return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly"))); } this.model.setExceptionBreakpoints(this.session.configuration.capabilities.exceptionBreakpointFilters); return configuration.request === 'attach' ? this.session.attach(configuration) : this.session.launch(configuration); }).then((result: DebugProtocol.Response) => { if (!this.session) { return TPromise.as(null); } if (configuration.internalConsoleOptions === 'openOnSessionStart' || (!this.viewModel.changedWorkbenchViewState && configuration.internalConsoleOptions !== 'neverOpen')) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } if (!this.viewModel.changedWorkbenchViewState && !this.partService.isSideBarHidden()) { // We only want to change the workbench view state on the first debug session #5738 and if the side bar is not hidden this.viewModel.changedWorkbenchViewState = true; this.viewletService.openViewlet(debug.VIEWLET_ID); } // Do not change status bar to orange if we are just running without debug. if (!configuration.noDebug) { this.partService.addClass('debugging'); } this.extensionService.activateByEvent(`onDebug:${configuration.type}`).done(null, errors.onUnexpectedError); this.inDebugMode.set(true); this.lazyTransitionToRunningState(); this.telemetryService.publicLog('debugSessionStart', { type: configuration.type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: `${ this.configurationManager.adapter.extensionDescription.publisher }.${ this.configurationManager.adapter.extensionDescription.name }`, isBuiltin: this.configurationManager.adapter.extensionDescription.isBuiltin }); }).then(undefined, (error: any) => { if (error instanceof Error && error.message === 'Canceled') { // Do not show 'canceled' error messages to the user #7906 return TPromise.as(null); } this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined }); this.setStateAndEmit(debug.State.Inactive); if (this.session) { this.session.disconnect().done(null, errors.onUnexpectedError); } // Show the repl if some error got logged there #5870 if (this.model.getReplElements().length > 0) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction]; return TPromise.wrapError(errors.create(error.message, { actions })); }); }); } private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> { if (!taskName) { return TPromise.as(null); } // run a task before starting a debug session return this.taskService.tasks().then(descriptions => { const filteredTasks = descriptions.filter(task => task.name === taskName); if (filteredTasks.length !== 1) { return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), { actions: [ this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), this.taskService.configureAction(), CloseAction ] })); } // task is already running - nothing to do. if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) { return TPromise.as(null); } if (this.lastTaskEvent) { // there is a different task running currently. return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName))); } // no task running, execute the preLaunchTask. const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => { this.lastTaskEvent = null; return result; }, err => { this.lastTaskEvent = null; }); if (filteredTasks[0].isWatching) { return new TPromise((c, e) => this.taskService.addOneTimeDisposableListener(TaskServiceEvents.Inactive, () => c(null))); } return taskPromise; }); } private rawAttach(port: number): TPromise<any> { if (this.session) { return this.session.attach({ port }); } this.setStateAndEmit(debug.State.Initializing); const configuration = <debug.IExtHostConfig>this.configurationManager.configuration; return this.doCreateSession({ type: configuration.type, request: 'attach', port, sourceMaps: configuration.sourceMaps, outDir: configuration.outDir, debugServer: configuration.debugServer }); } public restartSession(): TPromise<any> { return this.session ? this.session.disconnect(true).then(() => new TPromise<void>((c, e) => { setTimeout(() => { this.createSession(false, null).then(() => c(null), err => e(err)); }, 300); }) ) : this.createSession(false, null); } public getActiveSession(): debug.IRawDebugSession { return this.session; } private onSessionEnd(): void { if (this.session) { const bpsExist = this.model.getBreakpoints().length > 0; this.telemetryService.publicLog('debugSessionStop', { type: this.session.configuration.type, success: this.session.emittedStopped || !bpsExist, sessionLengthInSeconds: this.session.getLengthInSeconds(), breakpointCount: this.model.getBreakpoints().length, watchExpressionsCount: this.model.getWatchExpressions().length }); } this.session = null; try { this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd); } catch (e) { // an internal module might be open so the dispose can throw -> ignore and continue with stop session. } this.partService.removeClass('debugging'); this.model.clearThreads(true); this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); this.setStateAndEmit(debug.State.Inactive); // set breakpoints back to unverified since the session ended. // source reference changes across sessions, so we do not use it to persist the source. const data: { [id: string]: { line: number, verified: boolean } } = {}; this.model.getBreakpoints().forEach(bp => { delete bp.source.raw.sourceReference; data[bp.getId()] = { line: bp.lineNumber, verified: false }; }); this.model.updateBreakpoints(data); this.inDebugMode.reset(); } public getModel(): debug.IModel { return this.model; } public getViewModel(): debug.IViewModel { return this.viewModel; } public openOrRevealSource(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> { const visibleEditors = this.editorService.getVisibleEditors(); for (let i = 0; i < visibleEditors.length; i++) { const fileInput = asFileEditorInput(visibleEditors[i].input); if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) || (visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) { const control = <editorbrowser.ICodeEditor>visibleEditors[i].getControl(); if (control) { control.revealLineInCenterIfOutsideViewport(lineNumber); control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }); this.editorGroupService.activateGroup(i); if (!preserveFocus) { this.editorGroupService.focusGroup(i); } } return TPromise.as(null); } } if (source.inMemory) { // internal module if (source.reference !== 0 && this.session && source.available) { return this.session.source({ sourceReference: source.reference }).then(response => { const mime = response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0]; return this.getDebugStringEditorInput(source, response.body.content, mime); }, (err: DebugProtocol.ErrorResponse) => { // Display the error from debug adapter using a temporary editor #8836 return this.getDebugErrorEditorInput(source, err.message); }).then(editorInput => { return this.editorService.openEditor(editorInput, { preserveFocus, selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 } }, sideBySide); }); } return this.sourceIsUnavailable(source, sideBySide); } return this.fileService.resolveFile(source.uri).then(() => this.editorService.openEditor({ resource: source.uri, options: { selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }, preserveFocus: preserveFocus } }, sideBySide), err => this.sourceIsUnavailable(source, sideBySide) ); } private sourceIsUnavailable(source: Source, sideBySide: boolean): TPromise<any> { this.model.sourceIsUnavailable(source); const editorInput = this.getDebugErrorEditorInput(source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.name)); return this.editorService.openEditor(editorInput, { preserveFocus: true }, sideBySide); } public getConfigurationManager(): debug.IConfigurationManager { return this.configurationManager; } public next(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.next({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public stepIn(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.stepIn({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public stepOut(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.stepOut({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public stepBack(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.stepBack({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public continue(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.continue({ threadId }).then(response => { const allThreadsContinued = response.body ? response.body.allThreadsContinued !== false : true; this.lazyTransitionToRunningState(allThreadsContinued ? undefined : threadId); }); } public pause(threadId: number): TPromise<any> { if (!this.session) { return TPromise.as(null); } return this.session.pause({ threadId }); } public restartFrame(frameId: number): TPromise<any> { if (!this.session) { return TPromise.as(null); } return this.session.restartFrame({ frameId }); } public completions(text: string, position: Position): TPromise<ISuggestion[]> { if (!this.session || !this.session.configuration.capabilities.supportsCompletionsRequest) { return TPromise.as([]); } const focussedStackFrame = this.viewModel.getFocusedStackFrame(); return this.session.completions({ frameId: focussedStackFrame ? focussedStackFrame.frameId : undefined, text, column: position.column, line: position.lineNumber }).then(response => { return !response ? [] : response.body.targets.map(item => ({ label: item.label, insertText: item.text || item.label, type: item.type })); }, err => []); } private lazyTransitionToRunningState(threadId?: number): void { let setNewFocusedStackFrameScheduler: RunOnceScheduler; const toDispose = this.session.onDidStop(e => { if (e.body.threadId === threadId || e.body.allThreadsStopped || !threadId) { setNewFocusedStackFrameScheduler.cancel(); } }); this.model.clearThreads(false, threadId); // Get a top stack frame of a stopped thread if there is any. const threads = this.model.getThreads(); const stoppedReference = Object.keys(threads).filter(ref => threads[ref].stopped).pop(); const stoppedThread = stoppedReference ? threads[parseInt(stoppedReference)] : null; const callStack = stoppedThread ? stoppedThread.getCachedCallStack() : null; const stackFrameToFocus = callStack && callStack.length > 0 ? callStack[0] : null; if (!stoppedThread) { this.setStateAndEmit(this.configurationManager.configuration.noDebug ? debug.State.RunningNoDebug : debug.State.Running); } // Do not immediatly set a new focused stack frame since that might cause unnecessery flickering // of the tree in the debug viewlet. Only set focused stack frame if no stopped event has arrived in 500ms. setNewFocusedStackFrameScheduler = new RunOnceScheduler(() => { toDispose.dispose(); aria.status(nls.localize('debuggingContinued', "Debugging continued.")); this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError); }, 500); setNewFocusedStackFrameScheduler.schedule(); } private getDebugStringEditorInput(source: Source, value: string, mtype: string): DebugStringEditorInput { const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0); this.toDisposeOnSessionEnd.push(result); return result; } private getDebugErrorEditorInput(source: Source, value: string): DebugErrorEditorInput { const result = this.instantiationService.createInstance(DebugErrorEditorInput, source.name, value); this.toDisposeOnSessionEnd.push(result); return result; } private sendAllBreakpoints(): TPromise<any> { return TPromise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri))) .then(() => this.sendFunctionBreakpoints()) // send exception breakpoints at the end since some debug adapters rely on the order .then(() => this.sendExceptionBreakpoints()); } private sendBreakpoints(modelUri: uri, sourceModified = false): TPromise<void> { if (!this.session || !this.session.readyForBreakpoints) { return TPromise.as(null); } if (this.textFileService.isDirty(modelUri)) { // Only send breakpoints for a file once it is not dirty #8077 this.breakpointsToSendOnResourceSaved[modelUri.toString()] = true; return TPromise.as(null); } const breakpointsToSend = arrays.distinct( this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()), bp => `${bp.desiredLineNumber}` ); const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, this.model); return this.session.setBreakpoints({ source: rawSource, lines: breakpointsToSend.map(bp => bp.desiredLineNumber), breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition })), sourceModified }).then(response => { const data: { [id: string]: { line?: number, verified: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateBreakpoints(data); }); } private sendFunctionBreakpoints(): TPromise<void> { if (!this.session || !this.session.readyForBreakpoints || !this.session.configuration.capabilities.supportsFunctionBreakpoints) { return TPromise.as(null); } const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => { const data: { [id: string]: { name?: string, verified?: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateFunctionBreakpoints(data); }); } private sendExceptionBreakpoints(): TPromise<any> { if (!this.session || !this.session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) { return TPromise.as(null); } const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return this.session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) }); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED))); fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved[event.resource.toString()]) { this.breakpointsToSendOnResourceSaved[event.resource.toString()] = false; this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError); } }); } private store(): void { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE); this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.configurationManager.configurationName, StorageScope.WORKSPACE); this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions().map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } public dispose(): void { this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd); this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/parts/debug/electron-browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.9982359409332275, 0.028275081887841225, 0.00016120157670229673, 0.00017224409384652972, 0.1616830974817276 ]
{ "id": 10, "code_window": [ "\t\t\tbreakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition })),\n", "\t\t\tsourceModified\n", "\t\t}).then(response => {\n", "\t\t\tconst data: { [id: string]: { line?: number, verified: boolean } } = {};\n", "\t\t\tfor (let i = 0; i < breakpointsToSend.length; i++) {\n", "\t\t\t\tdata[breakpointsToSend[i].getId()] = response.body.breakpoints[i];\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!response || !response.body) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "add", "edit_start_line_idx": 1043 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "caseDescription": "大小寫須相符", "defaultLabel": "輸入", "regexDescription": "使用規則運算式", "wordsDescription": "全字拼寫須相符" }
i18n/cht/src/vs/base/browser/ui/findinput/findInput.i18n.json
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017298638704232872, 0.00017259092419408262, 0.00017219547589775175, 0.00017259092419408262, 3.954555722884834e-7 ]
{ "id": 10, "code_window": [ "\t\t\tbreakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition })),\n", "\t\t\tsourceModified\n", "\t\t}).then(response => {\n", "\t\t\tconst data: { [id: string]: { line?: number, verified: boolean } } = {};\n", "\t\t\tfor (let i = 0; i < breakpointsToSend.length; i++) {\n", "\t\t\t\tdata[breakpointsToSend[i].getId()] = response.body.breakpoints[i];\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!response || !response.body) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "add", "edit_start_line_idx": 1043 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "debugLinuxConfiguration": "Linux 특정 시작 구성 특성입니다.", "debugName": "구성 이름이며, 구성 시작 드롭다운 메뉴에 표시됩니다.", "debugOSXConfiguration": "OS X 특정 시작 구성 특성입니다.", "debugPrelaunchTask": "디버그 세션이 시작되기 이전에 실행할 작업입니다.", "debugRequest": "구성 형식을 요청합니다. \"시작\" 또는 \"연결\"일 수 있습니다.", "debugType": "구성의 형식입니다.", "debugWindowsConfiguration": "Windows 특정 시작 구성 특성입니다.", "internalConsoleOptions": "내부 디버그 콘솔의 동작을 제어합니다.", "relativePathsNotConverted": "상대 경로는 더 이상 절대 경로로 자동으로 변환되지 않습니다. ${workspaceRoot}를 접두사로 사용해 보세요." }
i18n/kor/src/vs/workbench/parts/debug/node/debugAdapter.i18n.json
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00016753959062043577, 0.00016703653091099113, 0.0001665334712015465, 0.00016703653091099113, 5.030597094446421e-7 ]
{ "id": 10, "code_window": [ "\t\t\tbreakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition })),\n", "\t\t\tsourceModified\n", "\t\t}).then(response => {\n", "\t\t\tconst data: { [id: string]: { line?: number, verified: boolean } } = {};\n", "\t\t\tfor (let i = 0; i < breakpointsToSend.length; i++) {\n", "\t\t\t\tdata[breakpointsToSend[i].getId()] = response.body.breakpoints[i];\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!response || !response.body) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "add", "edit_start_line_idx": 1043 }
// ATTENTION - THIS DIRECTORY CONTAINS THIRD PARTY OPEN SOURCE MATERIALS: [{ "name": "language-rust", "version": "0.4.4", "license": "MIT", "repositoryURL": "https://github.com/zargony/atom-language-rust", "description": "The files syntaxes/rust.json was derived from the Atom package https://atom.io/packages/language-rust." }]
extensions/rust/OSSREADME.json
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017064269923139364, 0.00017064269923139364, 0.00017064269923139364, 0.00017064269923139364, 0 ]
{ "id": 11, "code_window": [ "\n", "\t\tconst breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());\n", "\t\treturn this.session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => {\n", "\t\t\tconst data: { [id: string]: { name?: string, verified?: boolean } } = {};\n", "\t\t\tfor (let i = 0; i < breakpointsToSend.length; i++) {\n", "\t\t\t\tdata[breakpointsToSend[i].getId()] = response.body.breakpoints[i];\n", "\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!response || !response.body) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "add", "edit_start_line_idx": 1059 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import nls = require('vs/nls'); import lifecycle = require('vs/base/common/lifecycle'); import {guessMimeTypes} from 'vs/base/common/mime'; import Event, {Emitter} from 'vs/base/common/event'; import uri from 'vs/base/common/uri'; import {RunOnceScheduler} from 'vs/base/common/async'; import {Action} from 'vs/base/common/actions'; import arrays = require('vs/base/common/arrays'); import types = require('vs/base/common/types'); import errors = require('vs/base/common/errors'); import severity from 'vs/base/common/severity'; import {TPromise} from 'vs/base/common/winjs.base'; import aria = require('vs/base/browser/ui/aria/aria'); import editorbrowser = require('vs/editor/browser/editorBrowser'); import {ISuggestion} from 'vs/editor/common/modes'; import {Position} from 'vs/editor/common/core/position'; import {IContextKeyService, IContextKey} from 'vs/platform/contextkey/common/contextkey'; import {IMarkerService} from 'vs/platform/markers/common/markers'; import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle'; import {IExtensionService} from 'vs/platform/extensions/common/extensions'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {IFileService, FileChangesEvent, FileChangeType, EventType} from 'vs/platform/files/common/files'; import {IEventService} from 'vs/platform/event/common/event'; import {IMessageService, CloseAction} from 'vs/platform/message/common/message'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {TelemetryService} from 'vs/platform/telemetry/common/telemetryService'; import {TelemetryAppenderClient} from 'vs/platform/telemetry/common/telemetryIpc'; import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage'; import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService'; import {asFileEditorInput} from 'vs/workbench/common/editor'; import debug = require('vs/workbench/parts/debug/common/debug'); import {RawDebugSession} from 'vs/workbench/parts/debug/electron-browser/rawDebugSession'; import model = require('vs/workbench/parts/debug/common/debugModel'); import {DebugStringEditorInput, DebugErrorEditorInput} from 'vs/workbench/parts/debug/browser/debugEditorInputs'; import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel'); import debugactions = require('vs/workbench/parts/debug/browser/debugActions'); import {ConfigurationManager} from 'vs/workbench/parts/debug/node/debugConfigurationManager'; import {Source} from 'vs/workbench/parts/debug/common/debugSource'; import {ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary} from 'vs/workbench/parts/tasks/common/taskService'; import {TaskError, TaskErrors} from 'vs/workbench/parts/tasks/common/taskSystem'; import {IViewletService} from 'vs/workbench/services/viewlet/common/viewletService'; import {IPanelService} from 'vs/workbench/services/panel/common/panelService'; import {IPartService} from 'vs/workbench/services/part/common/partService'; import {ITextFileService} from 'vs/workbench/parts/files/common/files'; import {IConfigurationService} from 'vs/platform/configuration/common/configuration'; import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {IWindowService, IBroadcast} from 'vs/workbench/services/window/electron-browser/windowService'; import {ILogEntry, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL} from 'vs/workbench/services/thread/electron-browser/threadService'; import {ipcRenderer as ipc} from 'electron'; import {Client} from 'vs/base/parts/ipc/node/ipc.cp'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname'; export class DebugService implements debug.IDebugService { public _serviceBrand: any; private _state: debug.State; private _onDidChangeState: Emitter<debug.State>; private session: RawDebugSession; private model: model.Model; private viewModel: viewmodel.ViewModel; private configurationManager: ConfigurationManager; private customTelemetryService: ITelemetryService; private lastTaskEvent: TaskEvent; private toDispose: lifecycle.IDisposable[]; private toDisposeOnSessionEnd: lifecycle.IDisposable[]; private inDebugMode: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: { [uri: string]: boolean }; constructor( @IStorageService private storageService: IStorageService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @ITextFileService private textFileService: ITextFileService, @IViewletService private viewletService: IViewletService, @IPanelService private panelService: IPanelService, @IFileService private fileService: IFileService, @IMessageService private messageService: IMessageService, @IPartService private partService: IPartService, @IWindowService private windowService: IWindowService, @ITelemetryService private telemetryService: ITelemetryService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IEventService eventService: IEventService, @ILifecycleService private lifecycleService: ILifecycleService, @IInstantiationService private instantiationService: IInstantiationService, @IExtensionService private extensionService: IExtensionService, @IMarkerService private markerService: IMarkerService, @ITaskService private taskService: ITaskService, @IConfigurationService private configurationService: IConfigurationService ) { this.toDispose = []; this.toDisposeOnSessionEnd = []; this.session = null; this.breakpointsToSendOnResourceSaved = {}; this._state = debug.State.Inactive; this._onDidChangeState = new Emitter<debug.State>(); if (!this.contextService.getWorkspace()) { this._state = debug.State.Disabled; } this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, 'null')); this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadWatchExpressions()); this.toDispose.push(this.model); this.viewModel = new viewmodel.ViewModel(); this.registerListeners(eventService, lifecycleService); } private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void { this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e))); if (this.taskService) { this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => { this.lastTaskEvent = e; })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => { if (e.type === TaskType.SingleRun) { this.lastTaskEvent = null; } })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => { this.lastTaskEvent = null; })); } lifecycleService.onShutdown(this.store, this); lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.windowService.onBroadcast(this.onBroadcast, this)); } private onBroadcast(broadcast: IBroadcast): void { // attach: PH is ready to be attached to if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) { this.rawAttach(broadcast.payload.port); return; } if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) { this.onSessionEnd(); return; } // from this point on we require an active session let session = this.getActiveSession(); if (!session || session.configuration.type !== 'extensionHost') { return; // we are only intersted if we have an active debug session for extensionHost } // a plugin logged output, show it inside the REPL if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) { let extensionOutput: ILogEntry = broadcast.payload; let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info; let args: any[] = []; try { let parsed = JSON.parse(extensionOutput.arguments); args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o])); } catch (error) { args.push(extensionOutput.arguments); } // add output for each argument logged let simpleVals: any[] = []; for (let i = 0; i < args.length; i++) { let a = args[i]; // undefined gets printed as 'undefined' if (typeof a === 'undefined') { simpleVals.push('undefined'); } // null gets printed as 'null' else if (a === null) { simpleVals.push('null'); } // objects & arrays are special because we want to inspect them in the REPL else if (types.isObject(a) || Array.isArray(a)) { // flush any existing simple values logged if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); simpleVals = []; } // show object this.logToRepl(a, sev); } // string: watch out for % replacement directive // string substitution and formatting @ https://developer.chrome.com/devtools/docs/console else if (typeof a === 'string') { let buf = ''; for (let j = 0, len = a.length; j < len; j++) { if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) { i++; // read over substitution buf += !types.isUndefinedOrNull(args[i]) ? args[i] : ''; // replace j++; // read over directive } else { buf += a[j]; } } simpleVals.push(buf); } // number or boolean is joined together else { simpleVals.push(a); } } // flush simple values if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); } } } private registerSessionListeners(): void { this.toDisposeOnSessionEnd.push(this.session); this.toDisposeOnSessionEnd.push(this.session.onDidInitialize(event => { aria.status(nls.localize('debuggingStarted', "Debugging started.")); this.sendAllBreakpoints().then(() => { if (this.session.configuration.capabilities.supportsConfigurationDoneRequest) { this.session.configurationDone().done(null, e => { // Disconnect the debug session on configuration done error #10596 if (this.session) { this.session.disconnect().done(null, errors.onUnexpectedError); } this.messageService.show(severity.Error, e.message); }); } }); })); this.toDisposeOnSessionEnd.push(this.session.onDidStop(event => { this.setStateAndEmit(debug.State.Stopped); const threadId = event.body.threadId; this.getThreadData().done(() => { this.model.rawUpdate({ threadId, stoppedDetails: event.body, allThreadsStopped: event.body.allThreadsStopped }); const thread = this.model.getThreads()[threadId]; thread.getCallStack(this).then(callStack => { if (callStack.length > 0) { // focus first stack frame from top that has source location const stackFrameToFocus = arrays.first(callStack, sf => sf.source && sf.source.available, callStack[0]); this.setFocusedStackFrameAndEvaluate(stackFrameToFocus, thread).done(null, errors.onUnexpectedError); this.windowService.getWindow().focus(); aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber)); return this.openOrRevealSource(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false); } else { this.setFocusedStackFrameAndEvaluate(null, thread).done(null, errors.onUnexpectedError); } }); }, errors.onUnexpectedError); })); this.toDisposeOnSessionEnd.push(this.session.onDidThread(event => { if (event.body.reason === 'started') { this.getThreadData().done(null, errors.onUnexpectedError); } else if (event.body.reason === 'exited') { this.model.clearThreads(true, event.body.threadId); } })); this.toDisposeOnSessionEnd.push(this.session.onDidTerminateDebugee(event => { aria.status(nls.localize('debuggingStopped', "Debugging stopped.")); if (this.session && this.session.getId() === event.body.sessionId) { if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) { this.restartSession().done(null, err => this.messageService.show(severity.Error, err.message)); } else { this.session.disconnect().done(null, errors.onUnexpectedError); } } })); this.toDisposeOnSessionEnd.push(this.session.onDidContinued(event => { this.lazyTransitionToRunningState(event.body.allThreadsContinued ? undefined : event.body.threadId); })); this.toDisposeOnSessionEnd.push(this.session.onDidOutput(event => { if (event.body && event.body.category === 'telemetry') { // only log telemetry events from debug adapter if the adapter provided the telemetry key // and the user opted in telemetry if (this.customTelemetryService && this.telemetryService.isOptedIn) { this.customTelemetryService.publicLog(event.body.output, event.body.data); } } else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) { this.onOutput(event); } })); this.toDisposeOnSessionEnd.push(this.session.onDidBreakpoint(event => { const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined; const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (breakpoint) { this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint }); } else { const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (functionBreakpoint) { this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint }); } } })); this.toDisposeOnSessionEnd.push(this.session.onDidExitAdapter(event => { // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (this.session.configuration.type === 'extensionHost' && this._state === debug.State.RunningNoDebug) { ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath); } if (this.session && this.session.getId() === event.body.sessionId) { this.onSessionEnd(); } })); } private onOutput(event: DebugProtocol.OutputEvent): void { const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info; this.appendReplOutput(event.body.output, outputSeverity); } private getThreadData(): TPromise<void> { return this.session.threads().then(response => { response.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread })); }); } private loadBreakpoints(): debug.IBreakpoint[] { let result: debug.IBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }), breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] { let result: debug.IFunctionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new model.FunctionBreakpoint(fb.name, fb.enabled); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] { let result: debug.IExceptionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadWatchExpressions(): model.Expression[] { let result: model.Expression[]; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string } ) => { return new model.Expression(watchStoredData.name, false, watchStoredData.id); }); } catch (e) { } return result || []; } public get state(): debug.State { return this._state; } public get onDidChangeState(): Event<debug.State> { return this._onDidChangeState.event; } private setStateAndEmit(newState: debug.State): void { this._state = newState; this._onDidChangeState.fire(newState); } public get enabled(): boolean { return !!this.contextService.getWorkspace(); } public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame, thread?: debug.IThread): TPromise<void> { if (!thread && focusedStackFrame) { thread = this.model.getThreads()[focusedStackFrame.threadId]; } this.viewModel.setFocusedStackFrame(focusedStackFrame, thread); if (focusedStackFrame) { return this.model.evaluateWatchExpressions(this.session, focusedStackFrame); } else { this.model.clearWatchExpressionValues(); return TPromise.as(null); } } public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof model.Breakpoint) { return this.sendBreakpoints((<model.Breakpoint>breakpoint).source.uri); } else if (breakpoint instanceof model.FunctionBreakpoint) { return this.sendFunctionBreakpoints(); } return this.sendExceptionBreakpoints(); } this.model.enableOrDisableAllBreakpoints(enable); return this.sendAllBreakpoints(); } public addBreakpoints(rawBreakpoints: debug.IRawBreakpoint[]): TPromise<void[]> { this.model.addBreakpoints(rawBreakpoints); const uris = arrays.distinct(rawBreakpoints, raw => raw.uri.toString()).map(raw => raw.uri); rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, rbp.uri.fsPath))); return TPromise.join(uris.map(uri => this.sendBreakpoints(uri))); } public removeBreakpoints(id?: string): TPromise<any> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.source.uri.fsPath))); const urisToClear = arrays.distinct(toRemove, bp => bp.source.uri.toString()).map(bp => bp.source.uri); this.model.removeBreakpoints(toRemove); return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri))); } public setBreakpointsActivated(activated: boolean): TPromise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } public addFunctionBreakpoint(): void { this.model.addFunctionBreakpoint(''); } public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> { this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } }); return this.sendFunctionBreakpoints(); } public removeFunctionBreakpoints(id?: string): TPromise<void> { this.model.removeFunctionBreakpoints(id); return this.sendFunctionBreakpoints(); } public addReplExpression(name: string): TPromise<void> { this.telemetryService.publicLog('debugService/addReplExpression'); const focussedStackFrame = this.viewModel.getFocusedStackFrame(); return this.model.addReplExpression(this.session, focussedStackFrame, name) // Evaluate all watch expressions again since repl evaluation might have changed some. .then(() => this.setFocusedStackFrameAndEvaluate(focussedStackFrame)); } public logToRepl(value: string | { [key: string]: any }, severity?: severity): void { this.model.logToRepl(value, severity); } public appendReplOutput(value: string, severity?: severity): void { this.model.appendReplOutput(value, severity); } public removeReplExpressions(): void { this.model.removeReplExpressions(); } public setVariable(variable: debug.IExpression, value: string): TPromise<any> { if (!this.session || !(variable instanceof model.Variable)) { return TPromise.as(null); } return this.session.setVariable({ name: variable.name, value, variablesReference: (<model.Variable>variable).parent.reference }).then(response => { variable.value = response.body.value; // Evaluate all watch expressions again since changing variable value might have changed some #8118. return this.setFocusedStackFrameAndEvaluate(this.viewModel.getFocusedStackFrame()); }, err => { (<model.Variable>variable).errorMessage = err.message; }); } public addWatchExpression(name: string): TPromise<void> { return this.model.addWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), name); } public renameWatchExpression(id: string, newName: string): TPromise<void> { return this.model.renameWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), id, newName); } public removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); } public createSession(noDebug: boolean, configuration?: debug.IConfig): TPromise<any> { this.removeReplExpressions(); return this.textFileService.saveAll() // make sure all dirty files are saved .then(() => this.configurationService.reloadConfiguration() // make sure configuration is up to date .then(() => this.extensionService.onReady() .then(() => this.configurationManager.setConfiguration(configuration || this.configurationManager.configurationName) .then(() => this.configurationManager.resolveInteractiveVariables()) .then(resolvedConfiguration => { configuration = resolvedConfiguration; if (!configuration) { return this.configurationManager.openConfigFile(false).then(openend => { if (openend) { this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application.")); } }); } if (configuration.silentlyAbort) { return; } configuration.noDebug = noDebug; if (!this.configurationManager.adapter) { return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type))) : TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."), { actions: [this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), CloseAction] })); } return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => { const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0; if (successExitCode || (errorCount === 0 && !failureExitCode)) { return this.doCreateSession(configuration); } this.messageService.show(severity.Error, { message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode), actions: [new Action('debug.continue', nls.localize('debugAnyway', "Debug Anyway"), null, true, () => { this.messageService.hideAll(); return this.doCreateSession(configuration); }), CloseAction] }); }, (err: TaskError) => { if (err.code !== TaskErrors.NotConfigured) { throw err; } this.messageService.show(err.severity, { message: err.message, actions: [this.taskService.configureAction(), CloseAction] }); }); })))); } private doCreateSession(configuration: debug.IExtHostConfig): TPromise<any> { this.setStateAndEmit(debug.State.Initializing); return this.telemetryService.getTelemetryInfo().then(info => { const telemetryInfo: { [key: string]: string } = Object.create(null); telemetryInfo['common.vscodemachineid'] = info.machineId; telemetryInfo['common.vscodesessionid'] = info.sessionId; return telemetryInfo; }).then(data => { const { aiKey, type } = this.configurationManager.adapter; const publisher = this.configurationManager.adapter.extensionDescription.publisher; this.customTelemetryService = null; if (aiKey) { const client = new Client( uri.parse(require.toUrl('bootstrap')).fsPath, { serverName: 'Debug Telemetry', timeout: 1000 * 60 * 5, args: [`${ publisher }.${ type }`, JSON.stringify(data), aiKey], env: { ELECTRON_RUN_AS_NODE: 1, PIPE_LOGGING: 'true', AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp' } } ); const channel = client.getChannel('telemetryAppender'); const appender = new TelemetryAppenderClient(channel); this.toDisposeOnSessionEnd.push(client); this.customTelemetryService = new TelemetryService({ appender }, this.configurationService); } this.session = this.instantiationService.createInstance(RawDebugSession, configuration.debugServer, this.configurationManager.adapter, this.customTelemetryService); this.registerSessionListeners(); return this.session.initialize({ adapterID: configuration.type, pathFormat: 'path', linesStartAt1: true, columnsStartAt1: true, supportsVariableType: true, // #8858 supportsVariablePaging: true, // #9537 supportsRunInTerminalRequest: true // #10574 }).then((result: DebugProtocol.InitializeResponse) => { if (!this.session) { return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly"))); } this.model.setExceptionBreakpoints(this.session.configuration.capabilities.exceptionBreakpointFilters); return configuration.request === 'attach' ? this.session.attach(configuration) : this.session.launch(configuration); }).then((result: DebugProtocol.Response) => { if (!this.session) { return TPromise.as(null); } if (configuration.internalConsoleOptions === 'openOnSessionStart' || (!this.viewModel.changedWorkbenchViewState && configuration.internalConsoleOptions !== 'neverOpen')) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } if (!this.viewModel.changedWorkbenchViewState && !this.partService.isSideBarHidden()) { // We only want to change the workbench view state on the first debug session #5738 and if the side bar is not hidden this.viewModel.changedWorkbenchViewState = true; this.viewletService.openViewlet(debug.VIEWLET_ID); } // Do not change status bar to orange if we are just running without debug. if (!configuration.noDebug) { this.partService.addClass('debugging'); } this.extensionService.activateByEvent(`onDebug:${configuration.type}`).done(null, errors.onUnexpectedError); this.inDebugMode.set(true); this.lazyTransitionToRunningState(); this.telemetryService.publicLog('debugSessionStart', { type: configuration.type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: `${ this.configurationManager.adapter.extensionDescription.publisher }.${ this.configurationManager.adapter.extensionDescription.name }`, isBuiltin: this.configurationManager.adapter.extensionDescription.isBuiltin }); }).then(undefined, (error: any) => { if (error instanceof Error && error.message === 'Canceled') { // Do not show 'canceled' error messages to the user #7906 return TPromise.as(null); } this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined }); this.setStateAndEmit(debug.State.Inactive); if (this.session) { this.session.disconnect().done(null, errors.onUnexpectedError); } // Show the repl if some error got logged there #5870 if (this.model.getReplElements().length > 0) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction]; return TPromise.wrapError(errors.create(error.message, { actions })); }); }); } private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> { if (!taskName) { return TPromise.as(null); } // run a task before starting a debug session return this.taskService.tasks().then(descriptions => { const filteredTasks = descriptions.filter(task => task.name === taskName); if (filteredTasks.length !== 1) { return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), { actions: [ this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), this.taskService.configureAction(), CloseAction ] })); } // task is already running - nothing to do. if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) { return TPromise.as(null); } if (this.lastTaskEvent) { // there is a different task running currently. return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName))); } // no task running, execute the preLaunchTask. const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => { this.lastTaskEvent = null; return result; }, err => { this.lastTaskEvent = null; }); if (filteredTasks[0].isWatching) { return new TPromise((c, e) => this.taskService.addOneTimeDisposableListener(TaskServiceEvents.Inactive, () => c(null))); } return taskPromise; }); } private rawAttach(port: number): TPromise<any> { if (this.session) { return this.session.attach({ port }); } this.setStateAndEmit(debug.State.Initializing); const configuration = <debug.IExtHostConfig>this.configurationManager.configuration; return this.doCreateSession({ type: configuration.type, request: 'attach', port, sourceMaps: configuration.sourceMaps, outDir: configuration.outDir, debugServer: configuration.debugServer }); } public restartSession(): TPromise<any> { return this.session ? this.session.disconnect(true).then(() => new TPromise<void>((c, e) => { setTimeout(() => { this.createSession(false, null).then(() => c(null), err => e(err)); }, 300); }) ) : this.createSession(false, null); } public getActiveSession(): debug.IRawDebugSession { return this.session; } private onSessionEnd(): void { if (this.session) { const bpsExist = this.model.getBreakpoints().length > 0; this.telemetryService.publicLog('debugSessionStop', { type: this.session.configuration.type, success: this.session.emittedStopped || !bpsExist, sessionLengthInSeconds: this.session.getLengthInSeconds(), breakpointCount: this.model.getBreakpoints().length, watchExpressionsCount: this.model.getWatchExpressions().length }); } this.session = null; try { this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd); } catch (e) { // an internal module might be open so the dispose can throw -> ignore and continue with stop session. } this.partService.removeClass('debugging'); this.model.clearThreads(true); this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); this.setStateAndEmit(debug.State.Inactive); // set breakpoints back to unverified since the session ended. // source reference changes across sessions, so we do not use it to persist the source. const data: { [id: string]: { line: number, verified: boolean } } = {}; this.model.getBreakpoints().forEach(bp => { delete bp.source.raw.sourceReference; data[bp.getId()] = { line: bp.lineNumber, verified: false }; }); this.model.updateBreakpoints(data); this.inDebugMode.reset(); } public getModel(): debug.IModel { return this.model; } public getViewModel(): debug.IViewModel { return this.viewModel; } public openOrRevealSource(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> { const visibleEditors = this.editorService.getVisibleEditors(); for (let i = 0; i < visibleEditors.length; i++) { const fileInput = asFileEditorInput(visibleEditors[i].input); if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) || (visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) { const control = <editorbrowser.ICodeEditor>visibleEditors[i].getControl(); if (control) { control.revealLineInCenterIfOutsideViewport(lineNumber); control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }); this.editorGroupService.activateGroup(i); if (!preserveFocus) { this.editorGroupService.focusGroup(i); } } return TPromise.as(null); } } if (source.inMemory) { // internal module if (source.reference !== 0 && this.session && source.available) { return this.session.source({ sourceReference: source.reference }).then(response => { const mime = response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0]; return this.getDebugStringEditorInput(source, response.body.content, mime); }, (err: DebugProtocol.ErrorResponse) => { // Display the error from debug adapter using a temporary editor #8836 return this.getDebugErrorEditorInput(source, err.message); }).then(editorInput => { return this.editorService.openEditor(editorInput, { preserveFocus, selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 } }, sideBySide); }); } return this.sourceIsUnavailable(source, sideBySide); } return this.fileService.resolveFile(source.uri).then(() => this.editorService.openEditor({ resource: source.uri, options: { selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }, preserveFocus: preserveFocus } }, sideBySide), err => this.sourceIsUnavailable(source, sideBySide) ); } private sourceIsUnavailable(source: Source, sideBySide: boolean): TPromise<any> { this.model.sourceIsUnavailable(source); const editorInput = this.getDebugErrorEditorInput(source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.name)); return this.editorService.openEditor(editorInput, { preserveFocus: true }, sideBySide); } public getConfigurationManager(): debug.IConfigurationManager { return this.configurationManager; } public next(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.next({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public stepIn(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.stepIn({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public stepOut(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.stepOut({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public stepBack(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.stepBack({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public continue(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.continue({ threadId }).then(response => { const allThreadsContinued = response.body ? response.body.allThreadsContinued !== false : true; this.lazyTransitionToRunningState(allThreadsContinued ? undefined : threadId); }); } public pause(threadId: number): TPromise<any> { if (!this.session) { return TPromise.as(null); } return this.session.pause({ threadId }); } public restartFrame(frameId: number): TPromise<any> { if (!this.session) { return TPromise.as(null); } return this.session.restartFrame({ frameId }); } public completions(text: string, position: Position): TPromise<ISuggestion[]> { if (!this.session || !this.session.configuration.capabilities.supportsCompletionsRequest) { return TPromise.as([]); } const focussedStackFrame = this.viewModel.getFocusedStackFrame(); return this.session.completions({ frameId: focussedStackFrame ? focussedStackFrame.frameId : undefined, text, column: position.column, line: position.lineNumber }).then(response => { return !response ? [] : response.body.targets.map(item => ({ label: item.label, insertText: item.text || item.label, type: item.type })); }, err => []); } private lazyTransitionToRunningState(threadId?: number): void { let setNewFocusedStackFrameScheduler: RunOnceScheduler; const toDispose = this.session.onDidStop(e => { if (e.body.threadId === threadId || e.body.allThreadsStopped || !threadId) { setNewFocusedStackFrameScheduler.cancel(); } }); this.model.clearThreads(false, threadId); // Get a top stack frame of a stopped thread if there is any. const threads = this.model.getThreads(); const stoppedReference = Object.keys(threads).filter(ref => threads[ref].stopped).pop(); const stoppedThread = stoppedReference ? threads[parseInt(stoppedReference)] : null; const callStack = stoppedThread ? stoppedThread.getCachedCallStack() : null; const stackFrameToFocus = callStack && callStack.length > 0 ? callStack[0] : null; if (!stoppedThread) { this.setStateAndEmit(this.configurationManager.configuration.noDebug ? debug.State.RunningNoDebug : debug.State.Running); } // Do not immediatly set a new focused stack frame since that might cause unnecessery flickering // of the tree in the debug viewlet. Only set focused stack frame if no stopped event has arrived in 500ms. setNewFocusedStackFrameScheduler = new RunOnceScheduler(() => { toDispose.dispose(); aria.status(nls.localize('debuggingContinued', "Debugging continued.")); this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError); }, 500); setNewFocusedStackFrameScheduler.schedule(); } private getDebugStringEditorInput(source: Source, value: string, mtype: string): DebugStringEditorInput { const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0); this.toDisposeOnSessionEnd.push(result); return result; } private getDebugErrorEditorInput(source: Source, value: string): DebugErrorEditorInput { const result = this.instantiationService.createInstance(DebugErrorEditorInput, source.name, value); this.toDisposeOnSessionEnd.push(result); return result; } private sendAllBreakpoints(): TPromise<any> { return TPromise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri))) .then(() => this.sendFunctionBreakpoints()) // send exception breakpoints at the end since some debug adapters rely on the order .then(() => this.sendExceptionBreakpoints()); } private sendBreakpoints(modelUri: uri, sourceModified = false): TPromise<void> { if (!this.session || !this.session.readyForBreakpoints) { return TPromise.as(null); } if (this.textFileService.isDirty(modelUri)) { // Only send breakpoints for a file once it is not dirty #8077 this.breakpointsToSendOnResourceSaved[modelUri.toString()] = true; return TPromise.as(null); } const breakpointsToSend = arrays.distinct( this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()), bp => `${bp.desiredLineNumber}` ); const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, this.model); return this.session.setBreakpoints({ source: rawSource, lines: breakpointsToSend.map(bp => bp.desiredLineNumber), breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition })), sourceModified }).then(response => { const data: { [id: string]: { line?: number, verified: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateBreakpoints(data); }); } private sendFunctionBreakpoints(): TPromise<void> { if (!this.session || !this.session.readyForBreakpoints || !this.session.configuration.capabilities.supportsFunctionBreakpoints) { return TPromise.as(null); } const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => { const data: { [id: string]: { name?: string, verified?: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateFunctionBreakpoints(data); }); } private sendExceptionBreakpoints(): TPromise<any> { if (!this.session || !this.session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) { return TPromise.as(null); } const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return this.session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) }); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED))); fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved[event.resource.toString()]) { this.breakpointsToSendOnResourceSaved[event.resource.toString()] = false; this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError); } }); } private store(): void { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE); this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.configurationManager.configurationName, StorageScope.WORKSPACE); this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions().map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } public dispose(): void { this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd); this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/parts/debug/electron-browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.9976577758789062, 0.03357340767979622, 0.00016058959590736777, 0.0001753530523274094, 0.16553832590579987 ]
{ "id": 11, "code_window": [ "\n", "\t\tconst breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());\n", "\t\treturn this.session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => {\n", "\t\t\tconst data: { [id: string]: { name?: string, verified?: boolean } } = {};\n", "\t\t\tfor (let i = 0; i < breakpointsToSend.length; i++) {\n", "\t\t\t\tdata[breakpointsToSend[i].getId()] = response.body.breakpoints[i];\n", "\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!response || !response.body) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "add", "edit_start_line_idx": 1059 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const path = require('path'); const cp = require('child_process'); if (process.env['npm_config_disturl'] !== 'https://atom.io/download/atom-shell') { console.error("You can't use plain npm to install Code's dependencies."); console.error( /^win/.test(process.platform) ? "Please run '.\\scripts\\npm.bat install' instead." : "Please run './scripts/npm.sh install' instead." ); process.exit(1); } // make sure we install gulp watch for the system installed // node, since that is the driver of gulp if (process.platform !== 'win32') { const env = Object.assign({}, process.env); delete env['npm_config_disturl']; delete env['npm_config_target']; delete env['npm_config_runtime']; cp.spawnSync('npm', ['install'], { cwd: path.join(path.dirname(__dirname), 'lib', 'watch'), stdio: 'inherit', env }); }
build/npm/preinstall.js
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017612117517273873, 0.00017476253560744226, 0.00017283554188907146, 0.0001750467054080218, 0.0000013747085176873952 ]
{ "id": 11, "code_window": [ "\n", "\t\tconst breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());\n", "\t\treturn this.session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => {\n", "\t\t\tconst data: { [id: string]: { name?: string, verified?: boolean } } = {};\n", "\t\t\tfor (let i = 0; i < breakpointsToSend.length; i++) {\n", "\t\t\t\tdata[breakpointsToSend[i].getId()] = response.body.breakpoints[i];\n", "\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!response || !response.body) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "add", "edit_start_line_idx": 1059 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" enable-background="new 0 0 16 16" height="16" width="16"><path fill="#1E1E1E" d="M13.5 4.2C13.1 2.1 10.8 0 9.3 0H6.7c-.4 0-.6.2-.6.2C4 .8 2.5 2.7 2.5 4.9c0 .5-.1 2.3 1.7 3.8.5.5 1.2 2 1.3 2.4v3.3L7.1 16h2l1.5-1.6V11c.1-.4.8-1.9 1.3-2.3 1.1-.9 1.5-1.9 1.6-2.7V4.2z"/><g><g fill="#C5C5C5"><path d="M6.5 12h3v1h-3zM7.5 15h1.1l.9-1h-3z"/></g><path fill="#DDB204" d="M12.6 5c0-2.3-1.8-4.1-4.1-4.1-.1 0-1.4.1-1.4.1-2.1.3-3.7 2-3.7 4 0 .1-.2 1.6 1.4 3 .7.7 1.5 2.4 1.6 2.9l.1.1h3l.1-.2c.1-.5.9-2.2 1.6-2.9 1.6-1.3 1.4-2.8 1.4-2.9zm-3 1l-.5 3h-.6V6c1.1 0 .9-1 .9-1H6.5v.1c0 .2.1.9 1 .9v3H7l-.2-.7L6.5 6c-.7 0-.9-.4-1-.7v-.4c0-.8.9-.9.9-.9h3.1s1 .1 1 1c0 0 .1 1-.9 1z"/></g><path fill="#252526" d="M10.5 5c0-.9-1-1-1-1H6.4s-.9.1-.9.9v.4c0 .3.3.7.9.7l.4 2.3.2.7h.5V6c-1 0-1-.7-1-.9V5h3s.1 1-.9 1v3h.6l.5-3c.9 0 .8-1 .8-1z"/></svg>
src/vs/editor/contrib/quickFix/browser/lightbulb-dark.svg
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.0002539039996918291, 0.0002539039996918291, 0.0002539039996918291, 0.0002539039996918291, 0 ]
{ "id": 11, "code_window": [ "\n", "\t\tconst breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated());\n", "\t\treturn this.session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => {\n", "\t\t\tconst data: { [id: string]: { name?: string, verified?: boolean } } = {};\n", "\t\t\tfor (let i = 0; i < breakpointsToSend.length; i++) {\n", "\t\t\t\tdata[breakpointsToSend[i].getId()] = response.body.breakpoints[i];\n", "\t\t\t}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif (!response || !response.body) {\n", "\t\t\t\treturn;\n", "\t\t\t}\n", "\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "add", "edit_start_line_idx": 1059 }
<svg viewBox="0 0 11 11" xmlns="http://www.w3.org/2000/svg"><path transform="rotate(90 5.6171650886535645,5.55808973312378) " fill="#424242" d="m9.60717,8.70809l1.26,-1.26l-5.04,-5.04l-5.46,5.04l1.26,1.26l4.2,-3.78l3.78,3.78z"/></svg>
src/vs/base/browser/ui/scrollbar/media/arrow-right.svg
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017479465168435127, 0.00017479465168435127, 0.00017479465168435127, 0.00017479465168435127, 0 ]
{ "id": 12, "code_window": [ "\t}\n", "\n", "\tprotected send(command: string, args: any, cancelOnDisconnect = true): TPromise<DebugProtocol.Response> {\n", "\t\treturn this.initServer().then(() => {\n", "\t\t\tconst promise = super.send(command, args).then(response => response, (errorResponse: DebugProtocol.ErrorResponse) => {\n", "\t\t\t\tconst error = errorResponse.body ? errorResponse.body.error : null;\n", "\t\t\t\tconst telemetryMessage = error ? debug.formatPII(error.format, true, error.variables) : errorResponse.message;\n", "\t\t\t\tif (error && error.sendTelemetry) {\n", "\t\t\t\t\tthis.telemetryService.publicLog('debugProtocolErrorResponse', { error: telemetryMessage });\n", "\t\t\t\t\tif (this.customTelemetryService) {\n", "\t\t\t\t\t\tthis.customTelemetryService.publicLog('debugProtocolErrorResponse', { error: telemetryMessage });\n", "\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tconst error = errorResponse && errorResponse.body ? errorResponse.body.error : null;\n", "\t\t\t\tconst errorMessage = errorResponse ? errorResponse.message : '';\n", "\t\t\t\tconst telemetryMessage = error ? debug.formatPII(error.format, true, error.variables) : errorMessage;\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/rawDebugSession.ts", "type": "replace", "edit_start_line_idx": 157 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import {TPromise} from 'vs/base/common/winjs.base'; import nls = require('vs/nls'); import lifecycle = require('vs/base/common/lifecycle'); import Event, {Emitter} from 'vs/base/common/event'; import uuid = require('vs/base/common/uuid'); import objects = require('vs/base/common/objects'); import severity from 'vs/base/common/severity'; import types = require('vs/base/common/types'); import arrays = require('vs/base/common/arrays'); import debug = require('vs/workbench/parts/debug/common/debug'); import {Source} from 'vs/workbench/parts/debug/common/debugSource'; const MAX_REPL_LENGTH = 10000; const UNKNOWN_SOURCE_LABEL = nls.localize('unknownSource', "Unknown Source"); function massageValue(value: string): string { return value ? value.replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t') : value; } export function evaluateExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, expression: Expression, context: string): TPromise<Expression> { if (!session) { expression.value = context === 'repl' ? nls.localize('startDebugFirst', "Please start a debug session to evaluate") : Expression.DEFAULT_VALUE; expression.available = false; expression.reference = 0; return TPromise.as(expression); } return session.evaluate({ expression: expression.name, frameId: stackFrame ? stackFrame.frameId : undefined, context }).then(response => { expression.available = !!(response && response.body); if (response && response.body) { expression.value = response.body.result; expression.reference = response.body.variablesReference; expression.namedVariables = response.body.namedVariables; expression.indexedVariables = response.body.indexedVariables; expression.type = response.body.type; } return expression; }, err => { expression.value = err.message; expression.available = false; expression.reference = 0; return expression; }); } const notPropertySyntax = /^[a-zA-Z_][a-zA-Z0-9_]*$/; const arrayElementSyntax = /\[.*\]$/; export function getFullExpressionName(expression: debug.IExpression, sessionType: string): string { let names = [expression.name]; if (expression instanceof Variable) { let v = (<Variable> expression).parent; while (v instanceof Variable || v instanceof Expression) { names.push((<Variable> v).name); v = (<Variable> v).parent; } } names = names.reverse(); let result = null; names.forEach(name => { if (!result) { result = name; } else if (arrayElementSyntax.test(name) || (sessionType === 'node' && !notPropertySyntax.test(name))) { // use safe way to access node properties a['property_name']. Also handles array elements. result = name && name.indexOf('[') === 0 ? `${ result }${ name }` : `${ result }['${ name }']`; } else { result = `${ result }.${ name }`; } }); return result; } export class Thread implements debug.IThread { private promisedCallStack: TPromise<debug.IStackFrame[]>; private cachedCallStack: debug.IStackFrame[]; public stoppedDetails: debug.IRawStoppedDetails; public stopped: boolean; constructor(public name: string, public threadId: number) { this.promisedCallStack = undefined; this.stoppedDetails = undefined; this.cachedCallStack = undefined; this.stopped = false; } public getId(): string { return `thread:${ this.name }:${ this.threadId }`; } public clearCallStack(): void { this.promisedCallStack = undefined; this.cachedCallStack = undefined; } public getCachedCallStack(): debug.IStackFrame[] { return this.cachedCallStack; } public getCallStack(debugService: debug.IDebugService, getAdditionalStackFrames = false): TPromise<debug.IStackFrame[]> { if (!this.stopped) { return TPromise.as([]); } if (!this.promisedCallStack) { this.promisedCallStack = this.getCallStackImpl(debugService, 0).then(callStack => { this.cachedCallStack = callStack; return callStack; }); } else if (getAdditionalStackFrames) { this.promisedCallStack = this.promisedCallStack.then(callStackFirstPart => this.getCallStackImpl(debugService, callStackFirstPart.length).then(callStackSecondPart => { this.cachedCallStack = callStackFirstPart.concat(callStackSecondPart); return this.cachedCallStack; })); } return this.promisedCallStack; } private getCallStackImpl(debugService: debug.IDebugService, startFrame: number): TPromise<debug.IStackFrame[]> { let session = debugService.getActiveSession(); return session.stackTrace({ threadId: this.threadId, startFrame, levels: 20 }).then(response => { this.stoppedDetails.totalFrames = response.body.totalFrames; return response.body.stackFrames.map((rsf, level) => { if (!rsf) { return new StackFrame(this.threadId, 0, new Source({ name: UNKNOWN_SOURCE_LABEL }, false), nls.localize('unknownStack', "Unknown stack location"), undefined, undefined); } return new StackFrame(this.threadId, rsf.id, rsf.source ? new Source(rsf.source) : new Source({ name: UNKNOWN_SOURCE_LABEL }, false), rsf.name, rsf.line, rsf.column); }); }, (err: Error) => { this.stoppedDetails.framesErrorMessage = err.message; return []; }); } } export class OutputElement implements debug.ITreeElement { private static ID_COUNTER = 0; constructor(private id = OutputElement.ID_COUNTER++) { // noop } public getId(): string { return `outputelement:${ this.id }`; } } export class ValueOutputElement extends OutputElement { constructor( public value: string, public severity: severity, public category?: string, public counter: number = 1 ) { super(); } } export class KeyValueOutputElement extends OutputElement { private static MAX_CHILDREN = 1000; // upper bound of children per value private children: debug.ITreeElement[]; private _valueName: string; constructor(public key: string, public valueObj: any, public annotation?: string) { super(); this._valueName = null; } public get value(): string { if (this._valueName === null) { if (this.valueObj === null) { this._valueName = 'null'; } else if (Array.isArray(this.valueObj)) { this._valueName = `Array[${this.valueObj.length}]`; } else if (types.isObject(this.valueObj)) { this._valueName = 'Object'; } else if (types.isString(this.valueObj)) { this._valueName = `"${massageValue(this.valueObj)}"`; } else { this._valueName = String(this.valueObj); } if (!this._valueName) { this._valueName = ''; } } return this._valueName; } public getChildren(): debug.ITreeElement[] { if (!this.children) { if (Array.isArray(this.valueObj)) { this.children = (<any[]>this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map((v, index) => new KeyValueOutputElement(String(index), v, null)); } else if (types.isObject(this.valueObj)) { this.children = Object.getOwnPropertyNames(this.valueObj).slice(0, KeyValueOutputElement.MAX_CHILDREN).map(key => new KeyValueOutputElement(key, this.valueObj[key], null)); } else { this.children = []; } } return this.children; } } export abstract class ExpressionContainer implements debug.IExpressionContainer { public static allValues: { [id: string]: string } = {}; // Use chunks to support variable paging #9537 private static BASE_CHUNK_SIZE = 100; public valueChanged: boolean; private children: TPromise<debug.IExpression[]>; private _value: string; constructor( public reference: number, private id: string, private cacheChildren: boolean, public namedVariables: number, public indexedVariables: number, private startOfVariables = 0 ) { // noop } public getChildren(debugService: debug.IDebugService): TPromise<debug.IExpression[]> { if (!this.cacheChildren || !this.children) { const session = debugService.getActiveSession(); // only variables with reference > 0 have children. if (!session || this.reference <= 0) { this.children = TPromise.as([]); } else { // Check if object has named variables, fetch them independent from indexed variables #9670 this.children = (!!this.namedVariables ? this.fetchVariables(session, undefined, undefined, 'named') : TPromise.as([])).then(childrenArray => { // Use a dynamic chunk size based on the number of elements #9774 let chunkSize = ExpressionContainer.BASE_CHUNK_SIZE; while (this.indexedVariables > chunkSize * ExpressionContainer.BASE_CHUNK_SIZE) { chunkSize *= ExpressionContainer.BASE_CHUNK_SIZE; } if (this.indexedVariables > chunkSize) { // There are a lot of children, create fake intermediate values that represent chunks #9537 const numberOfChunks = Math.ceil(this.indexedVariables / chunkSize); for (let i = 0; i < numberOfChunks; i++) { const start = this.startOfVariables + i * chunkSize; const count = Math.min(chunkSize, this.indexedVariables - i * chunkSize); childrenArray.push(new Variable(this, this.reference, `[${start}..${start + count - 1}]`, '', null, count, null, true, start)); } return childrenArray; } const start = this.getChildrenInChunks ? this.startOfVariables : undefined; const count = this.getChildrenInChunks ? this.indexedVariables : undefined; return this.fetchVariables(session, start, count, 'indexed').then(variables => childrenArray.concat(variables)); }); } } return this.children; } public getId(): string { return this.id; } public get value(): string { return this._value; } private fetchVariables(session: debug.IRawDebugSession, start: number, count: number, filter: 'indexed'|'named'): TPromise<Variable[]> { return session.variables({ variablesReference: this.reference, start, count, filter }).then(response => { return arrays.distinct(response.body.variables.filter(v => !!v), v => v.name).map( v => new Variable(this, v.variablesReference, v.name, v.value, v.namedVariables, v.indexedVariables, v.type) ); }, (e: Error) => [new Variable(this, 0, null, e.message, 0, 0, null, false)]); } // The adapter explicitly sents the children count of an expression only if there are lots of children which should be chunked. private get getChildrenInChunks(): boolean { return !!this.indexedVariables; } public set value(value: string) { this._value = massageValue(value); this.valueChanged = ExpressionContainer.allValues[this.getId()] && ExpressionContainer.allValues[this.getId()] !== Expression.DEFAULT_VALUE && ExpressionContainer.allValues[this.getId()] !== value; ExpressionContainer.allValues[this.getId()] = value; } } export class Expression extends ExpressionContainer implements debug.IExpression { static DEFAULT_VALUE = 'not available'; public available: boolean; public type: string; constructor(public name: string, cacheChildren: boolean, id = uuid.generateUuid()) { super(0, id, cacheChildren, 0, 0); this.value = Expression.DEFAULT_VALUE; this.available = false; } } export class Variable extends ExpressionContainer implements debug.IExpression { // Used to show the error message coming from the adapter when setting the value #7807 public errorMessage: string; constructor( public parent: debug.IExpressionContainer, reference: number, public name: string, value: string, namedVariables: number, indexedVariables: number, public type: string = null, public available = true, startOfVariables = 0 ) { super(reference, `variable:${parent.getId()}:${name}:${reference}`, true, namedVariables, indexedVariables, startOfVariables); this.value = massageValue(value); } } export class Scope extends ExpressionContainer implements debug.IScope { constructor( private threadId: number, public name: string, reference: number, public expensive: boolean, namedVariables: number, indexedVariables: number ) { super(reference, `scope:${threadId}:${name}:${reference}`, true, namedVariables, indexedVariables); } } export class StackFrame implements debug.IStackFrame { private scopes: TPromise<Scope[]>; constructor( public threadId: number, public frameId: number, public source: Source, public name: string, public lineNumber: number, public column: number ) { this.scopes = null; } public getId(): string { return `stackframe:${ this.threadId }:${ this.frameId }`; } public getScopes(debugService: debug.IDebugService): TPromise<debug.IScope[]> { if (!this.scopes) { this.scopes = debugService.getActiveSession().scopes({ frameId: this.frameId }).then(response => { return response.body.scopes.map(rs => new Scope(this.threadId, rs.name, rs.variablesReference, rs.expensive, rs.namedVariables, rs.indexedVariables)); }, err => []); } return this.scopes; } } export class Breakpoint implements debug.IBreakpoint { public lineNumber: number; public verified: boolean; public idFromAdapter: number; public message: string; private id: string; constructor( public source: Source, public desiredLineNumber: number, public enabled: boolean, public condition: string ) { if (enabled === undefined) { this.enabled = true; } this.lineNumber = this.desiredLineNumber; this.verified = false; this.id = uuid.generateUuid(); } public getId(): string { return this.id; } } export class FunctionBreakpoint implements debug.IFunctionBreakpoint { private id: string; public verified: boolean; public idFromAdapter: number; constructor(public name: string, public enabled: boolean) { this.verified = false; this.id = uuid.generateUuid(); } public getId(): string { return this.id; } } export class ExceptionBreakpoint implements debug.IExceptionBreakpoint { private id: string; constructor(public filter: string, public label: string, public enabled: boolean) { this.id = uuid.generateUuid(); } public getId(): string { return this.id; } } export class Model implements debug.IModel { private threads: { [reference: number]: debug.IThread; }; private toDispose: lifecycle.IDisposable[]; private replElements: debug.ITreeElement[]; private _onDidChangeBreakpoints: Emitter<void>; private _onDidChangeCallStack: Emitter<void>; private _onDidChangeWatchExpressions: Emitter<debug.IExpression>; private _onDidChangeREPLElements: Emitter<void>; constructor( private breakpoints: debug.IBreakpoint[], private breakpointsActivated: boolean, private functionBreakpoints: debug.IFunctionBreakpoint[], private exceptionBreakpoints: debug.IExceptionBreakpoint[], private watchExpressions: Expression[] ) { this.threads = {}; this.replElements = []; this.toDispose = []; this._onDidChangeBreakpoints = new Emitter<void>(); this._onDidChangeCallStack = new Emitter<void>(); this._onDidChangeWatchExpressions = new Emitter<debug.IExpression>(); this._onDidChangeREPLElements = new Emitter<void>(); } public getId(): string { return 'root'; } public get onDidChangeBreakpoints(): Event<void> { return this._onDidChangeBreakpoints.event; } public get onDidChangeCallStack(): Event<void> { return this._onDidChangeCallStack.event; } public get onDidChangeWatchExpressions(): Event<debug.IExpression> { return this._onDidChangeWatchExpressions.event; } public get onDidChangeReplElements(): Event<void> { return this._onDidChangeREPLElements.event; } public getThreads(): { [reference: number]: debug.IThread; } { return this.threads; } public clearThreads(removeThreads: boolean, reference: number = undefined): void { if (reference) { if (this.threads[reference]) { this.threads[reference].clearCallStack(); this.threads[reference].stoppedDetails = undefined; this.threads[reference].stopped = false; if (removeThreads) { delete this.threads[reference]; } } } else { Object.keys(this.threads).forEach(ref => { this.threads[ref].clearCallStack(); this.threads[ref].stoppedDetails = undefined; this.threads[ref].stopped = false; }); if (removeThreads) { this.threads = {}; ExpressionContainer.allValues = {}; } } this._onDidChangeCallStack.fire(); } public getBreakpoints(): debug.IBreakpoint[] { return this.breakpoints; } public getFunctionBreakpoints(): debug.IFunctionBreakpoint[] { return this.functionBreakpoints; } public getExceptionBreakpoints(): debug.IExceptionBreakpoint[] { return this.exceptionBreakpoints; } public setExceptionBreakpoints(data: DebugProtocol.ExceptionBreakpointsFilter[]): void { if (data) { this.exceptionBreakpoints = data.map(d => { const ebp = this.exceptionBreakpoints.filter(ebp => ebp.filter === d.filter).pop(); return new ExceptionBreakpoint(d.filter, d.label, ebp ? ebp.enabled : d.default); }); } } public areBreakpointsActivated(): boolean { return this.breakpointsActivated; } public setBreakpointsActivated(activated: boolean): void { this.breakpointsActivated = activated; this._onDidChangeBreakpoints.fire(); } public addBreakpoints(rawData: debug.IRawBreakpoint[]): void { this.breakpoints = this.breakpoints.concat(rawData.map(rawBp => new Breakpoint(new Source(Source.toRawSource(rawBp.uri, this)), rawBp.lineNumber, rawBp.enabled, rawBp.condition))); this.breakpointsActivated = true; this._onDidChangeBreakpoints.fire(); } public removeBreakpoints(toRemove: debug.IBreakpoint[]): void { this.breakpoints = this.breakpoints.filter(bp => !toRemove.some(toRemove => toRemove.getId() === bp.getId())); this._onDidChangeBreakpoints.fire(); } public updateBreakpoints(data: { [id: string]: DebugProtocol.Breakpoint }): void { this.breakpoints.forEach(bp => { const bpData = data[bp.getId()]; if (bpData) { bp.lineNumber = bpData.line ? bpData.line : bp.lineNumber; bp.verified = bpData.verified; bp.idFromAdapter = bpData.id; bp.message = bpData.message; } }); this._onDidChangeBreakpoints.fire(); } public setEnablement(element: debug.IEnablement, enable: boolean): void { element.enabled = enable; if (element instanceof Breakpoint && !element.enabled) { var breakpoint = <Breakpoint> element; breakpoint.lineNumber = breakpoint.desiredLineNumber; breakpoint.verified = false; } this._onDidChangeBreakpoints.fire(); } public enableOrDisableAllBreakpoints(enable: boolean): void { this.breakpoints.forEach(bp => { bp.enabled = enable; if (!enable) { bp.lineNumber = bp.desiredLineNumber; bp.verified = false; } }); this.exceptionBreakpoints.forEach(ebp => ebp.enabled = enable); this.functionBreakpoints.forEach(fbp => fbp.enabled = enable); this._onDidChangeBreakpoints.fire(); } public addFunctionBreakpoint(functionName: string): void { this.functionBreakpoints.push(new FunctionBreakpoint(functionName, true)); this._onDidChangeBreakpoints.fire(); } public updateFunctionBreakpoints(data: { [id: string]: { name?: string, verified?: boolean; id?: number } }): void { this.functionBreakpoints.forEach(fbp => { const fbpData = data[fbp.getId()]; if (fbpData) { fbp.name = fbpData.name || fbp.name; fbp.verified = fbpData.verified; fbp.idFromAdapter = fbpData.id; } }); this._onDidChangeBreakpoints.fire(); } public removeFunctionBreakpoints(id?: string): void { this.functionBreakpoints = id ? this.functionBreakpoints.filter(fbp => fbp.getId() !== id) : []; this._onDidChangeBreakpoints.fire(); } public getReplElements(): debug.ITreeElement[] { return this.replElements; } public addReplExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> { const expression = new Expression(name, true); this.addReplElements([expression]); return evaluateExpression(session, stackFrame, expression, 'repl') .then(() => this._onDidChangeREPLElements.fire()); } public logToRepl(value: string | { [key: string]: any }, severity?: severity): void { let elements:OutputElement[] = []; let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]); // string message if (typeof value === 'string') { if (value && value.trim() && previousOutput && previousOutput.value === value && previousOutput.severity === severity) { previousOutput.counter++; // we got the same output (but not an empty string when trimmed) so we just increment the counter } else { let lines = value.trim().split('\n'); lines.forEach((line, index) => { elements.push(new ValueOutputElement(line, severity)); }); } } // key-value output else { elements.push(new KeyValueOutputElement((<any>value).prototype, value, nls.localize('snapshotObj', "Only primitive values are shown for this object."))); } if (elements.length) { this.addReplElements(elements); } this._onDidChangeREPLElements.fire(); } public appendReplOutput(value: string, severity?: severity): void { const elements: OutputElement[] = []; let previousOutput = this.replElements.length && (<ValueOutputElement>this.replElements[this.replElements.length - 1]); let lines = value.split('\n'); let groupTogether = !!previousOutput && (previousOutput.category === 'output' && severity === previousOutput.severity); if (groupTogether) { // append to previous line if same group previousOutput.value += lines.shift(); } else if (previousOutput && previousOutput.value === '') { // remove potential empty lines between different output types this.replElements.pop(); } // fill in lines as output value elements lines.forEach((line, index) => { elements.push(new ValueOutputElement(line, severity, 'output')); }); this.addReplElements(elements); this._onDidChangeREPLElements.fire(); } private addReplElements(newElements: debug.ITreeElement[]): void { this.replElements.push(...newElements); if (this.replElements.length > MAX_REPL_LENGTH) { this.replElements.splice(0, this.replElements.length - MAX_REPL_LENGTH); } } public removeReplExpressions(): void { if (this.replElements.length > 0) { this.replElements = []; this._onDidChangeREPLElements.fire(); } } public getWatchExpressions(): Expression[] { return this.watchExpressions; } public addWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, name: string): TPromise<void> { const we = new Expression(name, false); this.watchExpressions.push(we); if (!name) { this._onDidChangeWatchExpressions.fire(we); return TPromise.as(null); } return this.evaluateWatchExpressions(session, stackFrame, we.getId()); } public renameWatchExpression(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string, newName: string): TPromise<void> { const filtered = this.watchExpressions.filter(we => we.getId() === id); if (filtered.length === 1) { filtered[0].name = newName; return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => { this._onDidChangeWatchExpressions.fire(filtered[0]); }); } return TPromise.as(null); } public evaluateWatchExpressions(session: debug.IRawDebugSession, stackFrame: debug.IStackFrame, id: string = null): TPromise<void> { if (id) { const filtered = this.watchExpressions.filter(we => we.getId() === id); if (filtered.length !== 1) { return TPromise.as(null); } return evaluateExpression(session, stackFrame, filtered[0], 'watch').then(() => { this._onDidChangeWatchExpressions.fire(filtered[0]); }); } return TPromise.join(this.watchExpressions.map(we => evaluateExpression(session, stackFrame, we, 'watch'))).then(() => { this._onDidChangeWatchExpressions.fire(); }); } public clearWatchExpressionValues(): void { this.watchExpressions.forEach(we => { we.value = Expression.DEFAULT_VALUE; we.available = false; we.reference = 0; }); this._onDidChangeWatchExpressions.fire(); } public removeWatchExpressions(id: string = null): void { this.watchExpressions = id ? this.watchExpressions.filter(we => we.getId() !== id) : []; this._onDidChangeWatchExpressions.fire(); } public sourceIsUnavailable(source: Source): void { Object.keys(this.threads).forEach(key => { if (this.threads[key].getCachedCallStack()) { this.threads[key].getCachedCallStack().forEach(stackFrame => { if (stackFrame.source.uri.toString() === source.uri.toString()) { stackFrame.source.available = false; } }); } }); this._onDidChangeCallStack.fire(); } public rawUpdate(data: debug.IRawModelUpdate): void { if (data.thread && !this.threads[data.threadId]) { // A new thread came in, initialize it. this.threads[data.threadId] = new Thread(data.thread.name, data.thread.id); } if (data.stoppedDetails) { // Set the availability of the threads' callstacks depending on // whether the thread is stopped or not if (data.allThreadsStopped) { Object.keys(this.threads).forEach(ref => { // Only update the details if all the threads are stopped // because we don't want to overwrite the details of other // threads that have stopped for a different reason this.threads[ref].stoppedDetails = objects.clone(data.stoppedDetails); this.threads[ref].stopped = true; this.threads[ref].clearCallStack(); }); } else { // One thread is stopped, only update that thread. this.threads[data.threadId].stoppedDetails = data.stoppedDetails; this.threads[data.threadId].clearCallStack(); this.threads[data.threadId].stopped = true; } } this._onDidChangeCallStack.fire(); } public dispose(): void { this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/parts/debug/common/debugModel.ts
1
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.0018585410434752703, 0.00019869969401042908, 0.00016437766316812485, 0.00016827823128551245, 0.00019421265460550785 ]
{ "id": 12, "code_window": [ "\t}\n", "\n", "\tprotected send(command: string, args: any, cancelOnDisconnect = true): TPromise<DebugProtocol.Response> {\n", "\t\treturn this.initServer().then(() => {\n", "\t\t\tconst promise = super.send(command, args).then(response => response, (errorResponse: DebugProtocol.ErrorResponse) => {\n", "\t\t\t\tconst error = errorResponse.body ? errorResponse.body.error : null;\n", "\t\t\t\tconst telemetryMessage = error ? debug.formatPII(error.format, true, error.variables) : errorResponse.message;\n", "\t\t\t\tif (error && error.sendTelemetry) {\n", "\t\t\t\t\tthis.telemetryService.publicLog('debugProtocolErrorResponse', { error: telemetryMessage });\n", "\t\t\t\t\tif (this.customTelemetryService) {\n", "\t\t\t\t\t\tthis.customTelemetryService.publicLog('debugProtocolErrorResponse', { error: telemetryMessage });\n", "\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tconst error = errorResponse && errorResponse.body ? errorResponse.body.error : null;\n", "\t\t\t\tconst errorMessage = errorResponse ? errorResponse.message : '';\n", "\t\t\t\tconst telemetryMessage = error ? debug.formatPII(error.format, true, error.variables) : errorMessage;\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/rawDebugSession.ts", "type": "replace", "edit_start_line_idx": 157 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "dirtyFiles": "{0} file non salvati" }
i18n/ita/src/vs/workbench/parts/files/browser/fileTracker.i18n.json
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.000176370216649957, 0.000176370216649957, 0.000176370216649957, 0.000176370216649957, 0 ]
{ "id": 12, "code_window": [ "\t}\n", "\n", "\tprotected send(command: string, args: any, cancelOnDisconnect = true): TPromise<DebugProtocol.Response> {\n", "\t\treturn this.initServer().then(() => {\n", "\t\t\tconst promise = super.send(command, args).then(response => response, (errorResponse: DebugProtocol.ErrorResponse) => {\n", "\t\t\t\tconst error = errorResponse.body ? errorResponse.body.error : null;\n", "\t\t\t\tconst telemetryMessage = error ? debug.formatPII(error.format, true, error.variables) : errorResponse.message;\n", "\t\t\t\tif (error && error.sendTelemetry) {\n", "\t\t\t\t\tthis.telemetryService.publicLog('debugProtocolErrorResponse', { error: telemetryMessage });\n", "\t\t\t\t\tif (this.customTelemetryService) {\n", "\t\t\t\t\t\tthis.customTelemetryService.publicLog('debugProtocolErrorResponse', { error: telemetryMessage });\n", "\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tconst error = errorResponse && errorResponse.body ? errorResponse.body.error : null;\n", "\t\t\t\tconst errorMessage = errorResponse ? errorResponse.message : '';\n", "\t\t\t\tconst telemetryMessage = error ? debug.formatPII(error.format, true, error.variables) : errorMessage;\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/rawDebugSession.ts", "type": "replace", "edit_start_line_idx": 157 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "pleaseRestart": "Öffnen Sie das Stammverzeichnis des Repositorys, um auf Git-Features zuzugreifen.", "wrongRoot": "Dieses Verzeichnis scheint in einem Git-Repository enthalten zu sein." }
i18n/deu/src/vs/workbench/parts/git/browser/views/notroot/notrootView.i18n.json
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017382136138621718, 0.00017382136138621718, 0.00017382136138621718, 0.00017382136138621718, 0 ]
{ "id": 12, "code_window": [ "\t}\n", "\n", "\tprotected send(command: string, args: any, cancelOnDisconnect = true): TPromise<DebugProtocol.Response> {\n", "\t\treturn this.initServer().then(() => {\n", "\t\t\tconst promise = super.send(command, args).then(response => response, (errorResponse: DebugProtocol.ErrorResponse) => {\n", "\t\t\t\tconst error = errorResponse.body ? errorResponse.body.error : null;\n", "\t\t\t\tconst telemetryMessage = error ? debug.formatPII(error.format, true, error.variables) : errorResponse.message;\n", "\t\t\t\tif (error && error.sendTelemetry) {\n", "\t\t\t\t\tthis.telemetryService.publicLog('debugProtocolErrorResponse', { error: telemetryMessage });\n", "\t\t\t\t\tif (this.customTelemetryService) {\n", "\t\t\t\t\t\tthis.customTelemetryService.publicLog('debugProtocolErrorResponse', { error: telemetryMessage });\n", "\t\t\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tconst error = errorResponse && errorResponse.body ? errorResponse.body.error : null;\n", "\t\t\t\tconst errorMessage = errorResponse ? errorResponse.message : '';\n", "\t\t\t\tconst telemetryMessage = error ? debug.formatPII(error.format, true, error.variables) : errorMessage;\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/rawDebugSession.ts", "type": "replace", "edit_start_line_idx": 157 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "toggleComment": "Emmet: コメントの表示/非表示" }
i18n/jpn/src/vs/workbench/parts/emmet/node/actions/toggleComment.i18n.json
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017556987586431205, 0.00017556987586431205, 0.00017556987586431205, 0.00017556987586431205, 0 ]
{ "id": 13, "code_window": [ "\t\t\t\t\t// Do not show error message to user if showUser === false or 'canceled' error message #7906\n", "\t\t\t\t\treturn TPromise.as(null);\n", "\t\t\t\t}\n", "\n", "\t\t\t\tconst userMessage = error ? debug.formatPII(error.format, false, error.variables) : errorResponse.message;\n", "\t\t\t\tif (error && error.url) {\n", "\t\t\t\t\tconst label = error.urlLabel ? error.urlLabel : nls.localize('moreInfo', \"More Info\");\n", "\t\t\t\t\treturn TPromise.wrapError(errors.create(userMessage, { actions: [CloseAction, new Action('debug.moreInfo', label, null, true, () => {\n", "\t\t\t\t\t\tshell.openExternal(error.url);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tconst userMessage = error ? debug.formatPII(error.format, false, error.variables) : errorMessage;\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/rawDebugSession.ts", "type": "replace", "edit_start_line_idx": 170 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import nls = require('vs/nls'); import lifecycle = require('vs/base/common/lifecycle'); import {guessMimeTypes} from 'vs/base/common/mime'; import Event, {Emitter} from 'vs/base/common/event'; import uri from 'vs/base/common/uri'; import {RunOnceScheduler} from 'vs/base/common/async'; import {Action} from 'vs/base/common/actions'; import arrays = require('vs/base/common/arrays'); import types = require('vs/base/common/types'); import errors = require('vs/base/common/errors'); import severity from 'vs/base/common/severity'; import {TPromise} from 'vs/base/common/winjs.base'; import aria = require('vs/base/browser/ui/aria/aria'); import editorbrowser = require('vs/editor/browser/editorBrowser'); import {ISuggestion} from 'vs/editor/common/modes'; import {Position} from 'vs/editor/common/core/position'; import {IContextKeyService, IContextKey} from 'vs/platform/contextkey/common/contextkey'; import {IMarkerService} from 'vs/platform/markers/common/markers'; import {ILifecycleService} from 'vs/platform/lifecycle/common/lifecycle'; import {IExtensionService} from 'vs/platform/extensions/common/extensions'; import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation'; import {IFileService, FileChangesEvent, FileChangeType, EventType} from 'vs/platform/files/common/files'; import {IEventService} from 'vs/platform/event/common/event'; import {IMessageService, CloseAction} from 'vs/platform/message/common/message'; import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry'; import {TelemetryService} from 'vs/platform/telemetry/common/telemetryService'; import {TelemetryAppenderClient} from 'vs/platform/telemetry/common/telemetryIpc'; import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage'; import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService'; import {asFileEditorInput} from 'vs/workbench/common/editor'; import debug = require('vs/workbench/parts/debug/common/debug'); import {RawDebugSession} from 'vs/workbench/parts/debug/electron-browser/rawDebugSession'; import model = require('vs/workbench/parts/debug/common/debugModel'); import {DebugStringEditorInput, DebugErrorEditorInput} from 'vs/workbench/parts/debug/browser/debugEditorInputs'; import viewmodel = require('vs/workbench/parts/debug/common/debugViewModel'); import debugactions = require('vs/workbench/parts/debug/browser/debugActions'); import {ConfigurationManager} from 'vs/workbench/parts/debug/node/debugConfigurationManager'; import {Source} from 'vs/workbench/parts/debug/common/debugSource'; import {ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary} from 'vs/workbench/parts/tasks/common/taskService'; import {TaskError, TaskErrors} from 'vs/workbench/parts/tasks/common/taskSystem'; import {IViewletService} from 'vs/workbench/services/viewlet/common/viewletService'; import {IPanelService} from 'vs/workbench/services/panel/common/panelService'; import {IPartService} from 'vs/workbench/services/part/common/partService'; import {ITextFileService} from 'vs/workbench/parts/files/common/files'; import {IConfigurationService} from 'vs/platform/configuration/common/configuration'; import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {IWindowService, IBroadcast} from 'vs/workbench/services/window/electron-browser/windowService'; import {ILogEntry, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL} from 'vs/workbench/services/thread/electron-browser/threadService'; import {ipcRenderer as ipc} from 'electron'; import {Client} from 'vs/base/parts/ipc/node/ipc.cp'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname'; export class DebugService implements debug.IDebugService { public _serviceBrand: any; private _state: debug.State; private _onDidChangeState: Emitter<debug.State>; private session: RawDebugSession; private model: model.Model; private viewModel: viewmodel.ViewModel; private configurationManager: ConfigurationManager; private customTelemetryService: ITelemetryService; private lastTaskEvent: TaskEvent; private toDispose: lifecycle.IDisposable[]; private toDisposeOnSessionEnd: lifecycle.IDisposable[]; private inDebugMode: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: { [uri: string]: boolean }; constructor( @IStorageService private storageService: IStorageService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @ITextFileService private textFileService: ITextFileService, @IViewletService private viewletService: IViewletService, @IPanelService private panelService: IPanelService, @IFileService private fileService: IFileService, @IMessageService private messageService: IMessageService, @IPartService private partService: IPartService, @IWindowService private windowService: IWindowService, @ITelemetryService private telemetryService: ITelemetryService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IEventService eventService: IEventService, @ILifecycleService private lifecycleService: ILifecycleService, @IInstantiationService private instantiationService: IInstantiationService, @IExtensionService private extensionService: IExtensionService, @IMarkerService private markerService: IMarkerService, @ITaskService private taskService: ITaskService, @IConfigurationService private configurationService: IConfigurationService ) { this.toDispose = []; this.toDisposeOnSessionEnd = []; this.session = null; this.breakpointsToSendOnResourceSaved = {}; this._state = debug.State.Inactive; this._onDidChangeState = new Emitter<debug.State>(); if (!this.contextService.getWorkspace()) { this._state = debug.State.Disabled; } this.configurationManager = this.instantiationService.createInstance(ConfigurationManager, this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, 'null')); this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.model = new model.Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadWatchExpressions()); this.toDispose.push(this.model); this.viewModel = new viewmodel.ViewModel(); this.registerListeners(eventService, lifecycleService); } private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void { this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e))); if (this.taskService) { this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => { this.lastTaskEvent = e; })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => { if (e.type === TaskType.SingleRun) { this.lastTaskEvent = null; } })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => { this.lastTaskEvent = null; })); } lifecycleService.onShutdown(this.store, this); lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.windowService.onBroadcast(this.onBroadcast, this)); } private onBroadcast(broadcast: IBroadcast): void { // attach: PH is ready to be attached to if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) { this.rawAttach(broadcast.payload.port); return; } if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) { this.onSessionEnd(); return; } // from this point on we require an active session let session = this.getActiveSession(); if (!session || session.configuration.type !== 'extensionHost') { return; // we are only intersted if we have an active debug session for extensionHost } // a plugin logged output, show it inside the REPL if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) { let extensionOutput: ILogEntry = broadcast.payload; let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info; let args: any[] = []; try { let parsed = JSON.parse(extensionOutput.arguments); args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o])); } catch (error) { args.push(extensionOutput.arguments); } // add output for each argument logged let simpleVals: any[] = []; for (let i = 0; i < args.length; i++) { let a = args[i]; // undefined gets printed as 'undefined' if (typeof a === 'undefined') { simpleVals.push('undefined'); } // null gets printed as 'null' else if (a === null) { simpleVals.push('null'); } // objects & arrays are special because we want to inspect them in the REPL else if (types.isObject(a) || Array.isArray(a)) { // flush any existing simple values logged if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); simpleVals = []; } // show object this.logToRepl(a, sev); } // string: watch out for % replacement directive // string substitution and formatting @ https://developer.chrome.com/devtools/docs/console else if (typeof a === 'string') { let buf = ''; for (let j = 0, len = a.length; j < len; j++) { if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) { i++; // read over substitution buf += !types.isUndefinedOrNull(args[i]) ? args[i] : ''; // replace j++; // read over directive } else { buf += a[j]; } } simpleVals.push(buf); } // number or boolean is joined together else { simpleVals.push(a); } } // flush simple values if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); } } } private registerSessionListeners(): void { this.toDisposeOnSessionEnd.push(this.session); this.toDisposeOnSessionEnd.push(this.session.onDidInitialize(event => { aria.status(nls.localize('debuggingStarted', "Debugging started.")); this.sendAllBreakpoints().then(() => { if (this.session.configuration.capabilities.supportsConfigurationDoneRequest) { this.session.configurationDone().done(null, e => { // Disconnect the debug session on configuration done error #10596 if (this.session) { this.session.disconnect().done(null, errors.onUnexpectedError); } this.messageService.show(severity.Error, e.message); }); } }); })); this.toDisposeOnSessionEnd.push(this.session.onDidStop(event => { this.setStateAndEmit(debug.State.Stopped); const threadId = event.body.threadId; this.getThreadData().done(() => { this.model.rawUpdate({ threadId, stoppedDetails: event.body, allThreadsStopped: event.body.allThreadsStopped }); const thread = this.model.getThreads()[threadId]; thread.getCallStack(this).then(callStack => { if (callStack.length > 0) { // focus first stack frame from top that has source location const stackFrameToFocus = arrays.first(callStack, sf => sf.source && sf.source.available, callStack[0]); this.setFocusedStackFrameAndEvaluate(stackFrameToFocus, thread).done(null, errors.onUnexpectedError); this.windowService.getWindow().focus(); aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber)); return this.openOrRevealSource(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false); } else { this.setFocusedStackFrameAndEvaluate(null, thread).done(null, errors.onUnexpectedError); } }); }, errors.onUnexpectedError); })); this.toDisposeOnSessionEnd.push(this.session.onDidThread(event => { if (event.body.reason === 'started') { this.getThreadData().done(null, errors.onUnexpectedError); } else if (event.body.reason === 'exited') { this.model.clearThreads(true, event.body.threadId); } })); this.toDisposeOnSessionEnd.push(this.session.onDidTerminateDebugee(event => { aria.status(nls.localize('debuggingStopped', "Debugging stopped.")); if (this.session && this.session.getId() === event.body.sessionId) { if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) { this.restartSession().done(null, err => this.messageService.show(severity.Error, err.message)); } else { this.session.disconnect().done(null, errors.onUnexpectedError); } } })); this.toDisposeOnSessionEnd.push(this.session.onDidContinued(event => { this.lazyTransitionToRunningState(event.body.allThreadsContinued ? undefined : event.body.threadId); })); this.toDisposeOnSessionEnd.push(this.session.onDidOutput(event => { if (event.body && event.body.category === 'telemetry') { // only log telemetry events from debug adapter if the adapter provided the telemetry key // and the user opted in telemetry if (this.customTelemetryService && this.telemetryService.isOptedIn) { this.customTelemetryService.publicLog(event.body.output, event.body.data); } } else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) { this.onOutput(event); } })); this.toDisposeOnSessionEnd.push(this.session.onDidBreakpoint(event => { const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined; const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (breakpoint) { this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint }); } else { const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (functionBreakpoint) { this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint }); } } })); this.toDisposeOnSessionEnd.push(this.session.onDidExitAdapter(event => { // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (this.session.configuration.type === 'extensionHost' && this._state === debug.State.RunningNoDebug) { ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath); } if (this.session && this.session.getId() === event.body.sessionId) { this.onSessionEnd(); } })); } private onOutput(event: DebugProtocol.OutputEvent): void { const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info; this.appendReplOutput(event.body.output, outputSeverity); } private getThreadData(): TPromise<void> { return this.session.threads().then(response => { response.body.threads.forEach(thread => this.model.rawUpdate({ threadId: thread.id, thread })); }); } private loadBreakpoints(): debug.IBreakpoint[] { let result: debug.IBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new model.Breakpoint(new Source(breakpoint.source.raw ? breakpoint.source.raw : { path: uri.parse(breakpoint.source.uri).fsPath, name: breakpoint.source.name }), breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): debug.IFunctionBreakpoint[] { let result: debug.IFunctionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new model.FunctionBreakpoint(fb.name, fb.enabled); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): debug.IExceptionBreakpoint[] { let result: debug.IExceptionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new model.ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadWatchExpressions(): model.Expression[] { let result: model.Expression[]; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string } ) => { return new model.Expression(watchStoredData.name, false, watchStoredData.id); }); } catch (e) { } return result || []; } public get state(): debug.State { return this._state; } public get onDidChangeState(): Event<debug.State> { return this._onDidChangeState.event; } private setStateAndEmit(newState: debug.State): void { this._state = newState; this._onDidChangeState.fire(newState); } public get enabled(): boolean { return !!this.contextService.getWorkspace(); } public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame, thread?: debug.IThread): TPromise<void> { if (!thread && focusedStackFrame) { thread = this.model.getThreads()[focusedStackFrame.threadId]; } this.viewModel.setFocusedStackFrame(focusedStackFrame, thread); if (focusedStackFrame) { return this.model.evaluateWatchExpressions(this.session, focusedStackFrame); } else { this.model.clearWatchExpressionValues(); return TPromise.as(null); } } public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof model.Breakpoint) { return this.sendBreakpoints((<model.Breakpoint>breakpoint).source.uri); } else if (breakpoint instanceof model.FunctionBreakpoint) { return this.sendFunctionBreakpoints(); } return this.sendExceptionBreakpoints(); } this.model.enableOrDisableAllBreakpoints(enable); return this.sendAllBreakpoints(); } public addBreakpoints(rawBreakpoints: debug.IRawBreakpoint[]): TPromise<void[]> { this.model.addBreakpoints(rawBreakpoints); const uris = arrays.distinct(rawBreakpoints, raw => raw.uri.toString()).map(raw => raw.uri); rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, rbp.uri.fsPath))); return TPromise.join(uris.map(uri => this.sendBreakpoints(uri))); } public removeBreakpoints(id?: string): TPromise<any> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.source.uri.fsPath))); const urisToClear = arrays.distinct(toRemove, bp => bp.source.uri.toString()).map(bp => bp.source.uri); this.model.removeBreakpoints(toRemove); return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri))); } public setBreakpointsActivated(activated: boolean): TPromise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } public addFunctionBreakpoint(): void { this.model.addFunctionBreakpoint(''); } public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> { this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } }); return this.sendFunctionBreakpoints(); } public removeFunctionBreakpoints(id?: string): TPromise<void> { this.model.removeFunctionBreakpoints(id); return this.sendFunctionBreakpoints(); } public addReplExpression(name: string): TPromise<void> { this.telemetryService.publicLog('debugService/addReplExpression'); const focussedStackFrame = this.viewModel.getFocusedStackFrame(); return this.model.addReplExpression(this.session, focussedStackFrame, name) // Evaluate all watch expressions again since repl evaluation might have changed some. .then(() => this.setFocusedStackFrameAndEvaluate(focussedStackFrame)); } public logToRepl(value: string | { [key: string]: any }, severity?: severity): void { this.model.logToRepl(value, severity); } public appendReplOutput(value: string, severity?: severity): void { this.model.appendReplOutput(value, severity); } public removeReplExpressions(): void { this.model.removeReplExpressions(); } public setVariable(variable: debug.IExpression, value: string): TPromise<any> { if (!this.session || !(variable instanceof model.Variable)) { return TPromise.as(null); } return this.session.setVariable({ name: variable.name, value, variablesReference: (<model.Variable>variable).parent.reference }).then(response => { variable.value = response.body.value; // Evaluate all watch expressions again since changing variable value might have changed some #8118. return this.setFocusedStackFrameAndEvaluate(this.viewModel.getFocusedStackFrame()); }, err => { (<model.Variable>variable).errorMessage = err.message; }); } public addWatchExpression(name: string): TPromise<void> { return this.model.addWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), name); } public renameWatchExpression(id: string, newName: string): TPromise<void> { return this.model.renameWatchExpression(this.session, this.viewModel.getFocusedStackFrame(), id, newName); } public removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); } public createSession(noDebug: boolean, configuration?: debug.IConfig): TPromise<any> { this.removeReplExpressions(); return this.textFileService.saveAll() // make sure all dirty files are saved .then(() => this.configurationService.reloadConfiguration() // make sure configuration is up to date .then(() => this.extensionService.onReady() .then(() => this.configurationManager.setConfiguration(configuration || this.configurationManager.configurationName) .then(() => this.configurationManager.resolveInteractiveVariables()) .then(resolvedConfiguration => { configuration = resolvedConfiguration; if (!configuration) { return this.configurationManager.openConfigFile(false).then(openend => { if (openend) { this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application.")); } }); } if (configuration.silentlyAbort) { return; } configuration.noDebug = noDebug; if (!this.configurationManager.adapter) { return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type))) : TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."), { actions: [this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), CloseAction] })); } return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => { const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0; if (successExitCode || (errorCount === 0 && !failureExitCode)) { return this.doCreateSession(configuration); } this.messageService.show(severity.Error, { message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode), actions: [new Action('debug.continue', nls.localize('debugAnyway', "Debug Anyway"), null, true, () => { this.messageService.hideAll(); return this.doCreateSession(configuration); }), CloseAction] }); }, (err: TaskError) => { if (err.code !== TaskErrors.NotConfigured) { throw err; } this.messageService.show(err.severity, { message: err.message, actions: [this.taskService.configureAction(), CloseAction] }); }); })))); } private doCreateSession(configuration: debug.IExtHostConfig): TPromise<any> { this.setStateAndEmit(debug.State.Initializing); return this.telemetryService.getTelemetryInfo().then(info => { const telemetryInfo: { [key: string]: string } = Object.create(null); telemetryInfo['common.vscodemachineid'] = info.machineId; telemetryInfo['common.vscodesessionid'] = info.sessionId; return telemetryInfo; }).then(data => { const { aiKey, type } = this.configurationManager.adapter; const publisher = this.configurationManager.adapter.extensionDescription.publisher; this.customTelemetryService = null; if (aiKey) { const client = new Client( uri.parse(require.toUrl('bootstrap')).fsPath, { serverName: 'Debug Telemetry', timeout: 1000 * 60 * 5, args: [`${ publisher }.${ type }`, JSON.stringify(data), aiKey], env: { ELECTRON_RUN_AS_NODE: 1, PIPE_LOGGING: 'true', AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp' } } ); const channel = client.getChannel('telemetryAppender'); const appender = new TelemetryAppenderClient(channel); this.toDisposeOnSessionEnd.push(client); this.customTelemetryService = new TelemetryService({ appender }, this.configurationService); } this.session = this.instantiationService.createInstance(RawDebugSession, configuration.debugServer, this.configurationManager.adapter, this.customTelemetryService); this.registerSessionListeners(); return this.session.initialize({ adapterID: configuration.type, pathFormat: 'path', linesStartAt1: true, columnsStartAt1: true, supportsVariableType: true, // #8858 supportsVariablePaging: true, // #9537 supportsRunInTerminalRequest: true // #10574 }).then((result: DebugProtocol.InitializeResponse) => { if (!this.session) { return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly"))); } this.model.setExceptionBreakpoints(this.session.configuration.capabilities.exceptionBreakpointFilters); return configuration.request === 'attach' ? this.session.attach(configuration) : this.session.launch(configuration); }).then((result: DebugProtocol.Response) => { if (!this.session) { return TPromise.as(null); } if (configuration.internalConsoleOptions === 'openOnSessionStart' || (!this.viewModel.changedWorkbenchViewState && configuration.internalConsoleOptions !== 'neverOpen')) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } if (!this.viewModel.changedWorkbenchViewState && !this.partService.isSideBarHidden()) { // We only want to change the workbench view state on the first debug session #5738 and if the side bar is not hidden this.viewModel.changedWorkbenchViewState = true; this.viewletService.openViewlet(debug.VIEWLET_ID); } // Do not change status bar to orange if we are just running without debug. if (!configuration.noDebug) { this.partService.addClass('debugging'); } this.extensionService.activateByEvent(`onDebug:${configuration.type}`).done(null, errors.onUnexpectedError); this.inDebugMode.set(true); this.lazyTransitionToRunningState(); this.telemetryService.publicLog('debugSessionStart', { type: configuration.type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: `${ this.configurationManager.adapter.extensionDescription.publisher }.${ this.configurationManager.adapter.extensionDescription.name }`, isBuiltin: this.configurationManager.adapter.extensionDescription.isBuiltin }); }).then(undefined, (error: any) => { if (error instanceof Error && error.message === 'Canceled') { // Do not show 'canceled' error messages to the user #7906 return TPromise.as(null); } this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined }); this.setStateAndEmit(debug.State.Inactive); if (this.session) { this.session.disconnect().done(null, errors.onUnexpectedError); } // Show the repl if some error got logged there #5870 if (this.model.getReplElements().length > 0) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction]; return TPromise.wrapError(errors.create(error.message, { actions })); }); }); } private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> { if (!taskName) { return TPromise.as(null); } // run a task before starting a debug session return this.taskService.tasks().then(descriptions => { const filteredTasks = descriptions.filter(task => task.name === taskName); if (filteredTasks.length !== 1) { return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), { actions: [ this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), this.taskService.configureAction(), CloseAction ] })); } // task is already running - nothing to do. if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) { return TPromise.as(null); } if (this.lastTaskEvent) { // there is a different task running currently. return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName))); } // no task running, execute the preLaunchTask. const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => { this.lastTaskEvent = null; return result; }, err => { this.lastTaskEvent = null; }); if (filteredTasks[0].isWatching) { return new TPromise((c, e) => this.taskService.addOneTimeDisposableListener(TaskServiceEvents.Inactive, () => c(null))); } return taskPromise; }); } private rawAttach(port: number): TPromise<any> { if (this.session) { return this.session.attach({ port }); } this.setStateAndEmit(debug.State.Initializing); const configuration = <debug.IExtHostConfig>this.configurationManager.configuration; return this.doCreateSession({ type: configuration.type, request: 'attach', port, sourceMaps: configuration.sourceMaps, outDir: configuration.outDir, debugServer: configuration.debugServer }); } public restartSession(): TPromise<any> { return this.session ? this.session.disconnect(true).then(() => new TPromise<void>((c, e) => { setTimeout(() => { this.createSession(false, null).then(() => c(null), err => e(err)); }, 300); }) ) : this.createSession(false, null); } public getActiveSession(): debug.IRawDebugSession { return this.session; } private onSessionEnd(): void { if (this.session) { const bpsExist = this.model.getBreakpoints().length > 0; this.telemetryService.publicLog('debugSessionStop', { type: this.session.configuration.type, success: this.session.emittedStopped || !bpsExist, sessionLengthInSeconds: this.session.getLengthInSeconds(), breakpointCount: this.model.getBreakpoints().length, watchExpressionsCount: this.model.getWatchExpressions().length }); } this.session = null; try { this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd); } catch (e) { // an internal module might be open so the dispose can throw -> ignore and continue with stop session. } this.partService.removeClass('debugging'); this.model.clearThreads(true); this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); this.setStateAndEmit(debug.State.Inactive); // set breakpoints back to unverified since the session ended. // source reference changes across sessions, so we do not use it to persist the source. const data: { [id: string]: { line: number, verified: boolean } } = {}; this.model.getBreakpoints().forEach(bp => { delete bp.source.raw.sourceReference; data[bp.getId()] = { line: bp.lineNumber, verified: false }; }); this.model.updateBreakpoints(data); this.inDebugMode.reset(); } public getModel(): debug.IModel { return this.model; } public getViewModel(): debug.IViewModel { return this.viewModel; } public openOrRevealSource(source: Source, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> { const visibleEditors = this.editorService.getVisibleEditors(); for (let i = 0; i < visibleEditors.length; i++) { const fileInput = asFileEditorInput(visibleEditors[i].input); if ((fileInput && fileInput.getResource().toString() === source.uri.toString()) || (visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === source.uri.toString())) { const control = <editorbrowser.ICodeEditor>visibleEditors[i].getControl(); if (control) { control.revealLineInCenterIfOutsideViewport(lineNumber); control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }); this.editorGroupService.activateGroup(i); if (!preserveFocus) { this.editorGroupService.focusGroup(i); } } return TPromise.as(null); } } if (source.inMemory) { // internal module if (source.reference !== 0 && this.session && source.available) { return this.session.source({ sourceReference: source.reference }).then(response => { const mime = response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0]; return this.getDebugStringEditorInput(source, response.body.content, mime); }, (err: DebugProtocol.ErrorResponse) => { // Display the error from debug adapter using a temporary editor #8836 return this.getDebugErrorEditorInput(source, err.message); }).then(editorInput => { return this.editorService.openEditor(editorInput, { preserveFocus, selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 } }, sideBySide); }); } return this.sourceIsUnavailable(source, sideBySide); } return this.fileService.resolveFile(source.uri).then(() => this.editorService.openEditor({ resource: source.uri, options: { selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }, preserveFocus: preserveFocus } }, sideBySide), err => this.sourceIsUnavailable(source, sideBySide) ); } private sourceIsUnavailable(source: Source, sideBySide: boolean): TPromise<any> { this.model.sourceIsUnavailable(source); const editorInput = this.getDebugErrorEditorInput(source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.name)); return this.editorService.openEditor(editorInput, { preserveFocus: true }, sideBySide); } public getConfigurationManager(): debug.IConfigurationManager { return this.configurationManager; } public next(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.next({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public stepIn(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.stepIn({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public stepOut(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.stepOut({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public stepBack(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.stepBack({ threadId }).then(() => { this.lazyTransitionToRunningState(threadId); }); } public continue(threadId: number): TPromise<void> { if (!this.session) { return TPromise.as(null); } return this.session.continue({ threadId }).then(response => { const allThreadsContinued = response.body ? response.body.allThreadsContinued !== false : true; this.lazyTransitionToRunningState(allThreadsContinued ? undefined : threadId); }); } public pause(threadId: number): TPromise<any> { if (!this.session) { return TPromise.as(null); } return this.session.pause({ threadId }); } public restartFrame(frameId: number): TPromise<any> { if (!this.session) { return TPromise.as(null); } return this.session.restartFrame({ frameId }); } public completions(text: string, position: Position): TPromise<ISuggestion[]> { if (!this.session || !this.session.configuration.capabilities.supportsCompletionsRequest) { return TPromise.as([]); } const focussedStackFrame = this.viewModel.getFocusedStackFrame(); return this.session.completions({ frameId: focussedStackFrame ? focussedStackFrame.frameId : undefined, text, column: position.column, line: position.lineNumber }).then(response => { return !response ? [] : response.body.targets.map(item => ({ label: item.label, insertText: item.text || item.label, type: item.type })); }, err => []); } private lazyTransitionToRunningState(threadId?: number): void { let setNewFocusedStackFrameScheduler: RunOnceScheduler; const toDispose = this.session.onDidStop(e => { if (e.body.threadId === threadId || e.body.allThreadsStopped || !threadId) { setNewFocusedStackFrameScheduler.cancel(); } }); this.model.clearThreads(false, threadId); // Get a top stack frame of a stopped thread if there is any. const threads = this.model.getThreads(); const stoppedReference = Object.keys(threads).filter(ref => threads[ref].stopped).pop(); const stoppedThread = stoppedReference ? threads[parseInt(stoppedReference)] : null; const callStack = stoppedThread ? stoppedThread.getCachedCallStack() : null; const stackFrameToFocus = callStack && callStack.length > 0 ? callStack[0] : null; if (!stoppedThread) { this.setStateAndEmit(this.configurationManager.configuration.noDebug ? debug.State.RunningNoDebug : debug.State.Running); } // Do not immediatly set a new focused stack frame since that might cause unnecessery flickering // of the tree in the debug viewlet. Only set focused stack frame if no stopped event has arrived in 500ms. setNewFocusedStackFrameScheduler = new RunOnceScheduler(() => { toDispose.dispose(); aria.status(nls.localize('debuggingContinued', "Debugging continued.")); this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError); }, 500); setNewFocusedStackFrameScheduler.schedule(); } private getDebugStringEditorInput(source: Source, value: string, mtype: string): DebugStringEditorInput { const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0); this.toDisposeOnSessionEnd.push(result); return result; } private getDebugErrorEditorInput(source: Source, value: string): DebugErrorEditorInput { const result = this.instantiationService.createInstance(DebugErrorEditorInput, source.name, value); this.toDisposeOnSessionEnd.push(result); return result; } private sendAllBreakpoints(): TPromise<any> { return TPromise.join(arrays.distinct(this.model.getBreakpoints(), bp => bp.source.uri.toString()).map(bp => this.sendBreakpoints(bp.source.uri))) .then(() => this.sendFunctionBreakpoints()) // send exception breakpoints at the end since some debug adapters rely on the order .then(() => this.sendExceptionBreakpoints()); } private sendBreakpoints(modelUri: uri, sourceModified = false): TPromise<void> { if (!this.session || !this.session.readyForBreakpoints) { return TPromise.as(null); } if (this.textFileService.isDirty(modelUri)) { // Only send breakpoints for a file once it is not dirty #8077 this.breakpointsToSendOnResourceSaved[modelUri.toString()] = true; return TPromise.as(null); } const breakpointsToSend = arrays.distinct( this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.source.uri.toString() === modelUri.toString()), bp => `${bp.desiredLineNumber}` ); const rawSource = breakpointsToSend.length > 0 ? breakpointsToSend[0].source.raw : Source.toRawSource(modelUri, this.model); return this.session.setBreakpoints({ source: rawSource, lines: breakpointsToSend.map(bp => bp.desiredLineNumber), breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition })), sourceModified }).then(response => { const data: { [id: string]: { line?: number, verified: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateBreakpoints(data); }); } private sendFunctionBreakpoints(): TPromise<void> { if (!this.session || !this.session.readyForBreakpoints || !this.session.configuration.capabilities.supportsFunctionBreakpoints) { return TPromise.as(null); } const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return this.session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => { const data: { [id: string]: { name?: string, verified?: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateFunctionBreakpoints(data); }); } private sendExceptionBreakpoints(): TPromise<any> { if (!this.session || !this.session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) { return TPromise.as(null); } const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return this.session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) }); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.source.uri, FileChangeType.DELETED))); fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved[event.resource.toString()]) { this.breakpointsToSendOnResourceSaved[event.resource.toString()] = false; this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError); } }); } private store(): void { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE); this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.configurationManager.configurationName, StorageScope.WORKSPACE); this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions().map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } public dispose(): void { this.toDisposeOnSessionEnd = lifecycle.dispose(this.toDisposeOnSessionEnd); this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/parts/debug/electron-browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.004210534505546093, 0.00024050966021604836, 0.00016214116476476192, 0.00017052852490451187, 0.00048454105854034424 ]
{ "id": 13, "code_window": [ "\t\t\t\t\t// Do not show error message to user if showUser === false or 'canceled' error message #7906\n", "\t\t\t\t\treturn TPromise.as(null);\n", "\t\t\t\t}\n", "\n", "\t\t\t\tconst userMessage = error ? debug.formatPII(error.format, false, error.variables) : errorResponse.message;\n", "\t\t\t\tif (error && error.url) {\n", "\t\t\t\t\tconst label = error.urlLabel ? error.urlLabel : nls.localize('moreInfo', \"More Info\");\n", "\t\t\t\t\treturn TPromise.wrapError(errors.create(userMessage, { actions: [CloseAction, new Action('debug.moreInfo', label, null, true, () => {\n", "\t\t\t\t\t\tshell.openExternal(error.url);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tconst userMessage = error ? debug.formatPII(error.format, false, error.variables) : errorMessage;\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/rawDebugSession.ts", "type": "replace", "edit_start_line_idx": 170 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "typingsReference.already.exists": "{0} esiste già. Verificare che il file sia incluso nel file jsconfig.json del progetto", "typingsReference.error.download": "Non è possibile recuperare il file d.ts in {0}: {1}", "typingsReference.error.write": "Problema durante la creazione di {0}: {1}", "typingsReference.success.nojsconfig": "Download di {0} riuscito", "typingsReference.success.withjsconfig": "Download di {0} riuscito. Verificare che il file d.ts sia incluso nel file 'jsconfig.json' del progetto." }
i18n/ita/src/vs/languages/typescript/common/features/quickFixMainActions.i18n.json
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017016599304042757, 0.00017008457507472485, 0.00017000315710902214, 0.00017008457507472485, 8.141796570271254e-8 ]
{ "id": 13, "code_window": [ "\t\t\t\t\t// Do not show error message to user if showUser === false or 'canceled' error message #7906\n", "\t\t\t\t\treturn TPromise.as(null);\n", "\t\t\t\t}\n", "\n", "\t\t\t\tconst userMessage = error ? debug.formatPII(error.format, false, error.variables) : errorResponse.message;\n", "\t\t\t\tif (error && error.url) {\n", "\t\t\t\t\tconst label = error.urlLabel ? error.urlLabel : nls.localize('moreInfo', \"More Info\");\n", "\t\t\t\t\treturn TPromise.wrapError(errors.create(userMessage, { actions: [CloseAction, new Action('debug.moreInfo', label, null, true, () => {\n", "\t\t\t\t\t\tshell.openExternal(error.url);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tconst userMessage = error ? debug.formatPII(error.format, false, error.variables) : errorMessage;\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/rawDebugSession.ts", "type": "replace", "edit_start_line_idx": 170 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; // include these in the editor bundle because they are widely used by many languages import 'vs/editor/common/languages.common'; import Severity from 'vs/base/common/severity'; import {TPromise} from 'vs/base/common/winjs.base'; import {WorkerServer} from 'vs/base/common/worker/workerServer'; import {EventService} from 'vs/platform/event/common/eventService'; import {IEventService} from 'vs/platform/event/common/event'; import {AbstractExtensionService, ActivatedExtension} from 'vs/platform/extensions/common/abstractExtensionService'; import {IExtensionDescription, IExtensionService} from 'vs/platform/extensions/common/extensions'; import {ServiceCollection} from 'vs/platform/instantiation/common/serviceCollection'; import {InstantiationService} from 'vs/platform/instantiation/common/instantiationService'; import {ModeServiceImpl} from 'vs/editor/common/services/modeServiceImpl'; import {IModeService, ILanguageExtensionPoint} from 'vs/editor/common/services/modeService'; import {ResourceService} from 'vs/editor/common/services/resourceServiceImpl'; import {IResourceService} from 'vs/editor/common/services/resourceService'; import {CompatWorkerServiceWorker} from 'vs/editor/common/services/compatWorkerServiceWorker'; import {ICompatWorkerService} from 'vs/editor/common/services/compatWorkerService'; import {ILegacyLanguageDefinition} from 'vs/editor/common/modes/modesRegistry'; export interface IInitData { modesRegistryData?: { compatModes: ILegacyLanguageDefinition[]; languages: ILanguageExtensionPoint[]; }; } export interface ICallback { (something:any):void; } class WorkerExtensionService extends AbstractExtensionService<ActivatedExtension> { constructor() { super(true); } protected _showMessage(severity:Severity, msg:string): void { switch (severity) { case Severity.Error: console.error(msg); break; case Severity.Warning: console.warn(msg); break; case Severity.Info: console.info(msg); break; default: console.log(msg); } } protected _createFailedExtension(): ActivatedExtension { throw new Error('unexpected'); } protected _actualActivateExtension(extensionDescription: IExtensionDescription): TPromise<ActivatedExtension> { throw new Error('unexpected'); } } export class EditorWorkerServer { private compatWorkerService:CompatWorkerServiceWorker; constructor() { } public initialize(mainThread:WorkerServer, complete:ICallback, error:ICallback, progress:ICallback, initData:IInitData):void { const services = new ServiceCollection(); const instantiationService = new InstantiationService(services); const extensionService = new WorkerExtensionService(); services.set(IExtensionService, extensionService); const resourceService = new ResourceService(); services.set(IResourceService, resourceService); services.set(IEventService, new EventService()); const modeService = new ModeServiceImpl(instantiationService, extensionService); services.set(IModeService, modeService); this.compatWorkerService = new CompatWorkerServiceWorker(resourceService, modeService, initData.modesRegistryData); services.set(ICompatWorkerService, this.compatWorkerService); complete(undefined); } public request(mainThread:WorkerServer, complete:ICallback, error:ICallback, progress:ICallback, data:any):void { try { TPromise.as( this.compatWorkerService.handleMainRequest(data.target, data.methodName, data.args) ).then(complete, error); } catch (err) { error(err); } } } export var value = new EditorWorkerServer();
src/vs/editor/common/worker/editorWorkerServer.ts
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.00017534653306938708, 0.00016989455616567284, 0.00016429224342573434, 0.00016972539015114307, 0.0000034016968584182905 ]
{ "id": 13, "code_window": [ "\t\t\t\t\t// Do not show error message to user if showUser === false or 'canceled' error message #7906\n", "\t\t\t\t\treturn TPromise.as(null);\n", "\t\t\t\t}\n", "\n", "\t\t\t\tconst userMessage = error ? debug.formatPII(error.format, false, error.variables) : errorResponse.message;\n", "\t\t\t\tif (error && error.url) {\n", "\t\t\t\t\tconst label = error.urlLabel ? error.urlLabel : nls.localize('moreInfo', \"More Info\");\n", "\t\t\t\t\treturn TPromise.wrapError(errors.create(userMessage, { actions: [CloseAction, new Action('debug.moreInfo', label, null, true, () => {\n", "\t\t\t\t\t\tshell.openExternal(error.url);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tconst userMessage = error ? debug.formatPII(error.format, false, error.variables) : errorMessage;\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/rawDebugSession.ts", "type": "replace", "edit_start_line_idx": 170 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "smartSelect.jumpBracket": "Gehe zu Klammer" }
i18n/deu/src/vs/editor/contrib/smartSelect/common/jumpToBracket.i18n.json
0
https://github.com/microsoft/vscode/commit/62f00c94a577262ff1cd204fea805dbe86f76c97
[ 0.0001748556678649038, 0.0001748556678649038, 0.0001748556678649038, 0.0001748556678649038, 0 ]
{ "id": 0, "code_window": [ " throw new Error('Table meta is not available')\n", " }\n", "\n", " const formattedData = ref<Row[]>([])\n", "\n", " // const { api } = useApi()\n", "\n", " const { project } = useProject()\n", "\n", " const { $api } = useNuxtApp()\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const { api } = useApi()\n" ], "file_path": "packages/nc-gui/composables/useMapViewDataStore.ts", "type": "replace", "edit_start_line_idx": 35 }
import { UITypes, ViewTypes } from 'nocodb-sdk' import type { Api, ColumnType, FormColumnType, FormType, GalleryType, PaginatedType, TableType, ViewType } from 'nocodb-sdk' import type { ComputedRef, Ref } from 'vue' import { IsPublicInj, NOCO, NavigateDir, computed, extractPkFromRow, extractSdkResponseErrorMsg, getHTMLEncodedText, message, populateInsertObject, ref, until, useApi, useGlobal, useI18n, useMetas, useNuxtApp, useProject, useRouter, useSharedView, useSmartsheetStoreOrThrow, useUIPermission, } from '#imports' import type { Row } from '~/lib' const formatData = (list: Row[]) => list.map((row) => ({ row: { ...row }, oldRow: { ...row }, rowMeta: {}, })) export function useViewData( meta: Ref<TableType | undefined> | ComputedRef<TableType | undefined>, viewMeta: Ref<ViewType | undefined> | ComputedRef<(ViewType & { id: string }) | undefined>, where?: ComputedRef<string | undefined>, ) { if (!meta) { throw new Error('Table meta is not available') } const { t } = useI18n() const { api, isLoading, error } = useApi() const router = useRouter() const route = $(router.currentRoute) const { appInfo } = $(useGlobal()) const { getMeta } = useMetas() const appInfoDefaultLimit = appInfo.defaultLimit || 25 const _paginationData = ref<PaginatedType>({ page: 1, pageSize: appInfoDefaultLimit }) const aggCommentCount = ref<{ row_id: string; count: number }[]>([]) const galleryData = ref<GalleryType>() const formColumnData = ref<Record<string, any>[]>() const formViewData = ref<FormType>() const formattedData = ref<Row[]>([]) const isPublic = inject(IsPublicInj, ref(false)) const { project, isSharedBase } = useProject() const { sharedView, fetchSharedViewData, paginationData: sharedPaginationData } = useSharedView() const { $api, $e } = useNuxtApp() const { sorts, nestedFilters } = useSmartsheetStoreOrThrow() const { isUIAllowed } = useUIPermission() const routeQuery = $computed(() => route.query as Record<string, string>) const paginationData = computed({ get: () => (isPublic.value ? sharedPaginationData.value : _paginationData.value), set: (value) => { if (isPublic.value) { sharedPaginationData.value = value } else { _paginationData.value = value } }, }) const selectedAllRecords = computed({ get() { return !!formattedData.value.length && formattedData.value.every((row: Row) => row.rowMeta.selected) }, set(selected: boolean) { formattedData.value.forEach((row: Row) => (row.rowMeta.selected = selected)) }, }) const queryParams = computed(() => ({ offset: ((paginationData.value.page ?? 0) - 1) * (paginationData.value.pageSize ?? appInfoDefaultLimit), limit: paginationData.value.pageSize ?? appInfoDefaultLimit, where: where?.value ?? '', })) function addEmptyRow(addAfter = formattedData.value.length) { formattedData.value.splice(addAfter, 0, { row: {}, oldRow: {}, rowMeta: { new: true }, }) return formattedData.value[addAfter] } function removeLastEmptyRow() { const lastRow = formattedData.value[formattedData.value.length - 1] if (lastRow.rowMeta.new) { formattedData.value.pop() } } async function syncCount() { const { count } = await $api.dbViewRow.count( NOCO, project?.value?.title as string, meta?.value?.id as string, viewMeta?.value?.id as string, ) paginationData.value.totalRows = count } async function syncPagination() { // total records in the current table const count = paginationData.value?.totalRows ?? Infinity // the number of rows in a page const size = paginationData.value.pageSize ?? appInfoDefaultLimit // the current page number const currentPage = paginationData.value.page ?? 1 // the maximum possible page given the current count and the size const mxPage = Math.ceil(count / size) // calculate targetPage where 1 <= targetPage <= mxPage const targetPage = Math.max(1, Math.min(mxPage, currentPage)) // if the current page is greater than targetPage, // then the page should be changed instead of showing an empty page // e.g. deleting all records in the last page N should return N - 1 page if (currentPage > targetPage) { // change to target page and load data of that page changePage?.(targetPage) } else { // the current page is same as target page // reload it to avoid empty row in this page await loadData({ offset: (targetPage - 1) * size, where: where?.value, } as any) } } /** load row comments count */ async function loadAggCommentsCount() { if (isPublic.value || isSharedBase.value) return const ids = formattedData.value ?.filter(({ rowMeta: { new: isNew } }) => !isNew) ?.map(({ row }) => { return extractPkFromRow(row, meta?.value?.columns as ColumnType[]) }) if (!ids?.length || ids?.some((id) => !id)) return aggCommentCount.value = await $api.utils.commentCount({ ids, fk_model_id: meta.value?.id as string, }) for (const row of formattedData.value) { const id = extractPkFromRow(row.row, meta.value?.columns as ColumnType[]) row.rowMeta.commentCount = aggCommentCount.value?.find((c: Record<string, any>) => c.row_id === id)?.count || 0 } } async function loadData(params: Parameters<Api<any>['dbViewRow']['list']>[4] = {}) { debugger if ((!project?.value?.id || !meta.value?.id || !viewMeta.value?.id) && !isPublic.value) return const response = !isPublic.value ? await api.dbViewRow.list('noco', project.value.id!, meta.value!.id!, viewMeta.value!.id!, { ...queryParams.value, ...params, ...(isUIAllowed('sortSync') ? {} : { sortArrJson: JSON.stringify(sorts.value) }), ...(isUIAllowed('filterSync') ? {} : { filterArrJson: JSON.stringify(nestedFilters.value) }), where: where?.value, }) : await fetchSharedViewData({ sortsArr: sorts.value, filtersArr: nestedFilters.value }) formattedData.value = formatData(response.list) paginationData.value = response.pageInfo // to cater the case like when querying with a non-zero offset // the result page may point to the target page where the actual returned data don't display on const expectedPage = Math.max(1, Math.ceil(paginationData.value.totalRows! / paginationData.value.pageSize!)) if (expectedPage < paginationData.value.page!) { await changePage(expectedPage) } if (viewMeta.value?.type === ViewTypes.GRID) { await loadAggCommentsCount() } } async function loadGalleryData() { if (!viewMeta?.value?.id) return galleryData.value = isPublic.value ? (sharedView.value?.view as GalleryType) : await $api.dbView.galleryRead(viewMeta.value.id) // debugger } async function insertRow( currentRow: Row, ltarState: Record<string, any> = {}, { metaValue = meta.value, viewMetaValue = viewMeta.value }: { metaValue?: TableType; viewMetaValue?: ViewType } = {}, ) { const row = currentRow.row if (currentRow.rowMeta) currentRow.rowMeta.saving = true try { const { missingRequiredColumns, insertObj } = await populateInsertObject({ meta: metaValue!, ltarState, getMeta, row, }) if (missingRequiredColumns.size) return const insertedData = await $api.dbViewRow.create( NOCO, project?.value.id as string, metaValue?.id as string, viewMetaValue?.id as string, insertObj, ) Object.assign(currentRow, { row: { ...insertedData, ...row }, rowMeta: { ...(currentRow.rowMeta || {}), new: undefined }, oldRow: { ...insertedData }, }) await syncCount() return insertedData } catch (error: any) { message.error(await extractSdkResponseErrorMsg(error)) } finally { if (currentRow.rowMeta) currentRow.rowMeta.saving = false } } // inside this method use metaValue and viewMetaValue to refer meta // since sometimes we need to pass old metas async function updateRowProperty( toUpdate: Row, property: string, { metaValue = meta.value, viewMetaValue = viewMeta.value }: { metaValue?: TableType; viewMetaValue?: ViewType } = {}, ) { if (toUpdate.rowMeta) toUpdate.rowMeta.saving = true try { const id = extractPkFromRow(toUpdate.row, metaValue?.columns as ColumnType[]) const updatedRowData = await $api.dbViewRow.update( NOCO, project?.value.id as string, metaValue?.id as string, viewMetaValue?.id as string, encodeURIComponent(id), { // if value is undefined treat it as null [property]: toUpdate.row[property] ?? null, }, // todo: // { // query: { ignoreWebhook: !saved } // } ) // audit $api.utils.auditRowUpdate(encodeURIComponent(id), { fk_model_id: metaValue?.id as string, column_name: property, row_id: id, value: getHTMLEncodedText(toUpdate.row[property]), prev_value: getHTMLEncodedText(toUpdate.oldRow[property]), }) /** update row data(to sync formula and other related columns) * update only formula, rollup and auto updated datetime columns data to avoid overwriting any changes made by user */ Object.assign( toUpdate.row, metaValue!.columns!.reduce<Record<string, any>>((acc: Record<string, any>, col: ColumnType) => { if ( col.uidt === UITypes.Formula || col.uidt === UITypes.QrCode || col.uidt === UITypes.Barcode || col.uidt === UITypes.Rollup || col.au || col.cdf?.includes(' on update ') ) acc[col.title!] = updatedRowData[col.title!] return acc }, {} as Record<string, any>), ) Object.assign(toUpdate.oldRow, updatedRowData) } catch (e: any) { message.error(`${t('msg.error.rowUpdateFailed')} ${await extractSdkResponseErrorMsg(e)}`) } finally { if (toUpdate.rowMeta) toUpdate.rowMeta.saving = false } } async function updateOrSaveRow( row: Row, property?: string, ltarState?: Record<string, any>, args: { metaValue?: TableType; viewMetaValue?: ViewType } = {}, ) { // update changed status if (row.rowMeta) row.rowMeta.changed = false // if new row and save is in progress then wait until the save is complete await until(() => !(row.rowMeta?.new && row.rowMeta?.saving)).toMatch((v) => v) if (row.rowMeta.new) { return await insertRow(row, ltarState, args) } else { // if the field name is missing skip update if (property) { await updateRowProperty(row, property, args) } } } async function changePage(page: number) { paginationData.value.page = page await loadData({ offset: (page - 1) * (paginationData.value.pageSize || appInfoDefaultLimit), where: where?.value, } as any) $e('a:grid:pagination') } async function deleteRowById(id: string) { if (!id) { throw new Error("Delete not allowed for table which doesn't have primary Key") } const res: any = await $api.dbViewRow.delete( 'noco', project.value.id as string, meta.value?.id as string, viewMeta.value?.id as string, id, ) if (res.message) { message.info( `Row delete failed: ${`Unable to delete row with ID ${id} because of the following: \n${res.message.join('\n')}.\n Clear the data first & try again`})}`, ) return false } return true } async function deleteRow(rowIndex: number) { try { const row = formattedData.value[rowIndex] if (!row.rowMeta.new) { const id = meta?.value?.columns ?.filter((c) => c.pk) .map((c) => row.row[c.title!]) .join('___') const deleted = await deleteRowById(id as string) if (!deleted) { return } } formattedData.value.splice(rowIndex, 1) await syncCount() } catch (e: any) { message.error(`${t('msg.error.deleteRowFailed')}: ${await extractSdkResponseErrorMsg(e)}`) } } async function deleteSelectedRows() { let row = formattedData.value.length while (row--) { try { const { row: rowObj, rowMeta } = formattedData.value[row] as Record<string, any> if (!rowMeta.selected) { continue } if (!rowMeta.new) { const id = meta?.value?.columns ?.filter((c) => c.pk) .map((c) => rowObj[c.title as string]) .join('___') const successfulDeletion = await deleteRowById(id as string) if (!successfulDeletion) { continue } } formattedData.value.splice(row, 1) } catch (e: any) { return message.error(`${t('msg.error.deleteRowFailed')}: ${await extractSdkResponseErrorMsg(e)}`) } } await syncCount() await syncPagination() } async function loadFormView() { if (!viewMeta?.value?.id) return try { const { columns, ...view } = await $api.dbView.formRead(viewMeta.value.id) const fieldById = (columns || []).reduce( (o: Record<string, any>, f: Record<string, any>) => ({ ...o, [f.fk_column_id]: f, }), {} as Record<string, FormColumnType>, ) let order = 1 formViewData.value = view formColumnData.value = meta?.value?.columns ?.map((c: Record<string, any>) => ({ ...c, fk_column_id: c.id, fk_view_id: viewMeta.value?.id, ...(fieldById[c.id] ? fieldById[c.id] : {}), order: (fieldById[c.id] && fieldById[c.id].order) || order++, id: fieldById[c.id] && fieldById[c.id].id, })) .sort((a: Record<string, any>, b: Record<string, any>) => a.order - b.order) as Record<string, any>[] } catch (e: any) { return message.error(`${t('msg.error.setFormDataFailed')}: ${await extractSdkResponseErrorMsg(e)}`) } } async function updateFormView(view: FormType | undefined) { try { if (!viewMeta?.value?.id || !view) return await $api.dbView.formUpdate(viewMeta.value.id, view) } catch (e: any) { return message.error(`${t('msg.error.formViewUpdateFailed')}: ${await extractSdkResponseErrorMsg(e)}`) } } const removeRowIfNew = (row: Row) => { const index = formattedData.value.indexOf(row) if (index > -1 && row.rowMeta.new) { formattedData.value.splice(index, 1) } } // get current expanded row index function getExpandedRowIndex() { return formattedData.value.findIndex( (row: Row) => routeQuery.rowId === extractPkFromRow(row.row, meta.value?.columns as ColumnType[]), ) } const navigateToSiblingRow = async (dir: NavigateDir) => { const expandedRowIndex = getExpandedRowIndex() // calculate next row index based on direction let siblingRowIndex = expandedRowIndex + (dir === NavigateDir.NEXT ? 1 : -1) // if unsaved row skip it while (formattedData.value[siblingRowIndex]?.rowMeta?.new) { siblingRowIndex = siblingRowIndex + (dir === NavigateDir.NEXT ? 1 : -1) } const currentPage = paginationData?.value?.page || 1 // if next row index is less than 0, go to previous page and point to last element if (siblingRowIndex < 0) { // if first page, do nothing if (currentPage === 1) return message.info(t('msg.info.noMoreRecords')) await changePage(currentPage - 1) siblingRowIndex = formattedData.value.length - 1 // if next row index is greater than total rows in current view // then load next page of formattedData and set next row index to 0 } else if (siblingRowIndex >= formattedData.value.length) { if (paginationData?.value?.isLastPage) return message.info(t('msg.info.noMoreRecords')) await changePage(currentPage + 1) siblingRowIndex = 0 } // extract the row id of the sibling row const rowId = extractPkFromRow(formattedData.value[siblingRowIndex].row, meta.value?.columns as ColumnType[]) if (rowId) { router.push({ query: { ...routeQuery, rowId, }, }) } } return { error, isLoading, loadData, paginationData, queryParams, formattedData, insertRow, updateRowProperty, changePage, addEmptyRow, deleteRow, deleteSelectedRows, updateOrSaveRow, selectedAllRecords, syncCount, syncPagination, galleryData, loadGalleryData, loadFormView, formColumnData, formViewData, updateFormView, aggCommentCount, loadAggCommentsCount, removeLastEmptyRow, removeRowIfNew, navigateToSiblingRow, deleteRowById, getExpandedRowIndex, } }
packages/nc-gui/composables/useViewData.ts
1
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.9988844990730286, 0.40639522671699524, 0.00016329536447301507, 0.001951984828338027, 0.47385895252227783 ]
{ "id": 0, "code_window": [ " throw new Error('Table meta is not available')\n", " }\n", "\n", " const formattedData = ref<Row[]>([])\n", "\n", " // const { api } = useApi()\n", "\n", " const { project } = useProject()\n", "\n", " const { $api } = useNuxtApp()\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const { api } = useApi()\n" ], "file_path": "packages/nc-gui/composables/useMapViewDataStore.ts", "type": "replace", "edit_start_line_idx": 35 }
import Noco from '../Noco'; import NocoCache from '../cache/NocoCache'; import { CacheGetType, CacheScope, MetaTable } from '../utils/globals'; import { extractProps } from '../meta/helpers/extractProps'; import type { SelectOptionType } from 'nocodb-sdk'; export default class SelectOption implements SelectOptionType { id: string; title: string; fk_column_id: string; color: string; order: number; constructor(data: Partial<SelectOption>) { Object.assign(this, data); } public static async insert( data: Partial<SelectOption>, ncMeta = Noco.ncMeta ) { const insertObj = extractProps(data, [ 'id', 'title', 'fk_column_id', 'color', 'order', ]); const { id } = await ncMeta.metaInsert2( null, null, MetaTable.COL_SELECT_OPTIONS, insertObj ); await NocoCache.appendToList( CacheScope.COL_SELECT_OPTION, [data.fk_column_id], `${CacheScope.COL_SELECT_OPTION}:${id}` ); return this.get(id, ncMeta); } public static async get( selectOptionId: string, ncMeta = Noco.ncMeta ): Promise<SelectOption> { let data = selectOptionId && (await NocoCache.get( `${CacheScope.COL_SELECT_OPTION}:${selectOptionId}`, CacheGetType.TYPE_OBJECT )); if (!data) { data = await ncMeta.metaGet2( null, null, MetaTable.COL_SELECT_OPTIONS, selectOptionId ); await NocoCache.set( `${CacheScope.COL_SELECT_OPTION}:${selectOptionId}`, data ); } return data && new SelectOption(data); } public static async read(fk_column_id: string, ncMeta = Noco.ncMeta) { let options = await NocoCache.getList(CacheScope.COL_SELECT_OPTION, [ fk_column_id, ]); if (!options.length) { options = await ncMeta.metaList2( null, //, null, //model.db_alias, MetaTable.COL_SELECT_OPTIONS, { condition: { fk_column_id } } ); await NocoCache.setList( CacheScope.COL_SELECT_OPTION, [fk_column_id], options.map(({ created_at, updated_at, ...others }) => others) ); } return options?.length ? { options: options .map(({ created_at, updated_at, ...c }) => new SelectOption(c)) .sort((x, y) => x.order - y.order), } : null; } public static async find( fk_column_id: string, title: string, ncMeta = Noco.ncMeta ): Promise<SelectOption> { const data = await ncMeta.metaGet2( null, null, MetaTable.COL_SELECT_OPTIONS, { fk_column_id, title, } ); return data && new SelectOption(data); } }
packages/nocodb/src/lib/models/SelectOption.ts
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.0002121827274095267, 0.0001766309724189341, 0.00016556039918214083, 0.0001743650354910642, 0.000011425260709074792 ]
{ "id": 0, "code_window": [ " throw new Error('Table meta is not available')\n", " }\n", "\n", " const formattedData = ref<Row[]>([])\n", "\n", " // const { api } = useApi()\n", "\n", " const { project } = useProject()\n", "\n", " const { $api } = useNuxtApp()\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const { api } = useApi()\n" ], "file_path": "packages/nc-gui/composables/useMapViewDataStore.ts", "type": "replace", "edit_start_line_idx": 35 }
{ "compilerOptions": { "skipLibCheck": true, "composite": true, "target": "es2017", "outDir": "build/main", "rootDir": "src", "moduleResolution": "node", "module": "commonjs", "declaration": true, "inlineSourceMap": true, "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, "allowJs": false, // "strict": true /* Enable all strict type-checking options. */, /* Strict Type-Checking Options */ // "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */, // "strictNullChecks": true /* Enable strict null checks. */, // "strictFunctionTypes": true /* Enable strict checking of function types. */, // "strictPropertyInitialization": true /* Enable strict checking of property initialization in classes. */, // "noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */, // "alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */, "resolveJsonModule": true, /* Additional Checks */ "noUnusedLocals": false /* Report errors on unused locals. */, "noUnusedParameters": false /* Report errors on unused parameters. */, "noImplicitReturns": false /* Report error when not all code paths in function return a value. */, "noFallthroughCasesInSwitch": false /* Report errors for fallthrough cases in switch statement. */, /* Debugging Options */ "traceResolution": false /* Report module resolution log messages. */, "listEmittedFiles": false /* Print names of generated files part of the compilation. */, "listFiles": false /* Print names of files part of the compilation. */, "pretty": true /* Stylize errors and messages using color and context. */, /* Experimental Options */ // "experimentalDecorators": true /* Enables experimental support for ES7 decorators. */, // "emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */, "lib": [ "es2017" ], "types": [ "mocha", "node" ], "typeRoots": [ "node_modules/@types", "src/types" ] }, "parserOptions": { "sourceType": "module", "tsconfigRootDir": "./", "project": "./tsconfig.json", }, "include": [ "./tests/**/**/**.ts", "./tests/**/**.ts" // "**/*.ts", // "**/*.json" ], "exclude": [ ], "compileOnSave": false }
packages/nocodb/tests/unit/tsconfig.json
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.00017748636309988797, 0.00017359272169414908, 0.00016853876877576113, 0.000173316802829504, 0.0000027433970899437554 ]
{ "id": 0, "code_window": [ " throw new Error('Table meta is not available')\n", " }\n", "\n", " const formattedData = ref<Row[]>([])\n", "\n", " // const { api } = useApi()\n", "\n", " const { project } = useProject()\n", "\n", " const { $api } = useNuxtApp()\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const { api } = useApi()\n" ], "file_path": "packages/nc-gui/composables/useMapViewDataStore.ts", "type": "replace", "edit_start_line_idx": 35 }
<?xml version="1.0" encoding="UTF-8"?> <svg width="30px" height="30px" viewBox="0 0 30 30" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- Generator: Sketch 63.1 (92452) - https://sketch.com --> <title>MailerSend Copy 2</title> <desc>Created with Sketch.</desc> <g id="Website" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="Desktop-HD-Copy-25" transform="translate(-230.000000, -30.000000)"> <g id="MailerSend-Copy-2" transform="translate(230.000000, 30.000000)"> <g id="symbol-copy-2"> <path d="M29.5793151,10.1663649 C29.4628886,9.99688216 29.2691772,9.90994232 29.0738683,9.90994232 L17.9522395,9.90994232 L23.498176,1.04527667 C23.6409633,0.817634197 23.6489514,0.506049814 23.4756097,0.256222694 C23.3579849,0.0865401142 23.1622765,0 22.9661687,0 L13.3890387,0 C12.4274714,0 11.5290101,0.515643175 10.9904126,1.3764475 L0.106230039,18.7748078 C-0.0361578035,19.0026502 -0.0421488768,19.3142345 0.129395522,19.5640617 C0.245622344,19.7333445 0.439333714,19.8200845 0.634842406,19.8200845 L11.7508795,19.8200845 L6.20434385,28.6869486 C6.10449263,28.846838 6.07393815,29.0480987 6.11947031,29.2399659 C6.18956587,29.5371603 6.45277369,29.7322253 6.73655086,29.7322253 L16.3080893,29.7322253 C17.2768458,29.7322253 18.182097,29.2125849 18.7244888,28.345385 L24.0563444,19.8200845 L24.0565441,19.8200845 L29.6020812,10.9554189 C29.7446688,10.7277764 29.7506598,10.4157923 29.5793151,10.1663649" id="Fill-1" fill="#4E48E0"></path> <path d="M24.0576142,19.8181059 L18.7245604,28.3452051 C18.1821686,29.2126049 17.2767177,29.7320454 16.3081608,29.7320454 L6.73662243,29.7320454 C6.45284526,29.7320454 6.18963744,29.5371803 6.11954188,29.2399859 C6.07400973,29.0481187 6.1045642,28.846858 6.20441542,28.6869686 L11.7519496,19.8181059 L24.0576142,19.8181059 Z" id="Fill-3" fill="#4E48E0"></path> <path d="M17.9450419,9.90992233 L29.0738599,9.90992233 C29.2691689,9.90992233 29.4628803,9.99686217 29.5793068,10.166145 C29.7508512,10.4157723 29.7444608,10.7275565 29.6022726,10.9553989 L24.0567355,19.8200645 L11.746278,19.8200645 L17.9450419,9.90992233 Z" id="Fill-5" fill="#1C81C1"></path> <path d="M0.634794157,19.8200445 C0.439485167,19.8200445 0.245773797,19.7333046 0.129546975,19.5640217 C-0.0421971263,19.3141946 -0.036206053,19.0026102 0.106381492,18.7749677 L10.9905641,1.37640753 C11.5289618,0.515603203 12.4276228,-3.99723392e-05 13.3889904,-3.99723392e-05 L22.9661205,-3.99723392e-05 C23.1622283,-3.99723392e-05 23.3581364,0.0867000036 23.4757611,0.256182722 C23.6489031,0.506009841 23.640915,0.817594225 23.4983275,1.04543656 L11.7520295,19.8200445 L0.634794157,19.8200445 Z" id="Fill-7" fill="#5CC4CD"></path> </g> <g id="logo" transform="translate(41.937513, 6.195713)" fill="#3A3945"> <path d="M53.7579806,10.2010809 L54.0445536,10.2010809 L59.7304816,10.2010809 C59.9383718,10.2010809 60.5560515,10.2040788 60.5560515,10.2040788 C60.5560515,10.2040788 60.5558518,10.1639066 60.5211036,10.001419 C60.397288,9.41962162 60.1736213,8.88719006 59.7836024,8.43350402 C58.8769533,7.37983316 57.2675513,7.02048183 55.8914018,7.57529789 C54.7105613,8.05116859 54.0665209,8.9715317 53.7579806,10.2010809 M58.6045592,12.5132808 C57.068448,12.5132808 55.5327362,12.5166785 53.9968247,12.5092836 C53.7963235,12.5080844 53.7585797,12.5500554 53.8122997,12.747119 C54.2148998,14.216702 55.3849564,15.2248044 56.8909125,15.3884912 C58.5851881,15.5725638 60.1368761,15.1472581 61.5877143,14.2916502 L61.8471278,14.138756 L63.0715035,16.3122519 C63.0715035,16.3122519 63.0365555,16.3318384 62.9073481,16.4179788 C61.0828665,17.6383343 59.0740597,18.1663689 56.8875176,18.0386572 C55.9117715,17.9816967 54.9733697,17.7720417 54.0922825,17.3435383 C52.7894238,16.7101766 51.8304526,15.7290555 51.2569072,14.4003749 C50.4592956,12.5528534 50.4117665,10.6655594 51.1211095,8.78506074 C52.0319524,6.36973215 54.2528433,4.86617261 56.9514224,4.78323 C58.3427493,4.7404596 59.6635813,4.99868091 60.8484159,5.75935453 C62.5217226,6.83361114 63.314741,8.43090581 63.5166402,10.364168 C63.582542,10.9961307 63.5487923,11.625695 63.4940738,12.2574578 C63.4743033,12.4866992 63.4683122,12.517278 63.4683122,12.517278 C63.4683122,12.517278 60.1322829,12.5132808 58.6045592,12.5132808" id="Fill-1"></path> <path d="M89.0300452,10.2010809 L89.3164185,10.2010809 L95.0025462,10.2010809 C95.2104364,10.2010809 95.8281161,10.2040788 95.8281161,10.2040788 C95.8281161,10.2040788 95.8277167,10.1639066 95.7931682,10.001419 C95.669153,9.41962162 95.4454862,8.88719006 95.0554674,8.43350402 C94.149018,7.37983316 92.5394163,7.02048183 91.1634664,7.57529789 C89.9826259,8.05116859 89.3385855,8.9715317 89.0300452,10.2010809 M93.8764241,12.5132808 C92.3405126,12.5132808 90.8046011,12.5166785 89.2686897,12.5092836 C89.0681884,12.5080844 89.0304446,12.5500554 89.0843643,12.747119 C89.4867647,14.216702 90.6568213,15.2248044 92.1629772,15.3884912 C93.857053,15.5725638 95.4089407,15.1472581 96.8597789,14.2916502 L97.1189927,14.138756 L98.3435681,16.3122519 C98.3435681,16.3122519 98.3086202,16.3318384 98.179213,16.4179788 C96.3547315,17.6383343 94.3461243,18.1663689 92.1593825,18.0386572 C91.1836364,17.9816967 90.2452346,17.7720417 89.3643471,17.3435383 C88.0614884,16.7101766 87.1023175,15.7290555 86.5287721,14.4003749 C85.7311606,12.5528534 85.6836314,10.6655594 86.3931742,8.78506074 C87.304017,6.36973215 89.5247082,4.86617261 92.2232873,4.78323 C93.6148139,4.7404596 94.9354462,4.99868091 96.1204805,5.75935453 C97.7935876,6.83361114 98.5868057,8.43090581 98.7885051,10.364168 C98.8544069,10.9961307 98.8206572,11.625695 98.7659388,12.2574578 C98.7461682,12.4866992 98.7401771,12.517278 98.7401771,12.517278 C98.7401771,12.517278 95.4041478,12.5132808 93.8764241,12.5132808" id="Fill-3"></path> <path d="M79.9145274,4.78119142 C81.3104474,4.80797288 82.7061678,5.29743418 83.8378816,6.4478381 C83.9676881,6.57974682 84.0128209,6.62491556 84.0128209,6.62491556 L82.4297796,8.55398065 C82.4297796,8.55398065 82.4056156,8.53079669 82.2782055,8.41028009 C81.5460963,7.71875862 80.6893728,7.29844947 79.6672957,7.25927658 C79.3465736,7.24708502 79.0348381,7.28985542 78.7426734,7.42955875 C77.9522511,7.80749721 77.8364237,8.73565493 78.508023,9.29706643 C78.7302919,9.48273795 78.9917024,9.59346132 79.257706,9.69758927 C80.2148798,10.0709309 81.1876304,10.4064987 82.108059,10.8687788 C82.7810562,11.2067449 83.3853558,11.6348487 83.8097235,12.2730071 C84.6007449,13.4627838 84.4693407,15.2551434 83.5161609,16.397353 C82.6826029,17.3958621 81.5768505,17.869934 80.3209218,18.021629 C78.5265954,18.2382791 76.8780517,17.8625391 75.4371986,16.7271248 C75.0687476,16.4367258 74.7520195,16.0947624 74.4624509,15.7258177 C74.3767786,15.6164934 74.3520155,15.5815176 74.3520155,15.5815176 L76.0722523,13.7287997 C76.0722523,13.7287997 76.0936205,13.7541821 76.2066521,13.8900881 C76.8982216,14.7217126 77.7679258,15.2653364 78.8399285,15.4568039 C79.4522162,15.5659284 80.0559167,15.543344 80.6180791,15.2393544 C81.1870313,14.9321669 81.4348621,14.3909415 81.2583251,13.8581102 C81.1618688,13.5669117 80.9551768,13.3630528 80.7083446,13.1945694 C80.3790352,12.9695251 80.007389,12.8316205 79.6419335,12.6829234 C78.8589002,12.3647436 78.0586925,12.0879351 77.2952301,11.7229877 C76.2791441,11.2373238 75.5142837,10.5168224 75.2337018,9.38500558 C74.7859689,7.5800546 75.7193781,5.85684706 77.4945331,5.17212089 C78.214061,4.894513 78.9595503,4.78279031 79.9145274,4.78119142" id="Fill-5"></path> <path d="M29.226173,15.099651 C27.2055837,15.099651 25.5616332,13.4545894 25.5616332,11.4321889 C25.5616332,9.40998829 27.2055837,7.76492667 29.226173,7.76492667 C31.2467623,7.76492667 32.8907128,9.40998829 32.8907128,11.4321889 C32.8907128,13.4545894 31.2467623,15.099651 29.226173,15.099651 L29.226173,15.099651 Z M33.2164275,4.77959252 L32.9166742,6.31493007 C31.9846629,5.35099711 30.5909395,4.79038505 29.226173,4.79038505 C25.5668254,4.79038505 22.5896614,7.76992321 22.5896614,11.4321889 C22.5896614,15.0946545 25.5668254,18.0741927 29.226173,18.0741927 C30.5909395,18.0741927 31.9227551,17.5291698 32.9166742,16.5498475 L33.2164275,18.0801885 L35.8888456,18.0801885 L35.8888456,4.77959252 L33.2164275,4.77959252 Z" id="Fill-7"></path> <path d="M122.063246,15.099651 C120.042656,15.099651 118.398706,13.4545894 118.398706,11.4321889 C118.398706,9.40998829 120.042656,7.76492667 122.063246,7.76492667 C124.083835,7.76492667 125.727586,9.40998829 125.727586,11.4321889 C125.727586,13.4545894 124.083835,15.099651 122.063246,15.099651 L122.063246,15.099651 Z M125.753747,0.340864122 L125.753747,6.31493007 C124.814946,5.45192727 123.428012,4.79038505 122.063246,4.79038505 C118.403898,4.79038505 115.426734,7.76992321 115.426734,11.4321889 C115.426734,15.0946545 118.403898,18.0741927 122.063246,18.0741927 C123.428012,18.0741927 124.733667,17.4464271 125.753747,16.5496476 L126.053301,18.0801885 L128.725918,18.0801885 L128.725918,0.340864122 L125.753747,0.340864122 Z" id="Fill-10"></path> <polygon id="Fill-13" points="39.1462721 18.0801685 42.1184435 18.0801685 42.1184435 5.40513964 39.1462721 5.40513964"></polygon> <path d="M107.336269,4.78948568 C106.235509,4.78948568 104.973989,5.4880023 104.317167,6.33421672 L103.817911,4.77869314 L101.344996,4.77869314 L101.344996,10.6084589 L101.344996,18.0792891 L104.317167,18.0792891 L104.341132,18.0792891 L104.341132,10.6084589 C104.341132,9.04014422 105.68453,7.76402729 107.336269,7.76402729 C108.987608,7.76402729 110.331007,9.04014422 110.331007,10.6084589 L110.331007,18.0792891 L113.327143,18.0792891 L113.327143,10.6084589 C113.327143,7.40007915 110.639547,4.78948568 107.336269,4.78948568" id="Fill-1"></path> <polygon id="Fill-16" points="45.2152293 18.0801685 48.1874008 18.0801685 48.1874008 0.341043998 45.2152293 0.341043998"></polygon> <path d="M42.5730861,1.94215603 C42.5730861,0.869698169 41.7039811,-9.99308479e-05 40.6323778,-9.99308479e-05 C39.5605747,-9.99308479e-05 38.6916694,0.869698169 38.6916694,1.94215603 C38.6916694,3.01481375 39.5605747,3.88441199 40.6323778,3.88441199 C41.7039811,3.88441199 42.5730861,3.01481375 42.5730861,1.94215603" id="Fill-17"></path> <path d="M71.5361911,4.80247669 C70.5452676,4.88142206 69.6440104,5.44683079 68.8649712,5.99744976 L68.5654175,4.77969245 L65.8927997,4.77969245 L65.8927997,10.891663 C65.8658399,11.1263006 65.8504628,11.3595392 65.8504628,11.58958 L65.8504628,17.9963465 L65.8927997,17.9963465 L65.8927997,18.0802884 L68.8649712,18.0802884 L68.8649712,17.9963465 L68.9073081,17.9963465 L68.9073081,11.58958 C68.9073081,10.1767577 70.1129118,7.98487447 71.7782304,7.85236616 C72.1916145,7.81998857 72.5840298,7.87055358 73.1368062,8.02764487 L73.9729603,5.08508112 C73.3640675,4.91180103 72.5363009,4.72333145 71.5361911,4.80247669" id="Fill-18"></path> <path d="M14.4844781,4.78490884 C12.7632428,4.78490884 11.2149497,5.53818757 10.1495372,6.73156176 C9.08392495,5.53818757 7.53563191,4.78490884 5.81439655,4.78490884 C2.60837352,4.78490884 5.9910733e-05,7.39550231 5.9910733e-05,10.6038821 L5.9910733e-05,18.0747123 L2.97223138,18.0747123 L2.97223138,10.6038821 C2.97223138,9.03556739 4.24713177,7.75945046 5.81439655,7.75945046 C7.38166132,7.75945046 8.65656172,9.03556739 8.65656172,10.6038821 L8.65656172,18.0747123 L8.67014149,18.0747123 L10.1495372,18.0747123 L11.6287332,18.0747123 L11.642313,18.0747123 L11.642313,10.6038821 C11.642313,9.03556739 12.9172134,7.75945046 14.4844781,7.75945046 C16.0517429,7.75945046 17.3266433,9.03556739 17.3266433,10.6038821 L17.3266433,18.0747123 L20.2988148,18.0747123 L20.2988148,10.6038821 C20.2988148,7.39550231 17.6905012,4.78490884 14.4844781,4.78490884" id="Fill-19"></path> </g> </g> </g> </g> </svg>
packages/nc-gui/public/plugins/mailersend.svg
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.0013578602811321616, 0.00047513871686533093, 0.00016669582691974938, 0.00018799936515279114, 0.0005097595858387649 ]
{ "id": 1, "code_window": [ " )\n", " paginationData.value.totalRows = count\n", " }\n", "\n", " async function loadMapMeta() {\n", " alert('loadMapData')\n", " if (!viewMeta?.value?.id || !meta?.value?.columns) return\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "packages/nc-gui/composables/useMapViewDataStore.ts", "type": "replace", "edit_start_line_idx": 73 }
import { reactive } from 'vue' import type { ComputedRef, Ref } from 'vue' import type { ColumnType, MapType, PaginatedType, TableType, ViewType } from 'nocodb-sdk' import { IsPublicInj, ref, useInjectionState, useMetas, useProject } from '#imports' import type { Row } from '~/lib' const storedValue = localStorage.getItem('geodataToggleState') const initialState = storedValue ? JSON.parse(storedValue) : false export const geodataToggleState = reactive({ show: initialState }) const formatData = (list: Record<string, any>[]) => list.map( (row) => ({ row: { ...row }, oldRow: { ...row }, rowMeta: {}, } as Row), ) const [useProvideMapViewStore, useMapViewStore] = useInjectionState( ( meta: Ref<TableType | undefined>, viewMeta: Ref<ViewType | MapType | undefined> | ComputedRef<(ViewType & { id: string }) | undefined>, shared = false, where?: ComputedRef<string | undefined>, ) => { if (!meta) { throw new Error('Table meta is not available') } const formattedData = ref<Row[]>([]) // const { api } = useApi() const { project } = useProject() const { $api } = useNuxtApp() const { isUIAllowed } = useUIPermission() const isPublic = ref(shared) || inject(IsPublicInj, ref(false)) const { sorts, nestedFilters } = useSmartsheetStoreOrThrow() const { fetchSharedViewData } = useSharedView() const mapMetaData = ref<MapType>({}) const geoDataFieldColumn = ref<ColumnType | undefined>() const defaultPageSize = 1000 const paginationData = ref<PaginatedType>({ page: 1, pageSize: defaultPageSize }) const queryParams = computed(() => ({ limit: paginationData.value.pageSize ?? defaultPageSize, where: where?.value ?? '', })) async function syncCount() { const { count } = await $api.dbViewRow.count( NOCO, project?.value?.title as string, meta?.value?.id as string, viewMeta?.value?.id as string, ) paginationData.value.totalRows = count } async function loadMapMeta() { alert('loadMapData') if (!viewMeta?.value?.id || !meta?.value?.columns) return // mapMetaData.value = await $api.dbView.mapRead(viewMeta.value.id) geoDataFieldColumn.value = (meta.value.columns as ColumnType[]).filter((f) => f.id === mapMetaData.value.fk_geo_data_col_id)[0] || {} } async function loadMapData() { if ((!project?.value?.id || !meta.value?.id || !viewMeta.value?.id) && !isPublic?.value) return const res = !isPublic.value ? await api.dbViewRow.list('noco', project.value.id!, meta.value!.id!, viewMeta.value!.id!, { ...queryParams.value, ...(isUIAllowed('filterSync') ? {} : { filterArrJson: JSON.stringify(nestedFilters.value) }), where: where?.value, }) : await fetchSharedViewData({ sortsArr: sorts.value, filtersArr: nestedFilters.value }) formattedData.value = formatData(res.list) } async function updateMapMeta(updateObj: Partial<MapType>) { if (!viewMeta?.value?.id || !isUIAllowed('xcDatatableEditable')) return await $api.dbView.mapUpdate(viewMeta.value.id, { ...mapMetaData.value, ...updateObj, }) } const { getMeta } = useMetas() async function insertRow( currentRow: Row, ltarState: Record<string, any> = {}, { metaValue = meta.value, viewMetaValue = viewMeta.value, }: { metaValue?: MapType; viewMetaValue?: ViewType | MapType } = {}, ) { const row = currentRow.row if (currentRow.rowMeta) currentRow.rowMeta.saving = true try { const { missingRequiredColumns, insertObj } = await populateInsertObject({ meta: metaValue!, ltarState, getMeta, row, }) if (missingRequiredColumns.size) return const insertedData = await $api.dbViewRow.create( NOCO, project?.value.id as string, metaValue?.id as string, viewMetaValue?.id as string, insertObj, ) Object.assign(currentRow, { row: { ...insertedData, ...row }, rowMeta: { ...(currentRow.rowMeta || {}), new: undefined }, oldRow: { ...insertedData }, }) syncCount() return insertedData } catch (error: any) { message.error(await extractSdkResponseErrorMsg(error)) } finally { if (currentRow.rowMeta) currentRow.rowMeta.saving = false } } function addEmptyRow(addAfter = formattedData.value.length) { formattedData.value.splice(addAfter, 0, { row: {}, oldRow: {}, rowMeta: { new: true }, }) return formattedData.value[addAfter] } return { formattedData, loadMapData, loadMapMeta, updateMapMeta, mapMetaData, geoDataFieldColumn, addEmptyRow, insertRow, geodataToggleState, syncCount, paginationData, } }, ) export { useProvideMapViewStore } export function useMapViewStoreOrThrow() { const mapViewStore = useMapViewStore() if (mapViewStore == null) throw new Error('Please call `useProvideMapViewStore` on the appropriate parent component') return mapViewStore }
packages/nc-gui/composables/useMapViewDataStore.ts
1
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.9991301894187927, 0.1145704910159111, 0.00016283699369523674, 0.0035194577649235725, 0.3019714653491974 ]
{ "id": 1, "code_window": [ " )\n", " paginationData.value.totalRows = count\n", " }\n", "\n", " async function loadMapMeta() {\n", " alert('loadMapData')\n", " if (!viewMeta?.value?.id || !meta?.value?.columns) return\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "packages/nc-gui/composables/useMapViewDataStore.ts", "type": "replace", "edit_start_line_idx": 73 }
main.container{ max-width:100% !important; } footer a[href="https://nuxtjs.org"]{ display: none; }
packages/noco-docs/assets/main.css
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.00017108552856370807, 0.00017108552856370807, 0.00017108552856370807, 0.00017108552856370807, 0 ]
{ "id": 1, "code_window": [ " )\n", " paginationData.value.totalRows = count\n", " }\n", "\n", " async function loadMapMeta() {\n", " alert('loadMapData')\n", " if (!viewMeta?.value?.id || !meta?.value?.columns) return\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "packages/nc-gui/composables/useMapViewDataStore.ts", "type": "replace", "edit_start_line_idx": 73 }
import type { ColumnType, TableType, ViewType } from 'nocodb-sdk' import type { ComputedRef, InjectionKey, Ref } from 'vue' import type { EventHook } from '@vueuse/core' import type { useViewData } from '#imports' import type { Row, TabItem } from '~/lib' export const ActiveCellInj: InjectionKey<Ref<boolean>> = Symbol('active-cell') export const IsPublicInj: InjectionKey<Ref<boolean>> = Symbol('is-public') export const RowInj: InjectionKey<Ref<Row>> = Symbol('row') export const ColumnInj: InjectionKey<Ref<ColumnType & { meta: any }>> = Symbol('column-injection') export const MetaInj: InjectionKey<ComputedRef<TableType>> = Symbol('meta-injection') export const TabMetaInj: InjectionKey<ComputedRef<TabItem>> = Symbol('tab-meta-injection') export const PaginationDataInj: InjectionKey<ReturnType<typeof useViewData>['paginationData']> = Symbol('pagination-data-injection') export const ChangePageInj: InjectionKey<ReturnType<typeof useViewData>['changePage']> = Symbol('pagination-data-injection') export const IsFormInj: InjectionKey<Ref<boolean>> = Symbol('is-form-injection') export const IsGridInj: InjectionKey<Ref<boolean>> = Symbol('is-grid-injection') export const IsGalleryInj: InjectionKey<Ref<boolean>> = Symbol('is-gallery-injection') export const IsKanbanInj: InjectionKey<Ref<boolean>> = Symbol('is-kanban-injection') export const IsLockedInj: InjectionKey<Ref<boolean>> = Symbol('is-locked-injection') export const CellValueInj: InjectionKey<Ref<any>> = Symbol('cell-value-injection') export const ActiveViewInj: InjectionKey<Ref<ViewType>> = Symbol('active-view-injection') export const ReadonlyInj: InjectionKey<Ref<boolean>> = Symbol('readonly-injection') export const RowHeightInj: InjectionKey<ComputedRef<1 | 2 | 4 | 6 | undefined>> = Symbol('row-height-injection') /** when bool is passed, it indicates if a loading spinner should be visible while reloading */ export const ReloadViewDataHookInj: InjectionKey<EventHook<boolean | void>> = Symbol('reload-view-data-injection') export const ReloadViewMetaHookInj: InjectionKey<EventHook<boolean | void>> = Symbol('reload-view-meta-injection') export const ReloadRowDataHookInj: InjectionKey<EventHook<boolean | void>> = Symbol('reload-row-data-injection') export const OpenNewRecordFormHookInj: InjectionKey<EventHook<void>> = Symbol('open-new-record-form-injection') export const FieldsInj: InjectionKey<Ref<ColumnType[]>> = Symbol('fields-injection') export const EditModeInj: InjectionKey<Ref<boolean>> = Symbol('edit-mode-injection') export const SharedViewPasswordInj: InjectionKey<Ref<string | null>> = Symbol('shared-view-password-injection') export const CellUrlDisableOverlayInj: InjectionKey<Ref<boolean>> = Symbol('cell-url-disable-url') export const DropZoneRef: InjectionKey<Ref<Element | undefined>> = Symbol('drop-zone-ref') export const ToggleDialogInj: InjectionKey<Function> = Symbol('toggle-dialog-injection') export const CellClickHookInj: InjectionKey<EventHook<MouseEvent> | undefined> = Symbol('cell-click-injection') export const SaveRowInj: InjectionKey<(() => void) | undefined> = Symbol('save-row-injection')
packages/nc-gui/context/index.ts
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.004516285844147205, 0.0012749114539474249, 0.00016620763926766813, 0.00020857622439507395, 0.0018715799087658525 ]
{ "id": 1, "code_window": [ " )\n", " paginationData.value.totalRows = count\n", " }\n", "\n", " async function loadMapMeta() {\n", " alert('loadMapData')\n", " if (!viewMeta?.value?.id || !meta?.value?.columns) return\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [], "file_path": "packages/nc-gui/composables/useMapViewDataStore.ts", "type": "replace", "edit_start_line_idx": 73 }
import { XcActionType, XcType } from 'nocodb-sdk'; import OvhCloud from './OvhCloudPlugin'; import type { XcPluginConfig } from 'nc-plugin'; const config: XcPluginConfig = { builder: OvhCloud, title: 'OvhCloud Object Storage', version: '0.0.1', logo: 'plugins/ovhCloud.png', tags: 'Storage', description: 'Upload your files to a space that you can access via HTTPS using the OpenStack Swift API, or the S3 API. ', inputs: { title: 'Configure OvhCloud Object Storage', items: [ { key: 'bucket', label: 'Bucket Name', placeholder: 'Bucket Name', type: XcType.SingleLineText, required: true, }, { key: 'region', label: 'Region', placeholder: 'Region', type: XcType.SingleLineText, required: true, }, { key: 'access_key', label: 'Access Key', placeholder: 'Access Key', type: XcType.SingleLineText, required: true, }, { key: 'access_secret', label: 'Access Secret', placeholder: 'Access Secret', type: XcType.Password, required: true, }, ], actions: [ { label: 'Test', placeholder: 'Test', key: 'test', actionType: XcActionType.TEST, type: XcType.Button, }, { label: 'Save', placeholder: 'Save', key: 'save', actionType: XcActionType.SUBMIT, type: XcType.Button, }, ], msgOnInstall: 'Successfully installed and attachment will be stored in OvhCloud Object Storage', msgOnUninstall: '', }, category: 'Storage', }; export default config;
packages/nocodb/src/lib/plugins/ovhCloud/index.ts
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.00017706833023112267, 0.00017477947403676808, 0.00017086610023397952, 0.00017597948317416012, 0.000002178857812396018 ]
{ "id": 2, "code_window": [ " if (!viewMeta?.value?.id || !meta?.value?.columns) return\n", " // mapMetaData.value = await $api.dbView.mapRead(viewMeta.value.id)\n", " geoDataFieldColumn.value =\n", " (meta.value.columns as ColumnType[]).filter((f) => f.id === mapMetaData.value.fk_geo_data_col_id)[0] || {}\n", " }\n", "\n", " async function loadMapData() {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " mapMetaData.value = await $api.dbView.mapRead(viewMeta.value.id)\n" ], "file_path": "packages/nc-gui/composables/useMapViewDataStore.ts", "type": "replace", "edit_start_line_idx": 75 }
import { reactive } from 'vue' import type { ComputedRef, Ref } from 'vue' import type { ColumnType, MapType, PaginatedType, TableType, ViewType } from 'nocodb-sdk' import { IsPublicInj, ref, useInjectionState, useMetas, useProject } from '#imports' import type { Row } from '~/lib' const storedValue = localStorage.getItem('geodataToggleState') const initialState = storedValue ? JSON.parse(storedValue) : false export const geodataToggleState = reactive({ show: initialState }) const formatData = (list: Record<string, any>[]) => list.map( (row) => ({ row: { ...row }, oldRow: { ...row }, rowMeta: {}, } as Row), ) const [useProvideMapViewStore, useMapViewStore] = useInjectionState( ( meta: Ref<TableType | undefined>, viewMeta: Ref<ViewType | MapType | undefined> | ComputedRef<(ViewType & { id: string }) | undefined>, shared = false, where?: ComputedRef<string | undefined>, ) => { if (!meta) { throw new Error('Table meta is not available') } const formattedData = ref<Row[]>([]) // const { api } = useApi() const { project } = useProject() const { $api } = useNuxtApp() const { isUIAllowed } = useUIPermission() const isPublic = ref(shared) || inject(IsPublicInj, ref(false)) const { sorts, nestedFilters } = useSmartsheetStoreOrThrow() const { fetchSharedViewData } = useSharedView() const mapMetaData = ref<MapType>({}) const geoDataFieldColumn = ref<ColumnType | undefined>() const defaultPageSize = 1000 const paginationData = ref<PaginatedType>({ page: 1, pageSize: defaultPageSize }) const queryParams = computed(() => ({ limit: paginationData.value.pageSize ?? defaultPageSize, where: where?.value ?? '', })) async function syncCount() { const { count } = await $api.dbViewRow.count( NOCO, project?.value?.title as string, meta?.value?.id as string, viewMeta?.value?.id as string, ) paginationData.value.totalRows = count } async function loadMapMeta() { alert('loadMapData') if (!viewMeta?.value?.id || !meta?.value?.columns) return // mapMetaData.value = await $api.dbView.mapRead(viewMeta.value.id) geoDataFieldColumn.value = (meta.value.columns as ColumnType[]).filter((f) => f.id === mapMetaData.value.fk_geo_data_col_id)[0] || {} } async function loadMapData() { if ((!project?.value?.id || !meta.value?.id || !viewMeta.value?.id) && !isPublic?.value) return const res = !isPublic.value ? await api.dbViewRow.list('noco', project.value.id!, meta.value!.id!, viewMeta.value!.id!, { ...queryParams.value, ...(isUIAllowed('filterSync') ? {} : { filterArrJson: JSON.stringify(nestedFilters.value) }), where: where?.value, }) : await fetchSharedViewData({ sortsArr: sorts.value, filtersArr: nestedFilters.value }) formattedData.value = formatData(res.list) } async function updateMapMeta(updateObj: Partial<MapType>) { if (!viewMeta?.value?.id || !isUIAllowed('xcDatatableEditable')) return await $api.dbView.mapUpdate(viewMeta.value.id, { ...mapMetaData.value, ...updateObj, }) } const { getMeta } = useMetas() async function insertRow( currentRow: Row, ltarState: Record<string, any> = {}, { metaValue = meta.value, viewMetaValue = viewMeta.value, }: { metaValue?: MapType; viewMetaValue?: ViewType | MapType } = {}, ) { const row = currentRow.row if (currentRow.rowMeta) currentRow.rowMeta.saving = true try { const { missingRequiredColumns, insertObj } = await populateInsertObject({ meta: metaValue!, ltarState, getMeta, row, }) if (missingRequiredColumns.size) return const insertedData = await $api.dbViewRow.create( NOCO, project?.value.id as string, metaValue?.id as string, viewMetaValue?.id as string, insertObj, ) Object.assign(currentRow, { row: { ...insertedData, ...row }, rowMeta: { ...(currentRow.rowMeta || {}), new: undefined }, oldRow: { ...insertedData }, }) syncCount() return insertedData } catch (error: any) { message.error(await extractSdkResponseErrorMsg(error)) } finally { if (currentRow.rowMeta) currentRow.rowMeta.saving = false } } function addEmptyRow(addAfter = formattedData.value.length) { formattedData.value.splice(addAfter, 0, { row: {}, oldRow: {}, rowMeta: { new: true }, }) return formattedData.value[addAfter] } return { formattedData, loadMapData, loadMapMeta, updateMapMeta, mapMetaData, geoDataFieldColumn, addEmptyRow, insertRow, geodataToggleState, syncCount, paginationData, } }, ) export { useProvideMapViewStore } export function useMapViewStoreOrThrow() { const mapViewStore = useMapViewStore() if (mapViewStore == null) throw new Error('Please call `useProvideMapViewStore` on the appropriate parent component') return mapViewStore }
packages/nc-gui/composables/useMapViewDataStore.ts
1
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.99783855676651, 0.15634021162986755, 0.00016201661492232233, 0.0020251665264368057, 0.3533689081668854 ]
{ "id": 2, "code_window": [ " if (!viewMeta?.value?.id || !meta?.value?.columns) return\n", " // mapMetaData.value = await $api.dbView.mapRead(viewMeta.value.id)\n", " geoDataFieldColumn.value =\n", " (meta.value.columns as ColumnType[]).filter((f) => f.id === mapMetaData.value.fk_geo_data_col_id)[0] || {}\n", " }\n", "\n", " async function loadMapData() {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " mapMetaData.value = await $api.dbView.mapRead(viewMeta.value.id)\n" ], "file_path": "packages/nc-gui/composables/useMapViewDataStore.ts", "type": "replace", "edit_start_line_idx": 75 }
# Contributor Code of Conduct As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of the level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion. Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. This Code of Conduct is adapted from the Contributor Covenant, version 1.0.0, available at http://contributor-covenant.org/version/1/0/0/
.github/CODE_OF_CONDUCT.md
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.0001726232294458896, 0.00017175785615108907, 0.00017089248285628855, 0.00017175785615108907, 8.653732948005199e-7 ]
{ "id": 2, "code_window": [ " if (!viewMeta?.value?.id || !meta?.value?.columns) return\n", " // mapMetaData.value = await $api.dbView.mapRead(viewMeta.value.id)\n", " geoDataFieldColumn.value =\n", " (meta.value.columns as ColumnType[]).filter((f) => f.id === mapMetaData.value.fk_geo_data_col_id)[0] || {}\n", " }\n", "\n", " async function loadMapData() {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " mapMetaData.value = await $api.dbView.mapRead(viewMeta.value.id)\n" ], "file_path": "packages/nc-gui/composables/useMapViewDataStore.ts", "type": "replace", "edit_start_line_idx": 75 }
import type { ColumnType, LinkToAnotherRecordType } from 'nocodb-sdk' import { RelationTypes, UITypes } from 'nocodb-sdk' export const isLTAR = (uidt: string, colOptions: unknown): colOptions is LinkToAnotherRecordType => uidt === UITypes.LinkToAnotherRecord export const isHm = (column: ColumnType) => isLTAR(column.uidt, column.colOptions) && column.colOptions.type === RelationTypes.HAS_MANY export const isMm = (column: ColumnType) => isLTAR(column.uidt, column.colOptions) && column.colOptions.type === RelationTypes.MANY_TO_MANY export const isBt = (column: ColumnType) => isLTAR(column.uidt, column.colOptions) && column.colOptions.type === RelationTypes.BELONGS_TO export const isLookup = (column: ColumnType) => column.uidt === UITypes.Lookup export const isRollup = (column: ColumnType) => column.uidt === UITypes.Rollup export const isFormula = (column: ColumnType) => column.uidt === UITypes.Formula export const isQrCode = (column: ColumnType) => column.uidt === UITypes.QrCode export const isBarcode = (column: ColumnType) => column.uidt === UITypes.Barcode export const isCount = (column: ColumnType) => column.uidt === UITypes.Count
packages/nc-gui/utils/virtualCell.ts
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.0007704659947194159, 0.0003809081099461764, 0.0001670750352786854, 0.0002051832852885127, 0.0002758979971986264 ]
{ "id": 2, "code_window": [ " if (!viewMeta?.value?.id || !meta?.value?.columns) return\n", " // mapMetaData.value = await $api.dbView.mapRead(viewMeta.value.id)\n", " geoDataFieldColumn.value =\n", " (meta.value.columns as ColumnType[]).filter((f) => f.id === mapMetaData.value.fk_geo_data_col_id)[0] || {}\n", " }\n", "\n", " async function loadMapData() {\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " mapMetaData.value = await $api.dbView.mapRead(viewMeta.value.id)\n" ], "file_path": "packages/nc-gui/composables/useMapViewDataStore.ts", "type": "replace", "edit_start_line_idx": 75 }
import { CronJob } from 'cron'; import type { NcConfig } from '../../../interface/config'; import type Noco from '../../Noco'; import type BaseApiBuilder from './BaseApiBuilder'; // import * as tsc from "typescript"; export class XcCron { // @ts-ignore private app: Noco; // @ts-ignore private config: NcConfig; private apiBuilder: BaseApiBuilder<Noco>; private cronJobs: { [key: string]: CronJob }; constructor(config: NcConfig, apiBuilder: BaseApiBuilder<Noco>, app: Noco) { this.app = app; this.config = config; this.apiBuilder = apiBuilder; this.cronJobs = {}; } public async init(): Promise<any> { // const cronJobs = await this.apiBuilder.getDbDriver()('nc_cron').select(); const cronJobs = await this.apiBuilder .getXcMeta() .metaList('', this.apiBuilder.dbAlias, 'nc_cron'); for (const cron of cronJobs) { this.startCronJob(cron); } } public async restartCron(args: any): Promise<any> { // const cron = await this.apiBuilder.getDbDriver()('nc_cron').where('title', args.title).first(); const cron = await this.apiBuilder .getXcMeta() .metaGet('', this.apiBuilder.dbAlias, 'nc_cron', { title: args.title }); if (cron.id in this.cronJobs) { this.cronJobs[cron.id].stop(); } this.startCronJob(cron); } public async removeCron(args: any): Promise<any> { if (args.id in this.cronJobs) { this.cronJobs[args.id].stop(); delete this.cronJobs[args.id]; } } private startCronJob(cron): void { if (!cron.active) { return; } try { const job = new CronJob( cron.pattern, this.generateCronHandlerFromStringBody(cron.cron_handler), null, true, cron.timezone || 'America/Los_Angeles' ); job.start(); this.cronJobs[cron.id] = job; } catch (e) { console.log('Error in cron initialization : ', e.message); } } private generateCronHandlerFromStringBody(fnBody: string): any { // @ts-ignore let handler = () => { console.log('Empty handler'); }; if (fnBody && fnBody.trim()) { try { const js = `((async function(){ ${fnBody} }).bind(this))`; // const js = tsc.transpile(`((async function(){ // ${fnBody} // }).bind(this))`, { // strict: true, // strictPropertyInitialization: true, // strictNullChecks: true, // }); // tslint:disable-next-line:no-eval handler = eval(js); // console.timeEnd('startTrans') } catch (e) { console.log('Error in Cron handler transpilation', e); } // tslint:disable-next-line:no-eval } return handler; } }
packages/nocodb/src/lib/utils/common/XcCron.ts
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.00017899196245707572, 0.0001736940466798842, 0.00016726840112823993, 0.00017384391685482115, 0.0000030433111533056945 ]
{ "id": 3, "code_window": [ " row.rowMeta.commentCount = aggCommentCount.value?.find((c: Record<string, any>) => c.row_id === id)?.count || 0\n", " }\n", " }\n", "\n", " async function loadData(params: Parameters<Api<any>['dbViewRow']['list']>[4] = {}) {\n", " debugger\n", " if ((!project?.value?.id || !meta.value?.id || !viewMeta.value?.id) && !isPublic.value) return\n", " const response = !isPublic.value\n", " ? await api.dbViewRow.list('noco', project.value.id!, meta.value!.id!, viewMeta.value!.id!, {\n", " ...queryParams.value,\n", " ...params,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nc-gui/composables/useViewData.ts", "type": "replace", "edit_start_line_idx": 189 }
import { UITypes, ViewTypes } from 'nocodb-sdk' import type { Api, ColumnType, FormColumnType, FormType, GalleryType, PaginatedType, TableType, ViewType } from 'nocodb-sdk' import type { ComputedRef, Ref } from 'vue' import { IsPublicInj, NOCO, NavigateDir, computed, extractPkFromRow, extractSdkResponseErrorMsg, getHTMLEncodedText, message, populateInsertObject, ref, until, useApi, useGlobal, useI18n, useMetas, useNuxtApp, useProject, useRouter, useSharedView, useSmartsheetStoreOrThrow, useUIPermission, } from '#imports' import type { Row } from '~/lib' const formatData = (list: Row[]) => list.map((row) => ({ row: { ...row }, oldRow: { ...row }, rowMeta: {}, })) export function useViewData( meta: Ref<TableType | undefined> | ComputedRef<TableType | undefined>, viewMeta: Ref<ViewType | undefined> | ComputedRef<(ViewType & { id: string }) | undefined>, where?: ComputedRef<string | undefined>, ) { if (!meta) { throw new Error('Table meta is not available') } const { t } = useI18n() const { api, isLoading, error } = useApi() const router = useRouter() const route = $(router.currentRoute) const { appInfo } = $(useGlobal()) const { getMeta } = useMetas() const appInfoDefaultLimit = appInfo.defaultLimit || 25 const _paginationData = ref<PaginatedType>({ page: 1, pageSize: appInfoDefaultLimit }) const aggCommentCount = ref<{ row_id: string; count: number }[]>([]) const galleryData = ref<GalleryType>() const formColumnData = ref<Record<string, any>[]>() const formViewData = ref<FormType>() const formattedData = ref<Row[]>([]) const isPublic = inject(IsPublicInj, ref(false)) const { project, isSharedBase } = useProject() const { sharedView, fetchSharedViewData, paginationData: sharedPaginationData } = useSharedView() const { $api, $e } = useNuxtApp() const { sorts, nestedFilters } = useSmartsheetStoreOrThrow() const { isUIAllowed } = useUIPermission() const routeQuery = $computed(() => route.query as Record<string, string>) const paginationData = computed({ get: () => (isPublic.value ? sharedPaginationData.value : _paginationData.value), set: (value) => { if (isPublic.value) { sharedPaginationData.value = value } else { _paginationData.value = value } }, }) const selectedAllRecords = computed({ get() { return !!formattedData.value.length && formattedData.value.every((row: Row) => row.rowMeta.selected) }, set(selected: boolean) { formattedData.value.forEach((row: Row) => (row.rowMeta.selected = selected)) }, }) const queryParams = computed(() => ({ offset: ((paginationData.value.page ?? 0) - 1) * (paginationData.value.pageSize ?? appInfoDefaultLimit), limit: paginationData.value.pageSize ?? appInfoDefaultLimit, where: where?.value ?? '', })) function addEmptyRow(addAfter = formattedData.value.length) { formattedData.value.splice(addAfter, 0, { row: {}, oldRow: {}, rowMeta: { new: true }, }) return formattedData.value[addAfter] } function removeLastEmptyRow() { const lastRow = formattedData.value[formattedData.value.length - 1] if (lastRow.rowMeta.new) { formattedData.value.pop() } } async function syncCount() { const { count } = await $api.dbViewRow.count( NOCO, project?.value?.title as string, meta?.value?.id as string, viewMeta?.value?.id as string, ) paginationData.value.totalRows = count } async function syncPagination() { // total records in the current table const count = paginationData.value?.totalRows ?? Infinity // the number of rows in a page const size = paginationData.value.pageSize ?? appInfoDefaultLimit // the current page number const currentPage = paginationData.value.page ?? 1 // the maximum possible page given the current count and the size const mxPage = Math.ceil(count / size) // calculate targetPage where 1 <= targetPage <= mxPage const targetPage = Math.max(1, Math.min(mxPage, currentPage)) // if the current page is greater than targetPage, // then the page should be changed instead of showing an empty page // e.g. deleting all records in the last page N should return N - 1 page if (currentPage > targetPage) { // change to target page and load data of that page changePage?.(targetPage) } else { // the current page is same as target page // reload it to avoid empty row in this page await loadData({ offset: (targetPage - 1) * size, where: where?.value, } as any) } } /** load row comments count */ async function loadAggCommentsCount() { if (isPublic.value || isSharedBase.value) return const ids = formattedData.value ?.filter(({ rowMeta: { new: isNew } }) => !isNew) ?.map(({ row }) => { return extractPkFromRow(row, meta?.value?.columns as ColumnType[]) }) if (!ids?.length || ids?.some((id) => !id)) return aggCommentCount.value = await $api.utils.commentCount({ ids, fk_model_id: meta.value?.id as string, }) for (const row of formattedData.value) { const id = extractPkFromRow(row.row, meta.value?.columns as ColumnType[]) row.rowMeta.commentCount = aggCommentCount.value?.find((c: Record<string, any>) => c.row_id === id)?.count || 0 } } async function loadData(params: Parameters<Api<any>['dbViewRow']['list']>[4] = {}) { debugger if ((!project?.value?.id || !meta.value?.id || !viewMeta.value?.id) && !isPublic.value) return const response = !isPublic.value ? await api.dbViewRow.list('noco', project.value.id!, meta.value!.id!, viewMeta.value!.id!, { ...queryParams.value, ...params, ...(isUIAllowed('sortSync') ? {} : { sortArrJson: JSON.stringify(sorts.value) }), ...(isUIAllowed('filterSync') ? {} : { filterArrJson: JSON.stringify(nestedFilters.value) }), where: where?.value, }) : await fetchSharedViewData({ sortsArr: sorts.value, filtersArr: nestedFilters.value }) formattedData.value = formatData(response.list) paginationData.value = response.pageInfo // to cater the case like when querying with a non-zero offset // the result page may point to the target page where the actual returned data don't display on const expectedPage = Math.max(1, Math.ceil(paginationData.value.totalRows! / paginationData.value.pageSize!)) if (expectedPage < paginationData.value.page!) { await changePage(expectedPage) } if (viewMeta.value?.type === ViewTypes.GRID) { await loadAggCommentsCount() } } async function loadGalleryData() { if (!viewMeta?.value?.id) return galleryData.value = isPublic.value ? (sharedView.value?.view as GalleryType) : await $api.dbView.galleryRead(viewMeta.value.id) // debugger } async function insertRow( currentRow: Row, ltarState: Record<string, any> = {}, { metaValue = meta.value, viewMetaValue = viewMeta.value }: { metaValue?: TableType; viewMetaValue?: ViewType } = {}, ) { const row = currentRow.row if (currentRow.rowMeta) currentRow.rowMeta.saving = true try { const { missingRequiredColumns, insertObj } = await populateInsertObject({ meta: metaValue!, ltarState, getMeta, row, }) if (missingRequiredColumns.size) return const insertedData = await $api.dbViewRow.create( NOCO, project?.value.id as string, metaValue?.id as string, viewMetaValue?.id as string, insertObj, ) Object.assign(currentRow, { row: { ...insertedData, ...row }, rowMeta: { ...(currentRow.rowMeta || {}), new: undefined }, oldRow: { ...insertedData }, }) await syncCount() return insertedData } catch (error: any) { message.error(await extractSdkResponseErrorMsg(error)) } finally { if (currentRow.rowMeta) currentRow.rowMeta.saving = false } } // inside this method use metaValue and viewMetaValue to refer meta // since sometimes we need to pass old metas async function updateRowProperty( toUpdate: Row, property: string, { metaValue = meta.value, viewMetaValue = viewMeta.value }: { metaValue?: TableType; viewMetaValue?: ViewType } = {}, ) { if (toUpdate.rowMeta) toUpdate.rowMeta.saving = true try { const id = extractPkFromRow(toUpdate.row, metaValue?.columns as ColumnType[]) const updatedRowData = await $api.dbViewRow.update( NOCO, project?.value.id as string, metaValue?.id as string, viewMetaValue?.id as string, encodeURIComponent(id), { // if value is undefined treat it as null [property]: toUpdate.row[property] ?? null, }, // todo: // { // query: { ignoreWebhook: !saved } // } ) // audit $api.utils.auditRowUpdate(encodeURIComponent(id), { fk_model_id: metaValue?.id as string, column_name: property, row_id: id, value: getHTMLEncodedText(toUpdate.row[property]), prev_value: getHTMLEncodedText(toUpdate.oldRow[property]), }) /** update row data(to sync formula and other related columns) * update only formula, rollup and auto updated datetime columns data to avoid overwriting any changes made by user */ Object.assign( toUpdate.row, metaValue!.columns!.reduce<Record<string, any>>((acc: Record<string, any>, col: ColumnType) => { if ( col.uidt === UITypes.Formula || col.uidt === UITypes.QrCode || col.uidt === UITypes.Barcode || col.uidt === UITypes.Rollup || col.au || col.cdf?.includes(' on update ') ) acc[col.title!] = updatedRowData[col.title!] return acc }, {} as Record<string, any>), ) Object.assign(toUpdate.oldRow, updatedRowData) } catch (e: any) { message.error(`${t('msg.error.rowUpdateFailed')} ${await extractSdkResponseErrorMsg(e)}`) } finally { if (toUpdate.rowMeta) toUpdate.rowMeta.saving = false } } async function updateOrSaveRow( row: Row, property?: string, ltarState?: Record<string, any>, args: { metaValue?: TableType; viewMetaValue?: ViewType } = {}, ) { // update changed status if (row.rowMeta) row.rowMeta.changed = false // if new row and save is in progress then wait until the save is complete await until(() => !(row.rowMeta?.new && row.rowMeta?.saving)).toMatch((v) => v) if (row.rowMeta.new) { return await insertRow(row, ltarState, args) } else { // if the field name is missing skip update if (property) { await updateRowProperty(row, property, args) } } } async function changePage(page: number) { paginationData.value.page = page await loadData({ offset: (page - 1) * (paginationData.value.pageSize || appInfoDefaultLimit), where: where?.value, } as any) $e('a:grid:pagination') } async function deleteRowById(id: string) { if (!id) { throw new Error("Delete not allowed for table which doesn't have primary Key") } const res: any = await $api.dbViewRow.delete( 'noco', project.value.id as string, meta.value?.id as string, viewMeta.value?.id as string, id, ) if (res.message) { message.info( `Row delete failed: ${`Unable to delete row with ID ${id} because of the following: \n${res.message.join('\n')}.\n Clear the data first & try again`})}`, ) return false } return true } async function deleteRow(rowIndex: number) { try { const row = formattedData.value[rowIndex] if (!row.rowMeta.new) { const id = meta?.value?.columns ?.filter((c) => c.pk) .map((c) => row.row[c.title!]) .join('___') const deleted = await deleteRowById(id as string) if (!deleted) { return } } formattedData.value.splice(rowIndex, 1) await syncCount() } catch (e: any) { message.error(`${t('msg.error.deleteRowFailed')}: ${await extractSdkResponseErrorMsg(e)}`) } } async function deleteSelectedRows() { let row = formattedData.value.length while (row--) { try { const { row: rowObj, rowMeta } = formattedData.value[row] as Record<string, any> if (!rowMeta.selected) { continue } if (!rowMeta.new) { const id = meta?.value?.columns ?.filter((c) => c.pk) .map((c) => rowObj[c.title as string]) .join('___') const successfulDeletion = await deleteRowById(id as string) if (!successfulDeletion) { continue } } formattedData.value.splice(row, 1) } catch (e: any) { return message.error(`${t('msg.error.deleteRowFailed')}: ${await extractSdkResponseErrorMsg(e)}`) } } await syncCount() await syncPagination() } async function loadFormView() { if (!viewMeta?.value?.id) return try { const { columns, ...view } = await $api.dbView.formRead(viewMeta.value.id) const fieldById = (columns || []).reduce( (o: Record<string, any>, f: Record<string, any>) => ({ ...o, [f.fk_column_id]: f, }), {} as Record<string, FormColumnType>, ) let order = 1 formViewData.value = view formColumnData.value = meta?.value?.columns ?.map((c: Record<string, any>) => ({ ...c, fk_column_id: c.id, fk_view_id: viewMeta.value?.id, ...(fieldById[c.id] ? fieldById[c.id] : {}), order: (fieldById[c.id] && fieldById[c.id].order) || order++, id: fieldById[c.id] && fieldById[c.id].id, })) .sort((a: Record<string, any>, b: Record<string, any>) => a.order - b.order) as Record<string, any>[] } catch (e: any) { return message.error(`${t('msg.error.setFormDataFailed')}: ${await extractSdkResponseErrorMsg(e)}`) } } async function updateFormView(view: FormType | undefined) { try { if (!viewMeta?.value?.id || !view) return await $api.dbView.formUpdate(viewMeta.value.id, view) } catch (e: any) { return message.error(`${t('msg.error.formViewUpdateFailed')}: ${await extractSdkResponseErrorMsg(e)}`) } } const removeRowIfNew = (row: Row) => { const index = formattedData.value.indexOf(row) if (index > -1 && row.rowMeta.new) { formattedData.value.splice(index, 1) } } // get current expanded row index function getExpandedRowIndex() { return formattedData.value.findIndex( (row: Row) => routeQuery.rowId === extractPkFromRow(row.row, meta.value?.columns as ColumnType[]), ) } const navigateToSiblingRow = async (dir: NavigateDir) => { const expandedRowIndex = getExpandedRowIndex() // calculate next row index based on direction let siblingRowIndex = expandedRowIndex + (dir === NavigateDir.NEXT ? 1 : -1) // if unsaved row skip it while (formattedData.value[siblingRowIndex]?.rowMeta?.new) { siblingRowIndex = siblingRowIndex + (dir === NavigateDir.NEXT ? 1 : -1) } const currentPage = paginationData?.value?.page || 1 // if next row index is less than 0, go to previous page and point to last element if (siblingRowIndex < 0) { // if first page, do nothing if (currentPage === 1) return message.info(t('msg.info.noMoreRecords')) await changePage(currentPage - 1) siblingRowIndex = formattedData.value.length - 1 // if next row index is greater than total rows in current view // then load next page of formattedData and set next row index to 0 } else if (siblingRowIndex >= formattedData.value.length) { if (paginationData?.value?.isLastPage) return message.info(t('msg.info.noMoreRecords')) await changePage(currentPage + 1) siblingRowIndex = 0 } // extract the row id of the sibling row const rowId = extractPkFromRow(formattedData.value[siblingRowIndex].row, meta.value?.columns as ColumnType[]) if (rowId) { router.push({ query: { ...routeQuery, rowId, }, }) } } return { error, isLoading, loadData, paginationData, queryParams, formattedData, insertRow, updateRowProperty, changePage, addEmptyRow, deleteRow, deleteSelectedRows, updateOrSaveRow, selectedAllRecords, syncCount, syncPagination, galleryData, loadGalleryData, loadFormView, formColumnData, formViewData, updateFormView, aggCommentCount, loadAggCommentsCount, removeLastEmptyRow, removeRowIfNew, navigateToSiblingRow, deleteRowById, getExpandedRowIndex, } }
packages/nc-gui/composables/useViewData.ts
1
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.9985408782958984, 0.14286956191062927, 0.00016103213420137763, 0.0019858076702803373, 0.33357152342796326 ]
{ "id": 3, "code_window": [ " row.rowMeta.commentCount = aggCommentCount.value?.find((c: Record<string, any>) => c.row_id === id)?.count || 0\n", " }\n", " }\n", "\n", " async function loadData(params: Parameters<Api<any>['dbViewRow']['list']>[4] = {}) {\n", " debugger\n", " if ((!project?.value?.id || !meta.value?.id || !viewMeta.value?.id) && !isPublic.value) return\n", " const response = !isPublic.value\n", " ? await api.dbViewRow.list('noco', project.value.id!, meta.value!.id!, viewMeta.value!.id!, {\n", " ...queryParams.value,\n", " ...params,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nc-gui/composables/useViewData.ts", "type": "replace", "edit_start_line_idx": 189 }
declare module 'httpsnippet' { export default new ((): any => {})() }
packages/nc-gui/httpsnippet-shims.d.ts
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.00016937844338826835, 0.00016937844338826835, 0.00016937844338826835, 0.00016937844338826835, 0 ]
{ "id": 3, "code_window": [ " row.rowMeta.commentCount = aggCommentCount.value?.find((c: Record<string, any>) => c.row_id === id)?.count || 0\n", " }\n", " }\n", "\n", " async function loadData(params: Parameters<Api<any>['dbViewRow']['list']>[4] = {}) {\n", " debugger\n", " if ((!project?.value?.id || !meta.value?.id || !viewMeta.value?.id) && !isPublic.value) return\n", " const response = !isPublic.value\n", " ? await api.dbViewRow.list('noco', project.value.id!, meta.value!.id!, viewMeta.value!.id!, {\n", " ...queryParams.value,\n", " ...params,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nc-gui/composables/useViewData.ts", "type": "replace", "edit_start_line_idx": 189 }
import { isClient } from '@vueuse/core' import type { ComputedRef, Ref } from 'vue' function useSelectedCellKeyupListener( selected: Ref<boolean | undefined> | ComputedRef<boolean | undefined>, handler: (e: KeyboardEvent) => void, { immediate = false }: { immediate?: boolean } = {}, ) { if (isClient) { watch( selected, (nextVal: boolean | undefined, _: boolean | undefined, cleanup) => { // bind listener when `selected` is truthy if (nextVal) { document.addEventListener('keydown', handler, true) // if `selected` is falsy then remove the event handler } else { document.removeEventListener('keydown', handler, true) } // cleanup is called whenever the watcher is re-evaluated or stopped cleanup(() => { document.removeEventListener('keydown', handler, true) }) }, { immediate }, ) } } export { useSelectedCellKeyupListener, useSelectedCellKeyupListener as useActiveKeyupListener }
packages/nc-gui/composables/useSelectedCellKeyupListener/index.ts
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.0001741923624649644, 0.00017207450582645833, 0.0001690881617832929, 0.0001725087349768728, 0.0000018577428591015632 ]
{ "id": 3, "code_window": [ " row.rowMeta.commentCount = aggCommentCount.value?.find((c: Record<string, any>) => c.row_id === id)?.count || 0\n", " }\n", " }\n", "\n", " async function loadData(params: Parameters<Api<any>['dbViewRow']['list']>[4] = {}) {\n", " debugger\n", " if ((!project?.value?.id || !meta.value?.id || !viewMeta.value?.id) && !isPublic.value) return\n", " const response = !isPublic.value\n", " ? await api.dbViewRow.list('noco', project.value.id!, meta.value!.id!, viewMeta.value!.id!, {\n", " ...queryParams.value,\n", " ...params,\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nc-gui/composables/useViewData.ts", "type": "replace", "edit_start_line_idx": 189 }
<script setup lang="ts"> import { useQRCode } from '@vueuse/integrations/useQRCode' import { RowHeightInj } from '#imports' const maxNumberOfAllowedCharsForQrValue = 2000 const cellValue = inject(CellValueInj) const qrValue = computed(() => String(cellValue?.value)) const tooManyCharsForQrCode = computed(() => qrValue?.value.length > maxNumberOfAllowedCharsForQrValue) const showQrCode = computed(() => qrValue?.value?.length > 0 && !tooManyCharsForQrCode.value) const rowHeight = inject(RowHeightInj) const qrCode = useQRCode(qrValue, { width: 150, }) const qrCodeLarge = useQRCode(qrValue, { width: 600, }) const modalVisible = ref(false) const showQrModal = (ev: MouseEvent) => { ev.stopPropagation() modalVisible.value = true } const handleModalOkClick = () => (modalVisible.value = false) const { showEditNonEditableFieldWarning, showClearNonEditableFieldWarning } = useShowNotEditableWarning() </script> <template> <a-modal v-model:visible="modalVisible" :class="{ active: modalVisible }" wrap-class-name="nc-qr-code-large" :body-style="{ padding: '0px' }" @ok="handleModalOkClick" > <template #footer> <div class="mr-4" data-testid="nc-qr-code-large-value-label">{{ qrValue }}</div> </template> <img v-if="showQrCode" :src="qrCodeLarge" alt="QR Code" /> </a-modal> <div v-if="tooManyCharsForQrCode" class="text-left text-wrap mt-2 text-[#e65100] text-xs"> {{ $t('labels.qrCodeValueTooLong') }} </div> <img v-if="showQrCode && rowHeight" class="mx-auto" :style="{ height: rowHeight ? `${rowHeight * 1.4}rem` : `1.4rem` }" :src="qrCode" alt="QR Code" @click="showQrModal" /> <img v-else-if="showQrCode" class="mx-auto" :src="qrCode" alt="QR Code" @click="showQrModal" /> <div v-if="showEditNonEditableFieldWarning" class="text-left text-wrap mt-2 text-[#e65100] text-xs"> {{ $t('msg.warning.nonEditableFields.computedFieldUnableToClear') }} </div> <div v-if="showClearNonEditableFieldWarning" class="text-left text-wrap mt-2 text-[#e65100] text-xs"> {{ $t('msg.warning.nonEditableFields.qrFieldsCannotBeDirectlyChanged') }} </div> </template>
packages/nc-gui/components/virtual-cell/QrCode.vue
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.00017487334844190627, 0.00017123657744377851, 0.00016645918367430568, 0.00017218152061104774, 0.0000028640934033319354 ]
{ "id": 4, "code_window": [ " galleryData.value = isPublic.value\n", " ? (sharedView.value?.view as GalleryType)\n", " : await $api.dbView.galleryRead(viewMeta.value.id)\n", " // debugger\n", " }\n", "\n", " async function insertRow(\n", " currentRow: Row,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nc-gui/composables/useViewData.ts", "type": "replace", "edit_start_line_idx": 220 }
import { UITypes, ViewTypes } from 'nocodb-sdk' import type { Api, ColumnType, FormColumnType, FormType, GalleryType, PaginatedType, TableType, ViewType } from 'nocodb-sdk' import type { ComputedRef, Ref } from 'vue' import { IsPublicInj, NOCO, NavigateDir, computed, extractPkFromRow, extractSdkResponseErrorMsg, getHTMLEncodedText, message, populateInsertObject, ref, until, useApi, useGlobal, useI18n, useMetas, useNuxtApp, useProject, useRouter, useSharedView, useSmartsheetStoreOrThrow, useUIPermission, } from '#imports' import type { Row } from '~/lib' const formatData = (list: Row[]) => list.map((row) => ({ row: { ...row }, oldRow: { ...row }, rowMeta: {}, })) export function useViewData( meta: Ref<TableType | undefined> | ComputedRef<TableType | undefined>, viewMeta: Ref<ViewType | undefined> | ComputedRef<(ViewType & { id: string }) | undefined>, where?: ComputedRef<string | undefined>, ) { if (!meta) { throw new Error('Table meta is not available') } const { t } = useI18n() const { api, isLoading, error } = useApi() const router = useRouter() const route = $(router.currentRoute) const { appInfo } = $(useGlobal()) const { getMeta } = useMetas() const appInfoDefaultLimit = appInfo.defaultLimit || 25 const _paginationData = ref<PaginatedType>({ page: 1, pageSize: appInfoDefaultLimit }) const aggCommentCount = ref<{ row_id: string; count: number }[]>([]) const galleryData = ref<GalleryType>() const formColumnData = ref<Record<string, any>[]>() const formViewData = ref<FormType>() const formattedData = ref<Row[]>([]) const isPublic = inject(IsPublicInj, ref(false)) const { project, isSharedBase } = useProject() const { sharedView, fetchSharedViewData, paginationData: sharedPaginationData } = useSharedView() const { $api, $e } = useNuxtApp() const { sorts, nestedFilters } = useSmartsheetStoreOrThrow() const { isUIAllowed } = useUIPermission() const routeQuery = $computed(() => route.query as Record<string, string>) const paginationData = computed({ get: () => (isPublic.value ? sharedPaginationData.value : _paginationData.value), set: (value) => { if (isPublic.value) { sharedPaginationData.value = value } else { _paginationData.value = value } }, }) const selectedAllRecords = computed({ get() { return !!formattedData.value.length && formattedData.value.every((row: Row) => row.rowMeta.selected) }, set(selected: boolean) { formattedData.value.forEach((row: Row) => (row.rowMeta.selected = selected)) }, }) const queryParams = computed(() => ({ offset: ((paginationData.value.page ?? 0) - 1) * (paginationData.value.pageSize ?? appInfoDefaultLimit), limit: paginationData.value.pageSize ?? appInfoDefaultLimit, where: where?.value ?? '', })) function addEmptyRow(addAfter = formattedData.value.length) { formattedData.value.splice(addAfter, 0, { row: {}, oldRow: {}, rowMeta: { new: true }, }) return formattedData.value[addAfter] } function removeLastEmptyRow() { const lastRow = formattedData.value[formattedData.value.length - 1] if (lastRow.rowMeta.new) { formattedData.value.pop() } } async function syncCount() { const { count } = await $api.dbViewRow.count( NOCO, project?.value?.title as string, meta?.value?.id as string, viewMeta?.value?.id as string, ) paginationData.value.totalRows = count } async function syncPagination() { // total records in the current table const count = paginationData.value?.totalRows ?? Infinity // the number of rows in a page const size = paginationData.value.pageSize ?? appInfoDefaultLimit // the current page number const currentPage = paginationData.value.page ?? 1 // the maximum possible page given the current count and the size const mxPage = Math.ceil(count / size) // calculate targetPage where 1 <= targetPage <= mxPage const targetPage = Math.max(1, Math.min(mxPage, currentPage)) // if the current page is greater than targetPage, // then the page should be changed instead of showing an empty page // e.g. deleting all records in the last page N should return N - 1 page if (currentPage > targetPage) { // change to target page and load data of that page changePage?.(targetPage) } else { // the current page is same as target page // reload it to avoid empty row in this page await loadData({ offset: (targetPage - 1) * size, where: where?.value, } as any) } } /** load row comments count */ async function loadAggCommentsCount() { if (isPublic.value || isSharedBase.value) return const ids = formattedData.value ?.filter(({ rowMeta: { new: isNew } }) => !isNew) ?.map(({ row }) => { return extractPkFromRow(row, meta?.value?.columns as ColumnType[]) }) if (!ids?.length || ids?.some((id) => !id)) return aggCommentCount.value = await $api.utils.commentCount({ ids, fk_model_id: meta.value?.id as string, }) for (const row of formattedData.value) { const id = extractPkFromRow(row.row, meta.value?.columns as ColumnType[]) row.rowMeta.commentCount = aggCommentCount.value?.find((c: Record<string, any>) => c.row_id === id)?.count || 0 } } async function loadData(params: Parameters<Api<any>['dbViewRow']['list']>[4] = {}) { debugger if ((!project?.value?.id || !meta.value?.id || !viewMeta.value?.id) && !isPublic.value) return const response = !isPublic.value ? await api.dbViewRow.list('noco', project.value.id!, meta.value!.id!, viewMeta.value!.id!, { ...queryParams.value, ...params, ...(isUIAllowed('sortSync') ? {} : { sortArrJson: JSON.stringify(sorts.value) }), ...(isUIAllowed('filterSync') ? {} : { filterArrJson: JSON.stringify(nestedFilters.value) }), where: where?.value, }) : await fetchSharedViewData({ sortsArr: sorts.value, filtersArr: nestedFilters.value }) formattedData.value = formatData(response.list) paginationData.value = response.pageInfo // to cater the case like when querying with a non-zero offset // the result page may point to the target page where the actual returned data don't display on const expectedPage = Math.max(1, Math.ceil(paginationData.value.totalRows! / paginationData.value.pageSize!)) if (expectedPage < paginationData.value.page!) { await changePage(expectedPage) } if (viewMeta.value?.type === ViewTypes.GRID) { await loadAggCommentsCount() } } async function loadGalleryData() { if (!viewMeta?.value?.id) return galleryData.value = isPublic.value ? (sharedView.value?.view as GalleryType) : await $api.dbView.galleryRead(viewMeta.value.id) // debugger } async function insertRow( currentRow: Row, ltarState: Record<string, any> = {}, { metaValue = meta.value, viewMetaValue = viewMeta.value }: { metaValue?: TableType; viewMetaValue?: ViewType } = {}, ) { const row = currentRow.row if (currentRow.rowMeta) currentRow.rowMeta.saving = true try { const { missingRequiredColumns, insertObj } = await populateInsertObject({ meta: metaValue!, ltarState, getMeta, row, }) if (missingRequiredColumns.size) return const insertedData = await $api.dbViewRow.create( NOCO, project?.value.id as string, metaValue?.id as string, viewMetaValue?.id as string, insertObj, ) Object.assign(currentRow, { row: { ...insertedData, ...row }, rowMeta: { ...(currentRow.rowMeta || {}), new: undefined }, oldRow: { ...insertedData }, }) await syncCount() return insertedData } catch (error: any) { message.error(await extractSdkResponseErrorMsg(error)) } finally { if (currentRow.rowMeta) currentRow.rowMeta.saving = false } } // inside this method use metaValue and viewMetaValue to refer meta // since sometimes we need to pass old metas async function updateRowProperty( toUpdate: Row, property: string, { metaValue = meta.value, viewMetaValue = viewMeta.value }: { metaValue?: TableType; viewMetaValue?: ViewType } = {}, ) { if (toUpdate.rowMeta) toUpdate.rowMeta.saving = true try { const id = extractPkFromRow(toUpdate.row, metaValue?.columns as ColumnType[]) const updatedRowData = await $api.dbViewRow.update( NOCO, project?.value.id as string, metaValue?.id as string, viewMetaValue?.id as string, encodeURIComponent(id), { // if value is undefined treat it as null [property]: toUpdate.row[property] ?? null, }, // todo: // { // query: { ignoreWebhook: !saved } // } ) // audit $api.utils.auditRowUpdate(encodeURIComponent(id), { fk_model_id: metaValue?.id as string, column_name: property, row_id: id, value: getHTMLEncodedText(toUpdate.row[property]), prev_value: getHTMLEncodedText(toUpdate.oldRow[property]), }) /** update row data(to sync formula and other related columns) * update only formula, rollup and auto updated datetime columns data to avoid overwriting any changes made by user */ Object.assign( toUpdate.row, metaValue!.columns!.reduce<Record<string, any>>((acc: Record<string, any>, col: ColumnType) => { if ( col.uidt === UITypes.Formula || col.uidt === UITypes.QrCode || col.uidt === UITypes.Barcode || col.uidt === UITypes.Rollup || col.au || col.cdf?.includes(' on update ') ) acc[col.title!] = updatedRowData[col.title!] return acc }, {} as Record<string, any>), ) Object.assign(toUpdate.oldRow, updatedRowData) } catch (e: any) { message.error(`${t('msg.error.rowUpdateFailed')} ${await extractSdkResponseErrorMsg(e)}`) } finally { if (toUpdate.rowMeta) toUpdate.rowMeta.saving = false } } async function updateOrSaveRow( row: Row, property?: string, ltarState?: Record<string, any>, args: { metaValue?: TableType; viewMetaValue?: ViewType } = {}, ) { // update changed status if (row.rowMeta) row.rowMeta.changed = false // if new row and save is in progress then wait until the save is complete await until(() => !(row.rowMeta?.new && row.rowMeta?.saving)).toMatch((v) => v) if (row.rowMeta.new) { return await insertRow(row, ltarState, args) } else { // if the field name is missing skip update if (property) { await updateRowProperty(row, property, args) } } } async function changePage(page: number) { paginationData.value.page = page await loadData({ offset: (page - 1) * (paginationData.value.pageSize || appInfoDefaultLimit), where: where?.value, } as any) $e('a:grid:pagination') } async function deleteRowById(id: string) { if (!id) { throw new Error("Delete not allowed for table which doesn't have primary Key") } const res: any = await $api.dbViewRow.delete( 'noco', project.value.id as string, meta.value?.id as string, viewMeta.value?.id as string, id, ) if (res.message) { message.info( `Row delete failed: ${`Unable to delete row with ID ${id} because of the following: \n${res.message.join('\n')}.\n Clear the data first & try again`})}`, ) return false } return true } async function deleteRow(rowIndex: number) { try { const row = formattedData.value[rowIndex] if (!row.rowMeta.new) { const id = meta?.value?.columns ?.filter((c) => c.pk) .map((c) => row.row[c.title!]) .join('___') const deleted = await deleteRowById(id as string) if (!deleted) { return } } formattedData.value.splice(rowIndex, 1) await syncCount() } catch (e: any) { message.error(`${t('msg.error.deleteRowFailed')}: ${await extractSdkResponseErrorMsg(e)}`) } } async function deleteSelectedRows() { let row = formattedData.value.length while (row--) { try { const { row: rowObj, rowMeta } = formattedData.value[row] as Record<string, any> if (!rowMeta.selected) { continue } if (!rowMeta.new) { const id = meta?.value?.columns ?.filter((c) => c.pk) .map((c) => rowObj[c.title as string]) .join('___') const successfulDeletion = await deleteRowById(id as string) if (!successfulDeletion) { continue } } formattedData.value.splice(row, 1) } catch (e: any) { return message.error(`${t('msg.error.deleteRowFailed')}: ${await extractSdkResponseErrorMsg(e)}`) } } await syncCount() await syncPagination() } async function loadFormView() { if (!viewMeta?.value?.id) return try { const { columns, ...view } = await $api.dbView.formRead(viewMeta.value.id) const fieldById = (columns || []).reduce( (o: Record<string, any>, f: Record<string, any>) => ({ ...o, [f.fk_column_id]: f, }), {} as Record<string, FormColumnType>, ) let order = 1 formViewData.value = view formColumnData.value = meta?.value?.columns ?.map((c: Record<string, any>) => ({ ...c, fk_column_id: c.id, fk_view_id: viewMeta.value?.id, ...(fieldById[c.id] ? fieldById[c.id] : {}), order: (fieldById[c.id] && fieldById[c.id].order) || order++, id: fieldById[c.id] && fieldById[c.id].id, })) .sort((a: Record<string, any>, b: Record<string, any>) => a.order - b.order) as Record<string, any>[] } catch (e: any) { return message.error(`${t('msg.error.setFormDataFailed')}: ${await extractSdkResponseErrorMsg(e)}`) } } async function updateFormView(view: FormType | undefined) { try { if (!viewMeta?.value?.id || !view) return await $api.dbView.formUpdate(viewMeta.value.id, view) } catch (e: any) { return message.error(`${t('msg.error.formViewUpdateFailed')}: ${await extractSdkResponseErrorMsg(e)}`) } } const removeRowIfNew = (row: Row) => { const index = formattedData.value.indexOf(row) if (index > -1 && row.rowMeta.new) { formattedData.value.splice(index, 1) } } // get current expanded row index function getExpandedRowIndex() { return formattedData.value.findIndex( (row: Row) => routeQuery.rowId === extractPkFromRow(row.row, meta.value?.columns as ColumnType[]), ) } const navigateToSiblingRow = async (dir: NavigateDir) => { const expandedRowIndex = getExpandedRowIndex() // calculate next row index based on direction let siblingRowIndex = expandedRowIndex + (dir === NavigateDir.NEXT ? 1 : -1) // if unsaved row skip it while (formattedData.value[siblingRowIndex]?.rowMeta?.new) { siblingRowIndex = siblingRowIndex + (dir === NavigateDir.NEXT ? 1 : -1) } const currentPage = paginationData?.value?.page || 1 // if next row index is less than 0, go to previous page and point to last element if (siblingRowIndex < 0) { // if first page, do nothing if (currentPage === 1) return message.info(t('msg.info.noMoreRecords')) await changePage(currentPage - 1) siblingRowIndex = formattedData.value.length - 1 // if next row index is greater than total rows in current view // then load next page of formattedData and set next row index to 0 } else if (siblingRowIndex >= formattedData.value.length) { if (paginationData?.value?.isLastPage) return message.info(t('msg.info.noMoreRecords')) await changePage(currentPage + 1) siblingRowIndex = 0 } // extract the row id of the sibling row const rowId = extractPkFromRow(formattedData.value[siblingRowIndex].row, meta.value?.columns as ColumnType[]) if (rowId) { router.push({ query: { ...routeQuery, rowId, }, }) } } return { error, isLoading, loadData, paginationData, queryParams, formattedData, insertRow, updateRowProperty, changePage, addEmptyRow, deleteRow, deleteSelectedRows, updateOrSaveRow, selectedAllRecords, syncCount, syncPagination, galleryData, loadGalleryData, loadFormView, formColumnData, formViewData, updateFormView, aggCommentCount, loadAggCommentsCount, removeLastEmptyRow, removeRowIfNew, navigateToSiblingRow, deleteRowById, getExpandedRowIndex, } }
packages/nc-gui/composables/useViewData.ts
1
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.9989025592803955, 0.0906333401799202, 0.00016655698709655553, 0.0006548045785166323, 0.28091058135032654 ]
{ "id": 4, "code_window": [ " galleryData.value = isPublic.value\n", " ? (sharedView.value?.view as GalleryType)\n", " : await $api.dbView.galleryRead(viewMeta.value.id)\n", " // debugger\n", " }\n", "\n", " async function insertRow(\n", " currentRow: Row,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nc-gui/composables/useViewData.ts", "type": "replace", "edit_start_line_idx": 220 }
import { NcError } from '../meta/helpers/catchError'; import { extractProps } from '../meta/helpers/extractProps'; import Noco from '../Noco'; import { MetaTable } from '../utils/globals'; import type { SortType } from 'nocodb-sdk'; // Store is used for storing key value pairs export default class Store { key?: string; value?: string; type?: string; env?: string; tag?: string; project_id?: string; db_alias?: string; constructor(data: Partial<SortType>) { Object.assign(this, data); } public static get(key: string, ncMeta = Noco.ncMeta): Promise<Store> { return ncMeta.metaGet(null, null, MetaTable.STORE, { key }); } static async saveOrUpdate(store: Store, ncMeta = Noco.ncMeta) { if (!store.key) { NcError.badRequest('Key is required'); } const insertObj = extractProps(store, [ 'key', 'value', 'type', 'env', 'tag', ]); const existing = await Store.get(store.key, ncMeta); if (existing) { await ncMeta.metaUpdate(null, null, MetaTable.STORE, insertObj, { key: store.key, }); } else { await ncMeta.metaInsert(null, null, MetaTable.STORE, insertObj); } } }
packages/nocodb/src/lib/models/Store.ts
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.00017390192078892142, 0.00017094444774556905, 0.00016695258091203868, 0.00017147601465694606, 0.000002665802412593621 ]
{ "id": 4, "code_window": [ " galleryData.value = isPublic.value\n", " ? (sharedView.value?.view as GalleryType)\n", " : await $api.dbView.galleryRead(viewMeta.value.id)\n", " // debugger\n", " }\n", "\n", " async function insertRow(\n", " currentRow: Row,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nc-gui/composables/useViewData.ts", "type": "replace", "edit_start_line_idx": 220 }
const mimeIcons = { pdf: 'mdi-pdf-box', docx: 'mdi-file-word-outline', dotx: 'mdi-file-word-outline', odt: 'mdi-file-word-outline', odm: 'mdi-file-word-outline', ott: 'mdi-file-word-outline', ppt: 'mdi-file-powerpoint-box', pptx: 'mdi-file-powerpoint-box', sldx: 'mdi-file-powerpoint-box', ppsx: 'mdi-file-powerpoint-box', potx: 'mdi-file-powerpoint-box', xls: 'mdi-file-excel-outline', xlam: 'mdi-file-excel-outline', xlsb: 'mdi-file-excel-outline', xltm: 'mdi-file-excel-outline', xlsm: 'mdi-file-excel-outline', } export { mimeIcons }
packages/nc-gui/utils/mimeTypeUtils.ts
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.00017695118731353432, 0.00017180811846628785, 0.0001646501332288608, 0.0001738230203045532, 0.000005220080765866442 ]
{ "id": 4, "code_window": [ " galleryData.value = isPublic.value\n", " ? (sharedView.value?.view as GalleryType)\n", " : await $api.dbView.galleryRead(viewMeta.value.id)\n", " // debugger\n", " }\n", "\n", " async function insertRow(\n", " currentRow: Row,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nc-gui/composables/useViewData.ts", "type": "replace", "edit_start_line_idx": 220 }
import type { SortType, ViewType } from 'nocodb-sdk' import type { Ref } from 'vue' import { IsPublicInj, ReloadViewDataHookInj, extractSdkResponseErrorMsg, inject, message, ref, useNuxtApp, useProject, useSharedView, useSmartsheetStoreOrThrow, useUIPermission, } from '#imports' import type { TabItem } from '~/lib' export function useViewSorts(view: Ref<ViewType | undefined>, reloadData?: () => void) { const { sharedView } = useSharedView() const { sorts } = useSmartsheetStoreOrThrow() const { $api, $e } = useNuxtApp() const { isUIAllowed } = useUIPermission() const { isSharedBase } = useProject() const reloadHook = inject(ReloadViewDataHookInj) const isPublic = inject(IsPublicInj, ref(false)) const tabMeta = inject(TabMetaInj, ref({ sortsState: new Map() } as TabItem)) const loadSorts = async () => { if (isPublic.value) { // todo: sorts missing on `ViewType` const sharedSorts = (sharedView.value as any)?.sorts || [] sorts.value = [...sharedSorts] return } try { if (!isUIAllowed('sortSync')) { const sortsBackup = tabMeta.value.sortsState!.get(view.value!.id!) if (sortsBackup) { sorts.value = sortsBackup return } } if (!view?.value) return sorts.value = (await $api.dbTableSort.list(view.value!.id!)).sorts?.list || [] } catch (e: any) { console.error(e) message.error(await extractSdkResponseErrorMsg(e)) } } const saveOrUpdate = async (sort: SortType, i: number) => { if (isPublic.value || isSharedBase.value) { sorts.value[i] = sort sorts.value = [...sorts.value] reloadHook?.trigger() tabMeta.value.sortsState!.set(view.value!.id!, sorts.value) return } try { if (isUIAllowed('sortSync')) { if (sort.id) { await $api.dbTableSort.update(sort.id, sort) $e('sort-updated') } else { sorts.value[i] = (await $api.dbTableSort.create(view.value?.id as string, sort)) as unknown as SortType } } reloadData?.() $e('a:sort:dir', { direction: sort.direction }) } catch (e: any) { console.error(e) message.error(await extractSdkResponseErrorMsg(e)) } } const addSort = () => { sorts.value = [ ...sorts.value, { direction: 'asc', }, ] $e('a:sort:add', { length: sorts?.value?.length }) tabMeta.value.sortsState!.set(view.value!.id!, sorts.value) } const deleteSort = async (sort: SortType, i: number) => { try { if (isUIAllowed('sortSync') && sort.id && !isPublic.value && !isSharedBase.value) { await $api.dbTableSort.delete(sort.id) } sorts.value.splice(i, 1) sorts.value = [...sorts.value] tabMeta.value.sortsState!.set(view.value!.id!, sorts.value) reloadHook?.trigger() $e('a:sort:delete') } catch (e: any) { console.error(e) message.error(await extractSdkResponseErrorMsg(e)) } } return { sorts, loadSorts, addSort, deleteSort, saveOrUpdate } }
packages/nc-gui/composables/useViewSorts.ts
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.0037817370612174273, 0.0008465870632790029, 0.00016461435006931424, 0.00019711186178028584, 0.001159004052169621 ]
{ "id": 5, "code_window": [ "import { publicMetaService } from '../../services';\n", "import type { Request, Response } from 'express';\n", "\n", "export async function viewMetaGet(req: Request, res: Response) {\n", " console.log('FOO viewMetaGet');\n", " res.json(\n", " await publicMetaService.viewMetaGet({\n", " password: req.headers?.['xc-password'] as string,\n", " sharedViewUuid: req.params.sharedViewUuid,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nocodb/src/lib/controllers/publicControllers/publicMeta.ctl.ts", "type": "replace", "edit_start_line_idx": 6 }
import { Router } from 'express'; import catchError from '../../meta/helpers/catchError'; import { publicMetaService } from '../../services'; import type { Request, Response } from 'express'; export async function viewMetaGet(req: Request, res: Response) { console.log('FOO viewMetaGet'); res.json( await publicMetaService.viewMetaGet({ password: req.headers?.['xc-password'] as string, sharedViewUuid: req.params.sharedViewUuid, }) ); } async function publicSharedBaseGet(req, res): Promise<any> { res.json( await publicMetaService.publicSharedBaseGet({ sharedBaseUuid: req.params.sharedBaseUuid, }) ); } const router = Router({ mergeParams: true }); router.get( '/api/v1/db/public/shared-view/:sharedViewUuid/meta', catchError(viewMetaGet) ); router.get( '/api/v1/db/public/shared-base/:sharedBaseUuid/meta', catchError(publicSharedBaseGet) ); export default router;
packages/nocodb/src/lib/controllers/publicControllers/publicMeta.ctl.ts
1
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.9985566735267639, 0.5025601387023926, 0.00017014781769830734, 0.5057567954063416, 0.4943790137767792 ]
{ "id": 5, "code_window": [ "import { publicMetaService } from '../../services';\n", "import type { Request, Response } from 'express';\n", "\n", "export async function viewMetaGet(req: Request, res: Response) {\n", " console.log('FOO viewMetaGet');\n", " res.json(\n", " await publicMetaService.viewMetaGet({\n", " password: req.headers?.['xc-password'] as string,\n", " sharedViewUuid: req.params.sharedViewUuid,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nocodb/src/lib/controllers/publicControllers/publicMeta.ctl.ts", "type": "replace", "edit_start_line_idx": 6 }
# Reverse proxy domain and cloudflare token DOMAINNAME=example.com CF_DNS_API_TOKEN=SOME_CLOUDFLARE_TOKEN # Database DATABASE_NAME=xcdb DATABASE_USER=nocodb DATABASE_PW=SECURE_PW
docker-compose/traefik/.env
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.00016987773415166885, 0.00016987773415166885, 0.00016987773415166885, 0.00016987773415166885, 0 ]
{ "id": 5, "code_window": [ "import { publicMetaService } from '../../services';\n", "import type { Request, Response } from 'express';\n", "\n", "export async function viewMetaGet(req: Request, res: Response) {\n", " console.log('FOO viewMetaGet');\n", " res.json(\n", " await publicMetaService.viewMetaGet({\n", " password: req.headers?.['xc-password'] as string,\n", " sharedViewUuid: req.params.sharedViewUuid,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nocodb/src/lib/controllers/publicControllers/publicMeta.ctl.ts", "type": "replace", "edit_start_line_idx": 6 }
import { UITypes } from 'nocodb-sdk'; import { MetaTable } from '../utils/globals'; import Base from '../models/Base'; import Model from '../models/Model'; import NcConnectionMgrv2 from '../utils/common/NcConnectionMgrv2'; import { throwTimeoutError } from './ncUpgradeErrors'; import type { Knex } from 'knex'; import type { NcUpgraderCtx } from './NcUpgrader'; import type { XKnex } from '../db/sql-data-mapper/index'; import type { BaseType } from 'nocodb-sdk'; // before 0.103.0, an attachment object was like // [{ // "url": "http://localhost:8080/download/noco/xcdb/Sheet-1/title5/39A410.jpeg", // "title": "foo.jpeg", // "mimetype": "image/jpeg", // "size": 6494 // }] // in this way, if the base url is changed, the url will be broken // this upgrader is to convert the existing local attachment object to the following format // [{ // "url": "http://localhost:8080/download/noco/xcdb/Sheet-1/title5/39A410.jpeg", // "path": "download/noco/xcdb/Sheet-1/title5/39A410.jpeg", // "title": "foo.jpeg", // "mimetype": "image/jpeg", // "size": 6494 // }] // the new url will be constructed by `${ncSiteUrl}/${path}` in UI. the old url will be used for fallback // while other non-local attachments will remain unchanged function getTnPath(knex: XKnex, tb: Model) { const schema = (knex as any).searchPath?.(); const clientType = knex.clientType(); if (clientType === 'mssql' && schema) { return knex.raw('??.??', [schema, tb.table_name]).toQuery(); } else if (clientType === 'snowflake') { return [ knex.client.config.connection.database, knex.client.config.connection.schema, tb.table_name, ].join('.'); } else { return tb.table_name; } } export default async function ({ ncMeta }: NcUpgraderCtx) { const bases: BaseType[] = await ncMeta.metaList2(null, null, MetaTable.BASES); for (const _base of bases) { const base = new Base(_base); // skip if the project_id is missing if (!base.project_id) { continue; } const project = await ncMeta.metaGet2(null, null, MetaTable.PROJECT, { id: base.project_id, }); // skip if the project is missing if (!project) { continue; } const isProjectDeleted = project.deleted; const knex: Knex = base.is_meta ? ncMeta.knexConnection : await NcConnectionMgrv2.get(base); const models = await base.getModels(ncMeta); // used in timeout error message const timeoutErrorInfo = { projectTitle: project.title, connection: knex.client.config.connection, }; for (const model of models) { try { // if the table is missing in database, skip if (!(await knex.schema.hasTable(getTnPath(knex, model)))) { continue; } const updateRecords = []; // get all attachment & primary key columns // and filter out the columns that are missing in database const columns = await (await Model.get(model.id, ncMeta)) .getColumns(ncMeta) .then(async (columns) => { const filteredColumns = []; for (const column of columns) { if (column.uidt !== UITypes.Attachment && !column.pk) continue; if ( !(await knex.schema.hasColumn( getTnPath(knex, model), column.column_name )) ) continue; filteredColumns.push(column); } return filteredColumns; }); const attachmentColumns = columns .filter((c) => c.uidt === UITypes.Attachment) .map((c) => c.column_name); if (attachmentColumns.length === 0) { continue; } const primaryKeys = columns .filter((c) => c.pk) .map((c) => c.column_name); const records = await knex(getTnPath(knex, model)).select(); for (const record of records) { for (const attachmentColumn of attachmentColumns) { let attachmentMeta: Array<{ url: string; }>; // if parsing failed ignore the cell try { attachmentMeta = typeof record[attachmentColumn] === 'string' ? JSON.parse(record[attachmentColumn]) : record[attachmentColumn]; } catch {} // if cell data is not an array, ignore it if (!Array.isArray(attachmentMeta)) { continue; } if (attachmentMeta) { const newAttachmentMeta = []; for (const attachment of attachmentMeta) { if ('url' in attachment && typeof attachment.url === 'string') { const match = attachment.url.match(/^(.*)\/download\/(.*)$/); if (match) { // e.g. http://localhost:8080/download/noco/xcdb/Sheet-1/title5/ee2G8p_nute_gunray.png // match[1] = http://localhost:8080 // match[2] = download/noco/xcdb/Sheet-1/title5/ee2G8p_nute_gunray.png const path = `download/${match[2]}`; newAttachmentMeta.push({ ...attachment, path, }); } else { // keep it as it is newAttachmentMeta.push(attachment); } } } const where = primaryKeys .map((key) => { return { [key]: record[key] }; }) .reduce((acc, val) => Object.assign(acc, val), {}); updateRecords.push( await knex(getTnPath(knex, model)) .update({ [attachmentColumn]: JSON.stringify(newAttachmentMeta), }) .where(where) ); } } } await Promise.all(updateRecords); } catch (e) { // ignore the error related to deleted project if (!isProjectDeleted) { // throw the custom timeout error message if applicable throwTimeoutError(e, timeoutErrorInfo); // throw general error throw e; } } } } }
packages/nocodb/src/lib/version-upgrader/ncAttachmentUpgrader.ts
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.0012551951222121716, 0.00023292370315175503, 0.0001669697812758386, 0.0001719110005069524, 0.00024130272504407912 ]
{ "id": 5, "code_window": [ "import { publicMetaService } from '../../services';\n", "import type { Request, Response } from 'express';\n", "\n", "export async function viewMetaGet(req: Request, res: Response) {\n", " console.log('FOO viewMetaGet');\n", " res.json(\n", " await publicMetaService.viewMetaGet({\n", " password: req.headers?.['xc-password'] as string,\n", " sharedViewUuid: req.params.sharedViewUuid,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nocodb/src/lib/controllers/publicControllers/publicMeta.ctl.ts", "type": "replace", "edit_start_line_idx": 6 }
import { XcEmailPlugin } from 'nc-plugin'; import SMTP from './SMTP'; import type { IEmailAdapter } from 'nc-plugin'; class SMTPPlugin extends XcEmailPlugin { private static storageAdapter: SMTP; public getAdapter(): IEmailAdapter { return SMTPPlugin.storageAdapter; } public async init(config: any): Promise<any> { SMTPPlugin.storageAdapter = new SMTP(config); await SMTPPlugin.storageAdapter.init(); } } export default SMTPPlugin;
packages/nocodb/src/lib/plugins/smtp/SMTPPlugin.ts
0
https://github.com/nocodb/nocodb/commit/4de7f6f60e45e5d03a6a2ae87a438e3bff163900
[ 0.0001762458123266697, 0.0001751669478835538, 0.0001740880834404379, 0.0001751669478835538, 0.00000107886444311589 ]
{ "id": 0, "code_window": [ " entry: resolve(nitroContext.rollupConfig.output.dir, nitroContext.rollupConfig.output.entryFileNames)\n", " }\n", "}\n", "\n", "async function _watch (nitroContext: NitroContext) {\n", " const watcher = rollupWatch(nitroContext.rollupConfig)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "function startRollupWatcher (nitroContext: NitroContext) {\n" ], "file_path": "packages/nitro/src/build.ts", "type": "replace", "edit_start_line_idx": 81 }
import { resolve, join } from 'upath' import consola from 'consola' import { rollup, watch as rollupWatch } from 'rollup' import { readFile, emptyDir, copy } from 'fs-extra' import { printFSTree } from './utils/tree' import { getRollupConfig } from './rollup/config' import { hl, prettyPath, serializeTemplate, writeFile, isDirectory } from './utils' import { NitroContext } from './context' import { scanMiddleware } from './server/middleware' export async function prepare (nitroContext: NitroContext) { consola.info(`Nitro preset is ${hl(nitroContext.preset)}`) await cleanupDir(nitroContext.output.dir) if (!nitroContext.output.publicDir.startsWith(nitroContext.output.dir)) { await cleanupDir(nitroContext.output.publicDir) } if (!nitroContext.output.serverDir.startsWith(nitroContext.output.dir)) { await cleanupDir(nitroContext.output.serverDir) } } async function cleanupDir (dir: string) { consola.info('Cleaning up', prettyPath(dir)) await emptyDir(dir) } export async function generate (nitroContext: NitroContext) { consola.start('Generating public...') const clientDist = resolve(nitroContext._nuxt.buildDir, 'dist/client') if (await isDirectory(clientDist)) { await copy(clientDist, join(nitroContext.output.publicDir, nitroContext._nuxt.publicPath)) } const staticDir = resolve(nitroContext._nuxt.srcDir, nitroContext._nuxt.staticDir) if (await isDirectory(staticDir)) { await copy(staticDir, nitroContext.output.publicDir) } consola.success('Generated public ' + prettyPath(nitroContext.output.publicDir)) } export async function build (nitroContext: NitroContext) { // Compile html template const htmlSrc = resolve(nitroContext._nuxt.buildDir, `views/${{ 2: 'app', 3: 'document' }[2]}.template.html`) const htmlTemplate = { src: htmlSrc, contents: '', dst: '', compiled: '' } htmlTemplate.dst = htmlTemplate.src.replace(/.html$/, '.js').replace('app.', 'document.') htmlTemplate.contents = await readFile(htmlTemplate.src, 'utf-8') htmlTemplate.compiled = 'module.exports = ' + serializeTemplate(htmlTemplate.contents) await nitroContext._internal.hooks.callHook('nitro:template:document', htmlTemplate) await writeFile(htmlTemplate.dst, htmlTemplate.compiled) nitroContext.rollupConfig = getRollupConfig(nitroContext) await nitroContext._internal.hooks.callHook('nitro:rollup:before', nitroContext) return nitroContext._nuxt.dev ? _watch(nitroContext) : _build(nitroContext) } async function _build (nitroContext: NitroContext) { nitroContext.scannedMiddleware = await scanMiddleware(nitroContext._nuxt.serverDir) consola.start('Building server...') const build = await rollup(nitroContext.rollupConfig).catch((error) => { consola.error('Rollup error: ' + error.message) throw error }) consola.start('Writing server bundle...') await build.write(nitroContext.rollupConfig.output) consola.success('Server built') await printFSTree(nitroContext.output.serverDir) await nitroContext._internal.hooks.callHook('nitro:compiled', nitroContext) return { entry: resolve(nitroContext.rollupConfig.output.dir, nitroContext.rollupConfig.output.entryFileNames) } } async function _watch (nitroContext: NitroContext) { const watcher = rollupWatch(nitroContext.rollupConfig) nitroContext.scannedMiddleware = await scanMiddleware(nitroContext._nuxt.serverDir, (middleware, event, file) => { nitroContext.scannedMiddleware = middleware watcher.emit(event, file) } ) let start watcher.on('event', (event) => { switch (event.code) { // The watcher is (re)starting case 'START': return // Building an individual bundle case 'BUNDLE_START': start = Date.now() return // Finished building all bundles case 'END': nitroContext._internal.hooks.callHook('nitro:compiled', nitroContext) consola.success('Nitro built', start ? `in ${Date.now() - start} ms` : '') return // Encountered an error while bundling case 'ERROR': consola.error('Rollup error: ' + event.error) // consola.error(event.error) } }) }
packages/nitro/src/build.ts
1
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.9991441965103149, 0.2674959599971771, 0.0001677816326264292, 0.010143629275262356, 0.4230321943759918 ]
{ "id": 0, "code_window": [ " entry: resolve(nitroContext.rollupConfig.output.dir, nitroContext.rollupConfig.output.entryFileNames)\n", " }\n", "}\n", "\n", "async function _watch (nitroContext: NitroContext) {\n", " const watcher = rollupWatch(nitroContext.rollupConfig)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "function startRollupWatcher (nitroContext: NitroContext) {\n" ], "file_path": "packages/nitro/src/build.ts", "type": "replace", "edit_start_line_idx": 81 }
import '~polyfill' import { Server } from 'http' import { parentPort } from 'worker_threads' import type { AddressInfo } from 'net' import { handle } from '../server' const server = new Server(handle) const netServer = server.listen(0, () => { parentPort.postMessage({ event: 'listen', port: (netServer.address() as AddressInfo).port }) })
packages/nitro/src/runtime/entries/local.ts
0
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.00017477982328273356, 0.00017380883218720555, 0.00017283784109167755, 0.00017380883218720555, 9.709910955280066e-7 ]
{ "id": 0, "code_window": [ " entry: resolve(nitroContext.rollupConfig.output.dir, nitroContext.rollupConfig.output.entryFileNames)\n", " }\n", "}\n", "\n", "async function _watch (nitroContext: NitroContext) {\n", " const watcher = rollupWatch(nitroContext.rollupConfig)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "function startRollupWatcher (nitroContext: NitroContext) {\n" ], "file_path": "packages/nitro/src/build.ts", "type": "replace", "edit_start_line_idx": 81 }
import { resolve, dirname, relative } from 'upath' import globby from 'globby' import prettyBytes from 'pretty-bytes' import gzipSize from 'gzip-size' import { readFile } from 'fs-extra' import chalk from 'chalk' export async function printFSTree (dir) { const files = await globby('**/*.*', { cwd: dir }) const items = (await Promise.all(files.map(async (file) => { const path = resolve(dir, file) const src = await readFile(path) const size = src.byteLength const gzip = await gzipSize(src) return { file, path, size, gzip } }))).sort((a, b) => b.path.localeCompare(a.path)) let totalSize = 0 let totalGzip = 0 let totalNodeModulesSize = 0 let totalNodeModulesGzip = 0 items.forEach((item, index) => { let dir = dirname(item.file) if (dir === '.') { dir = '' } const rpath = relative(process.cwd(), item.path) const treeChar = index === items.length - 1 ? '└─' : '├─' const isNodeModules = item.file.includes('node_modules') if (isNodeModules) { totalNodeModulesSize += item.size totalNodeModulesGzip += item.gzip return } process.stdout.write(chalk.gray(` ${treeChar} ${rpath} (${prettyBytes(item.size)}) (${prettyBytes(item.gzip)} gzip)\n`)) totalSize += item.size totalGzip += item.gzip }) process.stdout.write(`${chalk.cyan('Σ Total size:')} ${prettyBytes(totalSize + totalNodeModulesSize)} (${prettyBytes(totalGzip + totalNodeModulesGzip)} gzip)\n`) }
packages/nitro/src/utils/tree.ts
0
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.0001778236182872206, 0.00017086800653487444, 0.0001674705999903381, 0.00017045700224116445, 0.0000037217698718450265 ]
{ "id": 0, "code_window": [ " entry: resolve(nitroContext.rollupConfig.output.dir, nitroContext.rollupConfig.output.entryFileNames)\n", " }\n", "}\n", "\n", "async function _watch (nitroContext: NitroContext) {\n", " const watcher = rollupWatch(nitroContext.rollupConfig)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "function startRollupWatcher (nitroContext: NitroContext) {\n" ], "file_path": "packages/nitro/src/build.ts", "type": "replace", "edit_start_line_idx": 81 }
import { resolve } from 'upath' import defu from 'defu' import type { NuxtOptions } from '@nuxt/types' import Hookable, { configHooksT } from 'hookable' import type { Preset } from '@nuxt/un' import { tryImport, resolvePath, detectTarget, extendPreset } from './utils' import * as PRESETS from './presets' import type { NodeExternalsOptions } from './rollup/plugins/externals' import type { ServerMiddleware } from './server/middleware' export interface NitroContext { timing: boolean inlineChunks: boolean minify: boolean sourceMap: boolean externals: boolean | NodeExternalsOptions analyze: boolean entry: string node: boolean preset: string rollupConfig?: any renderer: string serveStatic: boolean middleware: ServerMiddleware[] scannedMiddleware: ServerMiddleware[] hooks: configHooksT nuxtHooks: configHooksT ignore: string[] env: Preset output: { dir: string serverDir: string publicDir: string } _nuxt: { majorVersion: number dev: boolean rootDir: string srcDir: string buildDir: string generateDir: string staticDir: string serverDir: string routerBase: string publicPath: string isStatic: boolean fullStatic: boolean staticAssets: any runtimeConfig: { public: any, private: any } } _internal: { runtimeDir: string hooks: Hookable } } type DeepPartial<T> = { [P in keyof T]?: DeepPartial<T[P]> } export interface NitroInput extends DeepPartial<NitroContext> {} export type NitroPreset = NitroInput | ((input: NitroInput) => NitroInput) export function getNitroContext (nuxtOptions: NuxtOptions, input: NitroInput): NitroContext { const defaults: NitroContext = { timing: true, inlineChunks: true, minify: true, sourceMap: false, externals: false, analyze: false, entry: undefined, node: undefined, preset: undefined, rollupConfig: undefined, renderer: undefined, serveStatic: false, middleware: [], scannedMiddleware: [], ignore: [], env: {}, hooks: {}, nuxtHooks: {}, output: { dir: '{{ _nuxt.rootDir }}/.output', serverDir: '{{ output.dir }}/server', publicDir: '{{ output.dir }}/public' }, _nuxt: { majorVersion: nuxtOptions._majorVersion || 2, dev: nuxtOptions.dev, rootDir: nuxtOptions.rootDir, srcDir: nuxtOptions.srcDir, buildDir: nuxtOptions.buildDir, generateDir: nuxtOptions.generate.dir, staticDir: nuxtOptions.dir.static, serverDir: resolve(nuxtOptions.srcDir, (nuxtOptions.dir as any).server || 'server'), routerBase: nuxtOptions.router.base, publicPath: nuxtOptions.build.publicPath, isStatic: nuxtOptions.target === 'static' && !nuxtOptions.dev, fullStatic: nuxtOptions.target === 'static' && !nuxtOptions._legacyGenerate, // @ts-ignore staticAssets: nuxtOptions.generate.staticAssets, runtimeConfig: { public: nuxtOptions.publicRuntimeConfig, private: nuxtOptions.privateRuntimeConfig } }, _internal: { runtimeDir: resolve(__dirname, './runtime'), hooks: new Hookable() } } defaults.preset = input.preset || process.env.NITRO_PRESET || detectTarget() || 'server' let presetDefaults = PRESETS[defaults.preset] || tryImport(nuxtOptions.rootDir, defaults.preset) if (!presetDefaults) { throw new Error('Cannot resolve preset: ' + defaults.preset) } presetDefaults = presetDefaults.default || presetDefaults const _presetInput = defu(input, defaults) // @ts-ignore const _preset = extendPreset(input, presetDefaults)(_presetInput) const nitroContext: NitroContext = defu(input, _preset, defaults) as any nitroContext.output.dir = resolvePath(nitroContext, nitroContext.output.dir) nitroContext.output.publicDir = resolvePath(nitroContext, nitroContext.output.publicDir) nitroContext.output.serverDir = resolvePath(nitroContext, nitroContext.output.serverDir) nitroContext._internal.hooks.addHooks(nitroContext.hooks) // console.log(nitroContext) // process.exit(1) return nitroContext }
packages/nitro/src/context.ts
0
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.020253952592611313, 0.0038097011856734753, 0.00016726840112823993, 0.00017351449059788138, 0.006291160359978676 ]
{ "id": 1, "code_window": [ " const watcher = rollupWatch(nitroContext.rollupConfig)\n", "\n", " nitroContext.scannedMiddleware = await scanMiddleware(nitroContext._nuxt.serverDir,\n", " (middleware, event, file) => {\n", " nitroContext.scannedMiddleware = middleware\n", " watcher.emit(event, file)\n", " }\n", " )\n", "\n", " let start\n", "\n", " watcher.on('event', (event) => {\n", " switch (event.code) {\n", " // The watcher is (re)starting\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nitro/src/build.ts", "type": "replace", "edit_start_line_idx": 83 }
import { resolve, join } from 'upath' import consola from 'consola' import { rollup, watch as rollupWatch } from 'rollup' import { readFile, emptyDir, copy } from 'fs-extra' import { printFSTree } from './utils/tree' import { getRollupConfig } from './rollup/config' import { hl, prettyPath, serializeTemplate, writeFile, isDirectory } from './utils' import { NitroContext } from './context' import { scanMiddleware } from './server/middleware' export async function prepare (nitroContext: NitroContext) { consola.info(`Nitro preset is ${hl(nitroContext.preset)}`) await cleanupDir(nitroContext.output.dir) if (!nitroContext.output.publicDir.startsWith(nitroContext.output.dir)) { await cleanupDir(nitroContext.output.publicDir) } if (!nitroContext.output.serverDir.startsWith(nitroContext.output.dir)) { await cleanupDir(nitroContext.output.serverDir) } } async function cleanupDir (dir: string) { consola.info('Cleaning up', prettyPath(dir)) await emptyDir(dir) } export async function generate (nitroContext: NitroContext) { consola.start('Generating public...') const clientDist = resolve(nitroContext._nuxt.buildDir, 'dist/client') if (await isDirectory(clientDist)) { await copy(clientDist, join(nitroContext.output.publicDir, nitroContext._nuxt.publicPath)) } const staticDir = resolve(nitroContext._nuxt.srcDir, nitroContext._nuxt.staticDir) if (await isDirectory(staticDir)) { await copy(staticDir, nitroContext.output.publicDir) } consola.success('Generated public ' + prettyPath(nitroContext.output.publicDir)) } export async function build (nitroContext: NitroContext) { // Compile html template const htmlSrc = resolve(nitroContext._nuxt.buildDir, `views/${{ 2: 'app', 3: 'document' }[2]}.template.html`) const htmlTemplate = { src: htmlSrc, contents: '', dst: '', compiled: '' } htmlTemplate.dst = htmlTemplate.src.replace(/.html$/, '.js').replace('app.', 'document.') htmlTemplate.contents = await readFile(htmlTemplate.src, 'utf-8') htmlTemplate.compiled = 'module.exports = ' + serializeTemplate(htmlTemplate.contents) await nitroContext._internal.hooks.callHook('nitro:template:document', htmlTemplate) await writeFile(htmlTemplate.dst, htmlTemplate.compiled) nitroContext.rollupConfig = getRollupConfig(nitroContext) await nitroContext._internal.hooks.callHook('nitro:rollup:before', nitroContext) return nitroContext._nuxt.dev ? _watch(nitroContext) : _build(nitroContext) } async function _build (nitroContext: NitroContext) { nitroContext.scannedMiddleware = await scanMiddleware(nitroContext._nuxt.serverDir) consola.start('Building server...') const build = await rollup(nitroContext.rollupConfig).catch((error) => { consola.error('Rollup error: ' + error.message) throw error }) consola.start('Writing server bundle...') await build.write(nitroContext.rollupConfig.output) consola.success('Server built') await printFSTree(nitroContext.output.serverDir) await nitroContext._internal.hooks.callHook('nitro:compiled', nitroContext) return { entry: resolve(nitroContext.rollupConfig.output.dir, nitroContext.rollupConfig.output.entryFileNames) } } async function _watch (nitroContext: NitroContext) { const watcher = rollupWatch(nitroContext.rollupConfig) nitroContext.scannedMiddleware = await scanMiddleware(nitroContext._nuxt.serverDir, (middleware, event, file) => { nitroContext.scannedMiddleware = middleware watcher.emit(event, file) } ) let start watcher.on('event', (event) => { switch (event.code) { // The watcher is (re)starting case 'START': return // Building an individual bundle case 'BUNDLE_START': start = Date.now() return // Finished building all bundles case 'END': nitroContext._internal.hooks.callHook('nitro:compiled', nitroContext) consola.success('Nitro built', start ? `in ${Date.now() - start} ms` : '') return // Encountered an error while bundling case 'ERROR': consola.error('Rollup error: ' + event.error) // consola.error(event.error) } }) }
packages/nitro/src/build.ts
1
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.998396098613739, 0.34100568294525146, 0.00016764778411015868, 0.008022688329219818, 0.463727205991745 ]
{ "id": 1, "code_window": [ " const watcher = rollupWatch(nitroContext.rollupConfig)\n", "\n", " nitroContext.scannedMiddleware = await scanMiddleware(nitroContext._nuxt.serverDir,\n", " (middleware, event, file) => {\n", " nitroContext.scannedMiddleware = middleware\n", " watcher.emit(event, file)\n", " }\n", " )\n", "\n", " let start\n", "\n", " watcher.on('event', (event) => {\n", " switch (event.code) {\n", " // The watcher is (re)starting\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nitro/src/build.ts", "type": "replace", "edit_start_line_idx": 83 }
import consola from 'consola' import { extendPreset, prettyPath } from '../utils' import { NitroPreset, NitroContext } from '../context' import { node } from './node' export const cli: NitroPreset = extendPreset(node, { entry: '{{ _internal.runtimeDir }}/entries/cli', externals: true, inlineChunks: true, hooks: { 'nitro:compiled' ({ output }: NitroContext) { consola.info('Run with `node ' + prettyPath(output.serverDir) + ' [route]`') } } })
packages/nitro/src/presets/cli.ts
0
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.00019735713431145996, 0.00018662461661733687, 0.00017589209892321378, 0.00018662461661733687, 0.00001073251769412309 ]
{ "id": 1, "code_window": [ " const watcher = rollupWatch(nitroContext.rollupConfig)\n", "\n", " nitroContext.scannedMiddleware = await scanMiddleware(nitroContext._nuxt.serverDir,\n", " (middleware, event, file) => {\n", " nitroContext.scannedMiddleware = middleware\n", " watcher.emit(event, file)\n", " }\n", " )\n", "\n", " let start\n", "\n", " watcher.on('event', (event) => {\n", " switch (event.code) {\n", " // The watcher is (re)starting\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nitro/src/build.ts", "type": "replace", "edit_start_line_idx": 83 }
import '~polyfill' import { handle } from '../server' const functions = require('firebase-functions') export const server = functions.https.onRequest(handle)
packages/nitro/src/runtime/entries/firebase.ts
0
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.00017656793352216482, 0.00017656793352216482, 0.00017656793352216482, 0.00017656793352216482, 0 ]
{ "id": 1, "code_window": [ " const watcher = rollupWatch(nitroContext.rollupConfig)\n", "\n", " nitroContext.scannedMiddleware = await scanMiddleware(nitroContext._nuxt.serverDir,\n", " (middleware, event, file) => {\n", " nitroContext.scannedMiddleware = middleware\n", " watcher.emit(event, file)\n", " }\n", " )\n", "\n", " let start\n", "\n", " watcher.on('event', (event) => {\n", " switch (event.code) {\n", " // The watcher is (re)starting\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/nitro/src/build.ts", "type": "replace", "edit_start_line_idx": 83 }
import '~polyfill' import { localCall } from '../server' async function cli () { const url = process.argv[2] || '/' const debug = (label, ...args) => console.debug(`> ${label}:`, ...args) const r = await localCall({ url }) debug('URL', url) debug('StatusCode', r.status) debug('StatusMessage', r.statusText) // @ts-ignore for (const header of r.headers.entries()) { debug(header[0], header[1]) } console.log('\n', r.body.toString()) } if (require.main === module) { cli().catch((err) => { console.error(err) process.exit(1) }) }
packages/nitro/src/runtime/entries/cli.ts
0
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.00017289553943555802, 0.00017109727195929736, 0.00016818799485918134, 0.00017220829613506794, 0.000002076217242574785 ]
{ "id": 2, "code_window": [ " case 'ERROR':\n", " consola.error('Rollup error: ' + event.error)\n", " // consola.error(event.error)\n", " }\n", " })\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " return watcher\n", "}\n", "\n", "async function _watch (nitroContext: NitroContext) {\n", " let watcher = startRollupWatcher(nitroContext)\n", "\n", " nitroContext.scannedMiddleware = await scanMiddleware(nitroContext._nuxt.serverDir,\n", " (middleware, event) => {\n", " nitroContext.scannedMiddleware = middleware\n", " if (['add', 'addDir'].includes(event)) {\n", " watcher.close()\n", " watcher = startRollupWatcher(nitroContext)\n", " }\n", " }\n", " )\n" ], "file_path": "packages/nitro/src/build.ts", "type": "add", "edit_start_line_idx": 116 }
import { resolve, join, extname } from 'upath' import { joinURL } from 'ufo' import globby from 'globby' import { watch } from 'chokidar' export interface ServerMiddleware { route: string handle: string lazy?: boolean // Default is true promisify?: boolean // Default is true } function filesToMiddleware (files: string[], baseDir: string, basePath: string, overrides?: Partial<ServerMiddleware>): ServerMiddleware[] { return files.map((file) => { const route = joinURL(basePath, file.substr(0, file.length - extname(file).length)) const handle = resolve(baseDir, file) return { route, handle } }) .sort((a, b) => a.route.localeCompare(b.route)) .map(m => ({ ...m, ...overrides })) } export function scanMiddleware (serverDir: string, onChange?: Function): Promise<ServerMiddleware[]> { const pattern = '**/*.{js,ts}' const globalDir = resolve(serverDir, 'middleware') const apiDir = resolve(serverDir, 'api') const scan = async () => { const globalFiles = await globby(pattern, { cwd: globalDir }) const apiFiles = await globby(pattern, { cwd: apiDir }) return [ ...filesToMiddleware(globalFiles, globalDir, '/', { route: '/' }), ...filesToMiddleware(apiFiles, apiDir, '/api', { lazy: true }) ] } if (typeof onChange === 'function') { const watcher = watch([ join(globalDir, pattern), join(apiDir, pattern) ], { ignoreInitial: true }) watcher.on('all', async (event, file) => { onChange(await scan(), event, file) }) } return scan() } export function resolveMiddleware (serverMiddleware: any[], resolvePath: (string) => string) { const middleware: ServerMiddleware[] = [] const legacyMiddleware: ServerMiddleware[] = [] for (let m of serverMiddleware) { if (typeof m === 'string') { m = { handler: m } } const route = m.path || m.route || '/' const handle = m.handler || m.handle if (typeof handle !== 'string' || typeof route !== 'string') { legacyMiddleware.push(m) } else { middleware.push({ ...m, handle: resolvePath(handle), route }) } } return { middleware, legacyMiddleware } }
packages/nitro/src/server/middleware.ts
1
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.00018196397286374122, 0.0001715585240162909, 0.00016479227633681148, 0.00017044105334207416, 0.00000512178075950942 ]
{ "id": 2, "code_window": [ " case 'ERROR':\n", " consola.error('Rollup error: ' + event.error)\n", " // consola.error(event.error)\n", " }\n", " })\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " return watcher\n", "}\n", "\n", "async function _watch (nitroContext: NitroContext) {\n", " let watcher = startRollupWatcher(nitroContext)\n", "\n", " nitroContext.scannedMiddleware = await scanMiddleware(nitroContext._nuxt.serverDir,\n", " (middleware, event) => {\n", " nitroContext.scannedMiddleware = middleware\n", " if (['add', 'addDir'].includes(event)) {\n", " watcher.close()\n", " watcher = startRollupWatcher(nitroContext)\n", " }\n", " }\n", " )\n" ], "file_path": "packages/nitro/src/build.ts", "type": "add", "edit_start_line_idx": 116 }
import { extendPreset } from '../utils' import { NitroPreset } from '../context' import { node } from './node' export const local: NitroPreset = extendPreset(node, { entry: '{{ _internal.runtimeDir }}/entries/local', output: { serverDir: '{{ _nuxt.buildDir }}/nitro' }, minify: false, externals: { trace: false }, inlineChunks: true, timing: false, sourceMap: true })
packages/nitro/src/presets/local.ts
0
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.00017682655015960336, 0.0001741673913784325, 0.0001715082471491769, 0.0001741673913784325, 0.000002659151505213231 ]
{ "id": 2, "code_window": [ " case 'ERROR':\n", " consola.error('Rollup error: ' + event.error)\n", " // consola.error(event.error)\n", " }\n", " })\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " return watcher\n", "}\n", "\n", "async function _watch (nitroContext: NitroContext) {\n", " let watcher = startRollupWatcher(nitroContext)\n", "\n", " nitroContext.scannedMiddleware = await scanMiddleware(nitroContext._nuxt.serverDir,\n", " (middleware, event) => {\n", " nitroContext.scannedMiddleware = middleware\n", " if (['add', 'addDir'].includes(event)) {\n", " watcher.close()\n", " watcher = startRollupWatcher(nitroContext)\n", " }\n", " }\n", " )\n" ], "file_path": "packages/nitro/src/build.ts", "type": "add", "edit_start_line_idx": 116 }
import '~polyfill' import { localCall } from '../server' async function cli () { const url = process.argv[2] || '/' const debug = (label, ...args) => console.debug(`> ${label}:`, ...args) const r = await localCall({ url }) debug('URL', url) debug('StatusCode', r.status) debug('StatusMessage', r.statusText) // @ts-ignore for (const header of r.headers.entries()) { debug(header[0], header[1]) } console.log('\n', r.body.toString()) } if (require.main === module) { cli().catch((err) => { console.error(err) process.exit(1) }) }
packages/nitro/src/runtime/entries/cli.ts
0
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.00017437183123547584, 0.0001714396639727056, 0.00016714211960788816, 0.0001728050410747528, 0.0000031054116789164254 ]
{ "id": 2, "code_window": [ " case 'ERROR':\n", " consola.error('Rollup error: ' + event.error)\n", " // consola.error(event.error)\n", " }\n", " })\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " return watcher\n", "}\n", "\n", "async function _watch (nitroContext: NitroContext) {\n", " let watcher = startRollupWatcher(nitroContext)\n", "\n", " nitroContext.scannedMiddleware = await scanMiddleware(nitroContext._nuxt.serverDir,\n", " (middleware, event) => {\n", " nitroContext.scannedMiddleware = middleware\n", " if (['add', 'addDir'].includes(event)) {\n", " watcher.close()\n", " watcher = startRollupWatcher(nitroContext)\n", " }\n", " }\n", " )\n" ], "file_path": "packages/nitro/src/build.ts", "type": "add", "edit_start_line_idx": 116 }
import '~polyfill' export * from '../server'
packages/nitro/src/runtime/entries/node.ts
0
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.00017654620751272887, 0.00017654620751272887, 0.00017654620751272887, 0.00017654620751272887, 0 ]
{ "id": 3, "code_window": [ " })\n", " .sort((a, b) => a.route.localeCompare(b.route))\n", " .map(m => ({ ...m, ...overrides }))\n", "}\n", "\n", "export function scanMiddleware (serverDir: string, onChange?: Function): Promise<ServerMiddleware[]> {\n", " const pattern = '**/*.{js,ts}'\n", " const globalDir = resolve(serverDir, 'middleware')\n", " const apiDir = resolve(serverDir, 'api')\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export function scanMiddleware (serverDir: string, onChange?: (results: ServerMiddleware[], event: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir', file: string) => void): Promise<ServerMiddleware[]> {\n" ], "file_path": "packages/nitro/src/server/middleware.ts", "type": "replace", "edit_start_line_idx": 25 }
import { resolve, join, extname } from 'upath' import { joinURL } from 'ufo' import globby from 'globby' import { watch } from 'chokidar' export interface ServerMiddleware { route: string handle: string lazy?: boolean // Default is true promisify?: boolean // Default is true } function filesToMiddleware (files: string[], baseDir: string, basePath: string, overrides?: Partial<ServerMiddleware>): ServerMiddleware[] { return files.map((file) => { const route = joinURL(basePath, file.substr(0, file.length - extname(file).length)) const handle = resolve(baseDir, file) return { route, handle } }) .sort((a, b) => a.route.localeCompare(b.route)) .map(m => ({ ...m, ...overrides })) } export function scanMiddleware (serverDir: string, onChange?: Function): Promise<ServerMiddleware[]> { const pattern = '**/*.{js,ts}' const globalDir = resolve(serverDir, 'middleware') const apiDir = resolve(serverDir, 'api') const scan = async () => { const globalFiles = await globby(pattern, { cwd: globalDir }) const apiFiles = await globby(pattern, { cwd: apiDir }) return [ ...filesToMiddleware(globalFiles, globalDir, '/', { route: '/' }), ...filesToMiddleware(apiFiles, apiDir, '/api', { lazy: true }) ] } if (typeof onChange === 'function') { const watcher = watch([ join(globalDir, pattern), join(apiDir, pattern) ], { ignoreInitial: true }) watcher.on('all', async (event, file) => { onChange(await scan(), event, file) }) } return scan() } export function resolveMiddleware (serverMiddleware: any[], resolvePath: (string) => string) { const middleware: ServerMiddleware[] = [] const legacyMiddleware: ServerMiddleware[] = [] for (let m of serverMiddleware) { if (typeof m === 'string') { m = { handler: m } } const route = m.path || m.route || '/' const handle = m.handler || m.handle if (typeof handle !== 'string' || typeof route !== 'string') { legacyMiddleware.push(m) } else { middleware.push({ ...m, handle: resolvePath(handle), route }) } } return { middleware, legacyMiddleware } }
packages/nitro/src/server/middleware.ts
1
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.9986526966094971, 0.3767552077770233, 0.0005199581501074135, 0.007836641743779182, 0.481387734413147 ]
{ "id": 3, "code_window": [ " })\n", " .sort((a, b) => a.route.localeCompare(b.route))\n", " .map(m => ({ ...m, ...overrides }))\n", "}\n", "\n", "export function scanMiddleware (serverDir: string, onChange?: Function): Promise<ServerMiddleware[]> {\n", " const pattern = '**/*.{js,ts}'\n", " const globalDir = resolve(serverDir, 'middleware')\n", " const apiDir = resolve(serverDir, 'api')\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export function scanMiddleware (serverDir: string, onChange?: (results: ServerMiddleware[], event: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir', file: string) => void): Promise<ServerMiddleware[]> {\n" ], "file_path": "packages/nitro/src/server/middleware.ts", "type": "replace", "edit_start_line_idx": 25 }
import { relative, dirname, resolve } from 'upath' import fse from 'fs-extra' import jiti from 'jiti' import defu from 'defu' import Hookable from 'hookable' import consola from 'consola' import chalk from 'chalk' import { get } from 'dot-prop' import type { NitroPreset, NitroInput } from '../context' export const MODULE_DIR = resolve(__dirname, '..') export function hl (str: string) { return chalk.cyan(str) } export function prettyPath (p: string, highlight = true) { p = relative(process.cwd(), p) return highlight ? hl(p) : p } export function compileTemplate (contents: string) { return (params: Record<string, any>) => contents.replace(/{{ ?([\w.]+) ?}}/g, (_, match) => { const val = get(params, match) if (!val) { consola.warn(`cannot resolve template param '${match}' in ${contents.substr(0, 20)}`) } return val as string || `${match}` }) } export function serializeTemplate (contents: string) { // eslint-disable-next-line no-template-curly-in-string return `(params) => \`${contents.replace(/{{ (\w+) }}/g, '${params.$1}')}\`` } export function jitiImport (dir: string, path: string) { return jiti(dir)(path) } export function tryImport (dir: string, path: string) { try { return jitiImport(dir, path) } catch (_err) { } } export async function writeFile (file, contents, log = false) { await fse.mkdirp(dirname(file)) await fse.writeFile(file, contents, 'utf-8') if (log) { consola.info('Generated', prettyPath(file)) } } export function resolvePath (nitroContext: NitroInput, path: string | ((nitroContext) => string), resolveBase: string = ''): string { if (typeof path === 'function') { path = path(nitroContext) } if (typeof path !== 'string') { throw new TypeError('Invalid path: ' + path) } path = compileTemplate(path)(nitroContext) return resolve(resolveBase, path) } export function detectTarget () { if (process.env.NETLIFY) { return 'netlify' } if (process.env.NOW_BUILDER) { return 'vercel' } if (process.env.INPUT_AZURE_STATIC_WEB_APPS_API_TOKEN) { return 'azure' } } export async function isDirectory (path: string) { try { return (await fse.stat(path)).isDirectory() } catch (_err) { return false } } export function extendPreset (base: NitroPreset, preset: NitroPreset): NitroPreset { return (config: NitroInput) => { if (typeof preset === 'function') { preset = preset(config) } if (typeof base === 'function') { base = base(config) } return defu({ hooks: Hookable.mergeHooks(base.hooks, preset.hooks) }, preset, base) } } const _getDependenciesMode = { dev: ['devDependencies'], prod: ['dependencies'], all: ['devDependencies', 'dependencies'] } export function getDependencies (dir: string, mode: keyof typeof _getDependenciesMode = 'all') { const fields = _getDependenciesMode[mode] const pkg = require(resolve(dir, 'package.json')) const dependencies = [] for (const field of fields) { if (pkg[field]) { for (const name in pkg[field]) { dependencies.push(name) } } } return dependencies }
packages/nitro/src/utils/index.ts
0
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.00017532528727315366, 0.00016991590382531285, 0.0001660159759921953, 0.00016962458903435618, 0.0000021595246835204307 ]
{ "id": 3, "code_window": [ " })\n", " .sort((a, b) => a.route.localeCompare(b.route))\n", " .map(m => ({ ...m, ...overrides }))\n", "}\n", "\n", "export function scanMiddleware (serverDir: string, onChange?: Function): Promise<ServerMiddleware[]> {\n", " const pattern = '**/*.{js,ts}'\n", " const globalDir = resolve(serverDir, 'middleware')\n", " const apiDir = resolve(serverDir, 'api')\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export function scanMiddleware (serverDir: string, onChange?: (results: ServerMiddleware[], event: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir', file: string) => void): Promise<ServerMiddleware[]> {\n" ], "file_path": "packages/nitro/src/server/middleware.ts", "type": "replace", "edit_start_line_idx": 25 }
import '../app/config' import { createApp, useBase } from 'h3' import { createFetch } from 'ohmyfetch' import destr from 'destr' import { createCall, createFetch as createLocalFetch } from '@nuxt/un/runtime/fetch' import { timingMiddleware } from './timing' import { handleError } from './error' // @ts-ignore import serverMiddleware from '~serverMiddleware' const app = createApp({ debug: destr(process.env.DEBUG), onError: handleError }) app.use(timingMiddleware) app.use(serverMiddleware) app.use(() => import('../app/render').then(e => e.renderMiddleware), { lazy: true }) export const stack = app.stack export const handle = useBase(process.env.ROUTER_BASE, app) export const localCall = createCall(handle) export const localFetch = createLocalFetch(localCall, global.fetch) export const $fetch = global.$fetch = createFetch({ fetch: localFetch })
packages/nitro/src/runtime/server/index.ts
0
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.001383727416396141, 0.0006015063845552504, 0.00016491362475790083, 0.0002558780543040484, 0.0005543590523302555 ]
{ "id": 3, "code_window": [ " })\n", " .sort((a, b) => a.route.localeCompare(b.route))\n", " .map(m => ({ ...m, ...overrides }))\n", "}\n", "\n", "export function scanMiddleware (serverDir: string, onChange?: Function): Promise<ServerMiddleware[]> {\n", " const pattern = '**/*.{js,ts}'\n", " const globalDir = resolve(serverDir, 'middleware')\n", " const apiDir = resolve(serverDir, 'api')\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export function scanMiddleware (serverDir: string, onChange?: (results: ServerMiddleware[], event: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir', file: string) => void): Promise<ServerMiddleware[]> {\n" ], "file_path": "packages/nitro/src/server/middleware.ts", "type": "replace", "edit_start_line_idx": 25 }
import '~polyfill' import { localCall } from '../server' export default async function handle (context, req) { const url = '/' + (req.params.url || '') const { body, status, statusText, headers } = await localCall({ url, headers: req.headers, method: req.method, body: req.body }) context.res = { status, headers, body: body ? body.toString() : statusText } }
packages/nitro/src/runtime/entries/azure_functions.ts
0
https://github.com/nuxt/nuxt/commit/e1f409ea51f85a69b9315b0bdc1e0d30b26abfe5
[ 0.00017405339167453349, 0.00017131287313532084, 0.0001685723545961082, 0.00017131287313532084, 0.000002740518539212644 ]
{ "id": 0, "code_window": [ " * For non mixed scenarios this is undefined.\n", " */\n", " datasource?: string | null;\n", "\n", " metric?: any;\n", "\n", " /**\n", " * For limiting result lines.\n", " */\n", " maxLines?: number;\n", "}\n", "\n", "export interface DataQueryError {\n", " data?: {\n", " message?: string;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/grafana-data/src/types/datasource.ts", "type": "replace", "edit_start_line_idx": 393 }
import angular from 'angular'; import _ from 'lodash'; import { dateMath, DataQueryRequest, DataSourceApi } from '@grafana/data'; import { getBackendSrv } from '@grafana/runtime'; import { TemplateSrv } from 'app/features/templating/template_srv'; import { OpenTsdbOptions, OpenTsdbQuery } from './types'; export default class OpenTsDatasource extends DataSourceApi<OpenTsdbQuery, OpenTsdbOptions> { type: any; url: any; name: any; withCredentials: any; basicAuth: any; tsdbVersion: any; tsdbResolution: any; lookupLimit: any; tagKeys: any; aggregatorsPromise: any; filterTypesPromise: any; /** @ngInject */ constructor(instanceSettings: any, private templateSrv: TemplateSrv) { super(instanceSettings); this.type = 'opentsdb'; this.url = instanceSettings.url; this.name = instanceSettings.name; this.withCredentials = instanceSettings.withCredentials; this.basicAuth = instanceSettings.basicAuth; instanceSettings.jsonData = instanceSettings.jsonData || {}; this.tsdbVersion = instanceSettings.jsonData.tsdbVersion || 1; this.tsdbResolution = instanceSettings.jsonData.tsdbResolution || 1; this.lookupLimit = instanceSettings.jsonData.lookupLimit || 1000; this.tagKeys = {}; this.aggregatorsPromise = null; this.filterTypesPromise = null; } // Called once per panel (graph) query(options: DataQueryRequest) { const start = this.convertToTSDBTime(options.rangeRaw.from, false, options.timezone); const end = this.convertToTSDBTime(options.rangeRaw.to, true, options.timezone); const qs: any[] = []; _.each(options.targets, target => { if (!target.metric) { return; } qs.push(this.convertTargetToQuery(target, options, this.tsdbVersion)); }); const queries = _.compact(qs); // No valid targets, return the empty result to save a round trip. if (_.isEmpty(queries)) { return Promise.resolve({ data: [] }); } const groupByTags: any = {}; _.each(queries, query => { if (query.filters && query.filters.length > 0) { _.each(query.filters, val => { groupByTags[val.tagk] = true; }); } else { _.each(query.tags, (val, key) => { groupByTags[key] = true; }); } }); options.targets = _.filter(options.targets, query => { return query.hide !== true; }); return this.performTimeSeriesQuery(queries, start, end).then((response: any) => { const metricToTargetMapping = this.mapMetricsToTargets(response.data, options, this.tsdbVersion); const result = _.map(response.data, (metricData: any, index: number) => { index = metricToTargetMapping[index]; if (index === -1) { index = 0; } this._saveTagKeys(metricData); return this.transformMetricData(metricData, groupByTags, options.targets[index], options, this.tsdbResolution); }); return { data: result }; }); } annotationQuery(options: any) { const start = this.convertToTSDBTime(options.rangeRaw.from, false, options.timezone); const end = this.convertToTSDBTime(options.rangeRaw.to, true, options.timezone); const qs = []; const eventList: any[] = []; qs.push({ aggregator: 'sum', metric: options.annotation.target }); const queries = _.compact(qs); return this.performTimeSeriesQuery(queries, start, end).then((results: any) => { if (results.data[0]) { let annotationObject = results.data[0].annotations; if (options.annotation.isGlobal) { annotationObject = results.data[0].globalAnnotations; } if (annotationObject) { _.each(annotationObject, annotation => { const event = { text: annotation.description, time: Math.floor(annotation.startTime) * 1000, annotation: options.annotation, }; eventList.push(event); }); } } return eventList; }); } targetContainsTemplate(target: any) { if (target.filters && target.filters.length > 0) { for (let i = 0; i < target.filters.length; i++) { if (this.templateSrv.variableExists(target.filters[i].filter)) { return true; } } } if (target.tags && Object.keys(target.tags).length > 0) { for (const tagKey in target.tags) { if (this.templateSrv.variableExists(target.tags[tagKey])) { return true; } } } return false; } performTimeSeriesQuery(queries: any[], start: any, end: any) { let msResolution = false; if (this.tsdbResolution === 2) { msResolution = true; } const reqBody: any = { start: start, queries: queries, msResolution: msResolution, globalAnnotations: true, }; if (this.tsdbVersion === 3) { reqBody.showQuery = true; } // Relative queries (e.g. last hour) don't include an end time if (end) { reqBody.end = end; } const options = { method: 'POST', url: this.url + '/api/query', data: reqBody, }; this._addCredentialOptions(options); return getBackendSrv().datasourceRequest(options); } suggestTagKeys(metric: string | number) { return Promise.resolve(this.tagKeys[metric] || []); } _saveTagKeys(metricData: { tags: {}; aggregateTags: any; metric: string | number }) { const tagKeys = Object.keys(metricData.tags); _.each(metricData.aggregateTags, tag => { tagKeys.push(tag); }); this.tagKeys[metricData.metric] = tagKeys; } _performSuggestQuery(query: string, type: string) { return this._get('/api/suggest', { type, q: query, max: this.lookupLimit }).then((result: any) => { return result.data; }); } _performMetricKeyValueLookup(metric: string, keys: any) { if (!metric || !keys) { return Promise.resolve([]); } const keysArray = keys.split(',').map((key: any) => { return key.trim(); }); const key = keysArray[0]; let keysQuery = key + '=*'; if (keysArray.length > 1) { keysQuery += ',' + keysArray.splice(1).join(','); } const m = metric + '{' + keysQuery + '}'; return this._get('/api/search/lookup', { m: m, limit: this.lookupLimit }).then((result: any) => { result = result.data.results; const tagvs: any[] = []; _.each(result, r => { if (tagvs.indexOf(r.tags[key]) === -1) { tagvs.push(r.tags[key]); } }); return tagvs; }); } _performMetricKeyLookup(metric: any) { if (!metric) { return Promise.resolve([]); } return this._get('/api/search/lookup', { m: metric, limit: 1000 }).then((result: any) => { result = result.data.results; const tagks: any[] = []; _.each(result, r => { _.each(r.tags, (tagv, tagk) => { if (tagks.indexOf(tagk) === -1) { tagks.push(tagk); } }); }); return tagks; }); } _get(relativeUrl: string, params?: { type?: string; q?: string; max?: number; m?: any; limit?: number }) { const options = { method: 'GET', url: this.url + relativeUrl, params: params, }; this._addCredentialOptions(options); return getBackendSrv().datasourceRequest(options); } _addCredentialOptions(options: any) { if (this.basicAuth || this.withCredentials) { options.withCredentials = true; } if (this.basicAuth) { options.headers = { Authorization: this.basicAuth }; } } metricFindQuery(query: string) { if (!query) { return Promise.resolve([]); } let interpolated; try { interpolated = this.templateSrv.replace(query, {}, 'distributed'); } catch (err) { return Promise.reject(err); } const responseTransform = (result: any) => { return _.map(result, value => { return { text: value }; }); }; const metricsRegex = /metrics\((.*)\)/; const tagNamesRegex = /tag_names\((.*)\)/; const tagValuesRegex = /tag_values\((.*?),\s?(.*)\)/; const tagNamesSuggestRegex = /suggest_tagk\((.*)\)/; const tagValuesSuggestRegex = /suggest_tagv\((.*)\)/; const metricsQuery = interpolated.match(metricsRegex); if (metricsQuery) { return this._performSuggestQuery(metricsQuery[1], 'metrics').then(responseTransform); } const tagNamesQuery = interpolated.match(tagNamesRegex); if (tagNamesQuery) { return this._performMetricKeyLookup(tagNamesQuery[1]).then(responseTransform); } const tagValuesQuery = interpolated.match(tagValuesRegex); if (tagValuesQuery) { return this._performMetricKeyValueLookup(tagValuesQuery[1], tagValuesQuery[2]).then(responseTransform); } const tagNamesSuggestQuery = interpolated.match(tagNamesSuggestRegex); if (tagNamesSuggestQuery) { return this._performSuggestQuery(tagNamesSuggestQuery[1], 'tagk').then(responseTransform); } const tagValuesSuggestQuery = interpolated.match(tagValuesSuggestRegex); if (tagValuesSuggestQuery) { return this._performSuggestQuery(tagValuesSuggestQuery[1], 'tagv').then(responseTransform); } return Promise.resolve([]); } testDatasource() { return this._performSuggestQuery('cpu', 'metrics').then(() => { return { status: 'success', message: 'Data source is working' }; }); } getAggregators() { if (this.aggregatorsPromise) { return this.aggregatorsPromise; } this.aggregatorsPromise = this._get('/api/aggregators').then((result: any) => { if (result.data && _.isArray(result.data)) { return result.data.sort(); } return []; }); return this.aggregatorsPromise; } getFilterTypes() { if (this.filterTypesPromise) { return this.filterTypesPromise; } this.filterTypesPromise = this._get('/api/config/filters').then((result: any) => { if (result.data) { return Object.keys(result.data).sort(); } return []; }); return this.filterTypesPromise; } transformMetricData(md: { dps: any }, groupByTags: any, target: any, options: any, tsdbResolution: number) { const metricLabel = this.createMetricLabel(md, target, groupByTags, options); const dps: any[] = []; // TSDB returns datapoints has a hash of ts => value. // Can't use _.pairs(invert()) because it stringifies keys/values _.each(md.dps, (v: any, k: number) => { if (tsdbResolution === 2) { dps.push([v, k * 1]); } else { dps.push([v, k * 1000]); } }); return { target: metricLabel, datapoints: dps }; } createMetricLabel( md: { dps?: any; tags?: any; metric?: any }, target: { alias: string }, groupByTags: any, options: { scopedVars: any } ) { if (target.alias) { const scopedVars = _.clone(options.scopedVars || {}); _.each(md.tags, (value, key) => { scopedVars['tag_' + key] = { value: value }; }); return this.templateSrv.replace(target.alias, scopedVars); } let label = md.metric; const tagData: any[] = []; if (!_.isEmpty(md.tags)) { _.each(_.toPairs(md.tags), tag => { if (_.has(groupByTags, tag[0])) { tagData.push(tag[0] + '=' + tag[1]); } }); } if (!_.isEmpty(tagData)) { label += '{' + tagData.join(', ') + '}'; } return label; } convertTargetToQuery(target: any, options: any, tsdbVersion: number) { if (!target.metric || target.hide) { return null; } const query: any = { metric: this.templateSrv.replace(target.metric, options.scopedVars, 'pipe'), aggregator: 'avg', }; if (target.aggregator) { query.aggregator = this.templateSrv.replace(target.aggregator); } if (target.shouldComputeRate) { query.rate = true; query.rateOptions = { counter: !!target.isCounter, }; if (target.counterMax && target.counterMax.length) { query.rateOptions.counterMax = parseInt(target.counterMax, 10); } if (target.counterResetValue && target.counterResetValue.length) { query.rateOptions.resetValue = parseInt(target.counterResetValue, 10); } if (tsdbVersion >= 2) { query.rateOptions.dropResets = !query.rateOptions.counterMax && (!query.rateOptions.ResetValue || query.rateOptions.ResetValue === 0); } } if (!target.disableDownsampling) { let interval = this.templateSrv.replace(target.downsampleInterval || options.interval); if (interval.match(/\.[0-9]+s/)) { interval = parseFloat(interval) * 1000 + 'ms'; } query.downsample = interval + '-' + target.downsampleAggregator; if (target.downsampleFillPolicy && target.downsampleFillPolicy !== 'none') { query.downsample += '-' + target.downsampleFillPolicy; } } if (target.filters && target.filters.length > 0) { query.filters = angular.copy(target.filters); if (query.filters) { for (const filterKey in query.filters) { query.filters[filterKey].filter = this.templateSrv.replace( query.filters[filterKey].filter, options.scopedVars, 'pipe' ); } } } else { query.tags = angular.copy(target.tags); if (query.tags) { for (const tagKey in query.tags) { query.tags[tagKey] = this.templateSrv.replace(query.tags[tagKey], options.scopedVars, 'pipe'); } } } if (target.explicitTags) { query.explicitTags = true; } return query; } mapMetricsToTargets(metrics: any, options: any, tsdbVersion: number) { let interpolatedTagValue, arrTagV; return _.map(metrics, metricData => { if (tsdbVersion === 3) { return metricData.query.index; } else { return _.findIndex(options.targets as any[], target => { if (target.filters && target.filters.length > 0) { return target.metric === metricData.metric; } else { return ( target.metric === metricData.metric && _.every(target.tags, (tagV, tagK) => { interpolatedTagValue = this.templateSrv.replace(tagV, options.scopedVars, 'pipe'); arrTagV = interpolatedTagValue.split('|'); return _.includes(arrTagV, metricData.tags[tagK]) || interpolatedTagValue === '*'; }) ); } }); } }); } convertToTSDBTime(date: any, roundUp: any, timezone: any) { if (date === 'now') { return null; } date = dateMath.parse(date, roundUp, timezone); return date.valueOf(); } }
public/app/plugins/datasource/opentsdb/datasource.ts
1
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.08874684572219849, 0.002096272073686123, 0.0001662320428295061, 0.0001769668742781505, 0.012262287549674511 ]
{ "id": 0, "code_window": [ " * For non mixed scenarios this is undefined.\n", " */\n", " datasource?: string | null;\n", "\n", " metric?: any;\n", "\n", " /**\n", " * For limiting result lines.\n", " */\n", " maxLines?: number;\n", "}\n", "\n", "export interface DataQueryError {\n", " data?: {\n", " message?: string;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/grafana-data/src/types/datasource.ts", "type": "replace", "edit_start_line_idx": 393 }
import React from 'react'; // Ignoring because I couldn't get @types/react-select work wih Torkel's fork // @ts-ignore import { components } from '@torkelo/react-select'; export const IndicatorsContainer = (props: any) => { const isOpen = props.selectProps.menuIsOpen; return ( <components.IndicatorsContainer {...props}> <span className={`gf-form-select-box__select-arrow ${isOpen ? `gf-form-select-box__select-arrow--reversed` : ''}`} /> </components.IndicatorsContainer> ); }; export default IndicatorsContainer;
packages/grafana-ui/src/components/Select/IndicatorsContainer.tsx
0
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.00017043814295902848, 0.0001697674160823226, 0.0001690966892056167, 0.0001697674160823226, 6.707268767058849e-7 ]
{ "id": 0, "code_window": [ " * For non mixed scenarios this is undefined.\n", " */\n", " datasource?: string | null;\n", "\n", " metric?: any;\n", "\n", " /**\n", " * For limiting result lines.\n", " */\n", " maxLines?: number;\n", "}\n", "\n", "export interface DataQueryError {\n", " data?: {\n", " message?: string;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/grafana-data/src/types/datasource.ts", "type": "replace", "edit_start_line_idx": 393 }
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris package unix import ( "runtime" "unsafe" ) // ioctl itself should not be exposed directly, but additional get/set // functions for specific types are permissible. // IoctlSetInt performs an ioctl operation which sets an integer value // on fd, using the specified request number. func IoctlSetInt(fd int, req uint, value int) error { return ioctl(fd, req, uintptr(value)) } // IoctlSetWinsize performs an ioctl on fd with a *Winsize argument. // // To change fd's window size, the req argument should be TIOCSWINSZ. func IoctlSetWinsize(fd int, req uint, value *Winsize) error { // TODO: if we get the chance, remove the req parameter and // hardcode TIOCSWINSZ. err := ioctl(fd, req, uintptr(unsafe.Pointer(value))) runtime.KeepAlive(value) return err } // IoctlSetTermios performs an ioctl on fd with a *Termios. // // The req value will usually be TCSETA or TIOCSETA. func IoctlSetTermios(fd int, req uint, value *Termios) error { // TODO: if we get the chance, remove the req parameter. err := ioctl(fd, req, uintptr(unsafe.Pointer(value))) runtime.KeepAlive(value) return err } // IoctlGetInt performs an ioctl operation which gets an integer value // from fd, using the specified request number. // // A few ioctl requests use the return value as an output parameter; // for those, IoctlRetInt should be used instead of this function. func IoctlGetInt(fd int, req uint) (int, error) { var value int err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return value, err } func IoctlGetWinsize(fd int, req uint) (*Winsize, error) { var value Winsize err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } func IoctlGetTermios(fd int, req uint) (*Termios, error) { var value Termios err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err }
vendor/golang.org/x/sys/unix/ioctl.go
0
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.00023217711714096367, 0.00018020653806161135, 0.00016692982171662152, 0.0001712939701974392, 0.00002141736331395805 ]
{ "id": 0, "code_window": [ " * For non mixed scenarios this is undefined.\n", " */\n", " datasource?: string | null;\n", "\n", " metric?: any;\n", "\n", " /**\n", " * For limiting result lines.\n", " */\n", " maxLines?: number;\n", "}\n", "\n", "export interface DataQueryError {\n", " data?: {\n", " message?: string;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/grafana-data/src/types/datasource.ts", "type": "replace", "edit_start_line_idx": 393 }
package sqlstore import ( "context" "time" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" ) func init() { bus.AddHandler("sql", GetApiKeys) bus.AddHandler("sql", GetApiKeyById) bus.AddHandler("sql", GetApiKeyByName) bus.AddHandlerCtx("sql", DeleteApiKeyCtx) bus.AddHandler("sql", AddApiKey) } func GetApiKeys(query *models.GetApiKeysQuery) error { sess := x.Limit(100, 0).Where("org_id=? and ( expires IS NULL or expires >= ?)", query.OrgId, timeNow().Unix()).Asc("name") if query.IncludeExpired { sess = x.Limit(100, 0).Where("org_id=?", query.OrgId).Asc("name") } query.Result = make([]*models.ApiKey, 0) return sess.Find(&query.Result) } func DeleteApiKeyCtx(ctx context.Context, cmd *models.DeleteApiKeyCommand) error { return withDbSession(ctx, func(sess *DBSession) error { var rawSql = "DELETE FROM api_key WHERE id=? and org_id=?" _, err := sess.Exec(rawSql, cmd.Id, cmd.OrgId) return err }) } func AddApiKey(cmd *models.AddApiKeyCommand) error { return inTransaction(func(sess *DBSession) error { key := models.ApiKey{OrgId: cmd.OrgId, Name: cmd.Name} exists, _ := sess.Get(&key) if exists { return models.ErrDuplicateApiKey } updated := timeNow() var expires *int64 = nil if cmd.SecondsToLive > 0 { v := updated.Add(time.Second * time.Duration(cmd.SecondsToLive)).Unix() expires = &v } else if cmd.SecondsToLive < 0 { return models.ErrInvalidApiKeyExpiration } t := models.ApiKey{ OrgId: cmd.OrgId, Name: cmd.Name, Role: cmd.Role, Key: cmd.Key, Created: updated, Updated: updated, Expires: expires, } if _, err := sess.Insert(&t); err != nil { return err } cmd.Result = &t return nil }) } func GetApiKeyById(query *models.GetApiKeyByIdQuery) error { var apikey models.ApiKey has, err := x.Id(query.ApiKeyId).Get(&apikey) if err != nil { return err } else if !has { return models.ErrInvalidApiKey } query.Result = &apikey return nil } func GetApiKeyByName(query *models.GetApiKeyByNameQuery) error { var apikey models.ApiKey has, err := x.Where("org_id=? AND name=?", query.OrgId, query.KeyName).Get(&apikey) if err != nil { return err } else if !has { return models.ErrInvalidApiKey } query.Result = &apikey return nil }
pkg/services/sqlstore/apikey.go
0
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.00017677833966445178, 0.0001716599363135174, 0.00016705386224202812, 0.0001717536069918424, 0.000002654255013112561 ]
{ "id": 1, "code_window": [ " format?: string;\n", " reverse?: boolean;\n", " legendFormat?: string;\n", " valueWithRefId?: boolean;\n", "}\n", "\n", "export interface LokiOptions extends DataSourceJsonData {\n", " maxLines?: string;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " maxLines?: number;\n" ], "file_path": "public/app/plugins/datasource/loki/types.ts", "type": "add", "edit_start_line_idx": 44 }
import { Labels, DataQuery, DataSourceJsonData } from '@grafana/data'; export interface LokiLegacyQueryRequest { query: string; limit?: number; start?: number; end?: number; direction?: 'BACKWARD' | 'FORWARD'; regexp?: string; refId: string; } export interface LokiInstantQueryRequest { query: string; limit?: number; time?: string; direction?: 'BACKWARD' | 'FORWARD'; } export interface LokiRangeQueryRequest { query: string; limit?: number; start?: number; end?: number; step?: number; direction?: 'BACKWARD' | 'FORWARD'; } export enum LokiResultType { Stream = 'streams', Vector = 'vector', Matrix = 'matrix', } export interface LokiQuery extends DataQuery { expr: string; liveStreaming?: boolean; query?: string; regexp?: string; format?: string; reverse?: boolean; legendFormat?: string; valueWithRefId?: boolean; } export interface LokiOptions extends DataSourceJsonData { maxLines?: string; derivedFields?: DerivedFieldConfig[]; } export interface LokiVectorResult { metric: { [label: string]: string }; value: [number, string]; } export interface LokiVectorResponse { status: string; data: { resultType: LokiResultType.Vector; result: LokiVectorResult[]; }; } export interface LokiMatrixResult { metric: { [label: string]: string }; values: Array<[number, string]>; } export interface LokiMatrixResponse { status: string; data: { resultType: LokiResultType.Matrix; result: LokiMatrixResult[]; }; } export interface LokiStreamResult { stream: Record<string, string>; values: Array<[string, string]>; } export interface LokiStreamResponse { status: string; data: { resultType: LokiResultType.Stream; result: LokiStreamResult[]; }; } export interface LokiLegacyStreamResult { labels: string; entries: LokiLogsStreamEntry[]; search?: string; parsedLabels?: Labels; uniqueLabels?: Labels; } export interface LokiLegacyStreamResponse { streams: LokiLegacyStreamResult[]; } export interface LokiTailResponse { streams: LokiStreamResult[]; dropped_entries?: Array<{ labels: Record<string, string>; timestamp: string; }>; } export type LokiResult = LokiVectorResult | LokiMatrixResult | LokiStreamResult | LokiLegacyStreamResult; export type LokiResponse = LokiVectorResponse | LokiMatrixResponse | LokiStreamResponse; export interface LokiLogsStreamEntry { line: string; ts: string; // Legacy, was renamed to ts timestamp?: string; } export interface LokiExpression { regexp: string; query: string; } export type DerivedFieldConfig = { matcherRegex: string; name: string; url?: string; datasourceName?: string; }; export interface TransformerOptions { format: string; legendFormat: string; step: number; start: number; end: number; query: string; responseListLength: number; refId: string; valueWithRefId?: boolean; }
public/app/plugins/datasource/loki/types.ts
1
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.998017430305481, 0.06979517638683319, 0.00039127972559072077, 0.001331245875917375, 0.24812930822372437 ]
{ "id": 1, "code_window": [ " format?: string;\n", " reverse?: boolean;\n", " legendFormat?: string;\n", " valueWithRefId?: boolean;\n", "}\n", "\n", "export interface LokiOptions extends DataSourceJsonData {\n", " maxLines?: string;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " maxLines?: number;\n" ], "file_path": "public/app/plugins/datasource/loki/types.ts", "type": "add", "edit_start_line_idx": 44 }
import React from 'react'; import { shallow } from 'enzyme'; import { UnThemedLogLabels as LogLabels } from './LogLabels'; import { getTheme } from '../../themes'; describe('<LogLabels />', () => { it('renders notice when no labels are found', () => { const wrapper = shallow(<LogLabels labels={{}} theme={getTheme()} />); expect(wrapper.text()).toContain('no unique labels'); }); it('renders labels', () => { const wrapper = shallow(<LogLabels labels={{ foo: 'bar', baz: '42' }} theme={getTheme()} />); expect(wrapper.text()).toContain('bar'); expect(wrapper.text()).toContain('42'); }); it('exlcudes labels with certain names or labels starting with underscore', () => { const wrapper = shallow(<LogLabels labels={{ foo: 'bar', level: '42', _private: '13' }} theme={getTheme()} />); expect(wrapper.text()).toContain('bar'); expect(wrapper.text()).not.toContain('42'); expect(wrapper.text()).not.toContain('13'); }); });
packages/grafana-ui/src/components/Logs/LogLabels.test.tsx
0
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.0001770110975485295, 0.00017509981989860535, 0.00017345166997984052, 0.00017483666306361556, 0.0000014649950799139333 ]
{ "id": 1, "code_window": [ " format?: string;\n", " reverse?: boolean;\n", " legendFormat?: string;\n", " valueWithRefId?: boolean;\n", "}\n", "\n", "export interface LokiOptions extends DataSourceJsonData {\n", " maxLines?: string;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " maxLines?: number;\n" ], "file_path": "public/app/plugins/datasource/loki/types.ts", "type": "add", "edit_start_line_idx": 44 }
import { reducerTester } from '../../../../test/core/redux/reducerTester'; import { VariablesState } from '../state/variablesReducer'; import { createDataSourceOptions, dataSourceVariableReducer } from './reducer'; import { DataSourceVariableModel } from '../../templating/types'; import { getVariableTestContext } from '../state/helpers'; import cloneDeep from 'lodash/cloneDeep'; import { createDataSourceVariableAdapter } from './adapter'; import { DataSourceSelectItem } from '@grafana/data'; import { toVariablePayload } from '../state/types'; import { getMockPlugins } from '../../plugins/__mocks__/pluginMocks'; describe('dataSourceVariableReducer', () => { const adapter = createDataSourceVariableAdapter(); describe('when createDataSourceOptions is dispatched', () => { const plugins = getMockPlugins(3); const sources: DataSourceSelectItem[] = plugins.map(p => ({ name: p.name, value: `${p.name} value`, meta: p, sort: '', })); it.each` query | regex | includeAll | expected ${sources[1].meta.id} | ${undefined} | ${false} | ${[{ text: 'pretty cool plugin-1', value: 'pretty cool plugin-1', selected: false }]} ${'not-found-plugin'} | ${undefined} | ${false} | ${[{ text: 'No data sources found', value: '', selected: false }]} ${sources[1].meta.id} | ${/.*(pretty cool plugin-1).*/} | ${false} | ${[{ text: 'pretty cool plugin-1', value: 'pretty cool plugin-1', selected: false }]} ${sources[1].meta.id} | ${/.*(pretty cool plugin-2).*/} | ${false} | ${[{ text: 'No data sources found', value: '', selected: false }]} ${sources[1].meta.id} | ${undefined} | ${true} | ${[ { text: 'All', value: '$__all', selected: false }, { text: 'pretty cool plugin-1', value: 'pretty cool plugin-1', selected: false }, ]} ${'not-found-plugin'} | ${undefined} | ${true} | ${[ { text: 'All', value: '$__all', selected: false }, { text: 'No data sources found', value: '', selected: false }, ]} ${sources[1].meta.id} | ${/.*(pretty cool plugin-1).*/} | ${true} | ${[ { text: 'All', value: '$__all', selected: false }, { text: 'pretty cool plugin-1', value: 'pretty cool plugin-1', selected: false }, ]} ${sources[1].meta.id} | ${/.*(pretty cool plugin-2).*/} | ${true} | ${[ { text: 'All', value: '$__all', selected: false }, { text: 'No data sources found', value: '', selected: false }, ]} `( "when called with query: '$query' and regex: '$regex' and includeAll: '$includeAll' then state should be correct", ({ query, regex, includeAll, expected }) => { const { initialState } = getVariableTestContext<DataSourceVariableModel>(adapter, { query, includeAll }); const payload = toVariablePayload({ id: '0', type: 'datasource' }, { sources, regex }); reducerTester<VariablesState>() .givenReducer(dataSourceVariableReducer, cloneDeep(initialState)) .whenActionIsDispatched(createDataSourceOptions(payload)) .thenStateShouldEqual({ ...initialState, ['0']: ({ ...initialState['0'], options: expected, } as unknown) as DataSourceVariableModel, }); } ); }); });
public/app/features/variables/datasource/reducer.test.ts
0
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.0002212214021710679, 0.00017550447955727577, 0.0001643083814997226, 0.00016700528794899583, 0.000018876209651352838 ]
{ "id": 1, "code_window": [ " format?: string;\n", " reverse?: boolean;\n", " legendFormat?: string;\n", " valueWithRefId?: boolean;\n", "}\n", "\n", "export interface LokiOptions extends DataSourceJsonData {\n", " maxLines?: string;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " maxLines?: number;\n" ], "file_path": "public/app/plugins/datasource/loki/types.ts", "type": "add", "edit_start_line_idx": 44 }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package arrow import ( "fmt" "strconv" ) type BooleanType struct{} func (t *BooleanType) ID() Type { return BOOL } func (t *BooleanType) Name() string { return "bool" } func (t *BooleanType) String() string { return "bool" } // BitWidth returns the number of bits required to store a single element of this data type in memory. func (t *BooleanType) BitWidth() int { return 1 } type FixedSizeBinaryType struct { ByteWidth int } func (*FixedSizeBinaryType) ID() Type { return FIXED_SIZE_BINARY } func (*FixedSizeBinaryType) Name() string { return "fixed_size_binary" } func (t *FixedSizeBinaryType) BitWidth() int { return 8 * t.ByteWidth } func (t *FixedSizeBinaryType) String() string { return "fixed_size_binary[" + strconv.Itoa(t.ByteWidth) + "]" } type ( Timestamp int64 Time32 int32 Time64 int64 TimeUnit int Date32 int32 Date64 int64 Duration int64 ) const ( Nanosecond TimeUnit = iota Microsecond Millisecond Second ) func (u TimeUnit) String() string { return [...]string{"ns", "us", "ms", "s"}[uint(u)&3] } // TimestampType is encoded as a 64-bit signed integer since the UNIX epoch (2017-01-01T00:00:00Z). // The zero-value is a nanosecond and time zone neutral. Time zone neutral can be // considered UTC without having "UTC" as a time zone. type TimestampType struct { Unit TimeUnit TimeZone string } func (*TimestampType) ID() Type { return TIMESTAMP } func (*TimestampType) Name() string { return "timestamp" } func (t *TimestampType) String() string { switch len(t.TimeZone) { case 0: return "timestamp[" + t.Unit.String() + "]" default: return "timestamp[" + t.Unit.String() + ", tz=" + t.TimeZone + "]" } } // BitWidth returns the number of bits required to store a single element of this data type in memory. func (*TimestampType) BitWidth() int { return 64 } // Time32Type is encoded as a 32-bit signed integer, representing either seconds or milliseconds since midnight. type Time32Type struct { Unit TimeUnit } func (*Time32Type) ID() Type { return TIME32 } func (*Time32Type) Name() string { return "time32" } func (*Time32Type) BitWidth() int { return 32 } func (t *Time32Type) String() string { return "time32[" + t.Unit.String() + "]" } // Time64Type is encoded as a 64-bit signed integer, representing either microseconds or nanoseconds since midnight. type Time64Type struct { Unit TimeUnit } func (*Time64Type) ID() Type { return TIME64 } func (*Time64Type) Name() string { return "time64" } func (*Time64Type) BitWidth() int { return 64 } func (t *Time64Type) String() string { return "time64[" + t.Unit.String() + "]" } // DurationType is encoded as a 64-bit signed integer, representing an amount // of elapsed time without any relation to a calendar artifact. type DurationType struct { Unit TimeUnit } func (*DurationType) ID() Type { return DURATION } func (*DurationType) Name() string { return "duration" } func (*DurationType) BitWidth() int { return 64 } func (t *DurationType) String() string { return "duration[" + t.Unit.String() + "]" } // Float16Type represents a floating point value encoded with a 16-bit precision. type Float16Type struct{} func (t *Float16Type) ID() Type { return FLOAT16 } func (t *Float16Type) Name() string { return "float16" } func (t *Float16Type) String() string { return "float16" } // BitWidth returns the number of bits required to store a single element of this data type in memory. func (t *Float16Type) BitWidth() int { return 16 } // Decimal128Type represents a fixed-size 128-bit decimal type. type Decimal128Type struct { Precision int32 Scale int32 } func (*Decimal128Type) ID() Type { return DECIMAL } func (*Decimal128Type) Name() string { return "decimal" } func (*Decimal128Type) BitWidth() int { return 16 } func (t *Decimal128Type) String() string { return fmt.Sprintf("%s(%d, %d)", t.Name(), t.Precision, t.Scale) } // MonthInterval represents a number of months. type MonthInterval int32 // MonthIntervalType is encoded as a 32-bit signed integer, // representing a number of months. type MonthIntervalType struct{} func (*MonthIntervalType) ID() Type { return INTERVAL } func (*MonthIntervalType) Name() string { return "month_interval" } func (*MonthIntervalType) String() string { return "month_interval" } // BitWidth returns the number of bits required to store a single element of this data type in memory. func (t *MonthIntervalType) BitWidth() int { return 32 } // DayTimeInterval represents a number of days and milliseconds (fraction of day). type DayTimeInterval struct { Days int32 `json:"days"` Milliseconds int32 `json:"milliseconds"` } // DayTimeIntervalType is encoded as a pair of 32-bit signed integer, // representing a number of days and milliseconds (fraction of day). type DayTimeIntervalType struct{} func (*DayTimeIntervalType) ID() Type { return INTERVAL } func (*DayTimeIntervalType) Name() string { return "day_time_interval" } func (*DayTimeIntervalType) String() string { return "day_time_interval" } // BitWidth returns the number of bits required to store a single element of this data type in memory. func (t *DayTimeIntervalType) BitWidth() int { return 64 } var ( FixedWidthTypes = struct { Boolean FixedWidthDataType Date32 FixedWidthDataType Date64 FixedWidthDataType DayTimeInterval FixedWidthDataType Duration_s FixedWidthDataType Duration_ms FixedWidthDataType Duration_us FixedWidthDataType Duration_ns FixedWidthDataType Float16 FixedWidthDataType MonthInterval FixedWidthDataType Time32s FixedWidthDataType Time32ms FixedWidthDataType Time64us FixedWidthDataType Time64ns FixedWidthDataType Timestamp_s FixedWidthDataType Timestamp_ms FixedWidthDataType Timestamp_us FixedWidthDataType Timestamp_ns FixedWidthDataType }{ Boolean: &BooleanType{}, Date32: &Date32Type{}, Date64: &Date64Type{}, DayTimeInterval: &DayTimeIntervalType{}, Duration_s: &DurationType{Unit: Second}, Duration_ms: &DurationType{Unit: Millisecond}, Duration_us: &DurationType{Unit: Microsecond}, Duration_ns: &DurationType{Unit: Nanosecond}, Float16: &Float16Type{}, MonthInterval: &MonthIntervalType{}, Time32s: &Time32Type{Unit: Second}, Time32ms: &Time32Type{Unit: Millisecond}, Time64us: &Time64Type{Unit: Microsecond}, Time64ns: &Time64Type{Unit: Nanosecond}, Timestamp_s: &TimestampType{Unit: Second, TimeZone: "UTC"}, Timestamp_ms: &TimestampType{Unit: Millisecond, TimeZone: "UTC"}, Timestamp_us: &TimestampType{Unit: Microsecond, TimeZone: "UTC"}, Timestamp_ns: &TimestampType{Unit: Nanosecond, TimeZone: "UTC"}, } _ FixedWidthDataType = (*FixedSizeBinaryType)(nil) )
vendor/github.com/apache/arrow/go/arrow/datatype_fixedwidth.go
0
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.00019656198855955154, 0.00017201136506628245, 0.00016491221322212368, 0.00017020999803207815, 0.000006645963367191143 ]
{ "id": 2, "code_window": [ " }\n", "\n", " // Called once per panel (graph)\n", " query(options: DataQueryRequest) {\n", " const start = this.convertToTSDBTime(options.rangeRaw.from, false, options.timezone);\n", " const end = this.convertToTSDBTime(options.rangeRaw.to, true, options.timezone);\n", " const qs: any[] = [];\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " query(options: DataQueryRequest<OpenTsdbQuery>) {\n" ], "file_path": "public/app/plugins/datasource/opentsdb/datasource.ts", "type": "replace", "edit_start_line_idx": 40 }
import { Observable } from 'rxjs'; import { ComponentType } from 'react'; import { GrafanaPlugin, PluginMeta } from './plugin'; import { PanelData } from './panel'; import { LogRowModel } from './logs'; import { AnnotationEvent, KeyValue, LoadingState, TableData, TimeSeries } from './data'; import { DataFrame, DataFrameDTO } from './dataFrame'; import { RawTimeRange, TimeRange, AbsoluteTimeRange } from './time'; import { ScopedVars } from './ScopedVars'; import { CoreApp } from './app'; export interface DataSourcePluginOptionsEditorProps<JSONData = DataSourceJsonData, SecureJSONData = {}> { options: DataSourceSettings<JSONData, SecureJSONData>; onOptionsChange: (options: DataSourceSettings<JSONData, SecureJSONData>) => void; } // Utility type to extract the query type TQuery from a class extending DataSourceApi<TQuery, TOptions> export type DataSourceQueryType<DSType extends DataSourceApi<any, any>> = DSType extends DataSourceApi< infer TQuery, infer _TOptions > ? TQuery : never; // Utility type to extract the options type TOptions from a class extending DataSourceApi<TQuery, TOptions> export type DataSourceOptionsType<DSType extends DataSourceApi<any, any>> = DSType extends DataSourceApi< infer _TQuery, infer TOptions > ? TOptions : never; export class DataSourcePlugin< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataSourceQueryType<DSType>, TOptions extends DataSourceJsonData = DataSourceOptionsType<DSType>, TSecureOptions = {} > extends GrafanaPlugin<DataSourcePluginMeta<TOptions>> { components: DataSourcePluginComponents<DSType, TQuery, TOptions, TSecureOptions> = {}; constructor(public DataSourceClass: DataSourceConstructor<DSType, TQuery, TOptions>) { super(); } setConfigEditor(editor: ComponentType<DataSourcePluginOptionsEditorProps<TOptions, TSecureOptions>>) { this.components.ConfigEditor = editor; return this; } setConfigCtrl(ConfigCtrl: any) { this.angularConfigCtrl = ConfigCtrl; return this; } setQueryCtrl(QueryCtrl: any) { this.components.QueryCtrl = QueryCtrl; return this; } setAnnotationQueryCtrl(AnnotationsQueryCtrl: any) { this.components.AnnotationsQueryCtrl = AnnotationsQueryCtrl; return this; } setQueryEditor(QueryEditor: ComponentType<QueryEditorProps<DSType, TQuery, TOptions>>) { this.components.QueryEditor = QueryEditor; return this; } setExploreQueryField(ExploreQueryField: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>) { this.components.ExploreQueryField = ExploreQueryField; return this; } setExploreMetricsQueryField(ExploreQueryField: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>) { this.components.ExploreMetricsQueryField = ExploreQueryField; return this; } setExploreLogsQueryField(ExploreQueryField: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>) { this.components.ExploreLogsQueryField = ExploreQueryField; return this; } setExploreStartPage(ExploreStartPage: ComponentType<ExploreStartPageProps>) { this.components.ExploreStartPage = ExploreStartPage; return this; } setVariableQueryEditor(VariableQueryEditor: any) { this.components.VariableQueryEditor = VariableQueryEditor; return this; } setMetadataInspector(MetadataInspector: ComponentType<MetadataInspectorProps<DSType, TQuery, TOptions>>) { this.components.MetadataInspector = MetadataInspector; return this; } setComponentsFromLegacyExports(pluginExports: any) { this.angularConfigCtrl = pluginExports.ConfigCtrl; this.components.QueryCtrl = pluginExports.QueryCtrl; this.components.AnnotationsQueryCtrl = pluginExports.AnnotationsQueryCtrl; this.components.ExploreQueryField = pluginExports.ExploreQueryField; this.components.ExploreStartPage = pluginExports.ExploreStartPage; this.components.QueryEditor = pluginExports.QueryEditor; this.components.VariableQueryEditor = pluginExports.VariableQueryEditor; } } export interface DataSourcePluginMeta<T extends KeyValue = {}> extends PluginMeta<T> { builtIn?: boolean; // Is this for all metrics?: boolean; logs?: boolean; annotations?: boolean; alerting?: boolean; tracing?: boolean; mixed?: boolean; hasQueryHelp?: boolean; category?: string; queryOptions?: PluginMetaQueryOptions; sort?: number; streaming?: boolean; } interface PluginMetaQueryOptions { cacheTimeout?: boolean; maxDataPoints?: boolean; minInterval?: boolean; } export interface DataSourcePluginComponents< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData, TSecureOptions = {} > { QueryCtrl?: any; AnnotationsQueryCtrl?: any; VariableQueryEditor?: any; QueryEditor?: ComponentType<QueryEditorProps<DSType, TQuery, TOptions>>; ExploreQueryField?: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>; ExploreMetricsQueryField?: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>; ExploreLogsQueryField?: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>; ExploreStartPage?: ComponentType<ExploreStartPageProps>; ConfigEditor?: ComponentType<DataSourcePluginOptionsEditorProps<TOptions, TSecureOptions>>; MetadataInspector?: ComponentType<MetadataInspectorProps<DSType, TQuery, TOptions>>; } // Only exported for tests export interface DataSourceConstructor< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData > { new (instanceSettings: DataSourceInstanceSettings<TOptions>, ...args: any[]): DSType; } /** * The main data source abstraction interface, represents an instance of a data source * * Although this is a class, datasource implementations do not *yet* need to extend it. * As such, we can not yet add functions with default implementations. */ export abstract class DataSourceApi< TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData > { /** * Set in constructor */ readonly name: string; /** * Set in constructor */ readonly id: number; /** * min interval range */ interval?: string; constructor(instanceSettings: DataSourceInstanceSettings<TOptions>) { this.name = instanceSettings.name; this.id = instanceSettings.id; this.meta = {} as DataSourcePluginMeta; } /** * Imports queries from a different datasource */ importQueries?(queries: TQuery[], originMeta: PluginMeta): Promise<TQuery[]>; /** * Initializes a datasource after instantiation */ init?: () => void; /** * Query for data, and optionally stream results */ abstract query(request: DataQueryRequest<TQuery>): Promise<DataQueryResponse> | Observable<DataQueryResponse>; /** * Test & verify datasource settings & connection details */ abstract testDatasource(): Promise<any>; /** * Get hints for query improvements */ getQueryHints?(query: TQuery, results: any[], ...rest: any): QueryHint[]; /** * Convert a query to a simple text string */ getQueryDisplayText?(query: TQuery): string; /** * Retrieve context for a given log row */ getLogRowContext?: <TContextQueryOptions extends {}>( row: LogRowModel, options?: TContextQueryOptions ) => Promise<DataQueryResponse>; /** * Variable query action. */ metricFindQuery?(query: any, options?: any): Promise<MetricFindValue[]>; /** * Get tag keys for adhoc filters */ getTagKeys?(options?: any): Promise<MetricFindValue[]>; /** * Get tag values for adhoc filters */ getTagValues?(options: any): Promise<MetricFindValue[]>; /** * Set after constructor call, as the data source instance is the most common thing to pass around * we attach the components to this instance for easy access */ components?: DataSourcePluginComponents<DataSourceApi<TQuery, TOptions>, TQuery, TOptions>; /** * static information about the datasource */ meta: DataSourcePluginMeta; /** * Used by alerting to check if query contains template variables */ targetContainsTemplate?(query: TQuery): boolean; /** * Used in explore */ modifyQuery?(query: TQuery, action: QueryFixAction): TQuery; /** * Used in explore */ getHighlighterExpression?(query: TQuery): string[]; /** * Used in explore */ languageProvider?: any; getVersion?(optionalOptions?: any): Promise<string>; /** * Can be optionally implemented to allow datasource to be a source of annotations for dashboard. To be visible * in the annotation editor `annotations` capability also needs to be enabled in plugin.json. */ annotationQuery?(options: AnnotationQueryRequest<TQuery>): Promise<AnnotationEvent[]>; interpolateVariablesInQueries?(queries: TQuery[], scopedVars: ScopedVars | {}): TQuery[]; } export interface MetadataInspectorProps< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData > { datasource: DSType; // All Data from this DataSource data: DataFrame[]; } export interface QueryEditorProps< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData > { datasource: DSType; query: TQuery; onRunQuery: () => void; onChange: (value: TQuery) => void; /** * Contains query response filtered by refId of QueryResultBase and possible query error */ data?: PanelData; } export enum DataSourceStatus { Connected, Disconnected, } export enum ExploreMode { Logs = 'Logs', Metrics = 'Metrics', Tracing = 'Tracing', } export interface ExploreQueryFieldProps< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData > extends QueryEditorProps<DSType, TQuery, TOptions> { history: any[]; onBlur?: () => void; absoluteRange?: AbsoluteTimeRange; exploreMode?: ExploreMode; } export interface ExploreStartPageProps { datasource?: DataSourceApi; exploreMode: ExploreMode; onClickExample: (query: DataQuery) => void; } /** * Starting in v6.2 DataFrame can represent both TimeSeries and TableData */ export type LegacyResponseData = TimeSeries | TableData | any; export type DataQueryResponseData = DataFrame | DataFrameDTO | LegacyResponseData; export interface DataQueryResponse { /** * The response data. When streaming, this may be empty * or a partial result set */ data: DataQueryResponseData[]; /** * When returning multiple partial responses or streams * Use this key to inform Grafana how to combine the partial responses * Multiple responses with same key are replaced (latest used) */ key?: string; /** * Optionally include error info along with the response data */ error?: DataQueryError; /** * Use this to control which state the response should have * Defaults to LoadingState.Done if state is not defined */ state?: LoadingState; } export interface DataQuery { /** * A - Z */ refId: string; /** * true if query is disabled (ie not executed / sent to TSDB) */ hide?: boolean; /** * Unique, guid like, string used in explore mode */ key?: string; /** * For mixed data sources the selected datasource is on the query level. * For non mixed scenarios this is undefined. */ datasource?: string | null; metric?: any; /** * For limiting result lines. */ maxLines?: number; } export interface DataQueryError { data?: { message?: string; error?: string; }; message?: string; status?: string; statusText?: string; refId?: string; cancelled?: boolean; } export interface DataQueryRequest<TQuery extends DataQuery = DataQuery> { requestId: string; // Used to identify results and optionally cancel the request in backendSrv dashboardId: number; interval: string; intervalMs?: number; maxDataPoints?: number; panelId: number; range?: TimeRange; reverse?: boolean; scopedVars: ScopedVars; targets: TQuery[]; timezone: string; app: CoreApp | string; cacheTimeout?: string; exploreMode?: ExploreMode; rangeRaw?: RawTimeRange; timeInfo?: string; // The query time description (blue text in the upper right) // Request Timing startTime: number; endTime?: number; } export interface DataQueryTimings { dataProcessingTime: number; } export interface QueryFix { type: string; label: string; action?: QueryFixAction; } export interface QueryFixAction { type: string; query?: string; preventSubmit?: boolean; } export interface QueryHint { type: string; label: string; fix?: QueryFix; } export interface MetricFindValue { text: string; } export interface DataSourceJsonData { authType?: string; defaultRegion?: string; } /** * Data Source instance edit model. This is returned from: * /api/datasources */ export interface DataSourceSettings<T extends DataSourceJsonData = DataSourceJsonData, S = {}> { id: number; orgId: number; name: string; typeLogoUrl: string; type: string; access: string; url: string; password: string; user: string; database: string; basicAuth: boolean; basicAuthPassword: string; basicAuthUser: string; isDefault: boolean; jsonData: T; secureJsonData?: S; secureJsonFields?: KeyValue<boolean>; readOnly: boolean; withCredentials: boolean; version?: number; } /** * Frontend settings model that is passed to Datasource constructor. This differs a bit from the model above * as this data model is available to every user who has access to a data source (Viewers+). This is loaded * in bootData (on page load), or from: /api/frontend/settings */ export interface DataSourceInstanceSettings<T extends DataSourceJsonData = DataSourceJsonData> { id: number; type: string; name: string; meta: DataSourcePluginMeta; url?: string; jsonData: T; username?: string; password?: string; // when access is direct, for some legacy datasources database?: string; /** * This is the full Authorization header if basic auth is ennabled. * Only available here when access is Browser (direct), when access is Server (proxy) * The basic auth header, username & password is never exposted to browser/Frontend * so this will be empty then. */ basicAuth?: string; withCredentials?: boolean; } export interface DataSourceSelectItem { name: string; value: string | null; meta: DataSourcePluginMeta; sort: string; } /** * Options passed to the datasource.annotationQuery method. See docs/plugins/developing/datasource.md */ export interface AnnotationQueryRequest<MoreOptions = {}> { range: TimeRange; rangeRaw: RawTimeRange; // Should be DataModel but cannot import that here from the main app. Needs to be moved to package first. dashboard: any; annotation: { datasource: string; enable: boolean; name: string; } & MoreOptions; } export interface HistoryItem<TQuery extends DataQuery = DataQuery> { ts: number; query: TQuery; } export abstract class LanguageProvider { abstract datasource: DataSourceApi<any, any>; abstract request: (url: string, params?: any) => Promise<any>; /** * Returns startTask that resolves with a task list when main syntax is loaded. * Task list consists of secondary promises that load more detailed language features. */ abstract start: () => Promise<any[]>; startTask?: Promise<any[]>; }
packages/grafana-data/src/types/datasource.ts
1
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.013707155361771584, 0.0014607800403609872, 0.00016560713993385434, 0.00037762767169624567, 0.002446334110572934 ]
{ "id": 2, "code_window": [ " }\n", "\n", " // Called once per panel (graph)\n", " query(options: DataQueryRequest) {\n", " const start = this.convertToTSDBTime(options.rangeRaw.from, false, options.timezone);\n", " const end = this.convertToTSDBTime(options.rangeRaw.to, true, options.timezone);\n", " const qs: any[] = [];\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " query(options: DataQueryRequest<OpenTsdbQuery>) {\n" ], "file_path": "public/app/plugins/datasource/opentsdb/datasource.ts", "type": "replace", "edit_start_line_idx": 40 }
+++ # ----------------------------------------------------------------------- # Do not edit this file. It is automatically generated by API Documenter. # ----------------------------------------------------------------------- title = "ToggleButton" keywords = ["grafana","documentation","sdk","@grafana/ui"] type = "docs" draft = true +++ ## ToggleButton variable ### ToggleButton variable <b>Signature</b> ```typescript ToggleButton: FC<ToggleButtonProps> ``` <b>Import</b> ```typescript import { ToggleButton } from '@grafana/ui'; ```
docs/sources/packages_api/ui/togglebutton.md
0
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.00017684204794932157, 0.0001727133203530684, 0.00016710307681933045, 0.00017419485084246844, 0.00000411161590818665 ]
{ "id": 2, "code_window": [ " }\n", "\n", " // Called once per panel (graph)\n", " query(options: DataQueryRequest) {\n", " const start = this.convertToTSDBTime(options.rangeRaw.from, false, options.timezone);\n", " const end = this.convertToTSDBTime(options.rangeRaw.to, true, options.timezone);\n", " const qs: any[] = [];\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " query(options: DataQueryRequest<OpenTsdbQuery>) {\n" ], "file_path": "public/app/plugins/datasource/opentsdb/datasource.ts", "type": "replace", "edit_start_line_idx": 40 }
// +build go1.7 package aws import "context" // BackgroundContext returns a context that will never be canceled, has no // values, and no deadline. This context is used by the SDK to provide // backwards compatibility with non-context API operations and functionality. // // Go 1.6 and before: // This context function is equivalent to context.Background in the Go stdlib. // // Go 1.7 and later: // The context returned will be the value returned by context.Background() // // See https://golang.org/pkg/context for more information on Contexts. func BackgroundContext() Context { return context.Background() }
vendor/github.com/aws/aws-sdk-go/aws/context_background_1_7.go
0
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.00017523305723443627, 0.00016963941743597388, 0.00016452866839244962, 0.00016915652668103576, 0.000004383367922855541 ]
{ "id": 2, "code_window": [ " }\n", "\n", " // Called once per panel (graph)\n", " query(options: DataQueryRequest) {\n", " const start = this.convertToTSDBTime(options.rangeRaw.from, false, options.timezone);\n", " const end = this.convertToTSDBTime(options.rangeRaw.to, true, options.timezone);\n", " const qs: any[] = [];\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " query(options: DataQueryRequest<OpenTsdbQuery>) {\n" ], "file_path": "public/app/plugins/datasource/opentsdb/datasource.ts", "type": "replace", "edit_start_line_idx": 40 }
/* Flot plugin for selecting regions of a plot. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The plugin supports these options: selection: { mode: null or "x" or "y" or "xy", color: color, shape: "round" or "miter" or "bevel", minSize: number of pixels } Selection support is enabled by setting the mode to one of "x", "y" or "xy". In "x" mode, the user will only be able to specify the x range, similarly for "y" mode. For "xy", the selection becomes a rectangle where both ranges can be specified. "color" is color of the selection (if you need to change the color later on, you can get to it with plot.getOptions().selection.color). "shape" is the shape of the corners of the selection. "minSize" is the minimum size a selection can be in pixels. This value can be customized to determine the smallest size a selection can be and still have the selection rectangle be displayed. When customizing this value, the fact that it refers to pixels, not axis units must be taken into account. Thus, for example, if there is a bar graph in time mode with BarWidth set to 1 minute, setting "minSize" to 1 will not make the minimum selection size 1 minute, but rather 1 pixel. Note also that setting "minSize" to 0 will prevent "plotunselected" events from being fired when the user clicks the mouse without dragging. When selection support is enabled, a "plotselected" event will be emitted on the DOM element you passed into the plot function. The event handler gets a parameter with the ranges selected on the axes, like this: placeholder.bind( "plotselected", function( event, ranges ) { alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to) // similar for yaxis - with multiple axes, the extra ones are in // x2axis, x3axis, ... }); The "plotselected" event is only fired when the user has finished making the selection. A "plotselecting" event is fired during the process with the same parameters as the "plotselected" event, in case you want to know what's happening while it's happening, A "plotunselected" event with no arguments is emitted when the user clicks the mouse to remove the selection. As stated above, setting "minSize" to 0 will destroy this behavior. The plugin allso adds the following methods to the plot object: - setSelection( ranges, preventEvent ) Set the selection rectangle. The passed in ranges is on the same form as returned in the "plotselected" event. If the selection mode is "x", you should put in either an xaxis range, if the mode is "y" you need to put in an yaxis range and both xaxis and yaxis if the selection mode is "xy", like this: setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } }); setSelection will trigger the "plotselected" event when called. If you don't want that to happen, e.g. if you're inside a "plotselected" handler, pass true as the second parameter. If you are using multiple axes, you can specify the ranges on any of those, e.g. as x2axis/x3axis/... instead of xaxis, the plugin picks the first one it sees. - clearSelection( preventEvent ) Clear the selection rectangle. Pass in true to avoid getting a "plotunselected" event. - getSelection() Returns the current selection in the same format as the "plotselected" event. If there's currently no selection, the function returns null. */ (function ($) { function init(plot) { var selection = { first: { x: -1, y: -1}, second: { x: -1, y: -1}, show: false, active: false }; // FIXME: The drag handling implemented here should be // abstracted out, there's some similar code from a library in // the navigation plugin, this should be massaged a bit to fit // the Flot cases here better and reused. Doing this would // make this plugin much slimmer. var savedhandlers = {}; var mouseUpHandler = null; function onMouseMove(e) { if (selection.active) { updateSelection(e); plot.getPlaceholder().trigger("plotselecting", [ getSelection() ]); } } function onMouseDown(e) { if (e.which != 1) // only accept left-click return; // cancel out any text selections document.body.focus(); // prevent text selection and drag in old-school browsers if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) { savedhandlers.onselectstart = document.onselectstart; document.onselectstart = function () { return false; }; } if (document.ondrag !== undefined && savedhandlers.ondrag == null) { savedhandlers.ondrag = document.ondrag; document.ondrag = function () { return false; }; } setSelectionPos(selection.first, e); selection.active = true; // this is a bit silly, but we have to use a closure to be // able to whack the same handler again mouseUpHandler = function (e) { onMouseUp(e); }; $(document).one("mouseup", mouseUpHandler); } function onMouseUp(e) { mouseUpHandler = null; // revert drag stuff for old-school browsers if (document.onselectstart !== undefined) document.onselectstart = savedhandlers.onselectstart; if (document.ondrag !== undefined) document.ondrag = savedhandlers.ondrag; // no more dragging selection.active = false; updateSelection(e); if (selectionIsSane()) triggerSelectedEvent(e); else { // this counts as a clear plot.getPlaceholder().trigger("plotunselected", [ ]); plot.getPlaceholder().trigger("plotselecting", [ null ]); } setTimeout(function() { plot.isSelecting = false; }, 10); return false; } function getSelection() { if (!selectionIsSane()) return null; if (!selection.show) return null; var r = {}, c1 = selection.first, c2 = selection.second; var axes = plot.getAxes(); // look if no axis is used var noAxisInUse = true; $.each(axes, function (name, axis) { if (axis.used) { anyUsed = false; } }) $.each(axes, function (name, axis) { if (axis.used || noAxisInUse) { var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]); r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) }; } }); return r; } function triggerSelectedEvent(event) { var r = getSelection(); // Add ctrlKey and metaKey to event r.ctrlKey = event.ctrlKey; r.metaKey = event.metaKey; plot.getPlaceholder().trigger("plotselected", [ r ]); // backwards-compat stuff, to be removed in future if (r.xaxis && r.yaxis) plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]); } function clamp(min, value, max) { return value < min ? min: (value > max ? max: value); } function setSelectionPos(pos, e) { var o = plot.getOptions(); var offset = plot.getPlaceholder().offset(); var plotOffset = plot.getPlotOffset(); pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width()); pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height()); if (o.selection.mode == "y") pos.x = pos == selection.first ? 0 : plot.width(); if (o.selection.mode == "x") pos.y = pos == selection.first ? 0 : plot.height(); } function updateSelection(pos) { if (pos.pageX == null) return; setSelectionPos(selection.second, pos); if (selectionIsSane()) { plot.isSelecting = true; selection.show = true; plot.triggerRedrawOverlay(); } else clearSelection(true); } function clearSelection(preventEvent) { if (selection.show) { selection.show = false; plot.triggerRedrawOverlay(); if (!preventEvent) plot.getPlaceholder().trigger("plotunselected", [ ]); } } // function taken from markings support in Flot function extractRange(ranges, coord) { var axis, from, to, key, axes = plot.getAxes(); for (var k in axes) { axis = axes[k]; if (axis.direction == coord) { key = coord + axis.n + "axis"; if (!ranges[key] && axis.n == 1) key = coord + "axis"; // support x1axis as xaxis if (ranges[key]) { from = ranges[key].from; to = ranges[key].to; break; } } } // backwards-compat stuff - to be removed in future if (!ranges[key]) { axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0]; from = ranges[coord + "1"]; to = ranges[coord + "2"]; } // auto-reverse as an added bonus if (from != null && to != null && from > to) { var tmp = from; from = to; to = tmp; } return { from: from, to: to, axis: axis }; } function setSelection(ranges, preventEvent) { var axis, range, o = plot.getOptions(); if (o.selection.mode == "y") { selection.first.x = 0; selection.second.x = plot.width(); } else { range = extractRange(ranges, "x"); selection.first.x = range.axis.p2c(range.from); selection.second.x = range.axis.p2c(range.to); } if (o.selection.mode == "x") { selection.first.y = 0; selection.second.y = plot.height(); } else { range = extractRange(ranges, "y"); selection.first.y = range.axis.p2c(range.from); selection.second.y = range.axis.p2c(range.to); } selection.show = true; plot.triggerRedrawOverlay(); if (!preventEvent && selectionIsSane()) triggerSelectedEvent(); } function selectionIsSane() { var minSize = plot.getOptions().selection.minSize; return Math.abs(selection.second.x - selection.first.x) >= minSize && Math.abs(selection.second.y - selection.first.y) >= minSize; } plot.clearSelection = clearSelection; plot.setSelection = setSelection; plot.getSelection = getSelection; plot.hooks.bindEvents.push(function(plot, eventHolder) { var o = plot.getOptions(); if (o.selection.mode != null) { eventHolder.mousemove(onMouseMove); eventHolder.mousedown(onMouseDown); } }); plot.hooks.drawOverlay.push(function (plot, ctx) { // draw selection if (selection.show && selectionIsSane()) { var plotOffset = plot.getPlotOffset(); var o = plot.getOptions(); ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); var c = $.color.parse(o.selection.color); ctx.strokeStyle = c.scale('a', 0.8).toString(); ctx.lineWidth = 1; ctx.lineJoin = o.selection.shape; ctx.fillStyle = c.scale('a', 0.4).toString(); var x = Math.min(selection.first.x, selection.second.x) + 0.5, y = Math.min(selection.first.y, selection.second.y) + 0.5, w = Math.abs(selection.second.x - selection.first.x) - 1, h = Math.abs(selection.second.y - selection.first.y) - 1; ctx.fillRect(x, y, w, h); ctx.strokeRect(x, y, w, h); ctx.restore(); } }); plot.hooks.shutdown.push(function (plot, eventHolder) { eventHolder.unbind("mousemove", onMouseMove); eventHolder.unbind("mousedown", onMouseDown); if (mouseUpHandler) { $(document).unbind("mouseup", mouseUpHandler); // grafana addition // In L114 this plugin is overrinding document.onselectstart handler to prevent default or custom behaviour // Then this patch is being restored during mouseup event. But, mouseup handler is unbound when this plugin is destroyed // and the overriden onselectstart handler is not restored. The problematic behaviour surfaces when flot is re-rendered // as a consequence of panel's model update. When i.e. options are applied via onBlur // event on some input which results in flot re-render. The mouseup handler should be called to resture the original handlers // but by the time the document mouseup event occurs, the event handler is no longer there, so onselectstart is permanently overriden. // To fix that we are making sure that the overrides are reverted when this plugin is destroyed, the same way as they would // via mouseup event handler (L138) if (document.onselectstart !== undefined) document.onselectstart = savedhandlers.onselectstart; if (document.ondrag !== undefined) document.ondrag = savedhandlers.ondrag; } }); } $.plot.plugins.push({ init: init, options: { selection: { mode: null, // one of null, "x", "y" or "xy" color: "#e8cfac", shape: "round", // one of "round", "miter", or "bevel" minSize: 5 // minimum number of pixels } }, name: 'selection', version: '1.1' }); })(jQuery);
public/vendor/flot/jquery.flot.selection.js
0
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.00035803980426862836, 0.00017963860591407865, 0.00016270521155092865, 0.0001715421094559133, 0.000035895081964554265 ]
{ "id": 3, "code_window": [ "import { DataQuery, DataSourceJsonData } from '@grafana/data';\n", "\n", "export interface OpenTsdbQuery extends DataQuery {}\n", "\n", "export interface OpenTsdbOptions extends DataSourceJsonData {\n", " tsdbVersion: number;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export interface OpenTsdbQuery extends DataQuery {\n", " metric?: any;\n", "}\n" ], "file_path": "public/app/plugins/datasource/opentsdb/types.ts", "type": "replace", "edit_start_line_idx": 2 }
import { Observable } from 'rxjs'; import { ComponentType } from 'react'; import { GrafanaPlugin, PluginMeta } from './plugin'; import { PanelData } from './panel'; import { LogRowModel } from './logs'; import { AnnotationEvent, KeyValue, LoadingState, TableData, TimeSeries } from './data'; import { DataFrame, DataFrameDTO } from './dataFrame'; import { RawTimeRange, TimeRange, AbsoluteTimeRange } from './time'; import { ScopedVars } from './ScopedVars'; import { CoreApp } from './app'; export interface DataSourcePluginOptionsEditorProps<JSONData = DataSourceJsonData, SecureJSONData = {}> { options: DataSourceSettings<JSONData, SecureJSONData>; onOptionsChange: (options: DataSourceSettings<JSONData, SecureJSONData>) => void; } // Utility type to extract the query type TQuery from a class extending DataSourceApi<TQuery, TOptions> export type DataSourceQueryType<DSType extends DataSourceApi<any, any>> = DSType extends DataSourceApi< infer TQuery, infer _TOptions > ? TQuery : never; // Utility type to extract the options type TOptions from a class extending DataSourceApi<TQuery, TOptions> export type DataSourceOptionsType<DSType extends DataSourceApi<any, any>> = DSType extends DataSourceApi< infer _TQuery, infer TOptions > ? TOptions : never; export class DataSourcePlugin< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataSourceQueryType<DSType>, TOptions extends DataSourceJsonData = DataSourceOptionsType<DSType>, TSecureOptions = {} > extends GrafanaPlugin<DataSourcePluginMeta<TOptions>> { components: DataSourcePluginComponents<DSType, TQuery, TOptions, TSecureOptions> = {}; constructor(public DataSourceClass: DataSourceConstructor<DSType, TQuery, TOptions>) { super(); } setConfigEditor(editor: ComponentType<DataSourcePluginOptionsEditorProps<TOptions, TSecureOptions>>) { this.components.ConfigEditor = editor; return this; } setConfigCtrl(ConfigCtrl: any) { this.angularConfigCtrl = ConfigCtrl; return this; } setQueryCtrl(QueryCtrl: any) { this.components.QueryCtrl = QueryCtrl; return this; } setAnnotationQueryCtrl(AnnotationsQueryCtrl: any) { this.components.AnnotationsQueryCtrl = AnnotationsQueryCtrl; return this; } setQueryEditor(QueryEditor: ComponentType<QueryEditorProps<DSType, TQuery, TOptions>>) { this.components.QueryEditor = QueryEditor; return this; } setExploreQueryField(ExploreQueryField: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>) { this.components.ExploreQueryField = ExploreQueryField; return this; } setExploreMetricsQueryField(ExploreQueryField: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>) { this.components.ExploreMetricsQueryField = ExploreQueryField; return this; } setExploreLogsQueryField(ExploreQueryField: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>) { this.components.ExploreLogsQueryField = ExploreQueryField; return this; } setExploreStartPage(ExploreStartPage: ComponentType<ExploreStartPageProps>) { this.components.ExploreStartPage = ExploreStartPage; return this; } setVariableQueryEditor(VariableQueryEditor: any) { this.components.VariableQueryEditor = VariableQueryEditor; return this; } setMetadataInspector(MetadataInspector: ComponentType<MetadataInspectorProps<DSType, TQuery, TOptions>>) { this.components.MetadataInspector = MetadataInspector; return this; } setComponentsFromLegacyExports(pluginExports: any) { this.angularConfigCtrl = pluginExports.ConfigCtrl; this.components.QueryCtrl = pluginExports.QueryCtrl; this.components.AnnotationsQueryCtrl = pluginExports.AnnotationsQueryCtrl; this.components.ExploreQueryField = pluginExports.ExploreQueryField; this.components.ExploreStartPage = pluginExports.ExploreStartPage; this.components.QueryEditor = pluginExports.QueryEditor; this.components.VariableQueryEditor = pluginExports.VariableQueryEditor; } } export interface DataSourcePluginMeta<T extends KeyValue = {}> extends PluginMeta<T> { builtIn?: boolean; // Is this for all metrics?: boolean; logs?: boolean; annotations?: boolean; alerting?: boolean; tracing?: boolean; mixed?: boolean; hasQueryHelp?: boolean; category?: string; queryOptions?: PluginMetaQueryOptions; sort?: number; streaming?: boolean; } interface PluginMetaQueryOptions { cacheTimeout?: boolean; maxDataPoints?: boolean; minInterval?: boolean; } export interface DataSourcePluginComponents< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData, TSecureOptions = {} > { QueryCtrl?: any; AnnotationsQueryCtrl?: any; VariableQueryEditor?: any; QueryEditor?: ComponentType<QueryEditorProps<DSType, TQuery, TOptions>>; ExploreQueryField?: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>; ExploreMetricsQueryField?: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>; ExploreLogsQueryField?: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>; ExploreStartPage?: ComponentType<ExploreStartPageProps>; ConfigEditor?: ComponentType<DataSourcePluginOptionsEditorProps<TOptions, TSecureOptions>>; MetadataInspector?: ComponentType<MetadataInspectorProps<DSType, TQuery, TOptions>>; } // Only exported for tests export interface DataSourceConstructor< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData > { new (instanceSettings: DataSourceInstanceSettings<TOptions>, ...args: any[]): DSType; } /** * The main data source abstraction interface, represents an instance of a data source * * Although this is a class, datasource implementations do not *yet* need to extend it. * As such, we can not yet add functions with default implementations. */ export abstract class DataSourceApi< TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData > { /** * Set in constructor */ readonly name: string; /** * Set in constructor */ readonly id: number; /** * min interval range */ interval?: string; constructor(instanceSettings: DataSourceInstanceSettings<TOptions>) { this.name = instanceSettings.name; this.id = instanceSettings.id; this.meta = {} as DataSourcePluginMeta; } /** * Imports queries from a different datasource */ importQueries?(queries: TQuery[], originMeta: PluginMeta): Promise<TQuery[]>; /** * Initializes a datasource after instantiation */ init?: () => void; /** * Query for data, and optionally stream results */ abstract query(request: DataQueryRequest<TQuery>): Promise<DataQueryResponse> | Observable<DataQueryResponse>; /** * Test & verify datasource settings & connection details */ abstract testDatasource(): Promise<any>; /** * Get hints for query improvements */ getQueryHints?(query: TQuery, results: any[], ...rest: any): QueryHint[]; /** * Convert a query to a simple text string */ getQueryDisplayText?(query: TQuery): string; /** * Retrieve context for a given log row */ getLogRowContext?: <TContextQueryOptions extends {}>( row: LogRowModel, options?: TContextQueryOptions ) => Promise<DataQueryResponse>; /** * Variable query action. */ metricFindQuery?(query: any, options?: any): Promise<MetricFindValue[]>; /** * Get tag keys for adhoc filters */ getTagKeys?(options?: any): Promise<MetricFindValue[]>; /** * Get tag values for adhoc filters */ getTagValues?(options: any): Promise<MetricFindValue[]>; /** * Set after constructor call, as the data source instance is the most common thing to pass around * we attach the components to this instance for easy access */ components?: DataSourcePluginComponents<DataSourceApi<TQuery, TOptions>, TQuery, TOptions>; /** * static information about the datasource */ meta: DataSourcePluginMeta; /** * Used by alerting to check if query contains template variables */ targetContainsTemplate?(query: TQuery): boolean; /** * Used in explore */ modifyQuery?(query: TQuery, action: QueryFixAction): TQuery; /** * Used in explore */ getHighlighterExpression?(query: TQuery): string[]; /** * Used in explore */ languageProvider?: any; getVersion?(optionalOptions?: any): Promise<string>; /** * Can be optionally implemented to allow datasource to be a source of annotations for dashboard. To be visible * in the annotation editor `annotations` capability also needs to be enabled in plugin.json. */ annotationQuery?(options: AnnotationQueryRequest<TQuery>): Promise<AnnotationEvent[]>; interpolateVariablesInQueries?(queries: TQuery[], scopedVars: ScopedVars | {}): TQuery[]; } export interface MetadataInspectorProps< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData > { datasource: DSType; // All Data from this DataSource data: DataFrame[]; } export interface QueryEditorProps< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData > { datasource: DSType; query: TQuery; onRunQuery: () => void; onChange: (value: TQuery) => void; /** * Contains query response filtered by refId of QueryResultBase and possible query error */ data?: PanelData; } export enum DataSourceStatus { Connected, Disconnected, } export enum ExploreMode { Logs = 'Logs', Metrics = 'Metrics', Tracing = 'Tracing', } export interface ExploreQueryFieldProps< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData > extends QueryEditorProps<DSType, TQuery, TOptions> { history: any[]; onBlur?: () => void; absoluteRange?: AbsoluteTimeRange; exploreMode?: ExploreMode; } export interface ExploreStartPageProps { datasource?: DataSourceApi; exploreMode: ExploreMode; onClickExample: (query: DataQuery) => void; } /** * Starting in v6.2 DataFrame can represent both TimeSeries and TableData */ export type LegacyResponseData = TimeSeries | TableData | any; export type DataQueryResponseData = DataFrame | DataFrameDTO | LegacyResponseData; export interface DataQueryResponse { /** * The response data. When streaming, this may be empty * or a partial result set */ data: DataQueryResponseData[]; /** * When returning multiple partial responses or streams * Use this key to inform Grafana how to combine the partial responses * Multiple responses with same key are replaced (latest used) */ key?: string; /** * Optionally include error info along with the response data */ error?: DataQueryError; /** * Use this to control which state the response should have * Defaults to LoadingState.Done if state is not defined */ state?: LoadingState; } export interface DataQuery { /** * A - Z */ refId: string; /** * true if query is disabled (ie not executed / sent to TSDB) */ hide?: boolean; /** * Unique, guid like, string used in explore mode */ key?: string; /** * For mixed data sources the selected datasource is on the query level. * For non mixed scenarios this is undefined. */ datasource?: string | null; metric?: any; /** * For limiting result lines. */ maxLines?: number; } export interface DataQueryError { data?: { message?: string; error?: string; }; message?: string; status?: string; statusText?: string; refId?: string; cancelled?: boolean; } export interface DataQueryRequest<TQuery extends DataQuery = DataQuery> { requestId: string; // Used to identify results and optionally cancel the request in backendSrv dashboardId: number; interval: string; intervalMs?: number; maxDataPoints?: number; panelId: number; range?: TimeRange; reverse?: boolean; scopedVars: ScopedVars; targets: TQuery[]; timezone: string; app: CoreApp | string; cacheTimeout?: string; exploreMode?: ExploreMode; rangeRaw?: RawTimeRange; timeInfo?: string; // The query time description (blue text in the upper right) // Request Timing startTime: number; endTime?: number; } export interface DataQueryTimings { dataProcessingTime: number; } export interface QueryFix { type: string; label: string; action?: QueryFixAction; } export interface QueryFixAction { type: string; query?: string; preventSubmit?: boolean; } export interface QueryHint { type: string; label: string; fix?: QueryFix; } export interface MetricFindValue { text: string; } export interface DataSourceJsonData { authType?: string; defaultRegion?: string; } /** * Data Source instance edit model. This is returned from: * /api/datasources */ export interface DataSourceSettings<T extends DataSourceJsonData = DataSourceJsonData, S = {}> { id: number; orgId: number; name: string; typeLogoUrl: string; type: string; access: string; url: string; password: string; user: string; database: string; basicAuth: boolean; basicAuthPassword: string; basicAuthUser: string; isDefault: boolean; jsonData: T; secureJsonData?: S; secureJsonFields?: KeyValue<boolean>; readOnly: boolean; withCredentials: boolean; version?: number; } /** * Frontend settings model that is passed to Datasource constructor. This differs a bit from the model above * as this data model is available to every user who has access to a data source (Viewers+). This is loaded * in bootData (on page load), or from: /api/frontend/settings */ export interface DataSourceInstanceSettings<T extends DataSourceJsonData = DataSourceJsonData> { id: number; type: string; name: string; meta: DataSourcePluginMeta; url?: string; jsonData: T; username?: string; password?: string; // when access is direct, for some legacy datasources database?: string; /** * This is the full Authorization header if basic auth is ennabled. * Only available here when access is Browser (direct), when access is Server (proxy) * The basic auth header, username & password is never exposted to browser/Frontend * so this will be empty then. */ basicAuth?: string; withCredentials?: boolean; } export interface DataSourceSelectItem { name: string; value: string | null; meta: DataSourcePluginMeta; sort: string; } /** * Options passed to the datasource.annotationQuery method. See docs/plugins/developing/datasource.md */ export interface AnnotationQueryRequest<MoreOptions = {}> { range: TimeRange; rangeRaw: RawTimeRange; // Should be DataModel but cannot import that here from the main app. Needs to be moved to package first. dashboard: any; annotation: { datasource: string; enable: boolean; name: string; } & MoreOptions; } export interface HistoryItem<TQuery extends DataQuery = DataQuery> { ts: number; query: TQuery; } export abstract class LanguageProvider { abstract datasource: DataSourceApi<any, any>; abstract request: (url: string, params?: any) => Promise<any>; /** * Returns startTask that resolves with a task list when main syntax is loaded. * Task list consists of secondary promises that load more detailed language features. */ abstract start: () => Promise<any[]>; startTask?: Promise<any[]>; }
packages/grafana-data/src/types/datasource.ts
1
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.20213571190834045, 0.007582542020827532, 0.00016503522056154907, 0.0002678822202142328, 0.027561286464333534 ]
{ "id": 3, "code_window": [ "import { DataQuery, DataSourceJsonData } from '@grafana/data';\n", "\n", "export interface OpenTsdbQuery extends DataQuery {}\n", "\n", "export interface OpenTsdbOptions extends DataSourceJsonData {\n", " tsdbVersion: number;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export interface OpenTsdbQuery extends DataQuery {\n", " metric?: any;\n", "}\n" ], "file_path": "public/app/plugins/datasource/opentsdb/types.ts", "type": "replace", "edit_start_line_idx": 2 }
import { alignYLevel } from '../align_yaxes'; describe('Graph Y axes aligner', () => { let yaxes, expected; let alignY = 0; describe('on the one hand with respect to zero', () => { it('Should shrink Y axis', () => { yaxes = [ { min: 5, max: 10 }, { min: 2, max: 3 }, ]; expected = [ { min: 5, max: 10 }, { min: 1.5, max: 3 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); it('Should shrink Y axis', () => { yaxes = [ { min: 2, max: 3 }, { min: 5, max: 10 }, ]; expected = [ { min: 1.5, max: 3 }, { min: 5, max: 10 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); it('Should shrink Y axis', () => { yaxes = [ { min: -10, max: -5 }, { min: -3, max: -2 }, ]; expected = [ { min: -10, max: -5 }, { min: -3, max: -1.5 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); it('Should shrink Y axis', () => { yaxes = [ { min: -3, max: -2 }, { min: -10, max: -5 }, ]; expected = [ { min: -3, max: -1.5 }, { min: -10, max: -5 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); }); describe('on the opposite sides with respect to zero', () => { it('Should shrink Y axes', () => { yaxes = [ { min: -3, max: -1 }, { min: 5, max: 10 }, ]; expected = [ { min: -3, max: 3 }, { min: -10, max: 10 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); it('Should shrink Y axes', () => { yaxes = [ { min: 1, max: 3 }, { min: -10, max: -5 }, ]; expected = [ { min: -3, max: 3 }, { min: -10, max: 10 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); }); describe('both across zero', () => { it('Should shrink Y axes', () => { yaxes = [ { min: -10, max: 5 }, { min: -2, max: 3 }, ]; expected = [ { min: -10, max: 15 }, { min: -2, max: 3 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); it('Should shrink Y axes', () => { yaxes = [ { min: -5, max: 10 }, { min: -3, max: 2 }, ]; expected = [ { min: -15, max: 10 }, { min: -3, max: 2 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); }); describe('one of graphs on zero', () => { it('Should shrink Y axes', () => { yaxes = [ { min: 0, max: 3 }, { min: 5, max: 10 }, ]; expected = [ { min: 0, max: 3 }, { min: 0, max: 10 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); it('Should shrink Y axes', () => { yaxes = [ { min: 5, max: 10 }, { min: 0, max: 3 }, ]; expected = [ { min: 0, max: 10 }, { min: 0, max: 3 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); it('Should shrink Y axes', () => { yaxes = [ { min: -3, max: 0 }, { min: -10, max: -5 }, ]; expected = [ { min: -3, max: 0 }, { min: -10, max: 0 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); it('Should shrink Y axes', () => { yaxes = [ { min: -10, max: -5 }, { min: -3, max: 0 }, ]; expected = [ { min: -10, max: 0 }, { min: -3, max: 0 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); }); describe('both graphs on zero', () => { it('Should shrink Y axes', () => { yaxes = [ { min: 0, max: 3 }, { min: -10, max: 0 }, ]; expected = [ { min: -3, max: 3 }, { min: -10, max: 10 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); it('Should shrink Y axes', () => { yaxes = [ { min: -3, max: 0 }, { min: 0, max: 10 }, ]; expected = [ { min: -3, max: 3 }, { min: -10, max: 10 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); }); describe('mixed placement of graphs relative to zero', () => { it('Should shrink Y axes', () => { yaxes = [ { min: -10, max: 5 }, { min: 1, max: 3 }, ]; expected = [ { min: -10, max: 5 }, { min: -6, max: 3 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); it('Should shrink Y axes', () => { yaxes = [ { min: 1, max: 3 }, { min: -10, max: 5 }, ]; expected = [ { min: -6, max: 3 }, { min: -10, max: 5 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); it('Should shrink Y axes', () => { yaxes = [ { min: -10, max: 5 }, { min: -3, max: -1 }, ]; expected = [ { min: -10, max: 5 }, { min: -3, max: 1.5 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); it('Should shrink Y axes', () => { yaxes = [ { min: -3, max: -1 }, { min: -10, max: 5 }, ]; expected = [ { min: -3, max: 1.5 }, { min: -10, max: 5 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); }); describe('on level not zero', () => { it('Should shrink Y axis', () => { alignY = 1; yaxes = [ { min: 5, max: 10 }, { min: 2, max: 4 }, ]; expected = [ { min: 4, max: 10 }, { min: 2, max: 4 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); it('Should shrink Y axes', () => { alignY = 2; yaxes = [ { min: -3, max: 1 }, { min: 5, max: 10 }, ]; expected = [ { min: -3, max: 7 }, { min: -6, max: 10 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); it('Should shrink Y axes', () => { alignY = -1; yaxes = [ { min: -5, max: 5 }, { min: -2, max: 3 }, ]; expected = [ { min: -5, max: 15 }, { min: -2, max: 3 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); it('Should shrink Y axes', () => { alignY = -2; yaxes = [ { min: -2, max: 3 }, { min: 5, max: 10 }, ]; expected = [ { min: -2, max: 3 }, { min: -2, max: 10 }, ]; alignYLevel(yaxes, alignY); expect(yaxes).toMatchObject(expected); }); }); describe('on level not number value', () => { it('Should ignore without errors', () => { yaxes = [ { min: 5, max: 10 }, { min: 2, max: 4 }, ]; expected = [ { min: 5, max: 10 }, { min: 2, max: 4 }, ]; alignYLevel(yaxes, 'q'); expect(yaxes).toMatchObject(expected); }); }); });
public/app/plugins/panel/graph/specs/align_yaxes.test.ts
0
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.00017859030049294233, 0.00017529574688524008, 0.00017007984570227563, 0.00017549740732647479, 0.0000017165031067634118 ]
{ "id": 3, "code_window": [ "import { DataQuery, DataSourceJsonData } from '@grafana/data';\n", "\n", "export interface OpenTsdbQuery extends DataQuery {}\n", "\n", "export interface OpenTsdbOptions extends DataSourceJsonData {\n", " tsdbVersion: number;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export interface OpenTsdbQuery extends DataQuery {\n", " metric?: any;\n", "}\n" ], "file_path": "public/app/plugins/datasource/opentsdb/types.ts", "type": "replace", "edit_start_line_idx": 2 }
import { toUrlParams } from '../utils/url'; describe('toUrlParams', () => { it('should encode object properties as url parameters', () => { const url = toUrlParams({ server: 'backend-01', hasSpace: 'has space', many: ['1', '2', '3'], true: true, number: 20, isNull: null, isUndefined: undefined, }); expect(url).toBe('server=backend-01&hasSpace=has%20space&many=1&many=2&many=3&true&number=20&isNull=&isUndefined='); }); }); describe('toUrlParams', () => { it('should encode the same way as angularjs', () => { const url = toUrlParams({ server: ':@', }); expect(url).toBe('server=:@'); }); });
public/app/core/specs/url.test.ts
0
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.0001758052530931309, 0.00017109191685449332, 0.00016790007066447288, 0.00016957041225396097, 0.0000034018814858427504 ]
{ "id": 3, "code_window": [ "import { DataQuery, DataSourceJsonData } from '@grafana/data';\n", "\n", "export interface OpenTsdbQuery extends DataQuery {}\n", "\n", "export interface OpenTsdbOptions extends DataSourceJsonData {\n", " tsdbVersion: number;\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export interface OpenTsdbQuery extends DataQuery {\n", " metric?: any;\n", "}\n" ], "file_path": "public/app/plugins/datasource/opentsdb/types.ts", "type": "replace", "edit_start_line_idx": 2 }
import { MssqlDatasource } from './datasource'; import { MssqlQueryCtrl } from './query_ctrl'; import { MssqlConfigCtrl } from './config_ctrl'; const defaultQuery = `SELECT <time_column> as time, <text_column> as text, <tags_column> as tags FROM <table name> WHERE $__timeFilter(time_column) ORDER BY <time_column> ASC`; class MssqlAnnotationsQueryCtrl { static templateUrl = 'partials/annotations.editor.html'; annotation: any; /** @ngInject */ constructor() { this.annotation.rawQuery = this.annotation.rawQuery || defaultQuery; } } export { MssqlDatasource, MssqlDatasource as Datasource, MssqlQueryCtrl as QueryCtrl, MssqlConfigCtrl as ConfigCtrl, MssqlAnnotationsQueryCtrl as AnnotationsQueryCtrl, };
public/app/plugins/datasource/mssql/module.ts
0
https://github.com/grafana/grafana/commit/19123444a139908f6729a60f3727eebe2a1ccdcd
[ 0.00025029006064869463, 0.00020580843556672335, 0.0001704363530734554, 0.00020125368610024452, 0.00002912028503487818 ]
{ "id": 0, "code_window": [ " }\n", "\n", " userMutator(data) {\n", " const options = [];\n", " for (let i = 0; i < data.pks.length; i += 1) {\n", " options.push({\n", " value: data.pks[i],\n", " label: this.userLabel(data.result[i]),\n", " });\n", " }\n", " return options;\n", " }\n", "\n", " dbMutator(data) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " return data.result.map(({ value, text }) => ({\n", " label: text,\n", " value,\n", " }));\n" ], "file_path": "superset-frontend/src/SqlLab/components/QuerySearch.jsx", "type": "replace", "edit_start_line_idx": 155 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import PropTypes from 'prop-types'; import Button from 'src/components/Button'; import Select from 'src/components/Select'; import { t, SupersetClient } from '@superset-ui/core'; import Loading from '../../components/Loading'; import QueryTable from './QueryTable'; import { now, epochTimeXHoursAgo, epochTimeXDaysAgo, epochTimeXYearsAgo, } from '../../modules/dates'; import { STATUS_OPTIONS, TIME_OPTIONS } from '../constants'; import AsyncSelect from '../../components/AsyncSelect'; const propTypes = { actions: PropTypes.object.isRequired, height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, displayLimit: PropTypes.number.isRequired, }; class QuerySearch extends React.PureComponent { constructor(props) { super(props); this.state = { databaseId: null, userId: null, searchText: null, from: '28 days ago', to: 'now', status: 'success', queriesArray: [], queriesLoading: true, }; this.userMutator = this.userMutator.bind(this); this.changeUser = this.changeUser.bind(this); this.dbMutator = this.dbMutator.bind(this); this.onChange = this.onChange.bind(this); this.changeSearch = this.changeSearch.bind(this); this.onKeyDown = this.onKeyDown.bind(this); this.changeFrom = this.changeFrom.bind(this); this.changeTo = this.changeTo.bind(this); this.changeStatus = this.changeStatus.bind(this); this.refreshQueries = this.refreshQueries.bind(this); this.onUserClicked = this.onUserClicked.bind(this); this.onDbClicked = this.onDbClicked.bind(this); } componentDidMount() { this.refreshQueries(); } onUserClicked(userId) { this.setState({ userId }, () => { this.refreshQueries(); }); } onDbClicked(dbId) { this.setState({ databaseId: dbId }, () => { this.refreshQueries(); }); } onChange(db) { const val = db ? db.value : null; this.setState({ databaseId: val }); } onKeyDown(event) { if (event.keyCode === 13) { this.refreshQueries(); } } getTimeFromSelection(selection) { switch (selection) { case 'now': return now(); case '1 hour ago': return epochTimeXHoursAgo(1); case '1 day ago': return epochTimeXDaysAgo(1); case '7 days ago': return epochTimeXDaysAgo(7); case '28 days ago': return epochTimeXDaysAgo(28); case '90 days ago': return epochTimeXDaysAgo(90); case '1 year ago': return epochTimeXYearsAgo(1); default: return null; } } changeFrom(user) { const val = user ? user.value : null; this.setState({ from: val }); } changeTo(status) { const val = status ? status.value : null; this.setState({ to: val }); } changeUser(user) { const val = user ? user.value : null; this.setState({ userId: val }); } insertParams(baseUrl, params) { const validParams = params.filter(function (p) { return p !== ''; }); return `${baseUrl}?${validParams.join('&')}`; } changeStatus(status) { const val = status ? status.value : null; this.setState({ status: val }); } changeSearch(event) { this.setState({ searchText: event.target.value }); } userLabel(user) { if (user.first_name && user.last_name) { return `${user.first_name} ${user.last_name}`; } return user.username; } userMutator(data) { const options = []; for (let i = 0; i < data.pks.length; i += 1) { options.push({ value: data.pks[i], label: this.userLabel(data.result[i]), }); } return options; } dbMutator(data) { const options = data.result.map(db => ({ value: db.id, label: db.database_name, })); this.props.actions.setDatabases(data.result); if (data.result.length === 0) { this.props.actions.addDangerToast( t("It seems you don't have access to any database"), ); } return options; } refreshQueries() { this.setState({ queriesLoading: true }); const params = [ this.state.userId ? `user_id=${this.state.userId}` : '', this.state.databaseId ? `database_id=${this.state.databaseId}` : '', this.state.searchText ? `search_text=${this.state.searchText}` : '', this.state.status ? `status=${this.state.status}` : '', this.state.from ? `from=${this.getTimeFromSelection(this.state.from)}` : '', this.state.to ? `to=${this.getTimeFromSelection(this.state.to)}` : '', ]; SupersetClient.get({ endpoint: this.insertParams('/superset/search_queries', params), }) .then(({ json }) => { this.setState({ queriesArray: json, queriesLoading: false }); }) .catch(() => { this.props.actions.addDangerToast( t('An error occurred when refreshing queries'), ); }); } render() { return ( <div> <div id="search-header" className="row space-1"> <div className="col-sm-2"> <AsyncSelect dataEndpoint="/users/api/read" mutator={this.userMutator} value={this.state.userId} onChange={this.changeUser} placeholder={t('Filter by user')} /> </div> <div className="col-sm-2"> <AsyncSelect onChange={this.onChange} dataEndpoint="/api/v1/database/?q=(filters:!((col:expose_in_sqllab,opr:eq,value:!t)))" value={this.state.databaseId} mutator={this.dbMutator} placeholder={t('Filter by database')} /> </div> <div className="col-sm-4"> <input type="text" onChange={this.changeSearch} onKeyDown={this.onKeyDown} className="form-control input-sm" placeholder={t('Query search string')} /> </div> <div className="col-sm-4 search-date-filter-container"> <Select name="select-from" placeholder={t('[From]-')} options={TIME_OPTIONS.slice(1, TIME_OPTIONS.length).map(xt => ({ value: xt, label: xt, }))} value={this.state.from} autosize={false} onChange={this.changeFrom} /> <Select name="select-to" placeholder={t('[To]-')} options={TIME_OPTIONS.map(xt => ({ value: xt, label: xt }))} value={this.state.to} autosize={false} onChange={this.changeTo} /> <Select name="select-status" placeholder={t('Filter by status')} options={Object.keys(STATUS_OPTIONS).map(s => ({ value: s, label: s, }))} value={this.state.status} isLoading={false} autosize={false} onChange={this.changeStatus} /> <Button buttonSize="small" buttonStyle="success" onClick={this.refreshQueries} > {t('Search')} </Button> </div> </div> <div className="scrollbar-container"> {this.state.queriesLoading ? ( <Loading /> ) : ( <div className="scrollbar-content" style={{ height: this.props.height }} > <QueryTable columns={[ 'state', 'db', 'user', 'time', 'progress', 'rows', 'sql', 'querylink', ]} onUserClicked={this.onUserClicked} onDbClicked={this.onDbClicked} queries={this.state.queriesArray} actions={this.props.actions} displayLimit={this.props.displayLimit} /> </div> )} </div> </div> ); } } QuerySearch.propTypes = propTypes; export default QuerySearch;
superset-frontend/src/SqlLab/components/QuerySearch.jsx
1
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.9981081485748291, 0.1286209523677826, 0.00016297104593832046, 0.00017475700587965548, 0.3250679075717926 ]
{ "id": 0, "code_window": [ " }\n", "\n", " userMutator(data) {\n", " const options = [];\n", " for (let i = 0; i < data.pks.length; i += 1) {\n", " options.push({\n", " value: data.pks[i],\n", " label: this.userLabel(data.result[i]),\n", " });\n", " }\n", " return options;\n", " }\n", "\n", " dbMutator(data) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " return data.result.map(({ value, text }) => ({\n", " label: text,\n", " value,\n", " }));\n" ], "file_path": "superset-frontend/src/SqlLab/components/QuerySearch.jsx", "type": "replace", "edit_start_line_idx": 155 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import FilterFieldItem from './FilterFieldItem'; import { getFilterColorMap } from '../../util/dashboardFiltersColorMap'; export default function renderFilterFieldTreeNodes({ nodes, activeKey }) { if (!nodes) { return []; } const root = nodes[0]; const allFilterNodes = root.children; const children = allFilterNodes.map(node => ({ ...node, children: node.children.map(child => { const { label, value } = child; const colorCode = getFilterColorMap()[value]; return { ...child, label: ( <FilterFieldItem isSelected={value === activeKey} label={label} colorCode={colorCode} /> ), }; }), })); return [ { ...root, label: <span className="root">{root.label}</span>, children, }, ]; }
superset-frontend/src/dashboard/components/filterscope/renderFilterFieldTreeNodes.jsx
0
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.00024460823624394834, 0.00018506415653973818, 0.00016749199130572379, 0.00017498197848908603, 0.00002678280907275621 ]
{ "id": 0, "code_window": [ " }\n", "\n", " userMutator(data) {\n", " const options = [];\n", " for (let i = 0; i < data.pks.length; i += 1) {\n", " options.push({\n", " value: data.pks[i],\n", " label: this.userLabel(data.result[i]),\n", " });\n", " }\n", " return options;\n", " }\n", "\n", " dbMutator(data) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " return data.result.map(({ value, text }) => ({\n", " label: text,\n", " value,\n", " }));\n" ], "file_path": "superset-frontend/src/SqlLab/components/QuerySearch.jsx", "type": "replace", "edit_start_line_idx": 155 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { SupersetClientResponse, t } from '@superset-ui/core'; import { SupersetError, ErrorTypeEnum, } from 'src/components/ErrorMessage/types'; import COMMON_ERR_MESSAGES from './errorMessages'; // The response always contains an error attribute, can contain anything from the // SupersetClientResponse object, and can contain a spread JSON blob export type ClientErrorObject = { error: string; errors?: SupersetError[]; link?: string; message?: string; severity?: string; stacktrace?: string; } & Partial<SupersetClientResponse>; export default function getClientErrorObject( response: SupersetClientResponse | (Response & { timeout: number }) | string, ): Promise<ClientErrorObject> { // takes a SupersetClientResponse as input, attempts to read response as Json if possible, // and returns a Promise that resolves to a plain object with error key and text value. return new Promise(resolve => { if (typeof response === 'string') { resolve({ error: response }); } else { const responseObject = response instanceof Response ? response : response.response; if (responseObject && !responseObject.bodyUsed) { // attempt to read the body as json, and fallback to text. we must clone the // response in order to fallback to .text() because Response is single-read responseObject .clone() .json() .then(errorJson => { let error = { ...responseObject, ...errorJson }; // Backwards compatibility for old error renderers with the new error object if (error.errors && error.errors.length > 0) { error.error = error.description = error.errors[0].message; error.link = error.errors[0]?.extra?.link; } if (error.stack) { error = { ...error, error: t('Unexpected error: ') + (error.description || t('(no description, click to see stack trace)')), stacktrace: error.stack, }; } else if ( error.responseText && error.responseText.indexOf('CSRF') >= 0 ) { error = { ...error, error: t(COMMON_ERR_MESSAGES.SESSION_TIMED_OUT), }; } resolve(error); }) .catch(() => { // fall back to reading as text responseObject.text().then(errorText => { resolve({ ...responseObject, error: errorText }); }); }); } else if ( 'statusText' in response && response.statusText === 'timeout' && 'timeout' in response ) { resolve({ ...responseObject, error: 'Request timed out', errors: [ { error_type: ErrorTypeEnum.FRONTEND_TIMEOUT_ERROR, extra: { timeout: response.timeout / 1000, issue_codes: [ { code: 1000, message: t( 'Issue 1000 - The dataset is too large to query.', ), }, { code: 1001, message: t( 'Issue 1001 - The database is under an unusual load.', ), }, ], }, level: 'error', message: 'Request timed out', }, ], }); } else { // fall back to Response.statusText or generic error of we cannot read the response const error = 'statusText' in response ? response.statusText : t('An error occurred'); resolve({ ...responseObject, error, }); } } }); }
superset-frontend/src/utils/getClientErrorObject.ts
0
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.00017622312589082867, 0.00017056913929991424, 0.0001668465993134305, 0.00017006898997351527, 0.0000029745335723418975 ]
{ "id": 0, "code_window": [ " }\n", "\n", " userMutator(data) {\n", " const options = [];\n", " for (let i = 0; i < data.pks.length; i += 1) {\n", " options.push({\n", " value: data.pks[i],\n", " label: this.userLabel(data.result[i]),\n", " });\n", " }\n", " return options;\n", " }\n", "\n", " dbMutator(data) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " return data.result.map(({ value, text }) => ({\n", " label: text,\n", " value,\n", " }));\n" ], "file_path": "superset-frontend/src/SqlLab/components/QuerySearch.jsx", "type": "replace", "edit_start_line_idx": 155 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ export default { default: null, mapStateToProps: state => ({ choices: state.datasource ? state.datasource.time_grain_sqla.filter(o => o[0] !== null) : null, }), };
superset-frontend/src/explore/controlPanels/timeGrainSqlaAnimationOverrides.js
0
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.00017622298037167639, 0.00017375692550558597, 0.00017067183216568083, 0.00017437597853131592, 0.000002308134526174399 ]
{ "id": 1, "code_window": [ " <div id=\"search-header\" className=\"row space-1\">\n", " <div className=\"col-sm-2\">\n", " <AsyncSelect\n", " dataEndpoint=\"/users/api/read\"\n", " mutator={this.userMutator}\n", " value={this.state.userId}\n", " onChange={this.changeUser}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " dataEndpoint=\"api/v1/query/related/user\"\n" ], "file_path": "superset-frontend/src/SqlLab/components/QuerySearch.jsx", "type": "replace", "edit_start_line_idx": 211 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import PropTypes from 'prop-types'; import Button from 'src/components/Button'; import Select from 'src/components/Select'; import { t, SupersetClient } from '@superset-ui/core'; import Loading from '../../components/Loading'; import QueryTable from './QueryTable'; import { now, epochTimeXHoursAgo, epochTimeXDaysAgo, epochTimeXYearsAgo, } from '../../modules/dates'; import { STATUS_OPTIONS, TIME_OPTIONS } from '../constants'; import AsyncSelect from '../../components/AsyncSelect'; const propTypes = { actions: PropTypes.object.isRequired, height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, displayLimit: PropTypes.number.isRequired, }; class QuerySearch extends React.PureComponent { constructor(props) { super(props); this.state = { databaseId: null, userId: null, searchText: null, from: '28 days ago', to: 'now', status: 'success', queriesArray: [], queriesLoading: true, }; this.userMutator = this.userMutator.bind(this); this.changeUser = this.changeUser.bind(this); this.dbMutator = this.dbMutator.bind(this); this.onChange = this.onChange.bind(this); this.changeSearch = this.changeSearch.bind(this); this.onKeyDown = this.onKeyDown.bind(this); this.changeFrom = this.changeFrom.bind(this); this.changeTo = this.changeTo.bind(this); this.changeStatus = this.changeStatus.bind(this); this.refreshQueries = this.refreshQueries.bind(this); this.onUserClicked = this.onUserClicked.bind(this); this.onDbClicked = this.onDbClicked.bind(this); } componentDidMount() { this.refreshQueries(); } onUserClicked(userId) { this.setState({ userId }, () => { this.refreshQueries(); }); } onDbClicked(dbId) { this.setState({ databaseId: dbId }, () => { this.refreshQueries(); }); } onChange(db) { const val = db ? db.value : null; this.setState({ databaseId: val }); } onKeyDown(event) { if (event.keyCode === 13) { this.refreshQueries(); } } getTimeFromSelection(selection) { switch (selection) { case 'now': return now(); case '1 hour ago': return epochTimeXHoursAgo(1); case '1 day ago': return epochTimeXDaysAgo(1); case '7 days ago': return epochTimeXDaysAgo(7); case '28 days ago': return epochTimeXDaysAgo(28); case '90 days ago': return epochTimeXDaysAgo(90); case '1 year ago': return epochTimeXYearsAgo(1); default: return null; } } changeFrom(user) { const val = user ? user.value : null; this.setState({ from: val }); } changeTo(status) { const val = status ? status.value : null; this.setState({ to: val }); } changeUser(user) { const val = user ? user.value : null; this.setState({ userId: val }); } insertParams(baseUrl, params) { const validParams = params.filter(function (p) { return p !== ''; }); return `${baseUrl}?${validParams.join('&')}`; } changeStatus(status) { const val = status ? status.value : null; this.setState({ status: val }); } changeSearch(event) { this.setState({ searchText: event.target.value }); } userLabel(user) { if (user.first_name && user.last_name) { return `${user.first_name} ${user.last_name}`; } return user.username; } userMutator(data) { const options = []; for (let i = 0; i < data.pks.length; i += 1) { options.push({ value: data.pks[i], label: this.userLabel(data.result[i]), }); } return options; } dbMutator(data) { const options = data.result.map(db => ({ value: db.id, label: db.database_name, })); this.props.actions.setDatabases(data.result); if (data.result.length === 0) { this.props.actions.addDangerToast( t("It seems you don't have access to any database"), ); } return options; } refreshQueries() { this.setState({ queriesLoading: true }); const params = [ this.state.userId ? `user_id=${this.state.userId}` : '', this.state.databaseId ? `database_id=${this.state.databaseId}` : '', this.state.searchText ? `search_text=${this.state.searchText}` : '', this.state.status ? `status=${this.state.status}` : '', this.state.from ? `from=${this.getTimeFromSelection(this.state.from)}` : '', this.state.to ? `to=${this.getTimeFromSelection(this.state.to)}` : '', ]; SupersetClient.get({ endpoint: this.insertParams('/superset/search_queries', params), }) .then(({ json }) => { this.setState({ queriesArray: json, queriesLoading: false }); }) .catch(() => { this.props.actions.addDangerToast( t('An error occurred when refreshing queries'), ); }); } render() { return ( <div> <div id="search-header" className="row space-1"> <div className="col-sm-2"> <AsyncSelect dataEndpoint="/users/api/read" mutator={this.userMutator} value={this.state.userId} onChange={this.changeUser} placeholder={t('Filter by user')} /> </div> <div className="col-sm-2"> <AsyncSelect onChange={this.onChange} dataEndpoint="/api/v1/database/?q=(filters:!((col:expose_in_sqllab,opr:eq,value:!t)))" value={this.state.databaseId} mutator={this.dbMutator} placeholder={t('Filter by database')} /> </div> <div className="col-sm-4"> <input type="text" onChange={this.changeSearch} onKeyDown={this.onKeyDown} className="form-control input-sm" placeholder={t('Query search string')} /> </div> <div className="col-sm-4 search-date-filter-container"> <Select name="select-from" placeholder={t('[From]-')} options={TIME_OPTIONS.slice(1, TIME_OPTIONS.length).map(xt => ({ value: xt, label: xt, }))} value={this.state.from} autosize={false} onChange={this.changeFrom} /> <Select name="select-to" placeholder={t('[To]-')} options={TIME_OPTIONS.map(xt => ({ value: xt, label: xt }))} value={this.state.to} autosize={false} onChange={this.changeTo} /> <Select name="select-status" placeholder={t('Filter by status')} options={Object.keys(STATUS_OPTIONS).map(s => ({ value: s, label: s, }))} value={this.state.status} isLoading={false} autosize={false} onChange={this.changeStatus} /> <Button buttonSize="small" buttonStyle="success" onClick={this.refreshQueries} > {t('Search')} </Button> </div> </div> <div className="scrollbar-container"> {this.state.queriesLoading ? ( <Loading /> ) : ( <div className="scrollbar-content" style={{ height: this.props.height }} > <QueryTable columns={[ 'state', 'db', 'user', 'time', 'progress', 'rows', 'sql', 'querylink', ]} onUserClicked={this.onUserClicked} onDbClicked={this.onDbClicked} queries={this.state.queriesArray} actions={this.props.actions} displayLimit={this.props.displayLimit} /> </div> )} </div> </div> ); } } QuerySearch.propTypes = propTypes; export default QuerySearch;
superset-frontend/src/SqlLab/components/QuerySearch.jsx
1
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.14763981103897095, 0.005065633449703455, 0.00016449384565930814, 0.00018205447122454643, 0.025612138211727142 ]
{ "id": 1, "code_window": [ " <div id=\"search-header\" className=\"row space-1\">\n", " <div className=\"col-sm-2\">\n", " <AsyncSelect\n", " dataEndpoint=\"/users/api/read\"\n", " mutator={this.userMutator}\n", " value={this.state.userId}\n", " onChange={this.changeUser}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " dataEndpoint=\"api/v1/query/related/user\"\n" ], "file_path": "superset-frontend/src/SqlLab/components/QuerySearch.jsx", "type": "replace", "edit_start_line_idx": 211 }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import React from 'react'; import { mount } from 'enzyme'; import { supersetTheme, ThemeProvider } from '@superset-ui/core'; import CodeModal from 'src/dashboard/components/CodeModal'; describe('CodeModal', () => { const mockedProps = { triggerNode: <i className="fa fa-edit" />, }; it('is valid', () => { expect(React.isValidElement(<CodeModal {...mockedProps} />)).toBe(true); }); it('renders the trigger node', () => { const wrapper = mount(<CodeModal {...mockedProps} />, { wrappingComponent: ThemeProvider, wrappingComponentProps: { theme: supersetTheme }, }); expect(wrapper.find('.fa-edit')).toExist(); }); });
superset-frontend/spec/javascripts/dashboard/components/CodeModal_spec.jsx
0
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.0001747411588439718, 0.0001734287361614406, 0.0001715776015771553, 0.00017369809211231768, 0.00000136140147333208 ]
{ "id": 1, "code_window": [ " <div id=\"search-header\" className=\"row space-1\">\n", " <div className=\"col-sm-2\">\n", " <AsyncSelect\n", " dataEndpoint=\"/users/api/read\"\n", " mutator={this.userMutator}\n", " value={this.state.userId}\n", " onChange={this.changeUser}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " dataEndpoint=\"api/v1/query/related/user\"\n" ], "file_path": "superset-frontend/src/SqlLab/components/QuerySearch.jsx", "type": "replace", "edit_start_line_idx": 211 }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M13.4099 12L19.7099 5.71C20.1021 5.31788 20.1021 4.68212 19.7099 4.29C19.3178 3.89788 18.6821 3.89788 18.2899 4.29L11.9999 10.59L5.70994 4.29C5.31782 3.89788 4.68206 3.89788 4.28994 4.29C3.89782 4.68212 3.89782 5.31788 4.28994 5.71L10.5899 12L4.28994 18.29C4.10063 18.4778 3.99414 18.7334 3.99414 19C3.99414 19.2666 4.10063 19.5222 4.28994 19.71C4.47771 19.8993 4.7333 20.0058 4.99994 20.0058C5.26658 20.0058 5.52217 19.8993 5.70994 19.71L11.9999 13.41L18.2899 19.71C18.4777 19.8993 18.7333 20.0058 18.9999 20.0058C19.2666 20.0058 19.5222 19.8993 19.7099 19.71C19.8993 19.5222 20.0057 19.2666 20.0057 19C20.0057 18.7334 19.8993 18.4778 19.7099 18.29L13.4099 12Z" fill="currentColor"/> </svg>
superset-frontend/images/icons/x-large.svg
0
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.0001774674019543454, 0.00017262269102502614, 0.0001684712915448472, 0.00017192937957588583, 0.00000370522252524097 ]
{ "id": 1, "code_window": [ " <div id=\"search-header\" className=\"row space-1\">\n", " <div className=\"col-sm-2\">\n", " <AsyncSelect\n", " dataEndpoint=\"/users/api/read\"\n", " mutator={this.userMutator}\n", " value={this.state.userId}\n", " onChange={this.changeUser}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " dataEndpoint=\"api/v1/query/related/user\"\n" ], "file_path": "superset-frontend/src/SqlLab/components/QuerySearch.jsx", "type": "replace", "edit_start_line_idx": 211 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Add new field 'is_restricted' to SqlMetric and DruidMetric Revision ID: d8bc074f7aad Revises: 1226819ee0e3 Create Date: 2016-06-07 12:33:25.756640 """ # revision identifiers, used by Alembic. revision = "d8bc074f7aad" down_revision = "1226819ee0e3" import sqlalchemy as sa from alembic import op from sqlalchemy import Boolean, Column, Integer from sqlalchemy.ext.declarative import declarative_base from superset import db Base = declarative_base() class DruidMetric(Base): """Declarative class used to do query in upgrade""" __tablename__ = "metrics" id = Column(Integer, primary_key=True) is_restricted = Column(Boolean, default=False, nullable=True) class SqlMetric(Base): """Declarative class used to do query in upgrade""" __tablename__ = "sql_metrics" id = Column(Integer, primary_key=True) is_restricted = Column(Boolean, default=False, nullable=True) def upgrade(): op.add_column("metrics", sa.Column("is_restricted", sa.Boolean(), nullable=True)) op.add_column( "sql_metrics", sa.Column("is_restricted", sa.Boolean(), nullable=True) ) bind = op.get_bind() session = db.Session(bind=bind) # don't use models.DruidMetric # because it assumes the context is consistent with the application for obj in session.query(DruidMetric).all(): obj.is_restricted = False for obj in session.query(SqlMetric).all(): obj.is_restricted = False session.commit() session.close() def downgrade(): with op.batch_alter_table("sql_metrics", schema=None) as batch_op: batch_op.drop_column("is_restricted") with op.batch_alter_table("metrics", schema=None) as batch_op: batch_op.drop_column("is_restricted")
superset/migrations/versions/d8bc074f7aad_add_new_field_is_restricted_to_.py
0
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.001526255626231432, 0.0003331603074911982, 0.0001697048282949254, 0.00017199643480125815, 0.0004228240577504039 ]
{ "id": 2, "code_window": [ "\n", "from superset.constants import RouteMethod\n", "from superset.models.sql_lab import Query\n", "from superset.queries.filters import QueryFilter\n", "from superset.queries.schemas import openapi_spec_methods_override\n", "from superset.views.base_api import BaseSupersetModelRestApi\n", "\n", "logger = logging.getLogger(__name__)\n", "\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "from superset.views.base_api import BaseSupersetModelRestApi, RelatedFieldFilter\n", "from superset.views.filters import FilterRelatedOwners\n" ], "file_path": "superset/queries/api.py", "type": "replace", "edit_start_line_idx": 24 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import logging from flask_appbuilder.models.sqla.interface import SQLAInterface from superset.constants import RouteMethod from superset.models.sql_lab import Query from superset.queries.filters import QueryFilter from superset.queries.schemas import openapi_spec_methods_override from superset.views.base_api import BaseSupersetModelRestApi logger = logging.getLogger(__name__) class QueryRestApi(BaseSupersetModelRestApi): datamodel = SQLAInterface(Query) resource_name = "query" allow_browser_login = True include_route_methods = {RouteMethod.GET, RouteMethod.GET_LIST} class_permission_name = "QueryView" list_columns = [ "user.username", "database.database_name", "status", "start_time", "end_time", ] show_columns = [ "client_id", "tmp_table_name", "tmp_schema_name", "status", "tab_name", "sql_editor_id", "database.id", "schema", "sql", "select_sql", "executed_sql", "limit", "select_as_cta", "select_as_cta_used", "progress", "rows", "error_message", "results_key", "start_time", "start_running_time", "end_time", "end_result_backend_time", "tracking_url", "changed_on", ] base_filters = [["id", QueryFilter, lambda: []]] base_order = ("changed_on", "desc") openapi_spec_tag = "Queries" openapi_spec_methods = openapi_spec_methods_override
superset/queries/api.py
1
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.9968113303184509, 0.12739263474941254, 0.00016877002781257033, 0.000174790620803833, 0.32867565751075745 ]
{ "id": 2, "code_window": [ "\n", "from superset.constants import RouteMethod\n", "from superset.models.sql_lab import Query\n", "from superset.queries.filters import QueryFilter\n", "from superset.queries.schemas import openapi_spec_methods_override\n", "from superset.views.base_api import BaseSupersetModelRestApi\n", "\n", "logger = logging.getLogger(__name__)\n", "\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "from superset.views.base_api import BaseSupersetModelRestApi, RelatedFieldFilter\n", "from superset.views.filters import FilterRelatedOwners\n" ], "file_path": "superset/queries/api.py", "type": "replace", "edit_start_line_idx": 24 }
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ This is the main entrypoint used by Celery workers. As such, it needs to call create_app() in order to initialize things properly """ # Superset framework imports from superset import create_app from superset.extensions import celery_app # Init the Flask app / configure everything create_app() # Need to import late, as the celery_app will have been setup by "create_app()" # pylint: disable=wrong-import-position, unused-import from . import cache, schedules # isort:skip # Export the celery app globally for Celery (as run on the cmd line) to find app = celery_app
superset/tasks/celery_app.py
0
https://github.com/apache/superset/commit/a6224a2ed2ce9425e0d97c151f60f3eed03828ec
[ 0.00043920104508288205, 0.00024010150809772313, 0.0001683173031779006, 0.00017644384934101254, 0.00011499851098051295 ]